Skip to content
This repository was archived by the owner on Jul 7, 2026. It is now read-only.
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
121 changes: 121 additions & 0 deletions api/reservation_statuses.php
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,
]);
124 changes: 124 additions & 0 deletions assets/reservation-statuses.js
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">&nbsp;</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;
});
Comment on lines +45 to +47

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recompute header styling when changing weeks

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/isPast values.

Useful? React with 👍 / 👎.

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);
});
13 changes: 7 additions & 6 deletions reservar/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
<link rel='icon' href='/assets/logo.png'>
<script src="/assets/theme-switcher.js"></script>
<script src="/assets/disable-double-submit.js"></script>
<script src="/assets/reservation-statuses.js"></script>
<style>
@media (max-width: 1366px) {
.table {
Expand Down Expand Up @@ -270,7 +271,7 @@ function handleAvailabilityCellClick(event) {
<button type='button' class='bulk-reservation-toggle-button' id='bulkReservationToggle' onclick='toggleBulkReservation(event)' aria-pressed='false'>Fazer reserva em massa</button>
</div>
<div class='reservation-table-container'>
<table class='table table-bordered' style='table-layout: fixed; width: 100%; max-width: 70%; margin: 0 auto; font-size: 0.85rem;'><thead><tr><th scope='col' style='font-size: 0.75rem;'>Tempos</th>"
<table id='reservationTable' data-sala='" . htmlspecialchars($sala, ENT_QUOTES, 'UTF-8') . "' data-before='" . htmlspecialchars($_GET['before'] ?? '', ENT_QUOTES, 'UTF-8') . "' class='table table-bordered' style='table-layout: fixed; width: 100%; max-width: 70%; margin: 0 auto; font-size: 0.85rem;'><thead><tr><th scope='col' style='font-size: 0.75rem;'>Tempos</th>"
);
$today = date("Y-m-d");
for ($i = 0; $i < 7; $i++) {
Expand All @@ -294,9 +295,9 @@ function handleAvailabilityCellClick(event) {
} elseif ($isHeaderPast) {
$headerStyle .= ' opacity: 0.5;';
}
echo "<th scope='col' style='{$headerStyle}'>{$diaFormatted}</th>";
echo "<th scope='col' class='reservation-day-header' style='{$headerStyle}'>{$diaFormatted}</th>";
};
echo "</tr></thead><tbody>";
echo "</tr></thead><tbody id='reservationTableBody'>";
$tempos = $db->query("SELECT * FROM tempos ORDER BY horashumanos ASC;");
// por cada tempo:
for ($i = 1; $i <= $tempos->num_rows; $i++) {
Expand Down Expand Up @@ -527,9 +528,9 @@ function handleAvailabilityCellClick(event) {
</form>";
$currentSalaId = $_POST['sala'] ?? $_GET['sala'];
echo "<div class='d-flex gap-2 mt-2'>";
echo "<a href='/reservar/?before={$segundadiaantes}&sala={$currentSalaId}' class='btn mb-2 btn-success'>Semana Anterior</a>";
echo "<a href='/reservar/?sala={$currentSalaId}' class='btn mb-2 btn-primary'>Semana Atual</a>";
echo "<a href='/reservar/?before={$segundadiadepois}&sala={$currentSalaId}' class='btn mb-2 btn-success'>Semana Seguinte</a>";
echo "<a id='previousWeekLink' data-week-before='{$segundadiaantes}' href='/reservar/?before={$segundadiaantes}&sala={$currentSalaId}' class='btn mb-2 btn-success'>Semana Anterior</a>";
echo "<a id='currentWeekLink' data-week-before='' href='/reservar/?sala={$currentSalaId}' class='btn mb-2 btn-primary'>Semana Atual</a>";
echo "<a id='nextWeekLink' data-week-before='{$segundadiadepois}' href='/reservar/?before={$segundadiadepois}&sala={$currentSalaId}' class='btn mb-2 btn-success'>Semana Seguinte</a>";
echo "</div></div>";
}
?>
Expand Down
Loading