Files
ppr-ng/web/drone-requests.html
T

691 lines
26 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drone Flight Requests</title>
<link rel="stylesheet" href="admin.css">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<style>
.workspace {
display: grid;
grid-template-columns: minmax(360px, 0.95fr) minmax(520px, 1.35fr);
gap: 1rem;
align-items: start;
}
.toolbar {
display: flex;
gap: 0.75rem;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
margin-bottom: 1rem;
}
.filter-row {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
align-items: center;
}
.request-list {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
overflow: hidden;
}
.request-list-body {
max-height: calc(100vh - 210px);
overflow-y: auto;
}
.request-row {
width: 100%;
display: grid;
grid-template-columns: 1fr auto;
gap: 0.5rem;
text-align: left;
padding: 0.85rem 1rem;
border: 0;
border-bottom: 1px solid #e6e9ec;
background: white;
cursor: pointer;
}
.request-row:hover,
.request-row.active {
background: #eef6fb;
}
.request-ref {
font-weight: 700;
color: #263645;
}
.request-meta,
.detail-meta {
color: #5d6d7e;
font-size: 0.88rem;
line-height: 1.45;
}
.status-pill {
align-self: start;
border-radius: 999px;
color: white;
display: inline-flex;
font-size: 0.75rem;
font-weight: 700;
justify-content: center;
min-width: 86px;
padding: 0.25rem 0.55rem;
}
.status-NEW { background: #3498db; }
.status-APPROVED { background: #27ae60; }
.status-DENIED { background: #c0392b; }
.status-PENDING { background: #f39c12; }
.status-CANCELED { background: #7f8c8d; }
.status-INFLIGHT { background: #8e44ad; }
.status-COMPLETED { background: #2c3e50; }
.detail-shell {
display: grid;
grid-template-rows: auto minmax(360px, 52vh) auto;
gap: 1rem;
}
.detail-panel,
.action-panel {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
overflow: hidden;
}
.detail-body,
.action-body {
padding: 1rem;
}
.detail-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 0.85rem;
}
.field-label {
color: #607080;
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
}
.field-value {
color: #263645;
font-weight: 600;
margin-top: 0.15rem;
overflow-wrap: anywhere;
}
.map-panel {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
overflow: hidden;
min-height: 360px;
}
#request-map {
width: 100%;
height: 100%;
min-height: 360px;
}
.action-row {
display: grid;
grid-template-columns: minmax(160px, 220px) 1fr auto;
gap: 0.75rem;
align-items: start;
}
textarea {
min-height: 86px;
resize: vertical;
}
select,
input,
textarea {
border: 1px solid #d6dce2;
border-radius: 5px;
font: inherit;
padding: 0.58rem 0.65rem;
width: 100%;
}
.journal {
margin-top: 1rem;
border-top: 1px solid #e6e9ec;
padding-top: 0.75rem;
}
.journal-entry {
border-bottom: 1px solid #eef1f4;
padding: 0.55rem 0;
}
.empty-state {
color: #607080;
padding: 2rem;
text-align: center;
}
.notification {
position: fixed;
right: 1rem;
top: 1rem;
transform: translateY(-120%);
transition: transform 0.2s ease;
z-index: 3000;
}
.notification.show {
transform: translateY(0);
}
@media (max-width: 980px) {
.workspace,
.detail-grid,
.action-row {
grid-template-columns: 1fr;
}
.request-list-body {
max-height: 360px;
}
}
</style>
</head>
<body>
<div class="top-bar">
<div class="title">
<h1 id="tower-title">Swansea Tower</h1>
</div>
<div class="menu-buttons">
<button class="btn btn-secondary" onclick="window.location.href = '/admin'">Tower</button>
<button class="btn btn-secondary" onclick="window.location.href = '/journal'">Journal</button>
</div>
<div class="user-info">
Logged in as: <span id="current-user">Loading...</span> |
<a href="#" onclick="logout()" style="color: white;">Logout</a>
</div>
</div>
<div class="container">
<div class="toolbar">
<div>
<h2>Drone Flight Requests</h2>
<div class="detail-meta">Requests from the public drone flight form</div>
</div>
<div class="filter-row">
<select id="status-filter" aria-label="Status filter">
<option value="">All statuses</option>
<option value="NEW">New</option>
<option value="PENDING">Pending</option>
<option value="APPROVED">Approved</option>
<option value="DENIED">Denied</option>
<option value="CANCELED">Canceled</option>
<option value="INFLIGHT">Inflight</option>
<option value="COMPLETED">Completed</option>
</select>
<button class="btn btn-primary" onclick="loadRequests()">Refresh</button>
</div>
</div>
<div class="workspace">
<section class="request-list">
<div class="table-header">Request Queue - <span id="request-count">0</span></div>
<div id="request-list-body" class="request-list-body">
<div class="empty-state">Loading requests...</div>
</div>
</section>
<section class="detail-shell">
<div class="detail-panel">
<div class="table-header">Selected Request</div>
<div id="detail-body" class="detail-body">
<div class="empty-state">Select a request to view its details.</div>
</div>
</div>
<div class="map-panel">
<div id="request-map"></div>
</div>
<div class="action-panel">
<div class="table-header">Lifecycle</div>
<div class="action-body">
<div class="action-row">
<select id="status-select" aria-label="New status">
<option value="NEW">NEW</option>
<option value="PENDING">PENDING</option>
<option value="APPROVED">APPROVED</option>
<option value="DENIED">DENIED</option>
<option value="CANCELED">CANCELED</option>
<option value="INFLIGHT">INFLIGHT</option>
<option value="COMPLETED">COMPLETED</option>
</select>
<textarea id="operator-comment" placeholder="Comment or request for more information"></textarea>
<div style="display: flex; flex-direction: column; gap: 0.5rem;">
<button class="btn btn-success" onclick="saveStatus()">Set Status</button>
<button class="btn btn-info" onclick="sendComment()">Send Comment</button>
</div>
</div>
<div id="journal" class="journal"></div>
</div>
</div>
</section>
</div>
</div>
<div id="notification" class="notification btn"></div>
<div id="loginModal" class="modal" style="display: none;">
<div class="modal-content" style="max-width: 420px;">
<div class="modal-header">
<h2>Login</h2>
</div>
<form id="login-form">
<div class="form-group">
<label for="login-username">Username</label>
<input type="text" id="login-username" required>
</div>
<div class="form-group">
<label for="login-password">Password</label>
<input type="password" id="login-password" required>
</div>
<div id="login-error" class="error-message" style="display: none;"></div>
<div class="form-actions">
<button id="login-btn" class="btn btn-primary" type="submit">Login</button>
</div>
</form>
</div>
</div>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
let accessToken = null;
let currentUser = null;
let selectedRequest = null;
let requests = [];
let map = null;
let mapLayers = [];
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('login-form').addEventListener('submit', handleLogin);
document.getElementById('status-filter').addEventListener('change', loadRequests);
initializeAuth();
initializeMap();
connectWebSocket();
});
function initializeMap() {
map = L.map('request-map').setView([51.6053, -4.0678], 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);
}
function initializeAuth() {
const token = localStorage.getItem('ppr_access_token');
const username = localStorage.getItem('ppr_username');
const expiry = localStorage.getItem('ppr_token_expiry');
if (token && username && expiry && Date.now() < parseInt(expiry)) {
accessToken = token;
currentUser = username;
document.getElementById('current-user').textContent = username;
loadRequests();
return;
}
showLogin();
}
function showLogin() {
document.getElementById('loginModal').style.display = 'block';
document.getElementById('login-username').focus();
}
function hideLogin() {
document.getElementById('loginModal').style.display = 'none';
document.getElementById('login-error').style.display = 'none';
document.getElementById('login-form').reset();
}
async function handleLogin(event) {
event.preventDefault();
const username = document.getElementById('login-username').value;
const password = document.getElementById('login-password').value;
const error = document.getElementById('login-error');
const button = document.getElementById('login-btn');
button.disabled = true;
error.style.display = 'none';
try {
const response = await fetch('/api/v1/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
});
const data = await response.json();
if (!response.ok) throw new Error(data.detail || 'Login failed');
const expiry = Date.now() + ((data.expires_in || 1800) * 1000);
localStorage.setItem('ppr_access_token', data.access_token);
localStorage.setItem('ppr_username', username);
localStorage.setItem('ppr_token_expiry', expiry.toString());
accessToken = data.access_token;
currentUser = username;
document.getElementById('current-user').textContent = username;
hideLogin();
loadRequests();
} catch (err) {
error.textContent = err.message;
error.style.display = 'block';
} finally {
button.disabled = false;
}
}
function logout() {
localStorage.removeItem('ppr_access_token');
localStorage.removeItem('ppr_username');
localStorage.removeItem('ppr_token_expiry');
accessToken = null;
currentUser = null;
selectedRequest = null;
showLogin();
}
async function authenticatedFetch(url, options = {}) {
if (!accessToken) {
showLogin();
throw new Error('No access token');
}
const response = await fetch(url, {
...options,
headers: {
...(options.headers || {}),
'Authorization': `Bearer ${accessToken}`
}
});
if (response.status === 401) {
logout();
throw new Error('Session expired');
}
return response;
}
async function loadRequests() {
if (!accessToken) return;
const status = document.getElementById('status-filter').value;
const url = status ? `/api/v1/drone-requests/?status=${encodeURIComponent(status)}` : '/api/v1/drone-requests/';
const body = document.getElementById('request-list-body');
body.innerHTML = '<div class="empty-state">Loading requests...</div>';
try {
const response = await authenticatedFetch(url);
if (!response.ok) throw new Error('Failed to load drone requests');
requests = await response.json();
renderRequestList();
if (selectedRequest) {
const fresh = requests.find(r => r.id === selectedRequest.id);
if (fresh) selectRequest(fresh.id);
}
} catch (err) {
body.innerHTML = `<div class="empty-state">${escapeHtml(err.message)}</div>`;
}
}
function renderRequestList() {
document.getElementById('request-count').textContent = requests.length;
const body = document.getElementById('request-list-body');
if (!requests.length) {
body.innerHTML = '<div class="empty-state">No requests match the current filter.</div>';
return;
}
body.innerHTML = requests.map(req => `
<button class="request-row ${selectedRequest && selectedRequest.id === req.id ? 'active' : ''}" onclick="selectRequest(${req.id})">
<div>
<div class="request-ref">${escapeHtml(req.reference_number)}</div>
<div class="request-meta">${escapeHtml(req.operator_name)} · ${formatDateTime(req.estimated_takeoff_at)}</div>
<div class="request-meta">${escapeHtml(req.location_description || `${req.location_latitude}, ${req.location_longitude}`)}</div>
</div>
<span class="status-pill status-${req.status}">${req.status}</span>
</button>
`).join('');
}
async function selectRequest(id) {
selectedRequest = requests.find(req => req.id === id);
if (!selectedRequest) return;
renderRequestList();
renderDetails();
renderMap();
await loadJournal();
}
function renderDetails() {
document.getElementById('status-select').value = selectedRequest.status;
document.getElementById('operator-comment').value = selectedRequest.operator_comments || '';
document.getElementById('detail-body').innerHTML = `
<div style="display: flex; justify-content: space-between; gap: 1rem; align-items: start; margin-bottom: 1rem;">
<div>
<h2>${escapeHtml(selectedRequest.reference_number)}</h2>
<div class="detail-meta">${escapeHtml(selectedRequest.operator_name)} · ${escapeHtml(selectedRequest.email)} · ${escapeHtml(selectedRequest.phone || '-')}</div>
</div>
<span class="status-pill status-${selectedRequest.status}">${selectedRequest.status}</span>
</div>
<div class="detail-grid">
${field('Operator ID', selectedRequest.operator_id)}
${field('Flyer', selectedRequest.flyer_name)}
${field('Flyer ID', selectedRequest.flyer_id)}
${field('Takeoff', formatDateTime(selectedRequest.estimated_takeoff_at))}
${field('Completion', formatDateTime(selectedRequest.estimated_completion_at))}
${field('Max Elevation', `${selectedRequest.maximum_elevation_ft_amsl} ft AMSL`)}
${field('Inside FRZ', selectedRequest.location_inside_frz === null ? '-' : (selectedRequest.location_inside_frz ? 'Yes' : 'No'))}
${field('Latitude', selectedRequest.location_latitude)}
${field('Longitude', selectedRequest.location_longitude)}
${field('Location', selectedRequest.location_description || '-')}
${field('Applicant Notes', selectedRequest.notes || '-')}
${field('Operator Comments', selectedRequest.operator_comments || '-')}
</div>
`;
}
function field(label, value) {
return `<div><div class="field-label">${escapeHtml(label)}</div><div class="field-value">${escapeHtml(value == null ? '-' : String(value))}</div></div>`;
}
function renderMap() {
clearMapLayers();
if (!selectedRequest || !map) return;
const point = [selectedRequest.location_latitude, selectedRequest.location_longitude];
const overlay = selectedRequest.prototype_overlay || {};
const arp = overlay.airport_reference_point || { lat: 51.6053, lng: -4.0678 };
const radius = overlay.frz_radius_metres || 3704;
addLayer(L.circle([arp.lat, arp.lng], {
radius,
color: '#2c3e50',
weight: 2,
fillColor: '#3498db',
fillOpacity: 0.08
}).addTo(map));
addRunwayProtectionRectangles(arp);
addLayer(L.marker(point).addTo(map).bindPopup(`
<strong>${escapeHtml(selectedRequest.reference_number)}</strong><br>
${escapeHtml(selectedRequest.operator_name)}<br>
${selectedRequest.maximum_elevation_ft_amsl} ft AMSL
`));
const group = L.featureGroup(mapLayers);
map.fitBounds(group.getBounds().pad(0.18));
setTimeout(() => map.invalidateSize(), 50);
}
function addRunwayProtectionRectangles(arp) {
addLayer(L.polygon(rotatedRectangle(arp.lat, arp.lng, 41, 5000, 1000), {
color: '#e67e22',
weight: 1,
fillOpacity: 0.08
}).addTo(map));
addLayer(L.polygon(rotatedRectangle(arp.lat, arp.lng, 95, 5000, 1000), {
color: '#e67e22',
weight: 1,
fillOpacity: 0.08
}).addTo(map));
}
function rotatedRectangle(lat, lng, bearingDeg, lengthM, widthM) {
const halfL = lengthM / 2;
const halfW = widthM / 2;
return [
offsetPoint(lat, lng, bearingDeg, halfL, halfW),
offsetPoint(lat, lng, bearingDeg, halfL, -halfW),
offsetPoint(lat, lng, bearingDeg, -halfL, -halfW),
offsetPoint(lat, lng, bearingDeg, -halfL, halfW)
];
}
function offsetPoint(lat, lng, bearingDeg, forwardM, rightM) {
const bearing = bearingDeg * Math.PI / 180;
const northM = Math.cos(bearing) * forwardM + Math.cos(bearing + Math.PI / 2) * rightM;
const eastM = Math.sin(bearing) * forwardM + Math.sin(bearing + Math.PI / 2) * rightM;
const latOffset = northM / 111320;
const lngOffset = eastM / (111320 * Math.cos(lat * Math.PI / 180));
return [lat + latOffset, lng + lngOffset];
}
function addLayer(layer) {
mapLayers.push(layer);
}
function clearMapLayers() {
mapLayers.forEach(layer => map.removeLayer(layer));
mapLayers = [];
}
async function saveStatus() {
if (!selectedRequest) return showNotification('Select a request first', true);
const status = document.getElementById('status-select').value;
const comment = document.getElementById('operator-comment').value.trim();
try {
const response = await authenticatedFetch(`/api/v1/drone-requests/${selectedRequest.id}/status`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status, comment: comment || null })
});
if (!response.ok) throw new Error('Failed to update status');
selectedRequest = await response.json();
showNotification('Status updated');
await loadRequests();
renderDetails();
await loadJournal();
} catch (err) {
showNotification(err.message, true);
}
}
async function sendComment() {
if (!selectedRequest) return showNotification('Select a request first', true);
const comment = document.getElementById('operator-comment').value.trim();
if (!comment) return showNotification('Enter a comment first', true);
try {
const response = await authenticatedFetch(`/api/v1/drone-requests/${selectedRequest.id}/comments`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ comment, email_applicant: true })
});
if (!response.ok) throw new Error('Failed to send comment');
selectedRequest = await response.json();
showNotification('Comment sent');
await loadRequests();
renderDetails();
await loadJournal();
} catch (err) {
showNotification(err.message, true);
}
}
async function loadJournal() {
const journal = document.getElementById('journal');
if (!selectedRequest) {
journal.innerHTML = '';
return;
}
try {
const response = await authenticatedFetch(`/api/v1/drone-requests/${selectedRequest.id}/journal`);
if (!response.ok) throw new Error('Failed to load journal');
const entries = await response.json();
journal.innerHTML = entries.length ? entries.map(entry => `
<div class="journal-entry">
<div>${escapeHtml(entry.entry)}</div>
<div class="request-meta">${escapeHtml(entry.user)} · ${formatDateTime(entry.entry_dt)}</div>
</div>
`).join('') : '<div class="request-meta">No journal entries yet.</div>';
} catch (err) {
journal.innerHTML = `<div class="request-meta">${escapeHtml(err.message)}</div>`;
}
}
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const ws = new WebSocket(`${protocol}//${window.location.host}/ws/tower-updates`);
ws.onmessage = event => {
if (event.data.startsWith('Heartbeat:')) return;
try {
const data = JSON.parse(event.data);
if (data.type && data.type.startsWith('drone_request_')) loadRequests();
} catch (err) {
console.warn('WebSocket parse failed', err);
}
};
}
function formatDateTime(value) {
if (!value) return '-';
const normalized = value.includes('T') ? value : value.replace(' ', 'T');
const date = new Date(normalized.endsWith('Z') ? normalized : `${normalized}Z`);
return date.toISOString().slice(0, 16).replace('T', ' ');
}
function escapeHtml(value) {
return String(value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
function showNotification(message, isError = false) {
const notification = document.getElementById('notification');
notification.textContent = message;
notification.className = `notification btn ${isError ? 'btn-danger' : 'btn-success'} show`;
setTimeout(() => notification.classList.remove('show'), 3000);
}
</script>
</body>
</html>