// frontend/src/pages/bellcloud/devices/tabs/OverviewTab.jsx // Overview tab — Hero (photo | hw info | subscription+warranty | uptime+issue), // Row 2 (auth access 30% | issues & notes 70%), Row 3 (live logs) import { useState, useEffect, useRef, useCallback } from 'react' import { useNavigate } from 'react-router-dom' import api from '@/lib/api' import { useToast } from '@/components/ui/Toast' import Button from '@/components/ui/Button' import StatusBadge from '@/components/ui/StatusBadge' import Spinner from '@/components/ui/Spinner' import Icon from '@/components/ui/Icon' import Modal from '@/components/ui/Modal' import { fmtDateMedium, fmtDateTimeMedium, fmtRelative, fmtLogTimestamp } from '@/lib/formatters' import { useMqttWebSocket } from '@/hooks/useMqttWebSocket' import { parseFirestoreDate, addDays, daysUntil, } from './shared' import DeviceNoteModal from '@/modals/bellcloud/devices/DeviceNoteModal' import EntryFormModal from '@/modals/crm/helpdesk/EntryFormModal' import CopyableSerial from '@/components/shared/CopyableSerial' // ─── Glass surface tokens ───────────────────────────────────────────────────── const GLASS = 'rgba(28, 32, 38, 0.30)' const GLASS_INNER = 'rgba(28, 32, 38, 0.40)' const GLASS_HOVER = 'rgba(49, 53, 60, 0.50)' const BLUR = 'blur(12px)' // ─── Helpers ────────────────────────────────────────────────────────────────── function calcPeriodProgress(start, end) { if (!start || !end) return null const total = end.getTime() - start.getTime() if (total <= 0) return null const elapsed = Date.now() - start.getTime() return Math.max(0, Math.min(100, (elapsed / total) * 100)) } function formatUptime(seconds) { if (seconds == null) return null const d = Math.floor(seconds / 86400) const h = Math.floor((seconds % 86400) / 3600) const m = Math.floor((seconds % 3600) / 60) return [d && `${d}d`, h && `${h}h`, m && `${m}m`].filter(Boolean).join(' ') || '< 1m' } function subscrDurationLabel(days) { if (!days) return null if (days % 365 === 0) return `${days / 365} yr` if (days % 30 === 0) return `${days / 30} mo` return `${days}d` } // Latest Device Issue color: severity sets the base hue, age controls intensity. // today = full opacity, fading out toward ~1 week, capped at a dim floor beyond that. const ALERT_SEVERITY_HUE = { CRITICAL: 'var(--color-danger)', FAILED: 'var(--color-danger)', WARNING: 'var(--color-warning)', } function alertEventStyle(occurredAtIso) { const hue = ALERT_SEVERITY_HUE[occurredAtIso.state] || 'var(--color-warning)' const ageMs = Date.now() - new Date(occurredAtIso.occurred_at).getTime() const ageDays = ageMs / 86400000 // 1.0 opacity at "today", fading linearly to a 0.35 floor by 7 days out. const opacity = Math.max(0.35, 1 - (ageDays / 7) * 0.65) return { color: hue, opacity } } // ─── Sub-components ─────────────────────────────────────────────────────────── function GlassCard({ children, style = {}, className = '' }) { return (
{children}
) } function SectionLabel({ children }) { return ( {children} ) } function InfoField({ label, children, mono = false }) { return (
{label} {children || '—'}
) } function ProgressTrack({ value, variant = 'primary' }) { const pct = Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0 const color = variant === 'success' ? 'var(--color-success)' : variant === 'danger' ? 'var(--color-danger)' : variant === 'warning' ? 'var(--color-warning)' : 'var(--color-primary)' return (
) } // Log level colour map const LOG_COLORS = { ERROR: { text: 'var(--color-danger)', bg: 'var(--color-danger-bg)' }, WARN: { text: 'var(--color-warning)', bg: 'var(--color-warning-bg)' }, INFO: { text: 'var(--color-info)', bg: 'var(--color-info-bg)' }, } // Message text colour — INFO stays neutral/white, only WARN/ERROR get coloured // so problem lines are the ones that visually stand out. const MESSAGE_TEXT_COLOR = { ERROR: 'var(--color-danger)', WARN: 'var(--color-warning)', INFO: 'var(--color-text-primary)', } // Level slider steps: 0=All, 1=INFO, 2=WARN, 3=ERROR const LEVEL_STEPS = [ { value: '', label: 'ALL', color: 'var(--color-text-muted)' }, { value: 'INFO', label: 'INFO', color: 'var(--color-info)' }, { value: 'WARN', label: 'WARN', color: 'var(--color-warning)' }, { value: 'ERROR', label: 'ERROR', color: 'var(--color-danger)' }, ] // ─── OverviewTab ────────────────────────────────────────────────────────────── export default function OverviewTab({ device, canEdit, sub, stats, sn, isOnline, mqttStatus, staffNotes, setStaffNotes, deviceUsers, usersLoading, onNavigateToManage, }) { const navigate = useNavigate() const { toast } = useToast() const id = device?.id || device?.device_id // ── Quick note ──────────────────────────────────────────────────────────── const [editingNote, setEditingNote] = useState(false) const [noteText, setNoteText] = useState(staffNotes || '') const [savingNote, setSavingNote] = useState(false) const noteRef = useRef(null) useEffect(() => { setNoteText(staffNotes || '') }, [staffNotes]) const saveNote = async (val) => { setSavingNote(true) try { await api.put(`/devices/${id}`, { staffNotes: val }) setStaffNotes(val) setEditingNote(false) toast.success('Saved', 'Quick note updated.') } catch (err) { toast.danger('Error', err.message || 'Failed to save note.') } finally { setSavingNote(false) } } // ── Hardware image ──────────────────────────────────────────────────────── const [hwImage, setHwImage] = useState('/devices/VesperPlus.png') const [hwVariant, setHwVariant] = useState('VesperPlus') const [hwRevision, setHwRevision] = useState(null) useEffect(() => { if (!sn) return Promise.all([ api.get(`/manufacturing/devices/${sn}`).catch(() => null), api.get('/crm/products').catch(() => null), ]).then(([mfgItem, productsRes]) => { if (mfgItem?.revision) setHwRevision(mfgItem.revision) const hwType = mfgItem?.hw_family || '' if (!hwType) return const products = productsRes?.products || [] const norm = s => (s || '').toLowerCase().replace(/[^a-z0-9]/g, '') const normHw = norm(hwType) const match = products.find( p => norm(p.name) === normHw || norm(p.sku) === normHw || norm(p.name).includes(normHw) || normHw.includes(norm(p.name)) ) if (match) { setHwVariant(match.name) if (match.photo_url) setHwImage(`/api${match.photo_url}`) } }).catch(() => {}) }, [sn]) // ── Issues + Notes ──────────────────────────────────────────────────────── const [notes, setNotes] = useState([]) const [notesLoading, setNotesLoading] = useState(false) const loadNotes = useCallback(async () => { if (!id) return setNotesLoading(true) try { const data = await api.get(`/devices/${id}/notes`) setNotes(data.notes || []) } catch { setNotes([]) } finally { setNotesLoading(false) } }, [id]) useEffect(() => { loadNotes() }, [loadNotes]) const [issues, setIssues] = useState([]) const [issuesLoading, setIssuesLoading] = useState(false) const loadIssues = useCallback(async () => { if (!id) return setIssuesLoading(true) try { const data = await api.get(`/notes/by-entity/device/${id}`) setIssues(Array.isArray(data) ? data : []) } catch { setIssues([]) } finally { setIssuesLoading(false) } }, [id]) useEffect(() => { loadIssues() }, [loadIssues]) const [noteModal, setNoteModal] = useState({ open: false }) const [issueModal, setIssueModal] = useState({ open: false, entry: null }) const [viewNote, setViewNote] = useState(null) // ── Latest device issue detail modal ───────────────────────────────────── const [alertModalOpen, setAlertModalOpen] = useState(false) const [alertLogs, setAlertLogs] = useState([]) const [alertLogsLoading, setAlertLogsLoading] = useState(false) const openAlertModal = useCallback(() => { setAlertModalOpen(true) if (!sn) return setAlertLogsLoading(true) api.get(`/mqtt/logs/${sn}?limit=20&offset=0`) .then(data => { const rows = (data.logs || []).filter(l => l.level === 'ERROR' || l.level === 'WARN') setAlertLogs(rows) }) .catch(() => setAlertLogs([])) .finally(() => setAlertLogsLoading(false)) }, [sn]) const handleNoteSaved = () => { setNoteModal({ open: false }) loadNotes() } const handleIssueSaved = () => { setIssueModal({ open: false, entry: null }) loadIssues() } // ── Live logs ───────────────────────────────────────────────────────────── const [logs, setLogs] = useState([]) const [logsInitialLoading, setLogsInitialLoading] = useState(true) const [levelStep, setLevelStep] = useState(0) // index into LEVEL_STEPS const [searchText, setSearchText] = useState('') const [autoScroll, setAutoScroll] = useState(true) const [autoRefresh, setAutoRefresh] = useState(true) const [liveLogs, setLiveLogs] = useState([]) const logsContainerRef = useRef(null) const logsHasLoadedOnce = useRef(false) const LIMIT = 50 const levelFilter = LEVEL_STEPS[levelStep].value // Stepped severity order: a level also matches everything more severe than it // (ALL < INFO < WARN < ERROR), so picking WARN also shows WARN and ERROR. const LEVEL_RANK = { INFO: 0, WARN: 1, ERROR: 2 } const meetsLevelFloor = lvl => !levelFilter || (LEVEL_RANK[lvl] ?? 0) >= LEVEL_RANK[levelFilter] // `background` fetches (polling / manual refresh) never toggle a loading // flag — only the very first load shows a spinner, so auto-sync and the // REFRESH button stay seamless instead of flickering every few seconds. const fetchLogs = useCallback(async (background = false) => { if (!sn) return if (!background && !logsHasLoadedOnce.current) setLogsInitialLoading(true) try { const params = new URLSearchParams({ limit: LIMIT, offset: 0 }) if (levelFilter) { params.set('level', levelFilter); params.set('min_level', 'true') } if (searchText) params.set('search', searchText) const data = await api.get(`/mqtt/logs/${sn}?${params}`) setLogs(data.logs || []) } catch { // silent } finally { logsHasLoadedOnce.current = true setLogsInitialLoading(false) } }, [sn, levelFilter, searchText]) useEffect(() => { if (sn) fetchLogs(false) }, [sn, fetchLogs]) useEffect(() => { if (!autoRefresh || !sn) return const t = setInterval(() => fetchLogs(true), 5000) return () => clearInterval(t) }, [autoRefresh, sn, fetchLogs]) const handleWsMessage = useCallback((data) => { if (data.type === 'system/logs' && data.device_serial === sn) { const entry = { id: Date.now(), level: data.payload?.level?.includes('EROR') ? 'ERROR' : data.payload?.level?.includes('WARN') ? 'WARN' : 'INFO', message: data.payload?.message || '', received_at: new Date().toISOString(), _live: true, } setLiveLogs(prev => [entry, ...prev].slice(0, 50)) } }, [sn]) useMqttWebSocket({ enabled: true, onMessage: handleWsMessage }) const allLogs = [ ...liveLogs.filter(l => { if (!meetsLevelFloor(l.level)) return false if (searchText && !l.message.toLowerCase().includes(searchText.toLowerCase())) return false return true }), ...logs, ] // Only auto-scroll to top when a genuinely NEW live log arrives — not when // the level filter / search changes the visible set (that should update // the list in place, without yanking the scroll position). const liveLogCount = liveLogs.length const prevLiveLogCount = useRef(liveLogCount) useEffect(() => { if (liveLogCount > prevLiveLogCount.current && autoScroll && logsContainerRef.current) { logsContainerRef.current.scrollTop = 0 } prevLiveLogCount.current = liveLogCount }, [liveLogCount, autoScroll]) // ── Service lifecycle ───────────────────────────────────────────────────── const subscrStart = parseFirestoreDate(sub?.subscrStart) const subscrEnd = subscrStart && sub?.subscrDuration ? addDays(subscrStart, sub.subscrDuration) : null const subscrDaysLeft = subscrEnd ? daysUntil(subscrEnd) : null const subscrProgress = calcPeriodProgress(subscrStart, subscrEnd) const warrantyStart = parseFirestoreDate(stats?.warrantyStart) const warrantyEnd = warrantyStart && stats?.warrantyPeriod ? addDays(warrantyStart, stats.warrantyPeriod) : null const warrantyDaysLeft = warrantyEnd ? daysUntil(warrantyEnd) : null const warrantyProgress = calcPeriodProgress(warrantyStart, warrantyEnd) const warrantyIsVoid = stats?.warrantyActive === false const warrantyOk = warrantyIsVoid ? false : (warrantyDaysLeft === null ? stats?.warrantyActive : warrantyDaysLeft > 0) const warrantyVariant = warrantyIsVoid ? 'warning' : warrantyOk ? 'success' : 'danger' const warrantyLabel = warrantyIsVoid ? 'Void' : warrantyOk ? 'Active' : 'Expired' const subscrVariant = subscrDaysLeft === null ? 'neutral' : subscrDaysLeft > 30 ? 'success' : subscrDaysLeft > 0 ? 'warning' : 'danger' // ── Render ──────────────────────────────────────────────────────────────── return (
{/* ── ROW 1: Hero card ────────────────────────────────────────────── */} {/* ── Online accent line (left edge of entire hero) ── */}
{/* ── Section A: Device photo ── */}
{/* Pulsating glow when online */} {isOnline && ( <>
{/* Expanding ring */}
)}
{hwVariant} { e.target.src = '/devices/VesperPlus.png' }} />
{/* ── Section B+D: Device info grid (Serial/HW/Uptime/Location/Rev/Issue) ── */}
{hwVariant} {mqttStatus?.last_heartbeat?.uptime_ms != null ? {formatUptime(Math.floor(mqttStatus.last_heartbeat.uptime_ms / 1000))} : Unavailable} {mqttStatus?.last_heartbeat?.firmware_version || '—'} {hwRevision || device.device_attributes?.firmwareVersion || '—'}
Latest Device Issue {mqttStatus?.last_alert_event ? (
{ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openAlertModal() } }} style={{ display: 'flex', flexDirection: 'column', gap: 2, cursor: 'pointer', borderRadius: 'var(--radius-sm)', marginInline: -4, paddingInline: 4, transition: 'background 0.15s', }} onMouseEnter={e => e.currentTarget.style.background = GLASS_INNER} onMouseLeave={e => e.currentTarget.style.background = 'transparent'} > {mqttStatus.last_alert_event.state} · {mqttStatus.last_alert_event.subsystem} · {fmtRelative(mqttStatus.last_alert_event.occurred_at)} {mqttStatus.last_alert_event.message || 'No details provided.'}
) : ( No recent issues )}
{/* ── Section C: Subscription + Warranty ── */}
{/* Subscription row */}
Subscription
{sub?.subscrTier ? ( {sub.subscrTier} {sub.subscrDuration ? ` · ${subscrDurationLabel(sub.subscrDuration)}` : ''} ) : ( Not set )}
{subscrStart ? fmtDateMedium(subscrStart) : '—'} 30 ? 'var(--color-success)' : subscrDaysLeft > 0 ? 'var(--color-warning)' : 'var(--color-danger)', }}> {subscrDaysLeft === null ? '—' : subscrDaysLeft > 0 ? `${subscrDaysLeft}d left` : 'Expired'} {subscrEnd ? fmtDateMedium(subscrEnd) : '—'}
{/* Warranty row */}
Warranty {warrantyLabel}
{warrantyStart ? fmtDateMedium(warrantyStart) : '—'} {warrantyDaysLeft === null ? '—' : warrantyDaysLeft > 0 ? `${warrantyDaysLeft}d left` : 'Expired'} {warrantyEnd ? fmtDateMedium(warrantyEnd) : '—'}
{/* ── ROW 1.5: Quick Note (full width, compact) ────────────────────── */}
Quick Note
{editingNote ? (