// 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 */}
>
)}

{ 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 ? (
) : (
{ setEditingNote(true); setTimeout(() => noteRef.current?.focus(), 0) } : undefined}
style={{
flex: 1,
fontSize: 'var(--font-size-sm)',
color: noteText ? 'var(--color-text-secondary)' : 'var(--color-text-muted)',
lineHeight: 1.6,
cursor: canEdit ? 'text' : 'default',
fontStyle: noteText ? 'normal' : 'italic',
paddingTop: 2,
}}
>
{noteText || 'No quick note set. Click to add one…'}
)}
{canEdit && !editingNote && (
)}
{/* ── ROW 2: Auth Access (30%) + Issues & Notes (70%) ─────────────── */}
{/* Auth Access */}
Auth Access
{deviceUsers.length > 0 && (
{deviceUsers.length}
)}
{usersLoading ? (
) : deviceUsers.length === 0 ? (
No users assigned to this device.
) : (
deviceUsers.map((user, i) => (
user.user_id && navigate(`/users/${user.user_id}`)}
style={{
display: 'flex',
alignItems: 'center',
gap: 'var(--space-3)',
padding: 'var(--space-2) var(--space-3)',
borderRadius: 'var(--radius-md)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
cursor: user.user_id ? 'pointer' : 'default',
transition: 'background 0.15s',
}}
onMouseEnter={e => e.currentTarget.style.background = GLASS_HOVER}
onMouseLeave={e => e.currentTarget.style.background = GLASS_INNER}
>
{user.photo_url ? (

) : (
(user.display_name || user.email || '?').charAt(0).toUpperCase()
)}
{user.display_name || user.email || 'Unknown User'}
{user.email && user.display_name && (
{user.email}
)}
{user.role &&
{user.role}}
))
)}
{/* Issues & Notes */}
Issues & Notes
{(notes.length + issues.length) > 0 && (
{notes.length + issues.length}
)}
{canEdit && (
<>
} onClick={() => setNoteModal({ open: true })}>
Add Note
} onClick={() => setIssueModal({ open: true, entry: null })}>
Record Issue
>
)}
{/* Notes */}
{notesLoading ? (
) : notes.length === 0 ? (
No notes for this device.
) : (
{notes.map((note, i) => (
setViewNote(note)}
style={{
padding: 'var(--space-3)',
borderRadius: 'var(--radius-md)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
cursor: 'pointer',
transition: 'border-color 0.15s',
}}
onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--color-border-strong)'}
onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--color-border)'}
>
{note.content || note.text || '—'}
{note.created_at && (
{fmtRelative(note.created_at)}
{note.created_by ? ` · ${note.created_by}` : ''}
)}
))}
)}
{/* Issues */}
{(issuesLoading || issues.length > 0) && (
Linked Issues
{issuesLoading ? (
) : (
{issues.map((issue, i) => {
const statusColors = {
open: { color: 'var(--color-danger)', bg: 'var(--color-danger-bg)' },
researching: { color: 'var(--color-warning)', bg: 'var(--color-warning-bg)' },
resolved: { color: 'var(--color-success)', bg: 'var(--color-success-bg)' },
}
const sc = statusColors[issue.status] || statusColors.open
return (
setIssueModal({ open: true, entry: issue })}
style={{
display: 'flex',
alignItems: 'center',
gap: 'var(--space-3)',
padding: 'var(--space-2) var(--space-3)',
borderRadius: 'var(--radius-md)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
cursor: 'pointer',
transition: 'border-color 0.15s',
}}
onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--color-border-strong)'}
onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--color-border)'}
>
{issue.status || 'open'}
{issue.title}
{issue.created_at && (
{fmtRelative(issue.created_at)}
)}
)
})}
)}
)}
{/* ── ROW 3: Live Logs ─────────────────────────────────────────────── */}
{/* Log panel header */}
{/* Terminal traffic-light dots */}
{['var(--color-danger)', 'var(--color-warning)', 'var(--color-success)'].map((c, i) => (
))}
Live Logs
{/* Live pulse indicator */}
{liveLogs.length > 0 && (
LIVE
)}
{/* Level colour slider */}
Level
{LEVEL_STEPS.map((step, idx) => (
))}
{/* Search */}
setSearchText(e.target.value)}
placeholder="Filter messages…"
style={{
height: 28,
padding: '0 var(--space-3)',
borderRadius: 'var(--radius-md)',
border: '1px solid var(--color-border-strong)',
background: GLASS_INNER,
backdropFilter: BLUR,
WebkitBackdropFilter: BLUR,
color: 'var(--color-text-primary)',
fontSize: 'var(--font-size-xs)',
fontFamily: 'var(--font-family-base)',
width: 160,
outline: 'none',
flexShrink: 0,
}}
/>
{/* Toggle: AUTO-SCROLL */}
{/* Toggle: AUTO-SYNC */}
{/* Refresh — same visual style as the toggle buttons. No spinner/dim-out:
a background sync must stay seamless, not flicker every few seconds. */}
{/* Log rows */}
{logsInitialLoading && allLogs.length === 0 ? (
) : allLogs.length === 0 ? (
No logs found.
) : (
{['Time', 'Level', 'Message'].map((h, i) => (
|
{h}
|
))}
{allLogs.map((log, idx) => {
const s = LOG_COLORS[log.level] || LOG_COLORS.INFO
return (
|
{fmtLogTimestamp(log.received_at)}
{log._live && (
LIVE
)}
|
{log.level}
|
{log.message}
|
)
})}
)}
{/* ── Responsive + animation styles ─────────────────────────────── */}
setNoteModal({ open: false })}
onSaved={handleNoteSaved}
/>
setIssueModal({ open: false, entry: null })}
onSaved={handleIssueSaved}
/>
{/* ── Note full-view mini modal ──────────────────────────────────────── */}
{viewNote && (
setViewNote(null)}
style={{
position: 'fixed', inset: 0, zIndex: 9999,
background: 'rgba(0,0,0,0.55)',
backdropFilter: 'blur(4px)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: 'var(--space-6)',
}}
>
e.stopPropagation()}
style={{
background: 'var(--color-bg-card)',
border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-xl)',
boxShadow: 'var(--shadow-xl)',
maxWidth: 560,
width: '100%',
display: 'flex',
flexDirection: 'column',
gap: 0,
overflow: 'hidden',
}}
>
Note
{viewNote.content || viewNote.text || '—'}
{viewNote.created_at && (
{fmtRelative(viewNote.created_at)}
{viewNote.created_by ? ` · ${viewNote.created_by}` : ''}
)}
)}
{/* ── Latest Device Issue detail modal ──────────────────────────────── */}
setAlertModalOpen(false)}
title="Latest Device Issue"
size="md"
>
{mqttStatus?.last_alert_event && (
{mqttStatus.last_alert_event.state} · {mqttStatus.last_alert_event.subsystem}
{fmtDateTimeMedium(mqttStatus.last_alert_event.occurred_at)}
{mqttStatus.last_alert_event.message || 'No details provided.'}
Recent Error & Warning Logs
{alertLogsLoading ? (
) : alertLogs.length === 0 ? (
No recent error or warning logs.
) : (
{alertLogs.map((log, i) => {
const s = LOG_COLORS[log.level] || LOG_COLORS.INFO
return (
{log.level}
{log.message}
{fmtLogTimestamp(log.received_at)}
)
})}
)}
)}
)
}