// Configuration let config = { apiBaseUrl: '/api', businessId: parseInt(localStorage.getItem('payfrit_portal_business')) || 0, stationId: null, stationName: null, stationColor: null, refreshInterval: 5000, }; // State let orders = []; let stations = []; let refreshTimer = null; // Status ID mapping const STATUS = { NEW: 1, PREPARING: 2, READY: 3, COMPLETED: 4 }; const STATUS_NAMES = { 1: 'New', 2: 'Preparing', 3: 'Ready', 4: 'Completed' }; // Initialize document.addEventListener('DOMContentLoaded', () => { loadConfig(); checkStationSelection(); updateClock(); setInterval(updateClock, 1000); // Monitor online/offline status window.addEventListener('online', () => { console.log('[KDS] Back online'); updateStatus(true); loadOrders(); // Refresh immediately when back online }); window.addEventListener('offline', () => { console.log('[KDS] Went offline'); updateStatus(false); }); // Initial connection check if (!navigator.onLine) { updateStatus(false); } }); // Update clock display function updateClock() { const now = new Date(); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); document.getElementById('clock').textContent = `${hours}:${minutes}:${seconds}`; } // Load config from localStorage function loadConfig() { // Load KDS-specific settings (station, refresh interval) const saved = localStorage.getItem('kds_config'); if (saved) { try { const parsed = JSON.parse(saved); config.stationId = parsed.stationId !== undefined ? parsed.stationId : null; config.stationName = parsed.stationName || null; config.stationColor = parsed.stationColor || null; config.refreshInterval = (parsed.refreshInterval || 5) * 1000; } catch (e) { console.error('[KDS] Failed to load config:', e); } } console.log('[KDS] Config loaded:', config); } function saveConfigToStorage() { localStorage.setItem('kds_config', JSON.stringify({ stationId: config.stationId, stationName: config.stationName, stationColor: config.stationColor, refreshInterval: config.refreshInterval / 1000 })); } // Check if station selection is needed async function checkStationSelection() { if (!config.businessId) { console.log('[KDS] No businessId - please log in via Portal first'); updateStatus(false, 'No business selected - log in via Portal'); return; } console.log('[KDS] Starting with businessId:', config.businessId, 'stationId:', config.stationId); // Load business name await loadName(); // If station already selected (including 0 for "all"), start KDS if (config.stationId !== null && config.stationId !== undefined) { updateStationBadge(); startAutoRefresh(); return; } // Load stations to see if we need to show picker await loadStations(); if (stations.length > 0) { showStationSelection(); } else { // No stations configured, default to all orders config.stationId = 0; updateStationBadge(); startAutoRefresh(); } } // Load business name from API async function loadName() { if (!config.businessId) return; try { const response = await fetch(`${config.apiBaseUrl}/businesses/get.cfm`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ BusinessID: config.businessId }) }); const data = await response.json(); if (data.OK && data.BUSINESS && data.BUSINESS.Name) { document.getElementById('businessName').textContent = ' - ' + data.BUSINESS.Name; } } catch (e) { console.error('[KDS] Failed to load business name:', e); } } // Load stations from API async function loadStations() { if (!config.businessId) return; try { const response = await fetch(`${config.apiBaseUrl}/stations/list.cfm`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ BusinessID: config.businessId }) }); const data = await response.json(); if (data.OK) { stations = data.STATIONS || []; } } catch (e) { console.error('Failed to load stations:', e); } } // Show station selection overlay async function showStationSelection() { if (stations.length === 0) { await loadStations(); } const overlay = document.getElementById('stationOverlay'); const buttons = document.getElementById('stationButtons'); let html = ` `; stations.forEach(s => { const color = s.Color || '#666'; html += ` `; }); buttons.innerHTML = html; overlay.classList.remove('hidden'); } // Select a station function selectStation(stationId, stationName, stationColor) { config.stationId = stationId; config.stationName = stationName; config.stationColor = stationColor; // Save to localStorage saveConfigToStorage(); // Hide overlay and start document.getElementById('stationOverlay').classList.add('hidden'); updateStationBadge(); startAutoRefresh(); } // Update station badge in header function updateStationBadge() { const badge = document.getElementById('stationBadge'); const name = config.stationId && config.stationName ? config.stationName : 'All'; badge.innerHTML = `/ ${escapeHtml(name)}`; } // Start auto-refresh function startAutoRefresh() { if (!config.businessId) return; loadOrders(); if (refreshTimer) clearInterval(refreshTimer); refreshTimer = setInterval(loadOrders, config.refreshInterval); } // Load orders from API async function loadOrders() { if (!config.businessId) return; // Check if online before attempting fetch if (!navigator.onLine) { updateStatus(false); return; } try { const url = `${config.apiBaseUrl}/orders/listForKDS.cfm`; const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ BusinessID: config.businessId, StationID: config.stationId || 0 }) }); const data = await response.json(); if (data.OK) { orders = data.ORDERS || []; renderOrders(); updateStatus(true, `${orders.length} active orders`); } else { updateStatus(false, `Error: ${data.MESSAGE || data.ERROR}`); } } catch (error) { console.error('Failed to load orders:', error); updateStatus(false, 'Connection error'); } } // Update status indicator function updateStatus(isConnected, message) { const indicator = document.getElementById('statusIndicator'); if (isConnected) { indicator.classList.remove('disconnected'); } else { indicator.classList.add('disconnected'); } } // Render orders to DOM function renderOrders() { const grid = document.getElementById('ordersGrid'); console.log('renderOrders called, orders count:', orders.length); if (orders.length === 0) { grid.innerHTML = `
New orders will appear here automatically