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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,9 @@ 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]

### Fixed
- Fixed the issue where a ticket could be solved without a solution

## [1.0.0-rc1]
11 changes: 11 additions & 0 deletions setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,17 @@ function plugin_init_moreoptions(): void
Controller::class, 'requireFieldsToClose',
];

// Both hooks below are called by GLPI core with an array of parameters (not an item
// instance), so they must be registered without an itemtype key: the callback filters
// on $params['item'] itself.
$PLUGIN_HOOKS[Hooks::TIMELINE_ACTIONS]['moreoptions'] = [
Controller::class, 'showSolutionRequirementsWarning',
];

$PLUGIN_HOOKS[Hooks::POST_ITEM_FORM]['moreoptions'] = [
Controller::class, 'markMandatoryTaskFields',
];

$PLUGIN_HOOKS[Hooks::PRE_ITEM_UPDATE]['moreoptions'][Ticket::class] = [
Controller::class, 'beforeCloseITILObject',
];
Expand Down
152 changes: 138 additions & 14 deletions src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
use CommonITILActor;
use CommonITILObject;
use CommonITILValidation;
use Glpi\Application\View\TemplateRenderer;
use GlpiPlugin\Moreoptions\Config;
use Group_Item;
use Group_Problem;
Expand Down Expand Up @@ -298,7 +299,14 @@ public static function beforeCloseITILObject(CommonDBTM $item): void
&& isset($item->input['status'])
&& ($item->input['status'] == CommonITILObject::CLOSED || $item->input['status'] == CommonITILObject::SOLVED)
) {
if (self::$solution_check_done && $item->input['status'] == CommonITILObject::SOLVED) {
// Consume the one-shot bypass as soon as it is read: it is only meant to let
// through the single status update that ITILSolution::post_addItem() performs
// on its parent right after the solution itself was validated and saved. Leaving
// it at `true` would silently skip this check for every later status change too.
$bypass = self::$solution_check_done;
self::$solution_check_done = false;

if ($bypass && $item->input['status'] == CommonITILObject::SOLVED) {
return;
}
$closed = self::requireFieldsToClose($item);
Expand Down Expand Up @@ -345,11 +353,17 @@ public static function preventClosure(CommonDBTM $item): bool
return true;
}

public static function requireFieldsToClose(CommonDBTM $item, bool $is_solution = false): bool
/**
* Determine which fields configured as required to close are missing on the given item.
*
* @return string[]|null Labels of the missing fields, an empty array if none are missing,
* or null if the check could not be performed (invalid actor class).
*/
private static function getMissingCloseFields(CommonDBTM $item, bool $is_solution): ?array
{
$conf = Config::getConfig();

$message = '';
$missing = [];
$itemtype = get_class($item);

$data = array_merge($item->fields, is_array($item->input) ? $item->input : []);
Expand All @@ -371,11 +385,11 @@ public static function requireFieldsToClose(CommonDBTM $item, bool $is_solution
'type' => CommonITILActor::ASSIGN,
]);
if (count($techs) == 0) {
$message .= '- ' . __s('Technician') . '<br>';
$missing[] = __s('Technician');
}
} else {
// If the user class is not valid, skip this check
return false;
return null;
}
}

Expand All @@ -385,37 +399,37 @@ public static function requireFieldsToClose(CommonDBTM $item, bool $is_solution
$group = new $groupClass();
} else {
// If the group class is not valid, skip this check
return false;
return null;
}
$groups = $group->find([
$itemIdField => $data['id'],
'type' => CommonITILActor::ASSIGN,
]);
if (count($groups) == 0) {
$message .= '- ' . __s('Technician group') . '<br>';
$missing[] = __s('Technician group');
}
}

// Check for required category
if ($conf->fields['require_category_to_close' . $configSuffix] == 1) {
if ((!isset($data['itilcategories_id']) || empty($data['itilcategories_id']))) {
$message .= '- ' . __s('Category') . '<br>';
$missing[] = __s('Category');
}
}

// Check for required location
if ($conf->fields['require_location_to_close' . $configSuffix] == 1) {
if ((!isset($data['locations_id']) || empty($data['locations_id']))) {
$message .= '- ' . __s('Location') . '<br>';
$missing[] = __s('Location');
}
}

// Check if solution exists before closing
// Check if solution exists before resolving/closing.
if (
!$is_solution
&& $conf->fields['require_solution_to_close' . $configSuffix] == 1
&& isset($data['status'])
&& $data['status'] == CommonITILObject::CLOSED
&& in_array($data['status'], [CommonITILObject::SOLVED, CommonITILObject::CLOSED], true)
) {
$solution = new ITILSolution();
$solutions = $solution->find([
Expand All @@ -426,20 +440,79 @@ public static function requireFieldsToClose(CommonDBTM $item, bool $is_solution
],
]);
if (count($solutions) == 0) {
$message .= '- ' . __s('Solution') . '<br>';
$missing[] = __s('Solution');
}
}

if (!empty($message)) {
return $missing;
}

public static function requireFieldsToClose(CommonDBTM $item, bool $is_solution = false): bool
{
$missing = self::getMissingCloseFields($item, $is_solution);

if ($missing === null) {
return false;
}

if (!empty($missing)) {
$itemTypeLabel = $item->getTypeName();

$message = sprintf(__s('To close this %s, you must fill in the following fields:', 'moreoptions'), $itemTypeLabel) . '<br>' . $message;
$message = sprintf(__s('To close this %s, you must fill in the following fields:', 'moreoptions'), $itemTypeLabel) . '<br>';
foreach ($missing as $field) {
$message .= '- ' . $field . '<br>';
}
Session::addMessageAfterRedirect($message, false, ERROR);
return false;
}
return true;
}

/**
* Hooked on {@link \Glpi\Plugin\Hooks::TIMELINE_ACTIONS}. Renders, into the ticket/change/
* problem timeline footer, a script that mutes the "Add a solution" action, adds a lock icon
* to it, and attaches a popover listing the missing fields, as soon as one of the fields
* required to close the item (technician, group, category, location...) is missing.
*
* This is purely client-side: it does not replace the server-side block already performed by
* {@see self::beforeCloseITILObject()} on actual submission, it just gives the user a visual
* hint before they even open the solution form.
*
* @param array<string, mixed> $params
*/
public static function showSolutionRequirementsWarning(array $params): void
{
$item = $params['item'] ?? null;
if (!($item instanceof CommonITILObject) || !$item->canSolve()) {
return;
}

$missing = self::getMissingCloseFields($item, true);
if (empty($missing)) {
// Nothing configured as required, or everything is already filled: let the
// normal "Add a solution" action be usable.
return;
}

$count = count($missing);
$header = sprintf(
_n(
'%1$d required field is missing, so this %2$s can\'t be solved yet.',
'%1$d required fields are missing, so this %2$s can\'t be solved yet.',
$count,
'moreoptions',
),
$count,
$item->getTypeName(1),
);

TemplateRenderer::getInstance()->display('@moreoptions/timeline_solution_warning.html.twig', [
'marker_id' => 'moreoptions-solution-warning-' . $item->getType() . '-' . $item->getID(),
'header' => $header,
'missing_fields' => $missing,
]);
}

public static function checkTaskRequirements(CommonDBTM $item): CommonDBTM
{
$conf = Config::getConfig();
Expand Down Expand Up @@ -478,6 +551,57 @@ public static function checkTaskRequirements(CommonDBTM $item): CommonDBTM
return $item;
}

/**
* Hooked on {@link \Glpi\Plugin\Hooks::POST_ITEM_FORM}. Renders, into the task creation/edit
* form, a script that marks the fields configured as mandatory in moreoptions (category,
* duration, technician, technician group) with the usual red "required" marker and blocks
* client-side submission of the form until they are filled.
*
* The server-side block already performed by {@see self::checkTaskRequirements()} on actual
* submission (PRE_ITEM_ADD) is kept as-is; this only prevents the user from submitting an
* incomplete task in the first place.
*
* @param array<string, mixed> $params
*/
public static function markMandatoryTaskFields(array $params): void
{
$item = $params['item'] ?? null;
if (
!($item instanceof TicketTask)
&& !($item instanceof ChangeTask)
&& !($item instanceof ProblemTask)
) {
return;
}

$conf = Config::getConfig();

$labels = [];
if ($conf->fields['mandatory_task_category'] == 1) {
$labels['taskcategories_id'] = __('Category');
}
if ($conf->fields['mandatory_task_duration'] == 1) {
$labels['actiontime'] = __('Duration');
}
if ($conf->fields['mandatory_task_user'] == 1) {
$labels['users_id_tech'] = __('User');
}
if ($conf->fields['mandatory_task_group'] == 1) {
$labels['groups_id_tech'] = __('Group');
}

if (empty($labels)) {
return;
}

TemplateRenderer::getInstance()->display('@moreoptions/timeline_task_mandatory_fields.html.twig', [
// Unique per-call anchor: lets the injected script find its own <form> reliably.
'marker_id' => 'moreoptions-task-mandatory-' . bin2hex(random_bytes(6)),
'field_labels' => $labels,
'error_message' => __('To create this task, you must fill in the following fields:', 'moreoptions'),
]);
}

public static function updateItemActors(CommonITILObject $item): CommonITILObject
{
$conf = Config::getConfig();
Expand Down
114 changes: 114 additions & 0 deletions templates/timeline_solution_warning.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
{#
# -------------------------------------------------------------------------
# MoreOptions plugin for GLPI
# -------------------------------------------------------------------------
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# -------------------------------------------------------------------------
# @copyright Copyright (C) 2025 by the MoreOptions plugin team.
# @license MIT https://opensource.org/licenses/mit-license.php
# @link https://github.com/pluginsGLPI/moreoptions
# -------------------------------------------------------------------------
#}

{#
# Rendered through the core `Hooks::TIMELINE_ACTIONS` hook (see Controller::showSolutionRequirementsWarning).
# We cannot alter the "Add a solution" action markup itself (rendered by GLPI core), so this
# only drops an invisible anchor + script that finds it and adjusts it client-side: mute its
# label, append a lock icon, and attach a tooltip listing the missing fields.
#}
{#
# Bootstrap's tooltip sanitizer strips `style` attributes from HTML content (its default
# allowlist has no entry for it), so text alignment has to go through an actual CSS class
# instead of an inline style, which would silently be removed.
#}
<style>
.moreoptions-solution-warning-text {
text-align: justify;
}
</style>

{% set tooltip_content %}
<div class="d-flex align-items-start gap-2">
<i class="ti ti-alert-triangle text-warning mt-1" aria-hidden="true"></i>
<div class="moreoptions-solution-warning-text">
<div class="mb-1">{{ header }}</div>
<ul class="mb-0 ps-3">
{% for field in missing_fields %}
<li>{{ field }}</li>
{% endfor %}
</ul>
</div>
</div>
{% endset %}

<span id="{{ marker_id }}" style="display: none;" aria-hidden="true"></span>
<script>
(function() {
var marker = document.getElementById({{ marker_id|json_encode|raw }});
var footer = marker ? marker.closest('#itil-footer') : null;
if (!footer) {
return;
}

var solutionToggle = footer.querySelector('[data-bs-target="#new-ITILSolution-block"]');
if (!solutionToggle) {
return;
}

solutionToggle.style.fontWeight = 'normal';
solutionToggle.style.cursor = 'not-allowed';

solutionToggle.style.display = 'flex';
solutionToggle.style.alignItems = 'center';
solutionToggle.style.justifyContent = 'space-between';
solutionToggle.style.gap = '.5rem';
solutionToggle.style.opacity = '0.6';

var contentWrapper = document.createElement('span');
contentWrapper.style.display = 'inline-flex';
contentWrapper.style.alignItems = 'center';
contentWrapper.style.gap = '.5rem';
contentWrapper.style.opacity = '0.6';
while (solutionToggle.firstChild) {
contentWrapper.appendChild(solutionToggle.firstChild);
}
solutionToggle.appendChild(contentWrapper);

var lock = document.createElement('i');
lock.className = 'ti ti-lock text-muted';
lock.setAttribute('aria-hidden', 'true');
solutionToggle.appendChild(lock);

// A tooltip (not a popover) so it keeps GLPI's dark bubble style: core deliberately
// styles popovers with a light background (see `.popover .popover-body` in
// _base.scss), while tooltips stay dark. Tooltips support HTML content too.
solutionToggle.setAttribute('data-bs-toggle', 'tooltip');
solutionToggle.setAttribute('data-bs-placement', 'right');
solutionToggle.setAttribute('data-bs-trigger', 'hover focus');
solutionToggle.setAttribute('data-bs-html', 'true');
solutionToggle.setAttribute('title', {{ tooltip_content|json_encode|raw }});

if (typeof initTooltips === 'function') {
initTooltips(footer);
}
})();
</script>
Loading