This repository was archived by the owner on Jul 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
feat(reservar): load weekly statuses asynchronously #191
Merged
marpisco
merged 1 commit into
main
from
codex/add-weekly-reservation-availability-endpoint
Jul 6, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| <?php | ||
| require_once(__DIR__ . '/../src/db.php'); | ||
| if (session_status() === PHP_SESSION_NONE) { session_start(); } | ||
|
|
||
| header('Content-Type: application/json'); | ||
|
|
||
| if (isset($_SESSION['pending_totp_user']) || isset($_SESSION['pending_user_setup'])) { | ||
| http_response_code(403); | ||
| echo json_encode(['error' => 'Autenticação incompleta']); | ||
| exit; | ||
| } | ||
|
|
||
| if (!isset($_SESSION['validity']) || $_SESSION['validity'] < time()) { | ||
| http_response_code(403); | ||
| echo json_encode(['error' => 'Sessão expirada']); | ||
| exit; | ||
| } | ||
|
|
||
| $sala = trim($_GET['sala'] ?? ''); | ||
| $before = trim($_GET['before'] ?? ''); | ||
|
|
||
| if ($sala === '') { | ||
| http_response_code(400); | ||
| echo json_encode(['error' => 'Sala inválida']); | ||
| exit; | ||
| } | ||
|
|
||
| $stmt = $db->prepare('SELECT id, tipo_sala, bloqueado FROM salas WHERE id = ?'); | ||
| $stmt->bind_param('s', $sala); | ||
| $stmt->execute(); | ||
| $salaData = $stmt->get_result()->fetch_assoc(); | ||
| $stmt->close(); | ||
|
|
||
| if (!$salaData) { | ||
| http_response_code(404); | ||
| echo json_encode(['error' => 'Sala não encontrada']); | ||
| exit; | ||
| } | ||
|
|
||
| if ($before !== '') { | ||
| $date = DateTime::createFromFormat('d-m-Y', $before); | ||
| $dateErrors = DateTime::getLastErrors(); | ||
| $hasDateErrors = is_array($dateErrors) && ($dateErrors['warning_count'] > 0 || $dateErrors['error_count'] > 0); | ||
| if (!$date || $hasDateErrors) { | ||
| http_response_code(400); | ||
| echo json_encode(['error' => 'Data inválida']); | ||
| exit; | ||
| } | ||
| $segunda = strtotime($date->format('Y-m-d')); | ||
| } else { | ||
| $segunda = strtotime('monday this week'); | ||
| } | ||
|
|
||
| $today = date('Y-m-d'); | ||
| $canCreateReservation = ($salaData['bloqueado'] != 1 || !empty($_SESSION['admin'])); | ||
| $days = []; | ||
| for ($i = 0; $i < 7; $i++) { | ||
| $dayDate = date('Y-m-d', strtotime("+{$i} day", $segunda)); | ||
| $days[] = [ | ||
| 'date' => $dayDate, | ||
| 'label' => date('d/m', strtotime($dayDate)) . '<br>' . date('Y', strtotime($dayDate)), | ||
| 'isToday' => $dayDate === $today, | ||
| 'isPast' => $dayDate < $today, | ||
| ]; | ||
| } | ||
|
|
||
| $tempos = []; | ||
| $temposResult = $db->query('SELECT id, horashumanos FROM tempos ORDER BY horashumanos ASC'); | ||
| while ($tempo = $temposResult->fetch_assoc()) { | ||
| $tempos[] = $tempo; | ||
| } | ||
|
|
||
| $statusBySlot = []; | ||
| $startDate = $days[0]['date']; | ||
| $endDate = $days[6]['date']; | ||
| $stmt = $db->prepare("SELECT r.tempo, r.data, r.aprovado, c.nome AS requisitor_nome | ||
| FROM reservas r | ||
| LEFT JOIN cache c ON c.id = r.requisitor | ||
| WHERE r.sala = ? AND r.data BETWEEN ? AND ?"); | ||
| $stmt->bind_param('sss', $sala, $startDate, $endDate); | ||
| $stmt->execute(); | ||
| $result = $stmt->get_result(); | ||
| while ($reservation = $result->fetch_assoc()) { | ||
| if ($reservation['aprovado'] == -1) { | ||
| continue; | ||
| } | ||
| $nome = $reservation['requisitor_nome'] ?? ''; | ||
| $nome = preg_replace('/^(\S+).*?(\S+)$/u', '$1 $2', $nome); | ||
| $statusBySlot[$reservation['tempo'] . '|' . $reservation['data']] = [ | ||
| 'status' => $reservation['aprovado'] == 0 ? 'pending' : 'occupied', | ||
| 'label' => $reservation['aprovado'] == 0 ? 'Pendente' : 'Ocupado', | ||
| 'requisitor' => $nome, | ||
| ]; | ||
| } | ||
| $stmt->close(); | ||
|
|
||
| $slots = []; | ||
| foreach ($tempos as $tempo) { | ||
| foreach ($days as $day) { | ||
| $key = $tempo['id'] . '|' . $day['date']; | ||
| $canInteract = (!$day['isPast'] || !empty($_SESSION['admin'])); | ||
| $slots[$tempo['id']][$day['date']] = $statusBySlot[$key] ?? [ | ||
| 'status' => 'free', | ||
| 'label' => 'Livre', | ||
| 'requisitor' => '', | ||
| ]; | ||
| $slots[$tempo['id']][$day['date']]['canInteract'] = $canInteract; | ||
| $slots[$tempo['id']][$day['date']]['canCreateReservation'] = $canCreateReservation; | ||
| } | ||
| } | ||
|
|
||
| echo json_encode([ | ||
| 'sala' => $sala, | ||
| 'before' => $before, | ||
| 'previousWeek' => date('d-m-Y', strtotime('-1 week', $segunda)), | ||
| 'nextWeek' => date('d-m-Y', strtotime('+1 week', $segunda)), | ||
| 'currentWeek' => '', | ||
| 'days' => $days, | ||
| 'tempos' => $tempos, | ||
| 'slots' => $slots, | ||
| ]); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| function reservationEscapeHtml(value) { | ||
| const div = document.createElement('div'); | ||
| div.textContent = value || ''; | ||
| return div.innerHTML; | ||
| } | ||
|
|
||
| function buildReservationSlotCell(slot, tempoId, salaId, date) { | ||
| const cellClass = slot.status === 'free' ? 'bg-success' : (slot.status === 'pending' ? 'bg-warning' : 'bg-danger'); | ||
| const label = reservationEscapeHtml(slot.label); | ||
| const requisitor = slot.requisitor ? '<br>' + reservationEscapeHtml(slot.requisitor) : ''; | ||
| const link = '/reservar/manage.php?tempo=' + encodeURIComponent(tempoId) + '&sala=' + encodeURIComponent(salaId) + '&data=' + encodeURIComponent(date); | ||
| const checkboxValue = encodeURIComponent(tempoId) + '|' + encodeURIComponent(salaId) + '|' + encodeURIComponent(date); | ||
| let content = ''; | ||
|
|
||
| if (slot.status === 'free' && slot.canCreateReservation && slot.canInteract) { | ||
| content = '<input type="checkbox" name="slots[]" value="' + checkboxValue + '" class="bulk-checkbox" style="width: 16px; height: 16px;">' + | ||
| '<a class="reserva" href="' + link + '" style="display: block; font-size: 0.75rem; word-break: break-word;">' + label + '</a>'; | ||
| } else if (slot.canInteract && slot.status !== 'free') { | ||
| content = '<a class="reserva" href="' + link + '" style="font-size: 0.75rem; word-break: break-word;">' + label + requisitor + '</a>'; | ||
| } else { | ||
| content = '<span style="font-size: 0.75rem; word-break: break-word;">' + label + requisitor + '</span>'; | ||
| } | ||
|
|
||
| return '<td class="' + cellClass + ' text-white text-center" style="padding: 4px; overflow: hidden; position: relative;">' + | ||
| '<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; min-height: 50px;' + (!slot.canInteract ? ' opacity: 0.5;' : '') + '">' + content + '</div></td>'; | ||
| } | ||
|
|
||
| function setReservationSkeleton() { | ||
| const tbody = document.getElementById('reservationTableBody'); | ||
| if (!tbody) return; | ||
|
|
||
| tbody.querySelectorAll('td').forEach(cell => { | ||
| cell.className = 'text-center'; | ||
| cell.innerHTML = '<span class="placeholder col-8"> </span>'; | ||
| }); | ||
| if (typeof clearBulkSelection === 'function') clearBulkSelection(); | ||
| } | ||
|
|
||
| function renderReservationStatuses(data) { | ||
| const table = document.getElementById('reservationTable'); | ||
| const tbody = document.getElementById('reservationTableBody'); | ||
| if (!table || !tbody) return; | ||
|
|
||
| table.dataset.before = data.before || ''; | ||
| document.querySelectorAll('.reservation-day-header').forEach((header, index) => { | ||
| if (data.days[index]) header.innerHTML = data.days[index].label; | ||
| }); | ||
| tbody.innerHTML = ''; | ||
| data.tempos.forEach(tempo => { | ||
| let row = '<tr><th scope="row" style="font-size: 0.75rem; padding: 4px;">' + reservationEscapeHtml(tempo.horashumanos) + '</th>'; | ||
| data.days.forEach(day => { | ||
| row += buildReservationSlotCell(data.slots[tempo.id][day.date], tempo.id, data.sala, day.date); | ||
| }); | ||
| row += '</tr>'; | ||
| tbody.insertAdjacentHTML('beforeend', row); | ||
| }); | ||
|
|
||
| document.querySelectorAll('.bulk-checkbox').forEach(checkbox => { | ||
| checkbox.addEventListener('change', updateBulkControls); | ||
| }); | ||
| if (typeof clearBulkSelection === 'function') clearBulkSelection(); | ||
| } | ||
|
|
||
| function updateReservationLinks(data) { | ||
| const salaId = encodeURIComponent(data.sala); | ||
| const links = [ | ||
| ['previousWeekLink', data.previousWeek, '/reservar/?before=' + encodeURIComponent(data.previousWeek) + '&sala=' + salaId], | ||
| ['currentWeekLink', '', '/reservar/?sala=' + salaId], | ||
| ['nextWeekLink', data.nextWeek, '/reservar/?before=' + encodeURIComponent(data.nextWeek) + '&sala=' + salaId] | ||
| ]; | ||
|
|
||
| links.forEach(([id, before, href]) => { | ||
| const link = document.getElementById(id); | ||
| if (link) { | ||
| link.dataset.weekBefore = before; | ||
| link.href = href; | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| function loadReservationStatuses(before, pushState) { | ||
| const table = document.getElementById('reservationTable'); | ||
| if (!table) return; | ||
|
|
||
| const params = new URLSearchParams(); | ||
| params.set('sala', table.dataset.sala); | ||
| if (before) params.set('before', before); | ||
|
|
||
| setReservationSkeleton(); | ||
| fetch('/api/reservation_statuses.php?' + params.toString(), { credentials: 'same-origin' }) | ||
| .then(response => { | ||
| if (!response.ok) throw new Error('Erro'); | ||
| return response.json(); | ||
| }) | ||
| .then(data => { | ||
| renderReservationStatuses(data); | ||
| updateReservationLinks(data); | ||
| if (pushState) { | ||
| const url = new URL(window.location.href); | ||
| url.searchParams.set('sala', data.sala); | ||
| if (data.before) url.searchParams.set('before', data.before); | ||
| else url.searchParams.delete('before'); | ||
| window.history.pushState({ before: data.before || '' }, '', url.toString()); | ||
| } | ||
| }) | ||
| .catch(() => window.location.reload()); | ||
| } | ||
|
|
||
| document.addEventListener('DOMContentLoaded', function() { | ||
| document.querySelectorAll('[data-week-before]').forEach(link => { | ||
| link.addEventListener('click', function(event) { | ||
| event.preventDefault(); | ||
| loadReservationStatuses(this.dataset.weekBefore, true); | ||
| }); | ||
| }); | ||
|
|
||
| window.addEventListener('popstate', function() { | ||
| const params = new URLSearchParams(window.location.search); | ||
| loadReservationStatuses(params.get('before') || '', false); | ||
| }); | ||
|
|
||
| const table = document.getElementById('reservationTable'); | ||
| if (table) loadReservationStatuses(table.dataset.before || '', false); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a user navigates weeks through the new async links, this only replaces each header's label and leaves the inline style that was rendered for the original week. Because the initial PHP markup encodes today/past state in that style, moving to another week keeps the old blue highlight or opacity on the same column, so the UI can mark the wrong date as today or past even though the API returns fresh
isToday/isPastvalues.Useful? React with 👍 / 👎.