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(admin): load pedidos asynchronously #190
Merged
marpisco
merged 4 commits into
main
from
codex/add-asynchronous-loading-for-pedidos-list
Jul 5, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
05a122b
fix(admin): resolve pedidos async review feedback
marpisco c180c0c
fix(admin): preserve pedidos search while reloading
marpisco a6e18b2
fix(admin): keep pedidos controls above empty state
marpisco 10ae7e7
fix(admin): keep pedidos search outside async results
marpisco 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,109 @@ | ||
| <?php | ||
| require_once(__DIR__ . '/../../src/db.php'); | ||
| require_once(__DIR__ . '/../../func/csrf.php'); | ||
| require_once(__DIR__ . '/../../func/email_helper.php'); | ||
| require_once(__DIR__ . '/../../func/logaction.php'); | ||
| if (session_status() === PHP_SESSION_NONE) { session_start(); } | ||
|
|
||
| header('Content-Type: application/json'); | ||
|
|
||
| function fail_json($message, $status = 400) { | ||
| http_response_code($status); | ||
| echo json_encode(['error' => $message]); | ||
| exit; | ||
| } | ||
|
|
||
| if (!isset($_SESSION['admin']) || !$_SESSION['admin']) { fail_json('Acesso negado.', 403); } | ||
| if (!isset($_SESSION['validity']) || $_SESSION['validity'] < time()) { fail_json('Sessão expirada', 403); } | ||
| if (isset($_SESSION['pending_totp_user']) || isset($_SESSION['pending_user_setup'])) { fail_json('Autenticação incompleta', 403); } | ||
| if ($_SERVER['REQUEST_METHOD'] !== 'POST') { fail_json('Método inválido.', 405); } | ||
| if (!verify_csrf_token($_POST['csrf_token'] ?? '')) { fail_json('Pedido inválido.', 403); } | ||
|
|
||
| $action = $_POST['action'] ?? ''; | ||
| $rawReservations = $_POST['reservations'] ?? '[]'; | ||
| $reservations = json_decode($rawReservations, true); | ||
| if (!is_array($reservations)) { fail_json('Dados inválidos.'); } | ||
| if (($action === 'aprovar' || $action === 'rejeitar') && empty($reservations)) { | ||
| $reservations[] = ['sala' => $_POST['sala'] ?? '', 'tempo' => $_POST['tempo'] ?? '', 'data' => $_POST['data'] ?? '']; | ||
| } | ||
| if (!in_array($action, ['aprovar', 'rejeitar'], true)) { fail_json('Ação inválida.'); } | ||
|
|
||
| $processed = 0; | ||
| $failed = 0; | ||
| $emailErrors = []; | ||
| $emailGroups = []; | ||
| $singleAction = count($reservations) === 1; | ||
|
|
||
| foreach ($reservations as $res) { | ||
| if (empty($res['sala']) || empty($res['tempo']) || empty($res['data'])) { | ||
| $failed++; | ||
| continue; | ||
| } | ||
|
|
||
| $stmt = $db->prepare('SELECT r.requisitor, s.nome as sala_nome, t.horashumanos as tempo_nome, c.nome as requisitor_nome FROM reservas r LEFT JOIN salas s ON r.sala = s.id LEFT JOIN tempos t ON r.tempo = t.id LEFT JOIN cache c ON r.requisitor = c.id WHERE r.sala=? AND r.tempo=? AND r.data=? AND r.aprovado=0'); | ||
| $stmt->bind_param('sss', $res['sala'], $res['tempo'], $res['data']); | ||
| $stmt->execute(); | ||
| $details = $stmt->get_result()->fetch_assoc(); | ||
| $stmt->close(); | ||
|
|
||
| if (!$details || empty($details['requisitor'])) { | ||
| $failed++; | ||
| continue; | ||
| } | ||
|
|
||
| if ($action === 'aprovar') { | ||
| $stmt = $db->prepare('UPDATE reservas SET aprovado=1 WHERE sala=? AND tempo=? AND data=? AND aprovado=0'); | ||
| } else { | ||
| $stmt = $db->prepare('DELETE FROM reservas WHERE sala=? AND tempo=? AND data=? AND aprovado=0'); | ||
| } | ||
| $stmt->bind_param('sss', $res['sala'], $res['tempo'], $res['data']); | ||
| $stmt->execute(); | ||
| $ok = $stmt->affected_rows > 0; | ||
| $stmt->close(); | ||
|
|
||
| if (!$ok) { | ||
| $failed++; | ||
| continue; | ||
| } | ||
|
|
||
| $reqId = $details['requisitor']; | ||
| if ($singleAction) { | ||
| $emailResult = $action === 'aprovar' | ||
| ? sendReservationApprovedEmail($db, $reqId, $res['sala'], $res['tempo'], $res['data']) | ||
| : sendReservationRejectedEmail($db, $reqId, $res['sala'], $res['tempo'], $res['data']); | ||
| if (!$emailResult['success'] && $emailResult['error'] !== 'Email not enabled') { | ||
| $emailErrors[] = "Utilizador ID: {$reqId}"; | ||
| } | ||
| } else { | ||
| $emailGroups[$reqId][] = [ | ||
| 'requisitor' => $reqId, | ||
| 'sala_nome' => $details['sala_nome'], | ||
| 'tempo_nome' => $details['tempo_nome'], | ||
| 'data' => $res['data'], | ||
| ]; | ||
| } | ||
|
|
||
| $verb = $action === 'aprovar' ? 'Aprovou' : 'Rejeitou'; | ||
| logaction("{$verb} a reserva do utilizador '{$details['requisitor_nome']}': sala '{$details['sala_nome']}' no dia {$res['data']} às {$details['tempo_nome']}", $_SESSION['id']); | ||
| $processed++; | ||
| } | ||
|
|
||
| foreach ($emailGroups as $reqId => $items) { | ||
| $emailResult = $action === 'aprovar' | ||
| ? sendBulkReservationApprovedEmail($db, $items) | ||
| : sendBulkReservationRejectedEmail($db, $items); | ||
| if (!$emailResult['success'] && $emailResult['error'] !== 'Email not enabled') { | ||
| $emailErrors[] = "Utilizador ID: {$reqId}"; | ||
| } | ||
| } | ||
|
|
||
| echo json_encode([ | ||
| 'success' => true, | ||
| 'processed' => $processed, | ||
| 'failed' => $failed, | ||
| 'emailErrors' => $emailErrors, | ||
| 'message' => $action === 'aprovar' ? 'Reserva(s) aprovada(s).' : 'Reserva(s) rejeitada(s).', | ||
| ]); | ||
|
|
||
| $db->close(); | ||
| ?> | ||
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,134 @@ | ||
| <?php | ||
| require_once(__DIR__ . '/../../src/db.php'); | ||
| if (session_status() === PHP_SESSION_NONE) { session_start(); } | ||
|
|
||
| header('Content-Type: application/json'); | ||
|
|
||
| if (!isset($_SESSION['admin']) || !$_SESSION['admin']) { | ||
| http_response_code(403); | ||
| echo json_encode(['error' => 'Acesso negado.']); | ||
| exit; | ||
| } | ||
| if (!isset($_SESSION['validity']) || $_SESSION['validity'] < time()) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When admins keep this page open and interact only through the new async list/action endpoints, these requests bypass Useful? React with 👍 / 👎. |
||
| http_response_code(403); | ||
| echo json_encode(['error' => 'Sessão expirada']); | ||
| exit; | ||
| } | ||
| if (isset($_SESSION['pending_totp_user']) || isset($_SESSION['pending_user_setup'])) { | ||
| http_response_code(403); | ||
| echo json_encode(['error' => 'Autenticação incompleta']); | ||
| exit; | ||
| } | ||
|
|
||
| $page = max(1, intval($_GET['page'] ?? 1)); | ||
| $limit = 20; | ||
| $offset = ($page - 1) * $limit; | ||
| $sala = $_GET['sala'] ?? '0'; | ||
| $requisitor = trim($_GET['requisitor'] ?? ''); | ||
| $search = trim($_GET['q'] ?? ''); | ||
|
|
||
| $where = ['r.aprovado = 0']; | ||
| $params = []; | ||
| $types = ''; | ||
|
|
||
| if ($requisitor !== '') { | ||
| $where[] = 'r.requisitor = ?'; | ||
| $params[] = $requisitor; | ||
| $types .= 's'; | ||
| } elseif ($sala !== '' && $sala !== '0') { | ||
| $where[] = 'r.sala = ?'; | ||
| $params[] = $sala; | ||
| $types .= 's'; | ||
| } | ||
|
|
||
| if ($search !== '') { | ||
| $where[] = '(s.nome LIKE ? OR c.nome LIKE ? OR r.motivo LIKE ? OR r.data LIKE ? OR t.horashumanos LIKE ?)'; | ||
| $searchParam = '%' . $search . '%'; | ||
| for ($i = 0; $i < 5; $i++) { | ||
| $params[] = $searchParam; | ||
| $types .= 's'; | ||
| } | ||
| } | ||
|
|
||
| $whereSql = implode(' AND ', $where); | ||
|
|
||
| $countStmt = $db->prepare("SELECT COUNT(*) as total | ||
| FROM reservas r | ||
| LEFT JOIN salas s ON r.sala = s.id | ||
| LEFT JOIN cache c ON r.requisitor = c.id | ||
| LEFT JOIN tempos t ON r.tempo = t.id | ||
| WHERE {$whereSql}"); | ||
| if ($types !== '') { | ||
| $countStmt->bind_param($types, ...$params); | ||
| } | ||
| $countStmt->execute(); | ||
| $total = intval($countStmt->get_result()->fetch_assoc()['total'] ?? 0); | ||
| $countStmt->close(); | ||
|
|
||
| $query = "SELECT r.sala, r.tempo, r.data, r.motivo, r.requisitor, s.nome as sala_nome, c.nome as requisitor_nome, t.horashumanos as tempo_nome | ||
| FROM reservas r | ||
| LEFT JOIN salas s ON r.sala = s.id | ||
| LEFT JOIN cache c ON r.requisitor = c.id | ||
| LEFT JOIN tempos t ON r.tempo = t.id | ||
| WHERE {$whereSql} | ||
| ORDER BY r.data ASC, r.tempo ASC, r.sala ASC | ||
| LIMIT ? OFFSET ?"; | ||
| $stmt = $db->prepare($query); | ||
| $listParams = array_merge($params, [$limit, $offset]); | ||
| $listTypes = $types . 'ii'; | ||
| $stmt->bind_param($listTypes, ...$listParams); | ||
| $stmt->execute(); | ||
| $result = $stmt->get_result(); | ||
|
|
||
| $pedidos = []; | ||
| while ($row = $result->fetch_assoc()) { | ||
| $pedidos[] = [ | ||
| 'sala' => $row['sala'], | ||
| 'tempo' => $row['tempo'], | ||
| 'data' => $row['data'], | ||
| 'motivo' => $row['motivo'] ?? '', | ||
| 'sala_nome' => $row['sala_nome'] ?? 'N/A', | ||
| 'requisitor_nome' => $row['requisitor_nome'] ?? 'N/A', | ||
| 'tempo_nome' => $row['tempo_nome'] ?? 'N/A', | ||
| 'data_formatada' => date('d/m/Y', strtotime($row['data'])), | ||
| 'is_today' => $row['data'] === date('Y-m-d'), | ||
| 'is_past' => strtotime($row['data']) < strtotime(date('Y-m-d')), | ||
| ]; | ||
| } | ||
| $stmt->close(); | ||
|
|
||
| $title = 'Todos os Pedidos Pendentes'; | ||
| if ($requisitor !== '') { | ||
| $nameStmt = $db->prepare('SELECT nome FROM cache WHERE id = ?'); | ||
| $nameStmt->bind_param('s', $requisitor); | ||
| $nameStmt->execute(); | ||
| $name = $nameStmt->get_result()->fetch_assoc()['nome'] ?? 'Utilizador'; | ||
| $nameStmt->close(); | ||
| $title = 'Pedidos Pendentes - ' . $name; | ||
| } elseif ($sala !== '' && $sala !== '0') { | ||
| $nameStmt = $db->prepare('SELECT nome FROM salas WHERE id = ?'); | ||
| $nameStmt->bind_param('s', $sala); | ||
| $nameStmt->execute(); | ||
| $name = $nameStmt->get_result()->fetch_assoc()['nome'] ?? 'Sala'; | ||
| $nameStmt->close(); | ||
| $title = 'Pedidos Pendentes - ' . $name; | ||
| } | ||
|
|
||
| $stats = [ | ||
| 'pendentes' => intval($db->query("SELECT COUNT(*) as total FROM reservas WHERE aprovado = 0")->fetch_assoc()['total'] ?? 0), | ||
| 'aprovadas' => intval($db->query("SELECT COUNT(*) as total FROM reservas WHERE aprovado = 1")->fetch_assoc()['total'] ?? 0), | ||
| 'hoje' => intval($db->query("SELECT COUNT(*) as total FROM reservas WHERE aprovado = 0 AND data = CURDATE()")->fetch_assoc()['total'] ?? 0), | ||
| ]; | ||
|
|
||
| echo json_encode([ | ||
| 'pedidos' => $pedidos, | ||
| 'total' => $total, | ||
| 'page' => $page, | ||
| 'limit' => $limit, | ||
| 'hasMore' => ($offset + count($pedidos)) < $total, | ||
| 'title' => $title, | ||
| 'stats' => $stats, | ||
| ]); | ||
|
|
||
| $db->close(); | ||
| ?> | ||
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.