Files
ppr-ng/web/reports.html
2025-12-18 11:53:44 -05:00

1113 lines
42 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PPR Reports - Swansea PPR</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f5f5f5;
color: #333;
}
.top-bar {
background: linear-gradient(135deg, #2c3e50, #3498db);
color: white;
padding: 0.5rem 2rem;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.title h1 {
margin: 0;
font-size: 1.5rem;
}
.menu-buttons {
display: flex;
gap: 1rem;
align-items: center;
}
.top-bar .user-info {
font-size: 0.9rem;
opacity: 0.9;
display: flex;
align-items: center;
gap: 0.3rem;
}
.container {
max-width: 1600px;
margin: 0 auto;
padding: 2rem;
}
.btn {
padding: 0.7rem 1.5rem;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 0.9rem;
font-weight: 500;
transition: all 0.3s ease;
text-decoration: none;
display: inline-block;
}
.btn-primary {
background-color: #3498db;
color: white;
}
.btn-primary:hover {
background-color: #2980b9;
}
.btn-success {
background-color: #27ae60;
color: white;
}
.btn-success:hover {
background-color: #229954;
}
.btn-secondary {
background-color: #95a5a6;
color: white;
}
.btn-secondary:hover {
background-color: #7f8c8d;
}
.btn-danger {
background-color: #e74c3c;
color: white;
}
.btn-danger:hover {
background-color: #c0392b;
}
.filters-section {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
padding: 1.5rem;
margin-bottom: 2rem;
}
.filters-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
align-items: end;
}
.filter-group {
display: flex;
flex-direction: column;
}
.filter-group label {
font-weight: 600;
margin-bottom: 0.5rem;
color: #555;
}
.filter-group input, .filter-group select {
padding: 0.6rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 0.9rem;
}
.filter-actions {
display: flex;
gap: 1rem;
align-items: end;
}
.reports-table {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
overflow: hidden;
}
.table-header {
background: #34495e;
color: white;
padding: 1rem;
font-weight: 500;
display: flex;
justify-content: space-between;
align-items: center;
}
.table-info {
font-size: 0.9rem;
opacity: 0.9;
}
.loading {
text-align: center;
padding: 3rem;
color: #666;
}
.spinner {
border: 3px solid #f3f3f3;
border-top: 3px solid #3498db;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto 1rem;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 0.5rem;
text-align: left;
border-bottom: 1px solid #eee;
font-size: 0.85rem;
}
th {
background-color: #f8f9fa;
font-weight: 600;
color: #495057;
position: sticky;
top: 0;
white-space: nowrap;
}
tbody tr {
transition: background-color 0.2s ease;
}
tbody tr:hover {
background-color: #f8f9fa;
}
.status {
display: inline-block;
padding: 0.2rem 0.5rem;
border-radius: 10px;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
}
.status.new { background: #e3f2fd; color: #1565c0; }
.status.confirmed { background: #e8f5e8; color: #2e7d32; }
.status.landed { background: #fff3e0; color: #ef6c00; }
.status.departed { background: #fce4ec; color: #c2185b; }
.status.canceled { background: #ffebee; color: #d32f2f; }
.status.deleted { background: #f3e5f5; color: #7b1fa2; }
.summary-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 8px;
padding: 2rem;
margin-bottom: 2rem;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.summary-title {
font-size: 1.5rem;
font-weight: 600;
margin-bottom: 1.5rem;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1.5rem;
}
.summary-item {
background: rgba(255,255,255,0.1);
border-radius: 6px;
padding: 1rem;
border-left: 4px solid rgba(255,255,255,0.3);
}
.summary-item-label {
font-size: 0.85rem;
opacity: 0.9;
margin-bottom: 0.5rem;
}
.summary-item-value {
font-size: 2rem;
font-weight: 700;
}
.no-data {
text-align: center;
padding: 3rem;
color: #666;
}
.export-buttons {
display: flex;
gap: 0.5rem;
}
.notification {
position: fixed;
top: 20px;
right: 20px;
background-color: #27ae60;
color: white;
padding: 12px 20px;
border-radius: 5px;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
z-index: 10000;
opacity: 0;
transform: translateY(-20px);
transition: all 0.3s ease;
font-weight: 500;
}
.notification.show {
opacity: 1;
transform: translateY(0);
}
.notification.error {
background-color: #e74c3c;
}
/* Responsive design */
@media (max-width: 768px) {
.container {
padding: 1rem;
}
.filters-grid {
grid-template-columns: 1fr;
}
.filter-actions {
flex-direction: column;
align-items: stretch;
}
.table-header {
flex-direction: column;
gap: 1rem;
align-items: flex-start;
}
.export-buttons {
width: 100%;
justify-content: center;
}
th, td {
padding: 0.3rem;
font-size: 0.75rem;
}
.btn {
padding: 0.5rem 1rem;
font-size: 0.8rem;
}
}
/* Scrollable table for mobile */
.table-container {
overflow-x: auto;
max-width: 100%;
}
.table-container table {
min-width: 1200px;
}
</style>
</head>
<body>
<div class="top-bar">
<div class="title">
<h1>📊 PPR Reports</h1>
</div>
<div class="menu-buttons">
<button class="btn btn-secondary" onclick="window.location.href='admin'">
← Back to Admin
</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">
<!-- Filters Section -->
<div class="filters-section">
<div class="filters-grid">
<div class="filter-group">
<label for="date-from">Date From:</label>
<input type="date" id="date-from">
</div>
<div class="filter-group">
<label for="date-to">Date To:</label>
<input type="date" id="date-to">
</div>
<div class="filter-group">
<label for="status-filter">Status:</label>
<select id="status-filter">
<option value="">All Statuses</option>
<option value="NEW">New</option>
<option value="CONFIRMED">Confirmed</option>
<option value="LANDED">Landed</option>
<option value="DEPARTED">Departed</option>
<option value="CANCELED">Canceled</option>
<option value="DELETED">Deleted</option>
</select>
</div>
<div class="filter-group">
<label for="search-input">Search:</label>
<input type="text" id="search-input" placeholder="Aircraft reg, callsign, captain, or airport...">
</div>
<div class="filter-actions">
<button class="btn btn-primary" onclick="loadReports()">
🔍 Search
</button>
<button class="btn btn-secondary" onclick="clearFilters()">
🗑️ Clear
</button>
</div>
</div>
</div>
<!-- Summary Box -->
<div class="summary-box">
<div class="summary-title">📊 Movements Summary</div>
<div class="summary-grid">
<!-- PPR Section -->
<div style="grid-column: 1/-1; padding-bottom: 1rem; border-bottom: 2px solid rgba(255,255,255,0.3);">
<div style="font-size: 0.95rem; font-weight: 600; margin-bottom: 0.6rem;">PPR Movements</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem;">
<div class="summary-item" style="padding: 0.6rem;">
<div class="summary-item-label" style="font-size: 0.75rem; margin-bottom: 0.2rem;">Arrivals (Landings)</div>
<div class="summary-item-value" style="font-size: 1.3rem;" id="ppr-arrivals">0</div>
</div>
<div class="summary-item" style="padding: 0.6rem;">
<div class="summary-item-label" style="font-size: 0.75rem; margin-bottom: 0.2rem;">Departures (Takeoffs)</div>
<div class="summary-item-value" style="font-size: 1.3rem;" id="ppr-departures">0</div>
</div>
<div class="summary-item" style="border-left-color: #ffd700; background: rgba(255,215,0,0.1); padding: 0.6rem;">
<div class="summary-item-label" style="font-weight: 600; font-size: 0.75rem; margin-bottom: 0.2rem;">PPR Total</div>
<div class="summary-item-value" style="font-size: 1.3rem;" id="ppr-total">0</div>
</div>
</div>
</div>
<!-- Non-PPR Section -->
<div style="grid-column: 1/-1; padding-bottom: 1rem; border-bottom: 2px solid rgba(255,255,255,0.3);">
<div style="font-size: 0.95rem; font-weight: 600; margin-bottom: 0.6rem;">Non-PPR Movements</div>
<div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 1rem;">
<div class="summary-item" style="padding: 0.6rem;">
<div class="summary-item-label" style="font-size: 0.75rem; margin-bottom: 0.2rem;">Local Flights</div>
<div class="summary-item-value" style="font-size: 1.3rem;" id="local-flights-movements">0</div>
</div>
<div class="summary-item" style="padding: 0.6rem;">
<div class="summary-item-label" style="font-size: 0.75rem; margin-bottom: 0.2rem;">Circuits</div>
<div class="summary-item-value" style="font-size: 1.3rem;" id="circuits-movements">0</div>
</div>
<div class="summary-item" style="padding: 0.6rem;">
<div class="summary-item-label" style="font-size: 0.75rem; margin-bottom: 0.2rem;">Arrivals</div>
<div class="summary-item-value" style="font-size: 1.3rem;" id="non-ppr-arrivals">0</div>
</div>
<div class="summary-item" style="padding: 0.6rem;">
<div class="summary-item-label" style="font-size: 0.75rem; margin-bottom: 0.2rem;">Departures</div>
<div class="summary-item-value" style="font-size: 1.3rem;" id="non-ppr-departures">0</div>
</div>
<div class="summary-item" style="border-left-color: #ffd700; background: rgba(255,215,0,0.1); padding: 0.6rem;">
<div class="summary-item-label" style="font-weight: 600; font-size: 0.75rem; margin-bottom: 0.2rem;">Non-PPR Total</div>
<div class="summary-item-value" style="font-size: 1.3rem;" id="non-ppr-total">0</div>
</div>
</div>
</div>
<!-- Grand Total -->
<div style="grid-column: 1/-1; text-align: center;">
<div style="font-size: 0.85rem; opacity: 0.9; margin-bottom: 0.3rem;">Grand Total Movements</div>
<div style="font-size: 2rem; font-weight: 700;" id="grand-total-movements">0</div>
</div>
</div>
</div>
<!-- Reports Table -->
<div class="reports-table">
<div class="table-header">
<div>
<strong>PPR Records</strong>
<div class="table-info" id="table-info">Loading...</div>
</div>
<div class="export-buttons">
<button class="btn btn-success" onclick="exportToCSV()">
📊 Export CSV
</button>
</div>
</div>
<div id="reports-loading" class="loading">
<div class="spinner"></div>
Loading reports...
</div>
<div id="reports-table-content" style="display: none;">
<div class="table-container">
<table>
<thead>
<tr>
<th>Status</th>
<th>Aircraft</th>
<th>Type</th>
<th>Callsign</th>
<th>Captain</th>
<th>From</th>
<th>ETA</th>
<th>POB In</th>
<th>To</th>
<th>ETD</th>
<th>POB Out</th>
<th>Fuel</th>
<th>Landed</th>
<th>Departed</th>
<th>Email</th>
<th>Phone</th>
<th>Notes</th>
<th>Submitted</th>
<th>Created By</th>
</tr>
</thead>
<tbody id="reports-table-body">
</tbody>
</table>
</div>
</div>
<div id="reports-no-data" class="no-data" style="display: none;">
<h3>No PPR records found</h3>
<p>No records match your current filters.</p>
</div>
</div>
<!-- Other Flights Table -->
<div class="reports-table" style="margin-top: 2rem;">
<div class="table-header">
<div>
<strong>Other Flights</strong>
<div class="table-info" id="other-flights-info">Loading...</div>
</div>
<div class="export-buttons">
<button class="btn btn-success" onclick="exportOtherFlightsToCSV()">
📊 Export CSV
</button>
</div>
</div>
<div id="other-flights-loading" class="loading">
<div class="spinner"></div>
Loading flights...
</div>
<div id="other-flights-table-content" style="display: none;">
<div class="table-container">
<table>
<thead>
<tr>
<th>Status</th>
<th>Type</th>
<th>Aircraft</th>
<th>Aircraft Type</th>
<th>Callsign</th>
<th>From</th>
<th>To</th>
<th>ETA / ETD</th>
<th>Landed / Departed</th>
<th>Circuits</th>
</tr>
</thead>
<tbody id="other-flights-table-body">
</tbody>
</table>
</div>
</div>
<div id="other-flights-no-data" class="no-data" style="display: none;">
<h3>No other flights found</h3>
<p>No flights match your current filters.</p>
</div>
</div>
</div>
<!-- Success Notification -->
<div id="notification" class="notification"></div>
<script>
let currentUser = null;
let accessToken = null;
let currentPPRs = []; // Store current results for export
let currentOtherFlights = []; // Store other flights for export
// Initialize the page
async function initializePage() {
await initializeAuth();
setupDefaultDateRange();
await loadReports();
}
// Set default date range to current month
function setupDefaultDateRange() {
const now = new Date();
const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
document.getElementById('date-from').value = firstDay.toISOString().split('T')[0];
document.getElementById('date-to').value = lastDay.toISOString().split('T')[0];
}
// Authentication management
async function initializeAuth() {
const cachedToken = localStorage.getItem('ppr_access_token');
const cachedUser = localStorage.getItem('ppr_username');
const tokenExpiry = localStorage.getItem('ppr_token_expiry');
if (cachedToken && cachedUser && tokenExpiry) {
const now = new Date().getTime();
if (now < parseInt(tokenExpiry)) {
accessToken = cachedToken;
currentUser = cachedUser;
document.getElementById('current-user').textContent = cachedUser;
return;
}
}
// No valid cached token, redirect to admin
window.location.href = 'admin';
}
function logout() {
localStorage.removeItem('ppr_access_token');
localStorage.removeItem('ppr_username');
localStorage.removeItem('ppr_token_expiry');
accessToken = null;
currentUser = null;
window.location.href = 'admin';
}
// Enhanced fetch wrapper with token expiry handling
async function authenticatedFetch(url, options = {}) {
if (!accessToken) {
window.location.href = 'admin';
throw new Error('No access token available');
}
const headers = {
...options.headers,
'Authorization': `Bearer ${accessToken}`
};
const response = await fetch(url, {
...options,
headers
});
if (response.status === 401) {
logout();
throw new Error('Session expired. Please log in again.');
}
return response;
}
// Load reports data
async function loadReports() {
document.getElementById('reports-loading').style.display = 'block';
document.getElementById('reports-table-content').style.display = 'none';
document.getElementById('reports-no-data').style.display = 'none';
document.getElementById('other-flights-loading').style.display = 'block';
document.getElementById('other-flights-table-content').style.display = 'none';
document.getElementById('other-flights-no-data').style.display = 'none';
try {
const dateFrom = document.getElementById('date-from').value;
const dateTo = document.getElementById('date-to').value;
const status = document.getElementById('status-filter').value;
const search = document.getElementById('search-input').value.trim();
let url = `/api/v1/pprs/?limit=10000`; // Large limit for reports
if (dateFrom) url += `&date_from=${dateFrom}`;
if (dateTo) url += `&date_to=${dateTo}`;
if (status) url += `&status=${status}`;
// Fetch all data in parallel
const [pprResponse, arrivalsResponse, departuresResponse, localFlightsResponse] = await Promise.all([
authenticatedFetch(url),
authenticatedFetch(`/api/v1/arrivals/?limit=10000${dateFrom ? `&date_from=${dateFrom}` : ''}${dateTo ? `&date_to=${dateTo}` : ''}`),
authenticatedFetch(`/api/v1/departures/?limit=10000${dateFrom ? `&date_from=${dateFrom}` : ''}${dateTo ? `&date_to=${dateTo}` : ''}`),
authenticatedFetch(`/api/v1/local-flights/?limit=10000${dateFrom ? `&date_from=${dateFrom}` : ''}${dateTo ? `&date_to=${dateTo}` : ''}`)
]);
if (!pprResponse.ok) {
throw new Error('Failed to fetch PPR records');
}
let pprs = await pprResponse.json();
// Apply client-side search filtering
if (search) {
const searchLower = search.toLowerCase();
pprs = pprs.filter(ppr =>
(ppr.ac_reg && ppr.ac_reg.toLowerCase().includes(searchLower)) ||
(ppr.ac_call && ppr.ac_call.toLowerCase().includes(searchLower)) ||
(ppr.captain && ppr.captain.toLowerCase().includes(searchLower)) ||
(ppr.in_from && ppr.in_from.toLowerCase().includes(searchLower)) ||
(ppr.out_to && ppr.out_to.toLowerCase().includes(searchLower))
);
}
currentPPRs = pprs; // Store for export
displayReports(pprs);
// Process other flights
let otherFlights = [];
if (arrivalsResponse.ok) {
const arrivals = await arrivalsResponse.json();
otherFlights.push(...arrivals.map(f => ({
...f,
flightType: 'ARRIVAL',
aircraft_type: f.type,
timeField: f.eta || f.landed_dt,
fromField: f.in_from,
toField: 'EGFH'
})));
}
if (departuresResponse.ok) {
const departures = await departuresResponse.json();
otherFlights.push(...departures.map(f => ({
...f,
flightType: 'DEPARTURE',
aircraft_type: f.type,
timeField: f.etd || f.departed_dt,
fromField: 'EGFH',
toField: f.out_to
})));
}
if (localFlightsResponse.ok) {
const localFlights = await localFlightsResponse.json();
otherFlights.push(...localFlights.map(f => ({
...f,
flightType: f.flight_type === 'CIRCUITS' ? 'CIRCUIT' : f.flight_type,
aircraft_type: f.type,
circuits: f.circuits,
timeField: f.departed_dt,
fromField: 'EGFH',
toField: 'EGFH'
})));
}
// Apply search filtering to other flights
if (search) {
const searchLower = search.toLowerCase();
otherFlights = otherFlights.filter(f =>
(f.registration && f.registration.toLowerCase().includes(searchLower)) ||
(f.callsign && f.callsign.toLowerCase().includes(searchLower)) ||
(f.fromField && f.fromField.toLowerCase().includes(searchLower)) ||
(f.toField && f.toField.toLowerCase().includes(searchLower))
);
}
currentOtherFlights = otherFlights;
displayOtherFlights(otherFlights);
// Calculate and display movements summary
calculateMovementsSummary(pprs, otherFlights, dateFrom, dateTo);
} catch (error) {
console.error('Error loading reports:', error);
if (error.message !== 'Session expired. Please log in again.') {
showNotification('Error loading reports', true);
}
}
document.getElementById('reports-loading').style.display = 'none';
document.getElementById('other-flights-loading').style.display = 'none';
}
// Calculate and display movements summary
function calculateMovementsSummary(pprs, otherFlights, dateFrom, dateTo) {
let pprArrivals = 0; // PPR landings
let pprDepartures = 0; // PPR takeoffs
let localFlightsMovements = 0;
let circuitsMovements = 0;
let nonPprArrivals = 0;
let nonPprDepartures = 0;
// Format date range for display
let dateRangeText = '';
if (dateFrom && dateTo && dateFrom === dateTo) {
// Single day
const date = new Date(dateFrom + 'T00:00:00Z');
dateRangeText = `for ${date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' })}`;
} else if (dateFrom && dateTo) {
// Date range
const fromDate = new Date(dateFrom + 'T00:00:00Z');
const toDate = new Date(dateTo + 'T00:00:00Z');
const fromText = fromDate.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' });
const toText = toDate.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' });
dateRangeText = `for ${fromText} to ${toText}`;
} else if (dateFrom) {
const date = new Date(dateFrom + 'T00:00:00Z');
dateRangeText = `from ${date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' })}`;
} else if (dateTo) {
const date = new Date(dateTo + 'T00:00:00Z');
dateRangeText = `until ${date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' })}`;
}
// Update summary title with date range
const summaryTitle = document.querySelector('.summary-title');
if (summaryTitle) {
summaryTitle.textContent = `📊 Movements Summary ${dateRangeText}`;
}
// PPR movements (excluding CANCELED):
// - LANDED = 1 arrival (landing)
// - DEPARTED = 1 departure + 1 arrival (because departure implies a prior landing)
pprs.filter(ppr => ppr.status !== 'CANCELED').forEach(ppr => {
if (ppr.status === 'LANDED') {
pprArrivals += 1;
} else if (ppr.status === 'DEPARTED') {
pprDepartures += 1;
pprArrivals += 1; // Each departure implies a landing happened
}
});
// Other flights movements (excluding CANCELLED)
otherFlights.filter(flight => flight.status !== 'CANCELLED').forEach(flight => {
if (flight.flightType === 'ARRIVAL') {
nonPprArrivals += 1;
} else if (flight.flightType === 'DEPARTURE') {
nonPprDepartures += 1;
} else if (flight.flightType === 'LOCAL') {
// 2 movements (takeoff + landing) for the flight itself
localFlightsMovements += 2;
} else if (flight.flightType === 'CIRCUIT') {
// 2 movements (takeoff + landing) plus the circuit count
const circuits = flight.circuits || 0;
circuitsMovements += 2 + circuits;
}
});
const pprTotal = pprArrivals + pprDepartures;
const nonPprTotal = localFlightsMovements + circuitsMovements + nonPprArrivals + nonPprDepartures;
const grandTotal = pprTotal + nonPprTotal;
// Update the summary display
document.getElementById('ppr-arrivals').textContent = pprArrivals;
document.getElementById('ppr-departures').textContent = pprDepartures;
document.getElementById('ppr-total').textContent = pprTotal;
document.getElementById('local-flights-movements').textContent = localFlightsMovements;
document.getElementById('circuits-movements').textContent = circuitsMovements;
document.getElementById('non-ppr-arrivals').textContent = nonPprArrivals;
document.getElementById('non-ppr-departures').textContent = nonPprDepartures;
document.getElementById('non-ppr-total').textContent = nonPprTotal;
document.getElementById('grand-total-movements').textContent = grandTotal;
}
// Display reports in table
async function displayReports(pprs) {
const tbody = document.getElementById('reports-table-body');
const tableInfo = document.getElementById('table-info');
tableInfo.textContent = `${pprs.length} records found`;
if (pprs.length === 0) {
document.getElementById('reports-no-data').style.display = 'block';
return;
}
// Sort by ETA (ascending)
pprs.sort((a, b) => {
if (!a.eta) return 1;
if (!b.eta) return -1;
return new Date(a.eta) - new Date(b.eta);
});
tbody.innerHTML = '';
document.getElementById('reports-table-content').style.display = 'block';
for (const ppr of pprs) {
const row = document.createElement('tr');
// Format dates
const eta = ppr.eta ? formatDateTime(ppr.eta) : '-';
const etd = ppr.etd ? formatDateTime(ppr.etd) : '-';
const landed = ppr.landed_dt ? formatDateTime(ppr.landed_dt) : '-';
const departed = ppr.departed_dt ? formatDateTime(ppr.departed_dt) : '-';
const submitted = ppr.submitted_dt ? formatDateTime(ppr.submitted_dt) : '-';
// Status styling
const statusClass = `status ${ppr.status.toLowerCase()}`;
const statusText = ppr.status.charAt(0).toUpperCase() + ppr.status.slice(1).toLowerCase();
row.innerHTML = `
<td><span class="${statusClass}">${statusText}</span></td>
<td>${ppr.ac_reg}</td>
<td>${ppr.ac_type}</td>
<td>${ppr.ac_call || '-'}</td>
<td>${ppr.captain}</td>
<td>${ppr.in_from}</td>
<td>${eta}</td>
<td>${ppr.pob_in}</td>
<td>${ppr.out_to || '-'}</td>
<td>${etd}</td>
<td>${ppr.pob_out || '-'}</td>
<td>${ppr.fuel || '-'}</td>
<td>${landed}</td>
<td>${departed}</td>
<td>${ppr.email || '-'}</td>
<td>${ppr.phone || '-'}</td>
<td>${ppr.notes || '-'}</td>
<td>${submitted}</td>
<td>${ppr.created_by || '-'}</td>
`;
tbody.appendChild(row);
}
}
// Display other flights in table
function displayOtherFlights(flights) {
const tbody = document.getElementById('other-flights-table-body');
const tableInfo = document.getElementById('other-flights-info');
tableInfo.textContent = `${flights.length} flights found`;
if (flights.length === 0) {
document.getElementById('other-flights-no-data').style.display = 'block';
return;
}
// Sort by time field (ascending)
flights.sort((a, b) => {
const aTime = a.timeField;
const bTime = b.timeField;
if (!aTime) return 1;
if (!bTime) return -1;
return new Date(aTime) - new Date(bTime);
});
tbody.innerHTML = '';
document.getElementById('other-flights-table-content').style.display = 'block';
for (const flight of flights) {
const row = document.createElement('tr');
const typeLabel = flight.flightType;
const registration = flight.registration || '-';
const aircraftType = flight.aircraft_type || '-';
const callsign = flight.callsign || '-';
const from = flight.fromField || '-';
const to = flight.toField || '-';
const timeDisplay = flight.timeField ? formatDateTime(flight.timeField) : '-';
const actualDisplay = flight.flightType === 'ARRIVAL'
? (flight.landed_dt ? formatDateTime(flight.landed_dt) : '-')
: (flight.departed_dt ? formatDateTime(flight.departed_dt) : '-');
const status = flight.status || (flight.flightType === 'CIRCUIT' ? 'COMPLETED' : 'PENDING');
const circuits = (flight.flightType === 'CIRCUIT' || flight.flightType === 'LOCAL') ? (flight.circuits > 0 ? flight.circuits : '-') : '-';
row.innerHTML = `
<td><span class="status ${status.toLowerCase()}">${status}</span></td>
<td><strong>${typeLabel}</strong></td>
<td>${registration}</td>
<td>${aircraftType}</td>
<td>${callsign}</td>
<td>${from}</td>
<td>${to}</td>
<td>${timeDisplay}</td>
<td>${actualDisplay}</td>
<td>${circuits}</td>
`;
tbody.appendChild(row);
}
}
function formatDateTime(dateStr) {
if (!dateStr) return '-';
let utcDateStr = dateStr;
if (!utcDateStr.includes('T')) {
utcDateStr = utcDateStr.replace(' ', 'T');
}
if (!utcDateStr.includes('Z')) {
utcDateStr += 'Z';
}
const date = new Date(utcDateStr);
// Format as dd/mm/yy hh:mm
const day = String(date.getDate()).padStart(2, '0');
const month = String(date.getMonth() + 1).padStart(2, '0');
const year = String(date.getFullYear()).slice(-2);
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${day}/${month}/${year} ${hours}:${minutes}`;
}
// Clear filters
function clearFilters() {
document.getElementById('status-filter').value = '';
document.getElementById('search-input').value = '';
setupDefaultDateRange();
loadReports();
}
// Export functions
function exportToCSV() {
if (currentPPRs.length === 0) {
showNotification('No data to export', true);
return;
}
const headers = [
'ID', 'Status', 'Aircraft Reg', 'Aircraft Type', 'Callsign', 'Captain',
'From', 'ETA', 'POB In', 'To', 'ETD', 'POB Out', 'Fuel',
'Landed', 'Departed', 'Email', 'Phone', 'Notes', 'Submitted', 'Created By'
];
const csvData = currentPPRs.map(ppr => [
ppr.id,
ppr.status,
ppr.ac_reg,
ppr.ac_type,
ppr.ac_call || '',
ppr.captain,
ppr.in_from,
ppr.eta ? formatDateTime(ppr.eta) : '',
ppr.pob_in,
ppr.out_to || '',
ppr.etd ? formatDateTime(ppr.etd) : '',
ppr.pob_out || '',
ppr.fuel || '',
ppr.landed_dt ? formatDateTime(ppr.landed_dt) : '',
ppr.departed_dt ? formatDateTime(ppr.departed_dt) : '',
ppr.email || '',
ppr.phone || '',
ppr.notes || '',
ppr.submitted_dt ? formatDateTime(ppr.submitted_dt) : '',
ppr.created_by || ''
]);
downloadCSV(headers, csvData, 'ppr_reports.csv');
}
function exportOtherFlightsToCSV() {
if (currentOtherFlights.length === 0) {
showNotification('No data to export', true);
return;
}
const headers = [
'Flight Type', 'Aircraft Registration', 'Aircraft Type', 'Callsign', 'From', 'To',
'ETA/ETD', 'Landed/Departed', 'Status', 'Circuits'
];
const csvData = currentOtherFlights.map(flight => [
flight.flightType,
flight.registration || '',
flight.aircraft_type || '',
flight.callsign || '',
flight.fromField || '',
flight.toField || '',
flight.timeField ? formatDateTime(flight.timeField) : '',
flight.flightType === 'ARRIVAL'
? (flight.landed_dt ? formatDateTime(flight.landed_dt) : '')
: (flight.departed_dt ? formatDateTime(flight.departed_dt) : ''),
flight.status || (flight.flightType === 'CIRCUIT' ? 'COMPLETED' : 'PENDING'),
(flight.flightType === 'CIRCUIT' || flight.flightType === 'LOCAL') ? (flight.circuits || '') : ''
]);
downloadCSV(headers, csvData, 'other_flights_reports.csv');
}
function downloadCSV(headers, data, filename) {
const csvContent = [
headers.join(','),
...data.map(row => row.map(cell => `"${cell}"`).join(','))
].join('\n');
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
showNotification(`Exported ${data.length} records to ${filename}`);
}
// Notification system
function showNotification(message, isError = false) {
const notification = document.getElementById('notification');
notification.textContent = message;
notification.className = 'notification' + (isError ? ' error' : '');
setTimeout(() => {
notification.classList.add('show');
}, 10);
setTimeout(() => {
notification.classList.remove('show');
}, 3000);
}
// Handle Enter key in search input
document.getElementById('search-input').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
loadReports();
}
});
// Initialize when page loads
document.addEventListener('DOMContentLoaded', initializePage);
</script>
</body>
</html>