Skip to content
Open
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Fixed

- Faster display of tickets with many reservation requests, of the reservable item list and of the form editor, and fewer SQL queries on every page

### Fixed

- Fix hidden question not available in anonymous forms

## [1.3.1] - 2026-10-06
Expand Down
38 changes: 19 additions & 19 deletions public/js/modules/ReservationRequestTimelineActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,42 +30,42 @@
*/

export class ReservationRequestTimelineActions {
#root;
#endpoint_url = `${CFG_GLPI.root_doc}/plugins/advancedforms/ReservationRequest`;
static #initialized = false;

/** @param {HTMLElement} root - one timeline card, rendered by templates/timeline/reservation_request.html.twig */
constructor(root) {
if (!root) {
/**
* Handles the approve/refuse buttons of every timeline card, rendered by
* templates/timeline/reservation_request.html.twig, with a single delegated
* listener: a ticket can carry hundreds of requests. Safe to call several times.
*/
static init() {
if (ReservationRequestTimelineActions.#initialized) {
return;
}
ReservationRequestTimelineActions.#initialized = true;

this.#root = root;

this.#initButtons();
$(document).on(
'click',
'.reservation-request-timeline-item [data-reservation-request-action]',
(e) => ReservationRequestTimelineActions.#onActionClicked($(e.currentTarget)),
);
}

#initButtons() {
const $buttons = $(this.#root).find('[data-reservation-request-action]');
if ($buttons.length === 0) {
return;
}

$buttons.on('click', (e) => this.#onActionClicked($(e.currentTarget), $buttons));
}
static #onActionClicked($button) {
const $root = $button.closest('.reservation-request-timeline-item');
const $buttons = $root.find('[data-reservation-request-action]');

#onActionClicked($button, $buttons) {
// Guard against double-submission while a request is in flight.
if ($buttons.prop('disabled')) {
return;
}

const id = $button.data('reservationRequestId');
const action = $button.data('reservationRequestAction');
const comment = $(this.#root).find('textarea[name="comment"]').val() ?? '';
const comment = $root.find('textarea[name="comment"]').val() ?? '';

$buttons.prop('disabled', true);

$.post(this.#endpoint_url, { id, action, comment })
$.post(`${CFG_GLPI.root_doc}/plugins/advancedforms/ReservationRequest`, { id, action, comment })
.done((data) => {
if (data.success) {
window.location.reload();
Expand Down
6 changes: 0 additions & 6 deletions setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,6 @@
*/
function plugin_init_advancedforms(): void
{
// Stop here if the plugin is not active
$is_active = (new Plugin())->isActivated("advancedforms");
if (!$is_active) {
return;
}

$hook_manager = new HookManager('advancedforms');
$hook_manager->registerCSSFile('css/advancedforms.css');
$hook_manager->registerJavascriptFile('js/advancedforms.js');
Expand Down
26 changes: 18 additions & 8 deletions src/Controller/ReservableItemsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,23 +98,33 @@ private function getReservableItemsForType(string $itemtype, string $search): ar
]);
}

$rows = $DB->request([
'FROM' => ReservationItem::getTable(),
'WHERE' => $where,
$rows = array_filter(
iterator_to_array($DB->request([
'FROM' => ReservationItem::getTable(),
'WHERE' => $where,
]), false),
fn($row): bool => is_array($row) && isset($row['items_id']) && is_numeric($row['items_id']),
);
if ($rows === []) {
return [];
}

// The list can hold thousands of assets: load them in one query, not one per item.
$items_rows = $item->find([
'id' => array_values(array_unique(array_map(fn(array $row): int => (int) $row['items_id'], $rows))),
]);

$itemtype_label = $itemtype::getTypeName(1);
$results = [];
foreach ($rows as $row) {
if (!is_array($row) || !isset($row['items_id']) || !is_numeric($row['items_id'])) {
$item_row = $items_rows[(int) $row['items_id']] ?? null;
if (!is_array($item_row)) {
continue;
}

if (!$item->getFromDB((int) $row['items_id'])) {
continue;
}
$item->getFromResultSet($item_row);

$id = $row['id'] ?? null;
$itemtype_label = $itemtype::getTypeName(1);
$results[] = [
'id' => is_numeric($id) ? (int) $id : 0,
'text' => sprintf('%s (%s)', $item->getName(), $itemtype_label),
Expand Down
89 changes: 70 additions & 19 deletions src/Model/TicketReservationRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ public function markUnavailable(): bool
}

/**
* @param bool|null $can_update_ticket see canAnswer()
* @return array{
* id: int,
* status: int,
Expand All @@ -219,7 +220,7 @@ public function markUnavailable(): bool
* is_direct_reservation: bool,
* }
*/
public function getTimelineInfo(): array
public function getTimelineInfo(?bool $can_update_ticket = null): array
{
return [
'id' => $this->getID(),
Expand All @@ -228,7 +229,7 @@ public function getTimelineInfo(): array
'begin' => $this->getNullableStringField('begin'),
'end' => $this->getNullableStringField('end'),
'comment_validation' => $this->getNullableStringField('comment_validation') ?? '',
'can_answer' => $this->canAnswer(),
'can_answer' => $this->canAnswer($can_update_ticket),
'is_direct_reservation' => $this->getIntField('status') === self::STATUS_ACCEPTED
&& $this->getIntField('users_id_validate') === 0,
];
Expand All @@ -237,38 +238,88 @@ public function getTimelineInfo(): array
/** Resolves the reservable asset's display name; empty string if it no longer exists. */
public static function getReservableItemName(int $reservationitems_id): string
{
$reservation_item = new ReservationItem();
if (!$reservation_item->getFromDB($reservationitems_id)) {
return '';
return self::getReservableItemNames([$reservationitems_id])[$reservationitems_id] ?? '';
}

/**
* Resolves the display names of several reservable assets with one query on
* the reservation items and one per asset itemtype, whatever their number.
*
* @param int[] $reservationitems_ids
* @return array<int, string> names indexed by reservation item id, without the ids whose asset no longer exists
*/
public static function getReservableItemNames(array $reservationitems_ids): array
{
global $DB;

$reservationitems_ids = array_values(array_unique(array_filter(
$reservationitems_ids,
fn(int $id): bool => $id > 0,
)));
if ($reservationitems_ids === []) {
return [];
}

$reservation_items = $DB->request([
'SELECT' => ['id', 'itemtype', 'items_id'],
'FROM' => ReservationItem::getTable(),
'WHERE' => ['id' => $reservationitems_ids],
]);

/** @var array<string, array<int, int>> $items_ids_by_itemtype items id indexed by reservation item id, per itemtype */
$items_ids_by_itemtype = [];
foreach ($reservation_items as $row) {
if (
!is_array($row)
|| !is_numeric($row['id'] ?? null)
|| !is_string($row['itemtype'] ?? null)
|| !is_numeric($row['items_id'] ?? null)
) {
continue;
}

$items_ids_by_itemtype[$row['itemtype']][(int) $row['id']] = (int) $row['items_id'];
}

$itemtype = $reservation_item->fields['itemtype'] ?? '';
$itemtype = is_string($itemtype) ? $itemtype : '';
$names = [];
foreach ($items_ids_by_itemtype as $itemtype => $items_ids) {
$item = getItemForItemtype($itemtype);
if (!$item instanceof CommonDBTM) {
continue;
}

$items_id = $reservation_item->fields['items_id'] ?? 0;
$items_id = is_numeric($items_id) ? (int) $items_id : 0;
$rows = $item->find(['id' => array_values(array_unique($items_ids))]);
foreach ($items_ids as $reservationitems_id => $items_id) {
if (!is_array($rows[$items_id] ?? null)) {
continue;
}

$item = getItemForItemtype($itemtype);
if (!$item instanceof CommonDBTM || !$item->getFromDB($items_id)) {
return '';
$item->getFromResultSet($rows[$items_id]);
$names[$reservationitems_id] = $item->getName();
}
}

return $item->getName();
return $names;
}

/** Whether the current user may approve/refuse this still-waiting request. */
public function canAnswer(): bool
/**
* Whether the current user may approve/refuse this still-waiting request.
*
* @param bool|null $can_update_ticket whether the current user can update the parent ticket, when the caller
* already knows it (timeline display); read from the database when null
*/
public function canAnswer(?bool $can_update_ticket = null): bool
{
if ($this->getIntField('status') !== self::STATUS_WAITING) {
return false;
}

$ticket = new Ticket();
if (!$ticket->getFromDB($this->getIntField('tickets_id'))) {
return false;
if ($can_update_ticket === null) {
$ticket = new Ticket();
$can_update_ticket = $ticket->getFromDB($this->getIntField('tickets_id')) && $ticket->canUpdateItem();
}

if (!$ticket->canUpdateItem()) {
if (!$can_update_ticket) {
return false;
}

Expand Down
33 changes: 29 additions & 4 deletions src/Service/ConfigManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ final class ConfigManager
{
use SingletonTrait;

/** @var array<mixed>|null */
private ?array $config_values = null;

public function renderConfigForm(): string
{
$twig = TemplateRenderer::getInstance();
Expand All @@ -76,10 +79,7 @@ public function getConfigurableQuestionTypes(): array
public function isConfigurableItemEnabled(
ConfigurableItemInterface $item,
): bool {
$config = Config::getConfigurationValue(
'advancedforms',
$item->getConfigKey(),
);
$config = $this->getConfigValues()[$item->getConfigKey()] ?? null;

if ($config === null) {
return false;
Expand All @@ -88,6 +88,31 @@ public function isConfigurableItemEnabled(
return (bool) $config;
}

/** Forgets the loaded configuration, the next read queries it again. */
public function clearCache(): void
{
$this->config_values = null;
}

/** Clears the cache when a configuration value of this plugin is saved. */
public static function onConfigChange(Config $config): void
{
if (($config->fields['context'] ?? null) === 'advancedforms') {
self::getInstance()->clearCache();
}
}

/**
* The plugin configuration is read on every request (plugin init) and many
* times per form editor display, so it is loaded once and kept in memory.
*
* @return array<mixed>
*/
private function getConfigValues(): array
{
return $this->config_values ??= Config::getConfigurationValues('advancedforms');
}

/** @return QuestionTypeInterface[] */
public function getEnabledQuestionsTypes(): array
{
Expand Down
15 changes: 11 additions & 4 deletions src/Service/InitManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ final class InitManager

public function init(): void
{
// Read the configuration once per init, it may have changed since the last one.
ConfigManager::getInstance()->clearCache();

$this->registerConfiguration();
$this->registerPluginTypes();
$this->registerDestinationFields();
Expand Down Expand Up @@ -88,6 +91,12 @@ private function registerConfiguration(): void
// @phpstan-ignore offsetAccess.nonOffsetAccessible (we don't have type hint for this array at this time)
$PLUGIN_HOOKS[Hooks::CONFIG_PAGE]['advancedforms'] = $url;

// Saved configuration values must be seen by the rest of the request.
foreach ([Hooks::ITEM_ADD, Hooks::ITEM_UPDATE, Hooks::ITEM_PURGE] as $hook) {
// @phpstan-ignore offsetAccess.nonOffsetAccessible, offsetAccess.nonOffsetAccessible (we don't have type hint for this array at this time)
$PLUGIN_HOOKS[$hook]['advancedforms'][Config::class] = ConfigManager::onConfigChange(...);
}

// Add configuration tab
Plugin::registerClass(ConfigTab::class, [
'addtabon' => Config::class,
Expand Down Expand Up @@ -153,9 +162,7 @@ private function registerPurgeHooks(): void
{
global $PLUGIN_HOOKS;

// @phpstan-ignore offsetAccess.nonOffsetAccessible (we don't have type hint for this array at this time)
$PLUGIN_HOOKS[Hooks::ITEM_PURGE]['advancedforms'] = [
Ticket::class => TicketReservationRequest::purgeForTicket(...),
];
// @phpstan-ignore offsetAccess.nonOffsetAccessible, offsetAccess.nonOffsetAccessible (we don't have type hint for this array at this time)
$PLUGIN_HOOKS[Hooks::ITEM_PURGE]['advancedforms'][Ticket::class] = TicketReservationRequest::purgeForTicket(...);
}
}
29 changes: 23 additions & 6 deletions src/Service/TimelineManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,22 +58,39 @@ public static function addTimelineItems(array $params): void
$timeline = &$params['timeline'];

$request = new TicketReservationRequest();
$rows = array_filter($request->find(['tickets_id' => $ticket->getID()]), is_array(...));
if ($rows === []) {
return;
}

foreach ($request->find(['tickets_id' => $ticket->getID()]) as $row) {
if (!is_array($row)) {
continue;
}
// A ticket can carry many requests: names and rights are resolved once for all of them.
$equipment_names = TicketReservationRequest::getReservableItemNames(array_map(
fn(array $row): int => is_numeric($row['reservationitems_id'] ?? null) ? (int) $row['reservationitems_id'] : 0,
$rows,
));
$can_update_ticket = null;
$actions_script_added = false;

foreach ($rows as $row) {
// find() already returns the full row; hydrate in place, no extra query.
$request->getFromResultSet($row);

$reservationitems_id = $request->fields['reservationitems_id'] ?? 0;
$reservationitems_id = is_numeric($reservationitems_id) ? (int) $reservationitems_id : 0;

$status = $request->fields['status'] ?? 0;
if ($can_update_ticket === null && is_numeric($status) && (int) $status === TicketReservationRequest::STATUS_WAITING) {
$can_update_ticket = $ticket->canUpdateItem();
}

$info = $request->getTimelineInfo($can_update_ticket ?? false);
$content = TemplateRenderer::getInstance()->render('@advancedforms/timeline/reservation_request.html.twig', [
'request' => $request->getTimelineInfo(),
'equipment_name' => TicketReservationRequest::getReservableItemName($reservationitems_id),
'request' => $info,
'equipment_name' => $equipment_names[$reservationitems_id] ?? '',
// The script handles the buttons of every request of the page, one copy is enough.
'include_actions_script' => $info['can_answer'] && !$actions_script_added,
]);
$actions_script_added = $actions_script_added || $info['can_answer'];

$date_creation = $request->fields['date_creation'] ?? null;
$users_id = $request->fields['users_id'] ?? 0;
Expand Down
Loading
Loading