fix: swap counts in the station card

main
Kirubakaran 2025-09-29 02:43:00 +05:30
parent 3a2cda3263
commit 2ea8e6990c
4 changed files with 226 additions and 195 deletions

View File

@ -5,7 +5,8 @@ import json
import csv
import io
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_socketio import SocketIO, join_room
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)
socketio = SocketIO(app, cors_allowed_origins="*")
IST = ZoneInfo("Asia/Kolkata")
# --- User Loader for Flask-Login ---
@login_manager.user_loader
def load_user(user_id):
@ -283,25 +286,29 @@ def get_stations():
@app.route('/api/stations/daily-stats', methods=['GET'])
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:
# --- CHANGE THESE TWO LINES ---
today_start = datetime.combine(datetime.utcnow().date(), time.min)
today_end = datetime.combine(datetime.utcnow().date(), time.max)
# Get the current time and date in your timezone (IST is defined globally)
now_ist = datetime.now(IST)
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(
MqttLog.station_id,
func.count(case((MqttLog.payload['eventType'] == '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'] == 'EVENT_SWAP_ABORTED', 1))).label('aborted')
func.count(case((MqttLog.payload['eventType'].astext == 'EVENT_SWAP_START', 1))).label('total_starts'),
func.count(case((MqttLog.payload['eventType'].astext == 'EVENT_SWAP_ENDED', 1))).label('completed'),
func.count(case((MqttLog.payload['eventType'].astext == 'EVENT_SWAP_ABORTED', 1))).label('aborted')
).filter(
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()
# Convert the list of tuples into a dictionary for easy lookup
stats_dict = {
station_id: {
"total_starts": total_starts,

View File

@ -117,7 +117,10 @@ document.addEventListener('DOMContentLoaded', () => {
//-- NEW: Fetch and apply daily stats to each card ---
const fetchAndApplyStats = async () => {
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
const stats = await response.json();
@ -158,7 +161,10 @@ document.addEventListener('DOMContentLoaded', () => {
}
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) {
alert(`Station "${stationName}" removed successfully.`);
allStations = []; // Force a full refresh on next poll
@ -175,26 +181,61 @@ document.addEventListener('DOMContentLoaded', () => {
});
// --- 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 () => {
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');
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
// A more efficient status-only update could go here later
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) {
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);
}
};

View File

@ -224,221 +224,204 @@
</div>
</div>
<script>
<script>
const API_BASE = 'http://192.168.1.10:5000/api';
// --- DOM Elements ---
const grid = document.getElementById('stations-grid');
const addStationCardTmpl = document.getElementById('add-station-card-template');
const stationCardTmpl = document.getElementById('station-card-template');
const searchEl = document.getElementById('search');
const emptyState = document.getElementById('empty-state');
const errorState = document.getElementById('error-state');
// THEMED STATUS DROPDOWN LOGIC
const statusBtn = document.getElementById('statusBtn');
const statusMenu = document.getElementById('statusMenu');
const statusBtn = document.getElementById('statusBtn');
const statusMenu = document.getElementById('statusMenu');
const statusLabel = document.getElementById('statusLabel');
let statusValue = 'all';
// Modals
const userModal = document.getElementById('userModal');
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 closeModal = (el) => { el.classList.add('hidden'); el.classList.remove('block'); };
// Header buttons
document.getElementById('addUserBtn').onclick = () => openModal(userModal);
document.getElementById('cancelUserBtn').onclick = () => closeModal(userModal);
document.getElementById('logoutBtn').onclick = () => { localStorage.clear(); window.location.href = './index.html'; };
document.getElementById('cancelStationBtn').onclick = () => closeModal(stationModal);
// (Your form submission logic for users and stations can remain the same)
// ...
// Forms
document.getElementById('userForm').onsubmit = async (e)=>{
e.preventDefault();
const payload = { username: newUsername.value.trim(), password: newPassword.value, is_admin: isAdmin.checked };
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); }
function statusStyles(status) {
const online = { dot: 'bg-emerald-400 animate-pulseDot', badge: 'bg-emerald-500/15 text-emerald-300 border border-emerald-400/20', text: 'Online' };
const offline = { dot: 'bg-rose-500', badge: 'bg-rose-500/15 text-rose-300 border border-rose-400/20', text: 'Offline' };
return String(status).toLowerCase() === 'online' ? online : offline;
}
document.getElementById('stationForm').onsubmit = async (e)=>{
e.preventDefault();
const payload = {
station_id: stationId.value.trim(),
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); }
}
// --- Main Rendering Function ---
function render(stationsToDisplay) {
grid.innerHTML = '';
errorState.classList.add('hidden');
function statusStyles(status){
const online = { dot:'bg-emerald-400 animate-pulseDot', badge:'bg-emerald-500/15 text-emerald-300 border border-emerald-400/20', text:'Online' };
const offline = { dot:'bg-rose-500', badge:'bg-rose-500/15 text-rose-300 border border-rose-400/20', text:'Offline' };
return String(status).toLowerCase()==='online'?online:offline;
}
if (!stationsToDisplay || stationsToDisplay.length === 0) {
emptyState.classList.remove('hidden');
} else {
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) {
statusValue = val;
statusLabel.textContent = label;
statusMenu.classList.add('hidden');
applyFilters(); // reuse your existing function
}
// --- Populate Card Details (No changes here) ---
card.querySelector('.station-name').textContent = s.name ?? `Station ${s.id || s.station_id}`;
card.querySelector('.product-id').textContent = s.product_id || '—';
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);
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){
grid.innerHTML = '';
card.querySelector('.metric-starts').textContent = 0;
card.querySelector('.metric-success').textContent = 0;
card.querySelector('.metric-aborted').textContent = 0;
if(!stations || stations.length===0){
emptyState.classList.remove('hidden');
} else {
emptyState.classList.add('hidden');
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);
// --- FIX: Added the full logic for the Open button ---
card.querySelector('.open-btn').addEventListener('click', () => {
const id = encodeURIComponent(s.id || s.station_id);
window.location.href = `./dashboard.html?stationId=${id}`;
});
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;
// --- FIX: Added the full logic for the Remove button ---
card.querySelector('.remove-btn').addEventListener('click', async () => {
const stationId = s.id || s.station_id;
const stationName = s.name;
// Metrics
const starts = s.total_swaps_started ?? s.metrics?.total_starts ?? 0;
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;
if (!confirm(`Are you sure you want to permanently remove "${stationName}"?`)) {
return;
}
// Open
card.querySelector('.open-btn').addEventListener('click', () => {
localStorage.setItem('selected_station', JSON.stringify(s));
const id = encodeURIComponent(s.id || s.station_id);
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;
try {
const response = await fetch(`${API_BASE}/stations/${stationId}`, {
method: 'DELETE',
credentials: 'include'
});
// 1. Confirm with the user
if (!confirm(`Are you sure you want to permanently remove "${stationName}"?`)) {
return;
}
if (response.ok) {
alert(`Station "${stationName}" removed successfully.`);
// 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 {
// 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);
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
const addNode = addStationCardTmpl.content.cloneNode(true);
const addCard = addNode.querySelector('div');
addCard.addEventListener('click', () => openModal(stationModal));
grid.appendChild(addNode);
if (window.lucide) {
lucide.createIcons();
}
if (window.lucide) {
lucide.createIcons();
}
}
statusBtn.addEventListener('click', () => {
statusMenu.classList.toggle('hidden');
});
statusMenu.querySelectorAll('button').forEach(b=>{
b.addEventListener('click', () => setStatus(b.dataset.value, b.textContent.trim()));
});
function applyFilters(){
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);
function applyFilters() {
const q = (searchEl.value || '').trim().toLowerCase();
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 = statusValue === 'all' || String(s.status).toLowerCase() === statusValue;
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(){
try{
const res = await fetch(`${API_BASE}/stations`);
const data = await res.json();
allStations = Array.isArray(data) ? data : (data.stations||[]);
applyFilters();
}catch(err){
errorState.textContent = 'Failed to load stations. Ensure API is running.';
errorState.classList.remove('hidden');
}
}
document.addEventListener('click', (e)=>{
if (!document.getElementById('statusFilterWrap').contains(e.target)) statusMenu.classList.add('hidden');
// --- MODIFIED: Main Function to Load and Poll for Data ---
const loadAndPollStations = async () => {
try {
const res = await fetch(`${API_BASE}/stations`);
if (!res.ok) throw new Error('Failed to fetch stations');
const data = await res.json();
const newStationList = Array.isArray(data) ? data : (data.stations || []);
// Only re-render the whole grid if the number of stations changes
if (newStationList.length !== allStations.length) {
allStations = newStationList;
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);
</script>
// --- MODIFIED: Start Everything on Page Load ---
document.addEventListener('DOMContentLoaded', () => {
loadAndPollStations(); // Load once immediately
pollingInterval = setInterval(loadAndPollStations, 10000); // Then poll every 10 seconds
});
</script>
</body>
</html>