fix: swap counts in the station card
parent
3a2cda3263
commit
2ea8e6990c
Binary file not shown.
|
|
@ -5,7 +5,8 @@ import json
|
||||||
import csv
|
import csv
|
||||||
import io
|
import io
|
||||||
import time
|
import time
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta, timezone, time as dt_time
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
from flask import Flask, jsonify, request, Response
|
from flask import Flask, jsonify, request, Response
|
||||||
from flask_socketio import SocketIO, join_room
|
from flask_socketio import SocketIO, join_room
|
||||||
from flask_cors import CORS
|
from flask_cors import CORS
|
||||||
|
|
@ -55,6 +56,8 @@ app.config['SECRET_KEY'] = os.getenv("SECRET_KEY", "a_very_secret_key")
|
||||||
db.init_app(app)
|
db.init_app(app)
|
||||||
socketio = SocketIO(app, cors_allowed_origins="*")
|
socketio = SocketIO(app, cors_allowed_origins="*")
|
||||||
|
|
||||||
|
IST = ZoneInfo("Asia/Kolkata")
|
||||||
|
|
||||||
# --- User Loader for Flask-Login ---
|
# --- User Loader for Flask-Login ---
|
||||||
@login_manager.user_loader
|
@login_manager.user_loader
|
||||||
def load_user(user_id):
|
def load_user(user_id):
|
||||||
|
|
@ -283,25 +286,29 @@ def get_stations():
|
||||||
@app.route('/api/stations/daily-stats', methods=['GET'])
|
@app.route('/api/stations/daily-stats', methods=['GET'])
|
||||||
def get_all_station_stats():
|
def get_all_station_stats():
|
||||||
"""
|
"""
|
||||||
Calculates the swap statistics for today for all stations.
|
Calculates the swap statistics for the current calendar day in the IST timezone.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
# --- CHANGE THESE TWO LINES ---
|
# Get the current time and date in your timezone (IST is defined globally)
|
||||||
today_start = datetime.combine(datetime.utcnow().date(), time.min)
|
now_ist = datetime.now(IST)
|
||||||
today_end = datetime.combine(datetime.utcnow().date(), time.max)
|
today_ist = now_ist.date()
|
||||||
|
|
||||||
# This is an efficient query that groups by station_id and counts events in one go
|
# Calculate the precise start and end of that day
|
||||||
|
start_of_day_ist = datetime.combine(today_ist, dt_time.min, tzinfo=IST)
|
||||||
|
end_of_day_ist = datetime.combine(today_ist, dt_time.max, tzinfo=IST)
|
||||||
|
|
||||||
|
# --- The rest of the query uses this new date range ---
|
||||||
stats = db.session.query(
|
stats = db.session.query(
|
||||||
MqttLog.station_id,
|
MqttLog.station_id,
|
||||||
func.count(case((MqttLog.payload['eventType'] == 'EVENT_SWAP_START', 1))).label('total_starts'),
|
func.count(case((MqttLog.payload['eventType'].astext == 'EVENT_SWAP_START', 1))).label('total_starts'),
|
||||||
func.count(case((MqttLog.payload['eventType'] == 'EVENT_SWAP_ENDED', 1))).label('completed'),
|
func.count(case((MqttLog.payload['eventType'].astext == 'EVENT_SWAP_ENDED', 1))).label('completed'),
|
||||||
func.count(case((MqttLog.payload['eventType'] == 'EVENT_SWAP_ABORTED', 1))).label('aborted')
|
func.count(case((MqttLog.payload['eventType'].astext == 'EVENT_SWAP_ABORTED', 1))).label('aborted')
|
||||||
).filter(
|
).filter(
|
||||||
MqttLog.topic_type == 'EVENTS',
|
MqttLog.topic_type == 'EVENTS',
|
||||||
MqttLog.timestamp.between(today_start, today_end)
|
# Use the new timezone-aware date range
|
||||||
|
MqttLog.timestamp.between(start_of_day_ist, end_of_day_ist)
|
||||||
).group_by(MqttLog.station_id).all()
|
).group_by(MqttLog.station_id).all()
|
||||||
|
|
||||||
# Convert the list of tuples into a dictionary for easy lookup
|
|
||||||
stats_dict = {
|
stats_dict = {
|
||||||
station_id: {
|
station_id: {
|
||||||
"total_starts": total_starts,
|
"total_starts": total_starts,
|
||||||
|
|
|
||||||
|
|
@ -117,7 +117,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
//-- NEW: Fetch and apply daily stats to each card ---
|
//-- NEW: Fetch and apply daily stats to each card ---
|
||||||
const fetchAndApplyStats = async () => {
|
const fetchAndApplyStats = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/stations/daily-stats`);
|
const response = await fetch(`${API_BASE}/stations/daily-stats`, {
|
||||||
|
method: 'GET',
|
||||||
|
credentials: 'include' // <-- ADD THIS LINE
|
||||||
|
});
|
||||||
if (!response.ok) return; // Fail silently if stats aren't available
|
if (!response.ok) return; // Fail silently if stats aren't available
|
||||||
const stats = await response.json();
|
const stats = await response.json();
|
||||||
|
|
||||||
|
|
@ -158,7 +161,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/stations/${stationId}`, { method: 'DELETE' });
|
const response = await fetch(`${API_BASE}/stations/${stationId}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
credentials: 'include' // <-- ADD THIS LINE
|
||||||
|
});
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
alert(`Station "${stationName}" removed successfully.`);
|
alert(`Station "${stationName}" removed successfully.`);
|
||||||
allStations = []; // Force a full refresh on next poll
|
allStations = []; // Force a full refresh on next poll
|
||||||
|
|
@ -175,26 +181,61 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- DATA FETCHING & POLLING ---
|
// --- DATA FETCHING & POLLING ---
|
||||||
|
// const loadAndPollStations = async () => {
|
||||||
|
// try {
|
||||||
|
// const response = await fetch(`${API_BASE}/stations`, {
|
||||||
|
// method: 'GET',
|
||||||
|
// credentials: 'include' // <-- ADD THIS LINE
|
||||||
|
// });
|
||||||
|
// if (!response.ok) throw new Error('Failed to fetch stations');
|
||||||
|
|
||||||
|
// const newStationList = await response.json();
|
||||||
|
|
||||||
|
// // If the number of stations has changed, we must do a full re-render.
|
||||||
|
// if (newStationList.length !== allStations.length) {
|
||||||
|
// allStations = newStationList;
|
||||||
|
// renderStations(allStations);
|
||||||
|
// } else {
|
||||||
|
// // Otherwise, we can do a more efficient status-only update.
|
||||||
|
// allStations = newStationList;
|
||||||
|
// updateStationStatuses(allStations);
|
||||||
|
// fetchAndApplyStats(); // Fetch and update daily stats
|
||||||
|
// }
|
||||||
|
// } catch (error) {
|
||||||
|
// console.error(error);
|
||||||
|
// stationCountEl.textContent = 'Could not load stations. Is the backend running?';
|
||||||
|
// if (pollingInterval) clearInterval(pollingInterval);
|
||||||
|
// }
|
||||||
|
// };
|
||||||
|
|
||||||
const loadAndPollStations = async () => {
|
const loadAndPollStations = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${API_BASE}/stations`);
|
const response = await fetch(`${API_BASE}/stations`, { credentials: 'include' });
|
||||||
|
if (response.status === 401) {
|
||||||
|
localStorage.clear();
|
||||||
|
window.location.href = 'index.html';
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (!response.ok) throw new Error('Failed to fetch stations');
|
if (!response.ok) throw new Error('Failed to fetch stations');
|
||||||
|
|
||||||
const newStationList = await response.json();
|
const newStationList = await response.json();
|
||||||
|
|
||||||
// If the number of stations has changed, we must do a full re-render.
|
|
||||||
if (newStationList.length !== allStations.length) {
|
if (newStationList.length !== allStations.length) {
|
||||||
allStations = newStationList;
|
allStations = newStationList;
|
||||||
renderStations(allStations);
|
renderStations(allStations);
|
||||||
} else {
|
} else {
|
||||||
// Otherwise, we can do a more efficient status-only update.
|
|
||||||
allStations = newStationList;
|
allStations = newStationList;
|
||||||
updateStationStatuses(allStations);
|
// A more efficient status-only update could go here later
|
||||||
fetchAndApplyStats(); // Fetch and update daily stats
|
renderStations(allStations); // Re-render to update statuses
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- THIS IS THE FIX ---
|
||||||
|
// Call this AFTER the if/else, so it always runs on a successful fetch.
|
||||||
|
fetchAndApplyStats();
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
stationCountEl.textContent = 'Could not load stations. Is the backend running?';
|
if (stationCountEl) stationCountEl.textContent = 'Could not load stations. Is the backend running?';
|
||||||
if (pollingInterval) clearInterval(pollingInterval);
|
if (pollingInterval) clearInterval(pollingInterval);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -224,221 +224,204 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const API_BASE = 'http://192.168.1.10:5000/api';
|
const API_BASE = 'http://192.168.1.10:5000/api';
|
||||||
|
|
||||||
|
// --- DOM Elements ---
|
||||||
const grid = document.getElementById('stations-grid');
|
const grid = document.getElementById('stations-grid');
|
||||||
const addStationCardTmpl = document.getElementById('add-station-card-template');
|
const addStationCardTmpl = document.getElementById('add-station-card-template');
|
||||||
const stationCardTmpl = document.getElementById('station-card-template');
|
const stationCardTmpl = document.getElementById('station-card-template');
|
||||||
|
|
||||||
const searchEl = document.getElementById('search');
|
const searchEl = document.getElementById('search');
|
||||||
const emptyState = document.getElementById('empty-state');
|
const emptyState = document.getElementById('empty-state');
|
||||||
const errorState = document.getElementById('error-state');
|
const errorState = document.getElementById('error-state');
|
||||||
|
const statusBtn = document.getElementById('statusBtn');
|
||||||
// THEMED STATUS DROPDOWN LOGIC
|
const statusMenu = document.getElementById('statusMenu');
|
||||||
const statusBtn = document.getElementById('statusBtn');
|
|
||||||
const statusMenu = document.getElementById('statusMenu');
|
|
||||||
const statusLabel = document.getElementById('statusLabel');
|
const statusLabel = document.getElementById('statusLabel');
|
||||||
let statusValue = 'all';
|
|
||||||
|
|
||||||
// Modals
|
|
||||||
const userModal = document.getElementById('userModal');
|
const userModal = document.getElementById('userModal');
|
||||||
const stationModal = document.getElementById('stationModal');
|
const stationModal = document.getElementById('stationModal');
|
||||||
|
|
||||||
|
// --- State Variables ---
|
||||||
|
let allStations = []; // Master list of stations
|
||||||
|
let statusValue = 'all';
|
||||||
|
let pollingInterval = null; // To hold our interval ID
|
||||||
|
|
||||||
|
// --- Modal & Form Logic (No changes needed here) ---
|
||||||
const openModal = (el) => { el.classList.remove('hidden'); el.classList.add('block'); };
|
const openModal = (el) => { el.classList.remove('hidden'); el.classList.add('block'); };
|
||||||
const closeModal = (el) => { el.classList.add('hidden'); el.classList.remove('block'); };
|
const closeModal = (el) => { el.classList.add('hidden'); el.classList.remove('block'); };
|
||||||
|
|
||||||
// Header buttons
|
|
||||||
document.getElementById('addUserBtn').onclick = () => openModal(userModal);
|
document.getElementById('addUserBtn').onclick = () => openModal(userModal);
|
||||||
document.getElementById('cancelUserBtn').onclick = () => closeModal(userModal);
|
document.getElementById('cancelUserBtn').onclick = () => closeModal(userModal);
|
||||||
document.getElementById('logoutBtn').onclick = () => { localStorage.clear(); window.location.href = './index.html'; };
|
document.getElementById('logoutBtn').onclick = () => { localStorage.clear(); window.location.href = './index.html'; };
|
||||||
document.getElementById('cancelStationBtn').onclick = () => closeModal(stationModal);
|
document.getElementById('cancelStationBtn').onclick = () => closeModal(stationModal);
|
||||||
|
// (Your form submission logic for users and stations can remain the same)
|
||||||
|
// ...
|
||||||
|
|
||||||
// Forms
|
function statusStyles(status) {
|
||||||
document.getElementById('userForm').onsubmit = async (e)=>{
|
const online = { dot: 'bg-emerald-400 animate-pulseDot', badge: 'bg-emerald-500/15 text-emerald-300 border border-emerald-400/20', text: 'Online' };
|
||||||
e.preventDefault();
|
const offline = { dot: 'bg-rose-500', badge: 'bg-rose-500/15 text-rose-300 border border-rose-400/20', text: 'Offline' };
|
||||||
const payload = { username: newUsername.value.trim(), password: newPassword.value, is_admin: isAdmin.checked };
|
return String(status).toLowerCase() === 'online' ? online : offline;
|
||||||
try {
|
|
||||||
const res = await fetch(`${API_BASE}/users`, {
|
|
||||||
method:'POST',
|
|
||||||
headers:{'Content-Type':'application/json'},
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
credentials: 'include'
|
|
||||||
});
|
|
||||||
if(!res.ok) throw new Error('Failed to add user');
|
|
||||||
closeModal(userModal); alert('User added');
|
|
||||||
} catch(err){ alert(err.message); }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('stationForm').onsubmit = async (e)=>{
|
// --- Main Rendering Function ---
|
||||||
e.preventDefault();
|
function render(stationsToDisplay) {
|
||||||
const payload = {
|
grid.innerHTML = '';
|
||||||
station_id: stationId.value.trim(),
|
errorState.classList.add('hidden');
|
||||||
product_id: stationProductId.value.trim(),
|
|
||||||
name: stationName.value.trim(),
|
|
||||||
location: stationLocation.value.trim(),
|
|
||||||
mqtt_broker: mqttBroker.value.trim(),
|
|
||||||
mqtt_port: Number(mqttPort.value),
|
|
||||||
mqtt_user: mqttUsername.value || null,
|
|
||||||
mqtt_password: mqttPassword.value || null,
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${API_BASE}/stations`, {
|
|
||||||
method:'POST',
|
|
||||||
headers:{'Content-Type':'application/json'},
|
|
||||||
body: JSON.stringify(payload),
|
|
||||||
credentials: 'include'
|
|
||||||
});
|
|
||||||
if(!res.ok) throw new Error('Failed to add station');
|
|
||||||
closeModal(stationModal); await loadStations();
|
|
||||||
} catch(err){ alert(err.message); }
|
|
||||||
}
|
|
||||||
|
|
||||||
function statusStyles(status){
|
if (!stationsToDisplay || stationsToDisplay.length === 0) {
|
||||||
const online = { dot:'bg-emerald-400 animate-pulseDot', badge:'bg-emerald-500/15 text-emerald-300 border border-emerald-400/20', text:'Online' };
|
emptyState.classList.remove('hidden');
|
||||||
const offline = { dot:'bg-rose-500', badge:'bg-rose-500/15 text-rose-300 border border-rose-400/20', text:'Offline' };
|
} else {
|
||||||
return String(status).toLowerCase()==='online'?online:offline;
|
emptyState.classList.add('hidden');
|
||||||
}
|
stationsToDisplay.forEach(s => {
|
||||||
|
const node = stationCardTmpl.content.cloneNode(true);
|
||||||
|
const card = node.querySelector('div');
|
||||||
|
card.dataset.stationId = s.id || s.station_id; // IMPORTANT for stats update
|
||||||
|
|
||||||
function setStatus(val, label) {
|
// --- Populate Card Details (No changes here) ---
|
||||||
statusValue = val;
|
card.querySelector('.station-name').textContent = s.name ?? `Station ${s.id || s.station_id}`;
|
||||||
statusLabel.textContent = label;
|
card.querySelector('.product-id').textContent = s.product_id || '—';
|
||||||
statusMenu.classList.add('hidden');
|
card.querySelector('.station-location').textContent = s.location ?? '—';
|
||||||
applyFilters(); // reuse your existing function
|
const idVal = s.id || s.station_id || '—';
|
||||||
}
|
const idEl = card.querySelector('.station-id');
|
||||||
|
idEl.textContent = idVal;
|
||||||
|
idEl.setAttribute('title', idVal);
|
||||||
|
|
||||||
let allStations = [];
|
const styles = statusStyles(s.status);
|
||||||
|
const dot = card.querySelector('.status-dot');
|
||||||
|
dot.className = `status-dot h-2.5 w-2.5 rounded-full ${styles.dot}`;
|
||||||
|
const badge = card.querySelector('.status-badge');
|
||||||
|
badge.className = `status-badge rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${styles.badge}`;
|
||||||
|
badge.textContent = styles.text;
|
||||||
|
|
||||||
function render(stations){
|
card.querySelector('.metric-starts').textContent = 0;
|
||||||
grid.innerHTML = '';
|
card.querySelector('.metric-success').textContent = 0;
|
||||||
|
card.querySelector('.metric-aborted').textContent = 0;
|
||||||
|
|
||||||
if(!stations || stations.length===0){
|
// --- FIX: Added the full logic for the Open button ---
|
||||||
emptyState.classList.remove('hidden');
|
card.querySelector('.open-btn').addEventListener('click', () => {
|
||||||
} else {
|
const id = encodeURIComponent(s.id || s.station_id);
|
||||||
emptyState.classList.add('hidden');
|
window.location.href = `./dashboard.html?stationId=${id}`;
|
||||||
for(const s of stations){
|
});
|
||||||
const node = stationCardTmpl.content.cloneNode(true);
|
|
||||||
const card = node.querySelector('div');
|
|
||||||
card.querySelector('.station-name').textContent = s.name ?? `Station ${s.id || s.station_id}`;
|
|
||||||
// const productIdVal = s.product_id || '—';
|
|
||||||
// const productIdEl = card.querySelector('.product-id');
|
|
||||||
// if (productIdEl) {
|
|
||||||
// // Use .innerHTML and add a styled <span> for the title
|
|
||||||
// productIdEl.innerHTML = `<span class="font-semibold text-white-500">Product ID: </span>${productIdVal}`;
|
|
||||||
// }
|
|
||||||
const productIdVal = s.product_id || '—';
|
|
||||||
const productIdEl = card.querySelector('.product-id');
|
|
||||||
if (productIdEl) {
|
|
||||||
productIdEl.textContent = productIdVal;
|
|
||||||
}
|
|
||||||
card.querySelector('.station-location').textContent = s.location ?? '—';
|
|
||||||
const idVal = s.id || s.station_id || '—';
|
|
||||||
const idEl = card.querySelector('.station-id');
|
|
||||||
idEl.textContent = idVal; idEl.setAttribute('title', idVal);
|
|
||||||
|
|
||||||
const styles = statusStyles(s.status);
|
// --- FIX: Added the full logic for the Remove button ---
|
||||||
const dot = card.querySelector('.status-dot');
|
card.querySelector('.remove-btn').addEventListener('click', async () => {
|
||||||
dot.className = `status-dot h-2.5 w-2.5 rounded-full ${styles.dot}`;
|
const stationId = s.id || s.station_id;
|
||||||
const badge = card.querySelector('.status-badge');
|
const stationName = s.name;
|
||||||
badge.className = `status-badge rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${styles.badge}`;
|
|
||||||
badge.textContent = styles.text;
|
|
||||||
|
|
||||||
// Metrics
|
if (!confirm(`Are you sure you want to permanently remove "${stationName}"?`)) {
|
||||||
const starts = s.total_swaps_started ?? s.metrics?.total_starts ?? 0;
|
return;
|
||||||
const success = s.total_swaps_success ?? s.metrics?.total_completed ?? 0;
|
}
|
||||||
const aborted = s.total_swaps_aborted ?? s.metrics?.total_aborted ?? 0;
|
|
||||||
card.querySelector('.metric-starts').textContent = starts;
|
|
||||||
card.querySelector('.metric-success').textContent = success;
|
|
||||||
card.querySelector('.metric-aborted').textContent = aborted;
|
|
||||||
|
|
||||||
// Open
|
try {
|
||||||
card.querySelector('.open-btn').addEventListener('click', () => {
|
const response = await fetch(`${API_BASE}/stations/${stationId}`, {
|
||||||
localStorage.setItem('selected_station', JSON.stringify(s));
|
method: 'DELETE',
|
||||||
const id = encodeURIComponent(s.id || s.station_id);
|
credentials: 'include'
|
||||||
window.location.href = `./dashboard.html?stationId=${id}`;
|
});
|
||||||
});
|
|
||||||
// --- ADD THIS NEW BLOCK FOR THE REMOVE BUTTON ---
|
|
||||||
card.querySelector('.remove-btn').addEventListener('click', async () => {
|
|
||||||
const stationId = s.id || s.station_id;
|
|
||||||
const stationName = s.name;
|
|
||||||
|
|
||||||
// 1. Confirm with the user
|
if (response.ok) {
|
||||||
if (!confirm(`Are you sure you want to permanently remove "${stationName}"?`)) {
|
alert(`Station "${stationName}" removed successfully.`);
|
||||||
return;
|
// Refresh the list immediately
|
||||||
}
|
loadAndPollStations();
|
||||||
|
} else {
|
||||||
|
const error = await response.json();
|
||||||
|
alert(`Failed to remove station: ${error.message}`);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error removing station:', error);
|
||||||
|
alert('An error occurred while trying to remove the station.');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
try {
|
grid.appendChild(node);
|
||||||
// 2. Call the DELETE API endpoint
|
});
|
||||||
const response = await fetch(`${API_BASE}/stations/${stationId}`, {
|
|
||||||
method: 'DELETE',
|
|
||||||
});
|
|
||||||
|
|
||||||
if (response.ok) {
|
|
||||||
alert(`Station "${stationName}" removed successfully.`);
|
|
||||||
// 3. Refresh the entire list from the server
|
|
||||||
loadStations();
|
|
||||||
} else {
|
|
||||||
const error = await response.json();
|
|
||||||
alert(`Failed to remove station: ${error.message}`);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error removing station:', error);
|
|
||||||
alert('An error occurred while trying to remove the station.');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
grid.appendChild(node);
|
|
||||||
}
|
}
|
||||||
}
|
// Append the "Add Station" card
|
||||||
|
const addNode = addStationCardTmpl.content.cloneNode(true);
|
||||||
|
addNode.querySelector('div').addEventListener('click', () => openModal(stationModal));
|
||||||
|
grid.appendChild(addNode);
|
||||||
|
|
||||||
// Finally, append the Add Station card LAST
|
if (window.lucide) {
|
||||||
const addNode = addStationCardTmpl.content.cloneNode(true);
|
lucide.createIcons();
|
||||||
const addCard = addNode.querySelector('div');
|
}
|
||||||
addCard.addEventListener('click', () => openModal(stationModal));
|
|
||||||
grid.appendChild(addNode);
|
|
||||||
|
|
||||||
if (window.lucide) {
|
|
||||||
lucide.createIcons();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
statusBtn.addEventListener('click', () => {
|
function applyFilters() {
|
||||||
statusMenu.classList.toggle('hidden');
|
const q = (searchEl.value || '').trim().toLowerCase();
|
||||||
});
|
const filtered = allStations.filter(s => {
|
||||||
statusMenu.querySelectorAll('button').forEach(b=>{
|
const matchesQ = !q || [s.name, s.id, s.station_id, s.location].filter(Boolean).some(v => String(v).toLowerCase().includes(q));
|
||||||
b.addEventListener('click', () => setStatus(b.dataset.value, b.textContent.trim()));
|
const matchesStatus = statusValue === 'all' || String(s.status).toLowerCase() === statusValue;
|
||||||
});
|
return matchesQ && matchesStatus;
|
||||||
|
});
|
||||||
function applyFilters(){
|
render(filtered);
|
||||||
const q = (searchEl.value||'').trim().toLowerCase();
|
|
||||||
const status = statusValue; // 'all' | 'online' | 'offline'
|
|
||||||
const filtered = allStations.filter(s=>{
|
|
||||||
const matchesQ = !q || [s.name, s.id, s.station_id, s.location].filter(Boolean).some(v=>String(v).toLowerCase().includes(q));
|
|
||||||
const matchesStatus = status==='all' || String(s.status).toLowerCase()===status;
|
|
||||||
return matchesQ && matchesStatus;
|
|
||||||
});
|
|
||||||
render(filtered);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- NEW: Function to Fetch and Apply Daily Stats ---
|
||||||
|
const fetchAndApplyStats = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${API_BASE}/stations/daily-stats`);
|
||||||
|
if (!response.ok) return; // Fail silently if stats aren't available
|
||||||
|
|
||||||
|
const stats = await response.json();
|
||||||
|
|
||||||
searchEl.addEventListener('input', ()=> setTimeout(applyFilters,150));
|
for (const stationId in stats) {
|
||||||
|
const stationCard = grid.querySelector(`[data-station-id="${stationId}"]`);
|
||||||
|
if (stationCard) {
|
||||||
|
const statData = stats[stationId];
|
||||||
|
stationCard.querySelector('.metric-starts').textContent = statData.total_starts;
|
||||||
|
stationCard.querySelector('.metric-success').textContent = statData.completed;
|
||||||
|
stationCard.querySelector('.metric-aborted').textContent = statData.aborted;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Could not fetch daily stats:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
async function loadStations(){
|
// --- MODIFIED: Main Function to Load and Poll for Data ---
|
||||||
try{
|
const loadAndPollStations = async () => {
|
||||||
const res = await fetch(`${API_BASE}/stations`);
|
try {
|
||||||
const data = await res.json();
|
const res = await fetch(`${API_BASE}/stations`);
|
||||||
allStations = Array.isArray(data) ? data : (data.stations||[]);
|
if (!res.ok) throw new Error('Failed to fetch stations');
|
||||||
applyFilters();
|
|
||||||
}catch(err){
|
const data = await res.json();
|
||||||
errorState.textContent = 'Failed to load stations. Ensure API is running.';
|
const newStationList = Array.isArray(data) ? data : (data.stations || []);
|
||||||
errorState.classList.remove('hidden');
|
|
||||||
}
|
// Only re-render the whole grid if the number of stations changes
|
||||||
}
|
if (newStationList.length !== allStations.length) {
|
||||||
document.addEventListener('click', (e)=>{
|
allStations = newStationList;
|
||||||
if (!document.getElementById('statusFilterWrap').contains(e.target)) statusMenu.classList.add('hidden');
|
applyFilters(); // This will call render()
|
||||||
|
} else {
|
||||||
|
// If station count is the same, just update the master list
|
||||||
|
allStations = newStationList;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Always fetch fresh stats after getting the station list
|
||||||
|
await fetchAndApplyStats();
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
errorState.textContent = 'Failed to load stations. Ensure API is running.';
|
||||||
|
errorState.classList.remove('hidden');
|
||||||
|
if (pollingInterval) clearInterval(pollingInterval); // Stop polling on error
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- Event Listeners for Filters ---
|
||||||
|
searchEl.addEventListener('input', () => setTimeout(applyFilters, 150));
|
||||||
|
statusBtn.addEventListener('click', () => statusMenu.classList.toggle('hidden'));
|
||||||
|
statusMenu.querySelectorAll('button').forEach(b => {
|
||||||
|
b.addEventListener('click', () => {
|
||||||
|
statusValue = b.dataset.value;
|
||||||
|
statusLabel.textContent = b.textContent.trim();
|
||||||
|
statusMenu.classList.add('hidden');
|
||||||
|
applyFilters();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', loadStations);
|
// --- MODIFIED: Start Everything on Page Load ---
|
||||||
</script>
|
document.addEventListener('DOMContentLoaded', () => {
|
||||||
|
loadAndPollStations(); // Load once immediately
|
||||||
|
pollingInterval = setInterval(loadAndPollStations, 10000); // Then poll every 10 seconds
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue