Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
61e6855
Add ReservationQuestionConfig
RomainLvr Jul 20, 2026
9d622ca
Add ReservationQuestionAnswer
RomainLvr Jul 20, 2026
c283899
Add missing license header to ReservationQuestionAnswerTest
RomainLvr Jul 20, 2026
a616b23
Add ReservationQuestion question type
RomainLvr Jul 20, 2026
ed58ce9
Add reservation widget AJAX controllers
RomainLvr Jul 20, 2026
93c9f80
Add missing test coverage
RomainLvr Jul 20, 2026
e8769a1
ReservationQuestion end-user widget (Select2 + Flatpickr)
RomainLvr Jul 20, 2026
bcfee79
Add PreReservationField strategy/config
RomainLvr Jul 20, 2026
869a68e
Add TicketReservationRequest model
RomainLvr Jul 21, 2026
9d08941
Add TicketReservationRequest notification target
RomainLvr Jul 21, 2026
844a556
Raise notification events on reservation request transitions
RomainLvr Jul 21, 2026
79bc2c3
Add PreReservationField destination config field
RomainLvr Jul 21, 2026
b8efd7a
Add test coverage for PreReservationField parse-failure path
RomainLvr Jul 21, 2026
bbab94b
Add reservation request timeline integration
RomainLvr Jul 21, 2026
5760873
Add missing card-rendering test coverage for TimelineManager
RomainLvr Jul 21, 2026
39cde5a
Add ReservationRequestController (approve/refuse)
RomainLvr Jul 22, 2026
5f4ccb5
Wire approve/refuse actions in the ticket timeline
RomainLvr Jul 22, 2026
6798332
Add reservation workflow test
RomainLvr Jul 22, 2026
a0d1d1b
Fix details
RomainLvr Jul 22, 2026
a5bb8bd
Rector
RomainLvr Jul 22, 2026
299856b
Fix phpstan
RomainLvr Jul 22, 2026
ce5dddc
Fix details
RomainLvr Jul 23, 2026
141434f
Fix notifications, validation & cleanup
RomainLvr Jul 28, 2026
28940f4
Update CHANGELOG
RomainLvr Jul 28, 2026
2138b39
Apply suggestions & improve Widget errors handling
RomainLvr Jul 28, 2026
0a08cdb
Fix rector
RomainLvr Jul 29, 2026
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

### Add

- Add Reservation question type
- Add configurable table question type

### Fixed
Expand Down
266 changes: 266 additions & 0 deletions public/js/modules/ReservationQuestionWidget.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
/**
* -------------------------------------------------------------------------
* advancedforms 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 advancedforms plugin team.
* @license MIT https://opensource.org/licenses/mit-license.php
* @link https://github.com/pluginsGLPI/advancedforms
* -------------------------------------------------------------------------
*/

export class ReservationQuestionWidget {
#root;
#endpoint_url = `${CFG_GLPI.root_doc}/plugins/advancedforms/ReservationWidget`;

/** @param {HTMLElement} root - root element rendered by templates/reservation_question.html.twig */
constructor(root) {
if (!root) {
return;
}

this.#root = root;

this.#initItemSelect();
this.#initDateChangeListeners();
this.#initSubmitReset();
}

/**
* The form renderer validates each question server-side before submitting and
* surfaces any error next to the question, so clear our inline availability
* hint on submit to avoid showing duplicate or stale messaging.
*/
#initSubmitReset() {
const form = this.#root.closest('form');
if (!form) {
return;
}

$(form).on('submit', () => this.#showAvailability(null));
$(form)
.find('[data-glpi-form-renderer-action="submit"]')
.on('click', () => this.#showAvailability(null));
}

#initItemSelect() {
const $select = $(this.#root.querySelector('[data-reservation-question-item-select]'));
if ($select.length === 0) {
return;
}

const allowed_itemtypes = JSON.parse(this.#root.dataset.allowedItemtypes || '[]');

$select.select2({
width: '100%',
allowClear: true,
placeholder: __('Select an item to reserve', 'advancedforms'),
ajax: {
url: `${this.#endpoint_url}/ReservableItems`,
type: 'POST',
delay: 250,
data: (params) => ({
allowed_itemtypes: allowed_itemtypes,
search: params.term || '',
}),
processResults: (data) => ({
results: this.#groupResultsByItemtype(Array.isArray(data) ? data : []),
}),
},
});

$select.on('select2:select', () => this.#onItemSelected());
$select.on('select2:clear select2:unselecting', () => this.#onItemCleared());
}

/** Groups flat {id, text, itemtype} results into Select2 optgroups per itemtype. */
#groupResultsByItemtype(data) {
const groups = new Map();

for (const item of data) {
const group_label = item.itemtype || '';
if (!groups.has(group_label)) {
groups.set(group_label, []);
}
groups.get(group_label).push({
id: item.id,
text: item.text,
});
}

return Array.from(groups, ([text, children]) => ({ text, children }));
}

#onItemSelected() {
const $select = $(this.#root.querySelector('[data-reservation-question-item-select]'));
this.#setReservationItemsId($select.val());
$(this.#root.querySelector('[data-reservation-question-dates]')).removeClass('d-none');
this.#checkAvailability();
this.#loadReservations();
}

#onItemCleared() {
this.#setReservationItemsId('');
if (this.#getBeginInput()) {
this.#getBeginInput().value = '';
}
if (this.#getEndInput()) {
this.#getEndInput().value = '';
}
$(this.#root.querySelector('[data-reservation-question-dates]')).addClass('d-none');
this.#showAvailability(null);
this.#renderReservations([]);
}

/** begin/end are rendered by the datetimeField macro (self-initializing Flatpickr); just react to changes. */
#initDateChangeListeners() {
const begin_input = this.#getBeginInput();
const end_input = this.#getEndInput();
if (!begin_input || !end_input) {
return;
}

$(begin_input).on('change', () => this.#checkAvailability());
$(end_input).on('change', () => this.#checkAvailability());
}

#getBeginInput() {
return this.#root.querySelector('[data-reservation-question-begin-picker]');
}

#getEndInput() {
return this.#root.querySelector('[data-reservation-question-end-picker]');
}

#setReservationItemsId(value) {
const input = this.#root.querySelector('[data-reservation-question-field="reservationitems_id"]');
if (input) {
input.value = value ?? '';
}
}

#checkAvailability() {
const reservationitems_id = this.#root.querySelector('[data-reservation-question-field="reservationitems_id"]')?.value ?? '';
const begin = this.#getBeginInput()?.value ?? '';
const end = this.#getEndInput()?.value ?? '';

if (!reservationitems_id || !begin || !end) {
this.#showAvailability(null);
return;
}

// Catch the obvious end-before-begin case locally, before asking the server.
if (!this.#isRangeValid(begin, end)) {
this.#showRangeError();
return;
}

$.post(`${this.#endpoint_url}/CheckAvailability`, { reservationitems_id, begin, end })
.done((data) => this.#showAvailability(data.available))
.fail(() => this.#showStatus(__('Could not check availability, please try again', 'advancedforms'), 'text-danger'));
}

/** @returns {boolean} false only when both dates parse and end is not strictly after begin. */
#isRangeValid(begin, end) {
const begin_ts = Date.parse(begin.replace(' ', 'T'));
const end_ts = Date.parse(end.replace(' ', 'T'));

if (Number.isNaN(begin_ts) || Number.isNaN(end_ts)) {
// Unparseable here: let the server-side validation decide.
return true;
}

return end_ts > begin_ts;
}

#showRangeError() {
this.#showStatus(__('The end date must be after the start date', 'advancedforms'), 'text-danger');
}

/** Fetches the equipment's existing reservations and lists them so the user can see busy slots. */
#loadReservations() {
const reservationitems_id = this.#root.querySelector('[data-reservation-question-field="reservationitems_id"]')?.value ?? '';
if (!reservationitems_id) {
this.#renderReservations([]);
return;
}

$.post(`${this.#endpoint_url}/Reservations`, { reservationitems_id })
.done((data) => this.#renderReservations(Array.isArray(data) ? data : []))
.fail(() => this.#renderReservations([]));
}

/** @param {Array<{begin: string, end: string}>} reservations */
#renderReservations(reservations) {
const container = this.#root.querySelector('[data-reservation-question-reservations]');
if (!container) {
return;
}

if (reservations.length === 0) {
container.innerHTML = '';
return;
}

const title = document.createElement('div');
title.className = 'text-muted small mb-1';
title.textContent = __('Existing reservations for this item', 'advancedforms');

const list = document.createElement('ul');
list.className = 'list-unstyled small mb-0';
for (const reservation of reservations) {
const line = document.createElement('li');
line.className = 'text-muted';
// textContent, never innerHTML: dates come from the server but stay untrusted here.
line.textContent = `${reservation.begin} → ${reservation.end}`;
list.appendChild(line);
}

container.replaceChildren(title, list);
}

#showAvailability(available) {
if (available === null || available === undefined) {
this.#showStatus('', null);
return;
}

this.#showStatus(
available ? __('This slot is available', 'advancedforms') : __('This slot is no longer available', 'advancedforms'),
available ? 'text-success' : 'text-danger',
);
}

/** Renders a single status line under the date pickers (availability, range error or request failure). */
#showStatus(text, css_class) {
const $result = $(this.#root.querySelector('[data-reservation-question-availability]'));
if ($result.length === 0) {
return;
}

$result.text(text).removeClass('text-danger text-success');
if (css_class) {
$result.addClass(css_class);
}
}
}
83 changes: 83 additions & 0 deletions public/js/modules/ReservationRequestTimelineActions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* -------------------------------------------------------------------------
* advancedforms 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 advancedforms plugin team.
* @license MIT https://opensource.org/licenses/mit-license.php
* @link https://github.com/pluginsGLPI/advancedforms
* -------------------------------------------------------------------------
*/

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

/** @param {HTMLElement} root - one timeline card, rendered by templates/timeline/reservation_request.html.twig */
constructor(root) {
if (!root) {
return;
}

this.#root = root;

this.#initButtons();
}

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

$buttons.on('click', (e) => this.#onActionClicked($(e.currentTarget), $buttons));
}

#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() ?? '';

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

$.post(this.#endpoint_url, { id, action, comment })
.done((data) => {
if (data.success) {
window.location.reload();
return;
}

glpi_toast_error(data.message || __('An error occurred', 'advancedforms'));
$buttons.prop('disabled', false);
})
.fail(() => {
glpi_toast_error(__('An error occurred', 'advancedforms'));
$buttons.prop('disabled', false);
});
}
}
Loading