diff --git a/CHANGELOG.md b/CHANGELOG.md index 9738197..8842a5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/public/js/modules/ReservationRequestTimelineActions.js b/public/js/modules/ReservationRequestTimelineActions.js index 275ed91..ef3d646 100644 --- a/public/js/modules/ReservationRequestTimelineActions.js +++ b/public/js/modules/ReservationRequestTimelineActions.js @@ -30,30 +30,30 @@ */ 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; @@ -61,11 +61,11 @@ export class ReservationRequestTimelineActions { 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(); diff --git a/setup.php b/setup.php index ba4f51f..78a7f18 100644 --- a/setup.php +++ b/setup.php @@ -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'); diff --git a/src/Controller/ReservableItemsController.php b/src/Controller/ReservableItemsController.php index bc64c36..029737b 100644 --- a/src/Controller/ReservableItemsController.php +++ b/src/Controller/ReservableItemsController.php @@ -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), diff --git a/src/Model/TicketReservationRequest.php b/src/Model/TicketReservationRequest.php index 462f600..69daa57 100644 --- a/src/Model/TicketReservationRequest.php +++ b/src/Model/TicketReservationRequest.php @@ -208,6 +208,7 @@ public function markUnavailable(): bool } /** + * @param bool|null $can_update_ticket see canAnswer() * @return array{ * id: int, * status: int, @@ -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(), @@ -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, ]; @@ -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 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> $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; } diff --git a/src/Service/ConfigManager.php b/src/Service/ConfigManager.php index 42470da..4b5e7c2 100644 --- a/src/Service/ConfigManager.php +++ b/src/Service/ConfigManager.php @@ -50,6 +50,9 @@ final class ConfigManager { use SingletonTrait; + /** @var array|null */ + private ?array $config_values = null; + public function renderConfigForm(): string { $twig = TemplateRenderer::getInstance(); @@ -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; @@ -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 + */ + private function getConfigValues(): array + { + return $this->config_values ??= Config::getConfigurationValues('advancedforms'); + } + /** @return QuestionTypeInterface[] */ public function getEnabledQuestionsTypes(): array { diff --git a/src/Service/InitManager.php b/src/Service/InitManager.php index d657c10..e00a8d2 100644 --- a/src/Service/InitManager.php +++ b/src/Service/InitManager.php @@ -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(); @@ -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, @@ -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(...); } } diff --git a/src/Service/TimelineManager.php b/src/Service/TimelineManager.php index fd201df..8e9afe2 100644 --- a/src/Service/TimelineManager.php +++ b/src/Service/TimelineManager.php @@ -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; diff --git a/templates/timeline/reservation_request.html.twig b/templates/timeline/reservation_request.html.twig index aa7a3f2..cf662f9 100644 --- a/templates/timeline/reservation_request.html.twig +++ b/templates/timeline/reservation_request.html.twig @@ -104,13 +104,11 @@ - + {% if include_actions_script ?? true %} + + {% endif %} {% endif %} diff --git a/tests/Front/ConfigFormTest.php b/tests/Front/ConfigFormTest.php index 004a7d0..bf83a9e 100644 --- a/tests/Front/ConfigFormTest.php +++ b/tests/Front/ConfigFormTest.php @@ -77,14 +77,14 @@ public function testTabHasContentExistOnConfigPageForAdmin(): void $this->assertCount(1, $config_header); } - public function testTabContentIsEmptyForTech(): void + public function testTabContentIsDeniedForTech(): void { + // Assert: the tab is refused as we lack rights to view config + $this->expectException(AccessDeniedHttpException::class); + // Act: go to the advanced form tab on the config $this->login('tech'); - $crawler = $this->get("/ajax/common.tabs.php", $this->getConfigTabUrlParams()); - - // Assert: no html was rendered as we lack rights to view config - $this->assertEmpty($crawler); + $this->get("/ajax/common.tabs.php", $this->getConfigTabUrlParams()); } #[DataProvider('provideQuestionTypes')] diff --git a/tests/Model/TicketReservationRequestTest.php b/tests/Model/TicketReservationRequestTest.php index 21aefc5..4990c92 100644 --- a/tests/Model/TicketReservationRequestTest.php +++ b/tests/Model/TicketReservationRequestTest.php @@ -545,9 +545,32 @@ public function testGetTimelineInfo(): void $this->assertFalse($info['is_direct_reservation']); } - private function getReservableItem(): ReservationItem + public function testGetReservableItemNamesResolvesSeveralItems(): void { - $computer = $this->createItem('Computer', ['name' => 'test-computer', 'entities_id' => 0]); + $this->login(); + $first = $this->getReservableItem('first-computer'); + $second = $this->getReservableItem('second-computer'); + + $names = TicketReservationRequest::getReservableItemNames([ + $first->getID(), + $second->getID(), + $first->getID(), + 0, + 999999, + ]); + + // Unknown ids are left out + $this->assertSame([ + $first->getID() => 'first-computer', + $second->getID() => 'second-computer', + ], $names); + $this->assertSame('second-computer', TicketReservationRequest::getReservableItemName($second->getID())); + $this->assertSame('', TicketReservationRequest::getReservableItemName(999999)); + } + + private function getReservableItem(string $name = 'test-computer'): ReservationItem + { + $computer = $this->createItem('Computer', ['name' => $name, 'entities_id' => 0]); return $this->createItem('ReservationItem', [ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), diff --git a/tests/Service/ConfigManagerTest.php b/tests/Service/ConfigManagerTest.php index 7837b67..261bff3 100644 --- a/tests/Service/ConfigManagerTest.php +++ b/tests/Service/ConfigManagerTest.php @@ -33,6 +33,7 @@ namespace GlpiPlugin\Advancedforms\Tests\Service; +use Config; use DOMElement; use GlpiPlugin\Advancedforms\Model\Config\ConfigurableItemInterface; use GlpiPlugin\Advancedforms\Model\QuestionType\ReservationQuestion; @@ -126,6 +127,22 @@ public function testQuestionTypeConfigValueWhenDisabled( $this->assertFalse($config_disabled); } + #[DataProvider('provideQuestionTypes')] + public function testSavedConfigValueIsSeenWithoutInit( + ConfigurableItemInterface $item, + ): void { + // Arrange: enable question type and load the configuration in memory + $this->enableConfigurableItem($item); + $manager = $this->getConfigManager(); + $this->assertTrue($manager->isConfigurableItemEnabled($item)); + + // Act: save the value again, without running the plugin init + Config::setConfigurationValues('advancedforms', [$item->getConfigKey() => 0]); + + // Assert: the cached configuration has been refreshed + $this->assertFalse($manager->isConfigurableItemEnabled($item)); + } + private function getConfigManager(): ConfigManager { return ConfigManager::getInstance(); diff --git a/tests/Service/TimelineManagerTest.php b/tests/Service/TimelineManagerTest.php index cec9860..065a450 100644 --- a/tests/Service/TimelineManagerTest.php +++ b/tests/Service/TimelineManagerTest.php @@ -332,6 +332,39 @@ public function testAddTimelineItemsRendersEquipmentNameAndTimeSlot(): void $this->assertStringContainsString('2026-05-06 10:30:00', $content); } + public function testAddTimelineItemsEmitsActionsScriptOnce(): void + { + $this->login(); + $ticket = $this->createItem('Ticket', ['name' => 't', 'content' => 'c', 'entities_id' => $this->getTestRootEntity(true)]); + $item = $this->getReservableItem(); + + $requests = []; + foreach (['09', '11'] as $hour) { + $requests[] = $this->createItem(TicketReservationRequest::class, [ + 'tickets_id' => $ticket->getID(), + 'reservationitems_id' => $item->getID(), + 'users_id' => Session::getLoginUserID(), + 'begin' => sprintf('2026-05-07 %s:00:00', $hour), + 'end' => sprintf('2026-05-07 %s:30:00', $hour), + 'status' => TicketReservationRequest::STATUS_WAITING, + ]); + } + + $timeline = []; + TimelineManager::addTimelineItems(['item' => $ticket, 'timeline' => &$timeline]); + + // Every request gets its buttons, the script handling them is emitted only once. + $contents = array_map( + fn(TicketReservationRequest $request): string => $timeline['TicketReservationRequest_' . $request->getID()]['item']['content'], + $requests, + ); + foreach ($contents as $content) { + $this->assertStringContainsString('data-reservation-request-action="approve"', $content); + } + + $this->assertSame(1, substr_count(implode('', $contents), 'ReservationRequestTimelineActions.js')); + } + private function getReservableItem(): ReservationItem { $computer = $this->createItem('Computer', ['name' => 'test-computer', 'entities_id' => $this->getTestRootEntity(true)]);