Initial Switch to V2. Completely Overhauled Backend, Frontend and General Structure.

This commit is contained in:
2026-04-17 14:45:30 +03:00
parent eb773c5531
commit 0a8a42d69b
447 changed files with 70696 additions and 492 deletions
@@ -0,0 +1,433 @@
// frontend/src/pages/bellcloud/devices/DeviceDetail.jsx
// Parent shell — data fetching, tab routing, modals. Tab content lives in tabs/
import { useState, useEffect, useCallback } from 'react'
import { useParams, useNavigate, useSearchParams } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import { useToast } from '@/components/ui/Toast'
import PageHeader from '@/components/ui/PageHeader'
import Button from '@/components/ui/Button'
import Tabs from '@/components/ui/Tabs'
import Spinner from '@/components/ui/Spinner'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import EditLocationModal from '@/modals/bellcloud/devices/EditLocationModal'
import EditAttributesModal from '@/modals/bellcloud/devices/EditAttributesModal'
import EditLoggingModal from '@/modals/bellcloud/devices/EditLoggingModal'
import EditMiscModal from '@/modals/bellcloud/devices/EditMiscModal'
import EditBellOutputsModal from '@/modals/bellcloud/devices/EditBellOutputsModal'
import EditClockSettingsModal from '@/modals/bellcloud/devices/EditClockSettingsModal'
import EditAlertsModal from '@/modals/bellcloud/devices/EditAlertsModal'
import EditBacklightModal from '@/modals/bellcloud/devices/EditBacklightModal'
import EditSubscriptionModal from '@/modals/bellcloud/devices/EditSubscriptionModal'
import EditWarrantyModal from '@/modals/bellcloud/devices/EditWarrantyModal'
import AssignCustomerModal from '@/modals/bellcloud/devices/AssignCustomerModal'
import OverviewTab from '@/pages/bellcloud/devices/tabs/OverviewTab'
import GeneralTab from '@/pages/bellcloud/devices/tabs/GeneralTab'
import BellsTab from '@/pages/bellcloud/devices/tabs/BellsTab'
import ClockTab from '@/pages/bellcloud/devices/tabs/ClockTab'
import WarrantyTab from '@/pages/bellcloud/devices/tabs/WarrantyTab'
import ManageTab from '@/pages/bellcloud/devices/tabs/ManageTab'
import ControlTab from '@/pages/bellcloud/devices/tabs/ControlTab'
// ─── Tab config ───────────────────────────────────────────────────────────────
const TABS = [
{ key: 'overview', label: 'Overview' },
{ key: 'general', label: 'General' },
{ key: 'bells', label: 'Bell Mechanisms' },
{ key: 'clock', label: 'Clock & Alerts' },
{ key: 'warranty', label: 'Warranty & Subscription' },
{ key: 'manage', label: 'Manage' },
{ key: 'control', label: 'Control' },
]
function resolveInitialTab(searchParams) {
const raw = searchParams.get('tab')
if (!raw) return 'overview'
const match = TABS.find(t => t.key === raw.toLowerCase())
return match ? match.key : 'overview'
}
// ─── DeviceDetail ─────────────────────────────────────────────────────────────
export default function DeviceDetail() {
const { id } = useParams()
const navigate = useNavigate()
const [searchParams, setSearchParams] = useSearchParams()
const { hasPermission } = useAuth()
const { toast } = useToast()
const canEdit = hasPermission('devices', 'edit')
// ── State ──────────────────────────────────────────────────────────────────
const [device, setDevice] = useState(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [mqttStatus, setMqttStatus] = useState(null)
const [activeTab, setActiveTab] = useState(() => resolveInitialTab(searchParams))
const [deviceUsers, setDeviceUsers] = useState([])
const [usersLoading, setUsersLoading] = useState(false)
const [ownerCustomer, setOwnerCustomer] = useState(null)
const [assigningCustomer, setAssigningCustomer] = useState(false)
const [tags, setTags] = useState([])
const [staffNotes, setStaffNotes] = useState('')
const [showDelete, setShowDelete] = useState(false)
const [deleting, setDeleting] = useState(false)
const [cmdHistory, setCmdHistory] = useState([])
const [cmdHistoryLoading, setCmdHistoryLoading] = useState(false)
const [sendingCmd, setSendingCmd] = useState('')
// Modal open flags
const [editingLocation, setEditingLocation] = useState(false)
const [editingAttributes, setEditingAttributes] = useState(false)
const [editingLogging, setEditingLogging] = useState(false)
const [editingMisc, setEditingMisc] = useState(false)
const [editingBellOutputs, setEditingBellOutputs] = useState(false)
const [editingClockSettings, setEditingClockSettings] = useState(false)
const [editingAlerts, setEditingAlerts] = useState(false)
const [editingBacklight, setEditingBacklight] = useState(false)
const [editingSubscription, setEditingSubscription] = useState(false)
const [editingWarranty, setEditingWarranty] = useState(false)
const [showAssignCustomer, setShowAssignCustomer] = useState(false)
// ── Data fetching ──────────────────────────────────────────────────────────
const loadDevice = useCallback(async () => {
setLoading(true)
setError('')
try {
const d = await api.get(`/devices/${id}`)
setDevice(d)
if (d.staffNotes) setStaffNotes(d.staffNotes)
if (Array.isArray(d.tags)) setTags(d.tags)
setLoading(false)
const sn = d.serial_number || d.device_id
if (sn) {
api.get('/mqtt/status').then(mqttData => {
if (mqttData?.devices) {
const match = mqttData.devices.find(s => s.device_serial === sn)
setMqttStatus(match || null)
}
}).catch(() => {})
}
if (d.customer_id) {
api.get(`/devices/${id}/customer`).then(res => {
setOwnerCustomer(res.customer || null)
}).catch(() => setOwnerCustomer(null))
} else {
setOwnerCustomer(null)
}
setUsersLoading(true)
api.get(`/devices/${id}/users`).then(data => {
setDeviceUsers(data.users || [])
}).catch(() => setDeviceUsers([])).finally(() => setUsersLoading(false))
} catch (err) {
setError(err.message || 'Failed to load device.')
setLoading(false)
}
}, [id])
useEffect(() => { loadDevice() }, [loadDevice])
const loadCmdHistory = useCallback(async () => {
const sn = device?.serial_number || device?.device_id
if (!sn) return
setCmdHistoryLoading(true)
try {
const data = await api.get(`/mqtt/commands/${sn}?limit=50`)
setCmdHistory(data.commands || [])
} catch {
setCmdHistory([])
} finally {
setCmdHistoryLoading(false)
}
}, [device])
useEffect(() => {
if (activeTab === 'control' && device) loadCmdHistory()
}, [activeTab, device, loadCmdHistory])
// ── Tab sync ───────────────────────────────────────────────────────────────
const handleTabChange = key => {
setActiveTab(key)
setSearchParams(prev => {
const next = new URLSearchParams(prev)
next.set('tab', key)
return next
}, { replace: true })
}
// ── Actions ────────────────────────────────────────────────────────────────
const handleDelete = async () => {
setDeleting(true)
try {
await api.delete(`/devices/${id}`)
toast.success('Deleted', 'Device removed.')
navigate('/devices')
} catch (err) {
toast.danger('Error', err.message || 'Failed to delete device.')
setDeleting(false)
setShowDelete(false)
}
}
const handleAssignCustomer = async customer => {
setAssigningCustomer(true)
try {
await api.post(`/devices/${id}/assign-customer`, { customer_id: customer.id })
setOwnerCustomer(customer)
setDevice(prev => ({ ...prev, customer_id: customer.id }))
setShowAssignCustomer(false)
toast.success('Assigned', `Assigned to ${[customer.name, customer.surname].filter(Boolean).join(' ')}.`)
} catch (err) {
toast.danger('Error', err.message || 'Failed to assign customer.')
} finally {
setAssigningCustomer(false)
}
}
const handleUnassignCustomer = async () => {
setAssigningCustomer(true)
try {
const cid = device?.customer_id
await api.delete(`/devices/${id}/assign-customer${cid ? `?customer_id=${cid}` : ''}`)
setOwnerCustomer(null)
setDevice(prev => ({ ...prev, customer_id: '' }))
toast.success('Removed', 'Customer unassigned.')
} catch (err) {
toast.danger('Error', err.message || 'Failed to unassign.')
} finally {
setAssigningCustomer(false)
}
}
const sendMqttCommand = async (cmd, contents = {}) => {
const deviceId = device?.device_id || device?.serial_number
if (!deviceId) return
setSendingCmd(cmd)
try {
await api.post(`/mqtt/command/${deviceId}`, { cmd, contents })
toast.success('Sent', `Command "${cmd}" sent.`)
loadCmdHistory()
} catch (err) {
toast.danger('Error', err.message || 'Failed to send command.')
} finally {
setSendingCmd('')
}
}
// ── Derived ────────────────────────────────────────────────────────────────
const attr = device?.device_attributes || {}
const clock = attr.clockSettings || {}
const sub = device?.device_subscription || {}
const stats = device?.device_stats || {}
const sn = device?.serial_number || device?.device_id
const isOnline = mqttStatus ? mqttStatus.online : device?.is_Online
// ── Render states ──────────────────────────────────────────────────────────
if (loading) {
return (
<div className="page-wrapper">
<div style={{ display: 'flex', justifyContent: 'center', paddingTop: 'var(--space-16)' }}>
<Spinner size="lg" />
</div>
</div>
)
}
if (error) {
return (
<div className="page-wrapper">
<div role="alert" style={{ backgroundColor: 'var(--color-danger-bg)', border: '1px solid var(--color-danger)', borderRadius: 'var(--radius-md)', padding: 'var(--space-4)', color: 'var(--color-danger)' }}>
{error}
</div>
</div>
)
}
if (!device) return null
// Props bundle passed to every tab
const tabProps = {
device,
canEdit,
onDeviceUpdated: setDevice,
attr,
clock,
sub,
stats,
sn,
isOnline,
tags,
setTags,
staffNotes,
setStaffNotes,
deviceUsers,
usersLoading,
ownerCustomer,
assigningCustomer,
cmdHistory,
cmdHistoryLoading,
sendingCmd,
loadDevice,
loadCmdHistory,
sendMqttCommand,
onShowDelete: () => setShowDelete(true),
onAssignCustomer: () => setShowAssignCustomer(true),
onUnassignCustomer: handleUnassignCustomer,
onEditLocation: () => setEditingLocation(true),
onEditAttributes: () => setEditingAttributes(true),
onEditLogging: () => setEditingLogging(true),
onEditMisc: () => setEditingMisc(true),
onEditBellOutputs: () => setEditingBellOutputs(true),
onEditClockSettings: () => setEditingClockSettings(true),
onEditAlerts: () => setEditingAlerts(true),
onEditBacklight: () => setEditingBacklight(true),
onEditSubscription: () => setEditingSubscription(true),
onEditWarranty: () => setEditingWarranty(true),
}
// ── Render ─────────────────────────────────────────────────────────────────
return (
<div className="page-wrapper">
<PageHeader
title={device.device_name || 'Unnamed Device'}
subtitle={sn}
>
{canEdit && (
<Button variant="secondary" onClick={() => navigate(`/devices/${id}/edit`)}>
Edit Device
</Button>
)}
</PageHeader>
<Tabs
tabs={TABS}
active={activeTab}
onChange={handleTabChange}
/>
<div style={{ flex: 1, minWidth: 0 }}>
{activeTab === 'overview' && <OverviewTab {...tabProps} />}
{activeTab === 'general' && <GeneralTab {...tabProps} />}
{activeTab === 'bells' && <BellsTab {...tabProps} />}
{activeTab === 'clock' && <ClockTab {...tabProps} />}
{activeTab === 'warranty' && <WarrantyTab {...tabProps} />}
{activeTab === 'manage' && <ManageTab {...tabProps} />}
{activeTab === 'control' && <ControlTab {...tabProps} />}
</div>
{/* ── Modals ────────────────────────────────────────────────────────── */}
<EditLocationModal
open={editingLocation}
onClose={() => setEditingLocation(false)}
onSaved={loadDevice}
device={device}
id={id}
/>
<EditAttributesModal
open={editingAttributes}
onClose={() => setEditingAttributes(false)}
onSaved={loadDevice}
attr={attr}
id={id}
/>
<EditLoggingModal
open={editingLogging}
onClose={() => setEditingLogging(false)}
onSaved={loadDevice}
attr={attr}
id={id}
/>
<EditMiscModal
open={editingMisc}
onClose={() => setEditingMisc(false)}
onSaved={loadDevice}
device={device}
attr={attr}
id={id}
/>
<EditBellOutputsModal
open={editingBellOutputs}
onClose={() => setEditingBellOutputs(false)}
onSaved={loadDevice}
attr={attr}
sub={sub}
id={id}
/>
<EditClockSettingsModal
open={editingClockSettings}
onClose={() => setEditingClockSettings(false)}
onSaved={loadDevice}
attr={attr}
sub={sub}
id={id}
/>
<EditAlertsModal
open={editingAlerts}
onClose={() => setEditingAlerts(false)}
onSaved={loadDevice}
clock={clock}
attr={attr}
id={id}
/>
<EditBacklightModal
open={editingBacklight}
onClose={() => setEditingBacklight(false)}
onSaved={loadDevice}
attr={attr}
clock={clock}
sub={sub}
id={id}
/>
<EditSubscriptionModal
open={editingSubscription}
onClose={() => setEditingSubscription(false)}
onSaved={loadDevice}
sub={sub}
id={id}
/>
<EditWarrantyModal
open={editingWarranty}
onClose={() => setEditingWarranty(false)}
onSaved={loadDevice}
stats={stats}
id={id}
/>
<AssignCustomerModal
open={showAssignCustomer}
onClose={() => setShowAssignCustomer(false)}
onSelect={handleAssignCustomer}
deviceId={id}
/>
<ConfirmDialog
open={showDelete}
variant="danger"
title="Delete Device"
message={`Are you sure you want to delete "${device.device_name || sn}"? This action cannot be undone.`}
confirmLabel="Delete"
onConfirm={handleDelete}
onCancel={() => setShowDelete(false)}
loading={deleting}
/>
</div>
)
}
@@ -0,0 +1,4 @@
// TODO: implement
export default function DeviceForm() {
return null
}
@@ -0,0 +1,638 @@
// frontend/src/pages/devices/DeviceList.jsx
import { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth } from '@/hooks/useAuth'
import PageHeader from '@/components/ui/PageHeader'
import Button from '@/components/ui/Button'
import DataTable from '@/components/ui/DataTable'
import StatusBadge from '@/components/ui/StatusBadge'
import Pagination from '@/components/ui/Pagination'
import SearchBar from '@/components/ui/SearchBar'
import RowActions from '@/components/ui/RowActions'
import Icon from '@/components/ui/Icon'
import SegmentedControl from '@/components/ui/SegmentedControl'
import DeleteDeviceModal from '@/modals/bellcloud/devices/DeleteDeviceModal'
import DeviceFiltersModal from '@/modals/bellcloud/devices/DeviceFiltersModal'
import DeviceListCardView from './DeviceListCardView'
import DeviceListMapView from './DeviceListMapView'
// ─── Column definitions ───────────────────────────────────────────────────────
// Columns marked sortable: name, location, totalBells, assignedUsers, maxOutputs,
// totalPlaybacks, totalHammerStrikes, totalWarnings, totalMelodies
const ALL_COLUMNS = [
{ key: 'status', label: '', pickerLabel: 'Status', defaultOn: true, width: '44px' },
{ key: 'name', label: 'Name', defaultOn: true, alwaysOn: true, sortable: true },
{ key: 'serialNumber', label: 'Serial Number', defaultOn: true },
{ key: 'location', label: 'Location', defaultOn: true, sortable: true },
{ key: 'subscrTier', label: 'Tier', defaultOn: true },
{ key: 'totalBells', label: 'Total Bells', defaultOn: true, sortable: true },
{ key: 'assignedUsers', label: 'Users', defaultOn: true, sortable: true },
{ key: 'maxOutputs', label: 'Max Outputs', defaultOn: false, sortable: true },
{ key: 'hasClock', label: 'Has Clock', defaultOn: false },
{ key: 'hasBells', label: 'Has Bells', defaultOn: false },
{ key: 'bellGuard', label: 'Bell Guard', defaultOn: false },
{ key: 'warningsOn', label: 'Warnings On', defaultOn: false },
{ key: 'serialLogLevel', label: 'Serial Log Level', defaultOn: false },
{ key: 'sdLogLevel', label: 'SD Log Level', defaultOn: false },
{ key: 'bellOutputs', label: 'Bell Outputs', defaultOn: false },
{ key: 'hammerTimings', label: 'Hammer Timings', defaultOn: false },
{ key: 'ringAlertsMaster', label: 'Ring Alerts', defaultOn: false },
{ key: 'totalPlaybacks', label: 'Playbacks', defaultOn: false, sortable: true },
{ key: 'totalHammerStrikes', label: 'Hammer Strikes', defaultOn: false, sortable: true },
{ key: 'totalWarnings', label: 'Warnings Given', defaultOn: false, sortable: true },
{ key: 'warrantyActive', label: 'Warranty', defaultOn: false },
{ key: 'totalMelodies', label: 'Melodies', defaultOn: false, sortable: true },
{ key: 'tags', label: 'Tags', defaultOn: false },
{ key: 'hw_family', label: 'HW Family', defaultOn: false },
{ key: 'hw_revision', label: 'HW Revision', defaultOn: false },
]
const ALL_KEYS = ALL_COLUMNS.map((c) => c.key)
function loadColumnPrefs() {
try {
const raw = localStorage.getItem('deviceListColumnPrefs')
if (raw) {
const prefs = JSON.parse(raw)
// prefs = { order: [...keys], visible: [...keys] }
if (prefs.order && prefs.visible) return prefs
}
} catch { /* ignore */ }
return {
order: ALL_KEYS,
visible: ALL_COLUMNS.filter((c) => c.defaultOn).map((c) => c.key),
}
}
function saveColumnPrefs(order, visible) {
try {
localStorage.setItem('deviceListColumnPrefs', JSON.stringify({ order, visible }))
} catch { /* ignore */ }
}
// ─── Helpers ──────────────────────────────────────────────────────────────────
function parseFirestoreDate(str) {
if (!str) return null
const cleaned = str.replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+\d{4}/, 'UTC')
const d = new Date(cleaned)
return isNaN(d.getTime()) ? null : d
}
function isSubscriptionActive(device) {
const sub = device.device_subscription
if (!sub?.subscrStart || !sub?.subscrDuration) return false
try {
const start = parseFirestoreDate(sub.subscrStart)
if (!start) return false
return new Date(start.getTime() + sub.subscrDuration * 86400000) > new Date()
} catch { return false }
}
function isWarrantyActive(device) {
const stats = device.device_stats
if (!stats?.warrantyStart || !stats?.warrantyPeriod) return !!stats?.warrantyActive
try {
const start = parseFirestoreDate(stats.warrantyStart)
if (!start) return !!stats?.warrantyActive
return new Date(start.getTime() + stats.warrantyPeriod * 86400000) > new Date()
} catch { return !!stats?.warrantyActive }
}
// ─── Cell sub-components ──────────────────────────────────────────────────────
function OnlineDot({ isOnline }) {
return (
<span
style={{
display: 'inline-block',
width: '8px',
height: '8px',
borderRadius: 'var(--radius-full)',
backgroundColor: isOnline ? 'var(--color-success)' : 'var(--color-bg-island)',
boxShadow: isOnline ? '0 0 6px var(--color-success)' : 'none',
flexShrink: 0,
}}
title={isOnline ? 'Online' : 'Offline'}
aria-label={isOnline ? 'Online' : 'Offline'}
/>
)
}
function BoolBadge({ value, yesLabel = 'Yes', noLabel = 'No' }) {
return (
<StatusBadge variant={value ? 'success' : 'neutral'} dot={false} size="sm">
{value ? yesLabel : noLabel}
</StatusBadge>
)
}
function TierBadge({ tier }) {
const t = (tier || 'basic').toLowerCase()
const variant = t === 'vip' || t === 'premium' ? 'primary' : t === 'custom' ? 'info' : 'neutral'
return (
<StatusBadge variant={variant} dot={false} size="sm">
{t.charAt(0).toUpperCase() + t.slice(1)}
</StatusBadge>
)
}
function TagList({ tags }) {
if (!tags?.length) return <span style={{ color: 'var(--color-text-muted)' }}>—</span>
return (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-1)' }}>
{tags.map((t) => (
<StatusBadge key={t} variant="info" dot={false} size="sm">{t}</StatusBadge>
))}
</div>
)
}
function Muted({ children }) {
return <span style={{ color: 'var(--color-text-muted)' }}>{children}</span>
}
// ─── Sorting helper ───────────────────────────────────────────────────────────
function getSortValue(device, key) {
const attr = device.device_attributes || {}
const sub = device.device_subscription || {}
const stats = device.device_stats || {}
switch (key) {
case 'name': return (device.device_name || '').toLowerCase()
case 'location': return (device.device_location || '').toLowerCase()
case 'totalBells': return attr.totalBells ?? -1
case 'assignedUsers': return Array.isArray(device.user_list) ? device.user_list.length : 0
case 'maxOutputs': return sub.maxOutputs ?? -1
case 'totalPlaybacks': return stats.totalPlaybacks ?? -1
case 'totalHammerStrikes': return stats.totalHammerStrikes ?? -1
case 'totalWarnings': return stats.totalWarningsGiven ?? -1
case 'totalMelodies': return device.device_melodies_all?.length ?? -1
default: return 0
}
}
function sortDevices(devices, key, dir) {
if (!key) return devices
return [...devices].sort((a, b) => {
const va = getSortValue(a, key)
const vb = getSortValue(b, key)
if (va < vb) return dir === 'asc' ? -1 : 1
if (va > vb) return dir === 'asc' ? 1 : -1
return 0
})
}
// ─── DeviceList ───────────────────────────────────────────────────────────────
export default function DeviceList() {
const navigate = useNavigate()
const { hasPermission } = useAuth()
const canEdit = hasPermission('devices', 'edit')
// Data
const [devices, setDevices] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [mqttStatusMap, setMqttStatusMap] = useState({})
const [mqttLoaded, setMqttLoaded] = useState(false)
// Server-side filters
const [search, setSearch] = useState('')
const [onlineFilter, setOnlineFilter] = useState('')
const [tierFilter, setTierFilter] = useState('')
// Client-side filters
const [subscrStatusFilter, setSubscrStatusFilter] = useState('')
const [warrantyStatusFilter, setWarrantyStatusFilter] = useState('')
const [hasClockFilter, setHasClockFilter] = useState('')
const [hasBellsFilter, setHasBellsFilter] = useState('')
// Column prefs (visibility + order)
const [colPrefs, setColPrefs] = useState(loadColumnPrefs)
// Sort
const [sortKey, setSortKey] = useState('')
const [sortDir, setSortDir] = useState('asc')
// Pagination
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
// View mode: 'table' | 'card' (map is temporarily disabled — access via /devices/map-preview)
const [viewMode, setViewMode] = useState(() => {
try {
const saved = localStorage.getItem('deviceListViewMode')
// Reset 'map' to 'table' while map view is under construction
return (saved === 'map' ? 'table' : saved) || 'table'
} catch { return 'table' }
})
// Filters modal
const [filtersOpen, setFiltersOpen] = useState(false)
// Delete modal
const [deleteTarget, setDeleteTarget] = useState(null)
const [deleteError, setDeleteError] = useState('')
// ── Column change handler ──────────────────────────────────────────────────
// Accepts either a new visible array (from toggle) or a new order array (from drag)
// DataTable calls onColumnChange with the new visibleKeys array for both operations
const handleColumnChange = useCallback((newVisibleKeys) => {
setColPrefs((prev) => {
// Detect if this is a reorder (same keys, different order) or visibility toggle
const sortedPrev = [...prev.visible].sort()
const sortedNext = [...newVisibleKeys].sort()
const isReorder = JSON.stringify(sortedPrev) === JSON.stringify(sortedNext)
let nextOrder = prev.order
let nextVisible = prev.visible
if (isReorder) {
// Drag reorder: update the order of visible keys, keeping hidden keys appended
const hiddenKeys = prev.order.filter((k) => !prev.visible.includes(k))
nextOrder = [...newVisibleKeys, ...hiddenKeys]
nextVisible = newVisibleKeys
} else {
// Visibility toggle: preserve order, just update visible set
nextVisible = newVisibleKeys
}
saveColumnPrefs(nextOrder, nextVisible)
return { order: nextOrder, visible: nextVisible }
})
}, [])
// ── Fetch devices ──────────────────────────────────────────────────────────
const fetchDevices = useCallback(async () => {
setLoading(true)
setMqttLoaded(false)
setError('')
try {
const params = new URLSearchParams()
if (search) params.set('search', search)
if (onlineFilter === 'true') params.set('online', 'true')
if (onlineFilter === 'false') params.set('online', 'false')
if (tierFilter) params.set('tier', tierFilter)
// Note: online filter is server-side — we pass it as a query param but
// the server returns ALL devices when the param is absent, so we also
// apply a client-side guard to ensure ONLINE-only actually filters.
const qs = params.toString()
const data = await api.get(`/devices${qs ? `?${qs}` : ''}`)
setDevices(data.devices ?? [])
api.get('/mqtt/status').then((mqttData) => {
if (mqttData?.devices) {
const map = {}
for (const s of mqttData.devices) map[s.device_serial] = s
setMqttStatusMap(map)
}
setMqttLoaded(true)
}).catch(() => { setMqttLoaded(true) })
} catch (err) {
setError(err.message || 'Failed to load devices.')
} finally {
setLoading(false)
}
}, [search, onlineFilter, tierFilter])
useEffect(() => { fetchDevices() }, [fetchDevices])
useEffect(() => {
setPage(1)
}, [search, onlineFilter, tierFilter, subscrStatusFilter, warrantyStatusFilter, hasClockFilter, hasBellsFilter])
// ── Delete ─────────────────────────────────────────────────────────────────
const handleDelete = async () => {
if (!deleteTarget) return
setDeleteError('')
try {
await api.delete(`/devices/${deleteTarget.id}`)
setDeleteTarget(null)
fetchDevices()
} catch (err) {
setDeleteError(err.message || 'Failed to delete device.')
}
}
// ── Client-side filtering + sorting ───────────────────────────────────────
const filteredDevices = devices.filter((device) => {
// Online/offline — wait for MQTT data before applying so we don't show
// false-negative "no devices" while the status map is still loading.
const sn = device.serial_number || device.device_id
const mqtt = mqttStatusMap[sn]
const isOnline = mqtt ? mqtt.online : (device.is_Online ?? false)
// Only apply online/offline filter once MQTT status has resolved —
// prevents false-negative empty table while the status map is still loading.
if (onlineFilter === 'true' && mqttLoaded && !isOnline) return false
if (onlineFilter === 'false' && mqttLoaded && isOnline) return false
if (subscrStatusFilter === 'active' && !isSubscriptionActive(device)) return false
if (subscrStatusFilter === 'expired' && isSubscriptionActive(device)) return false
if (warrantyStatusFilter === 'active' && !isWarrantyActive(device)) return false
if (warrantyStatusFilter === 'expired' && isWarrantyActive(device)) return false
if (hasClockFilter === 'yes' && !device.device_attributes?.hasClock) return false
if (hasClockFilter === 'no' && device.device_attributes?.hasClock) return false
if (hasBellsFilter === 'yes' && !device.device_attributes?.hasBells) return false
if (hasBellsFilter === 'no' && device.device_attributes?.hasBells) return false
return true
})
const sortedDevices = sortDevices(filteredDevices, sortKey, sortDir)
const total = sortedDevices.length
const pagedDevices = sortedDevices.slice((page - 1) * pageSize, page * pageSize)
// ── Active filter count (for badge on Filters button) ─────────────────────
const activeFilterCount = [onlineFilter, tierFilter, subscrStatusFilter, warrantyStatusFilter, hasClockFilter, hasBellsFilter].filter(Boolean).length
// ── Middle-click handler ───────────────────────────────────────────────────
const handleRowMiddleClick = (device, e) => {
if (e.button === 1) {
e.preventDefault()
window.open(`/devices/${device.id}`, '_blank', 'noopener,noreferrer')
}
}
// ── Build DataTable column definitions ────────────────────────────────────
// Respect the saved column order
const orderedVisible = colPrefs.order.filter((k) => colPrefs.visible.includes(k))
const tableColumns = orderedVisible
.map((key) => {
const c = ALL_COLUMNS.find((col) => col.key === key)
if (!c) return null
return {
key: c.key,
label: c.label,
width: c.width,
sortable: c.sortable,
render: (device) => {
const attr = device.device_attributes || {}
const clock = attr.clockSettings || {}
const sub = device.device_subscription || {}
const stats = device.device_stats || {}
const sn = device.serial_number || device.device_id
const mqtt = mqttStatusMap[sn]
const isOnline = mqtt ? mqtt.online : device.is_Online
switch (c.key) {
case 'status':
return <OnlineDot isOnline={isOnline} />
case 'name':
return (
<span style={{ fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)' }}>
{device.device_name || 'Unnamed Device'}
</span>
)
case 'serialNumber':
return (
<span style={{ fontFamily: 'var(--font-family-mono)', color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)' }}>
{sn || '—'}
</span>
)
case 'location':
return device.device_location || <Muted>—</Muted>
case 'subscrTier':
return <TierBadge tier={sub.subscrTier} />
case 'totalBells':
return attr.totalBells ?? 0
case 'assignedUsers':
return Array.isArray(device.user_list) ? device.user_list.length : 0
case 'maxOutputs':
return sub.maxOutputs ?? <Muted>—</Muted>
case 'hasClock':
return <BoolBadge value={attr.hasClock} />
case 'hasBells':
return <BoolBadge value={attr.hasBells} />
case 'bellGuard':
return <BoolBadge value={attr.bellGuardOn} />
case 'warningsOn':
return <BoolBadge value={attr.warningsOn} />
case 'serialLogLevel':
return attr.serialLogLevel ?? 0
case 'sdLogLevel':
return attr.sdLogLevel ?? 0
case 'bellOutputs':
return attr.bellOutputs?.length ? attr.bellOutputs.join(', ') : <Muted>—</Muted>
case 'hammerTimings':
return attr.hammerTimings?.length ? attr.hammerTimings.join(', ') : <Muted>—</Muted>
case 'ringAlertsMaster':
return <BoolBadge value={clock.ringAlertsMasterOn} yesLabel="ON" noLabel="OFF" />
case 'totalPlaybacks':
return stats.totalPlaybacks ?? 0
case 'totalHammerStrikes':
return stats.totalHammerStrikes ?? 0
case 'totalWarnings':
return stats.totalWarningsGiven ?? 0
case 'warrantyActive':
return <BoolBadge value={stats.warrantyActive} yesLabel="Active" noLabel="Expired" />
case 'totalMelodies':
return device.device_melodies_all?.length ?? 0
case 'tags':
return <TagList tags={device.tags} />
case 'hw_family':
return device.hw_family || <Muted>—</Muted>
case 'hw_revision':
return device.hw_revision || <Muted>—</Muted>
default:
return <Muted>—</Muted>
}
},
}
})
.filter(Boolean)
// Actions column (not part of ALL_COLUMNS — appended, never draggable)
tableColumns.push({
key: '__actions',
label: '',
width: '110px',
align: 'right',
render: (device) => (
<div onClick={(e) => e.stopPropagation()} style={{ display: 'flex', justifyContent: 'flex-end' }}>
<RowActions
actions={[
{
label: 'View Details',
icon: <Icon name="eye" size={14} />,
onClick: () => navigate(`/devices/${device.id}`),
},
...(canEdit ? [
{
label: 'Edit',
icon: <Icon name="edit" size={14} />,
color: 'var(--color-info)',
onClick: () => navigate(`/devices/${device.id}/edit`),
},
{
label: 'Delete',
icon: <Icon name="delete" size={14} />,
color: 'var(--color-danger)',
divider: true,
onClick: () => { setDeleteError(''); setDeleteTarget(device) },
},
] : []),
]}
/>
</div>
),
})
// ─────────────────────────────────────────────────────────────────────────
return (
<div className="page-wrapper">
{/* Page header */}
<PageHeader
title="Device Fleet"
subtitle={!loading
? `${filteredDevices.length} ${filteredDevices.length === 1 ? 'device' : 'devices'}`
: undefined
}
>
{canEdit && (
<Button variant="primary" onClick={() => navigate('/devices/new')}>
Add Device
</Button>
)}
</PageHeader>
{/* Toolbar + pagination + content — single tight-gap column so all three
items are visually grouped and equidistant from each other */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)', minWidth: 0 }}>
{/* Filter toolbar */}
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-3)', alignItems: 'center', minWidth: 0 }}>
<div style={{ flex: '1 1 0', minWidth: '180px' }}>
<SearchBar
value={search}
onChange={setSearch}
placeholder="Search by name, location, or serial…"
/>
</div>
<Button
variant={activeFilterCount > 0 ? 'secondary' : 'ghost'}
size="md"
onClick={() => setFiltersOpen(true)}
style={{ paddingTop: 'var(--space-3)', paddingBottom: 'var(--space-3)', lineHeight: 'var(--line-height-base)' }}
icon={
<svg width="14" height="14" viewBox="0 0 24 24" fill="none"
stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/>
</svg>
}
>
Filters{activeFilterCount > 0 ? ` (${activeFilterCount})` : ''}
</Button>
<SegmentedControl
options={[
{ value: 'table', label: 'Table', icon: <Icon name="more_horizontal" size={14} /> },
{ value: 'card', label: 'Cards', icon: <Icon name="dashboard" size={14} /> },
// Map option temporarily hidden — access via /devices/map-preview while under construction
]}
value={viewMode}
onChange={(v) => {
setViewMode(v)
try { localStorage.setItem('deviceListViewMode', v) } catch { /* ignore */ }
}}
size="md"
style={{ flexShrink: 0 }}
/>
</div>
{/* Error banner */}
{error && (
<div
role="alert"
style={{
backgroundColor: 'var(--color-danger-bg)',
border: '1px solid var(--color-danger-container)',
borderRadius: 'var(--radius-md)',
padding: 'var(--space-3) var(--space-4)',
color: 'var(--color-danger)',
fontSize: 'var(--font-size-sm)',
}}
>
{error}
</div>
)}
{total > 0 && viewMode !== 'map' && (
<Pagination
page={page}
pageSize={pageSize}
total={total}
onPageChange={setPage}
onSizeChange={(s) => { setPageSize(s); setPage(1) }}
pageSizes={[10, 20, 50, 100]}
/>
)}
{/* Table, Card, or Map view */}
{viewMode === 'map' ? (
<DeviceListMapView
devices={filteredDevices}
loading={loading}
mqttStatusMap={mqttStatusMap}
onView={(device) => navigate(`/devices/${device.id}`)}
/>
) : viewMode === 'card' ? (
<DeviceListCardView
devices={pagedDevices}
loading={loading}
mqttStatusMap={mqttStatusMap}
onView={(device) => navigate(`/devices/${device.id}`)}
onMiddleClick={(device, e) => handleRowMiddleClick(device, e)}
/>
) : (
<DataTable
columns={tableColumns}
data={pagedDevices}
loading={loading}
keyField="id"
emptyMessage="No devices found"
emptyDescription="Try adjusting your search or filters."
onRowClick={(device) => navigate(`/devices/${device.id}`)}
onRowMiddleClick={(device, e) => handleRowMiddleClick(device, e)}
skeletonRows={8}
sortKey={sortKey}
sortDir={sortDir}
onSort={(key, dir) => { setSortKey(key); setSortDir(dir); setPage(1) }}
allColumns={ALL_COLUMNS}
visibleKeys={colPrefs.visible}
onColumnChange={handleColumnChange}
/>
)}
</div>
{/* Filters modal */}
<DeviceFiltersModal
open={filtersOpen}
onClose={() => setFiltersOpen(false)}
onlineFilter={onlineFilter} setOnlineFilter={setOnlineFilter}
tierFilter={tierFilter} setTierFilter={setTierFilter}
subscrStatusFilter={subscrStatusFilter} setSubscrStatusFilter={setSubscrStatusFilter}
warrantyStatusFilter={warrantyStatusFilter} setWarrantyStatusFilter={setWarrantyStatusFilter}
hasClockFilter={hasClockFilter} setHasClockFilter={setHasClockFilter}
hasBellsFilter={hasBellsFilter} setHasBellsFilter={setHasBellsFilter}
/>
{/* Delete confirmation modal */}
<DeleteDeviceModal
device={deleteTarget}
onConfirm={handleDelete}
onCancel={() => { setDeleteTarget(null); setDeleteError('') }}
error={deleteError}
/>
</div>
)
}
@@ -0,0 +1,861 @@
// frontend/src/pages/bellcloud/devices/DeviceListCardView.jsx
//
// Card-based view of the Device Fleet list.
// Glassmorphism + gradient glow border (online=green, offline=grey)
// + real OSM tile map pulled from device_location_coordinates.
// All colours via design tokens only.
import { useMemo } from 'react'
import Icon from '@/components/ui/Icon'
// ─── Tier config ──────────────────────────────────────────────────────────────
const TIER_META = {
vip: { label: 'VIP' },
premium: { label: 'Premium' },
custom: { label: 'Custom' },
small: { label: 'Small' },
mini: { label: 'Mini' },
basic: { label: 'Basic' },
}
function getTierLabel(tier) {
return TIER_META[(tier || 'basic').toLowerCase()]?.label ?? 'Basic'
}
// ─── OSM tile helpers ─────────────────────────────────────────────────────────
// Convert lat/lng to OSM tile x/y at a given zoom level.
// Returns the exact tile coords AND the sub-tile pixel offset (0–255) of the coordinate.
function latLngToTile(lat, lng, zoom) {
const n = Math.pow(2, zoom)
const xFrac = ((lng + 180) / 360) * n
const latRad = (lat * Math.PI) / 180
const yFrac = ((1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2) * n
const x = Math.floor(xFrac)
const y = Math.floor(yFrac)
// px/py: how far into the focal tile the coordinate sits, in pixels (0–256)
const px = (xFrac - x) * 256
const py = (yFrac - y) * 256
return { x, y, px, py }
}
// Build a 4-wide × 3-tall grid of Stamen Toner tiles centred on the coordinate.
// Using 4 columns (dx = -2..+1) guarantees the grid is 1024px wide, which always
// exceeds the card width (~500px) even when the marker sits near the right edge
// of the focal tile (markerOffset.x up to 512px, anchor = 80% - markerOffset.x).
// markerOffset is the pixel position of the coordinate within the 1024×768 grid,
// measured from the grid's top-left. The grid is anchored via inline style so
// markerOffset lands at exactly 80%/60% of the card.
function buildTileGrid(lat, lng, zoom = 13) {
const { x, y, px, py } = latLngToTile(lat, lng, zoom)
const tiles = []
for (let dy = -1; dy <= 1; dy++) {
for (let dx = -2; dx <= 1; dx++) {
const tx = x + dx
const ty = y + dy
tiles.push({
url: `https://tiles.stadiamaps.com/tiles/stamen_toner/${zoom}/${tx}/${ty}.png`,
col: dx + 2 + 1, // cols 1–4
row: dy + 1 + 1, // rows 1–3
})
}
}
// The focal tile is at grid column index 2 (dx=0), so its left edge is at
// 2 × 256 = 512px from the grid's left. markerOffset.x = 512 + px.
return { tiles, markerOffset: { x: 512 + px, y: 256 + py } }
}
// Normalise GeoPoint from Firestore — can arrive as {lat,lng}, {latitude,longitude},
// or a Firestore GeoPoint object with .latitude / .longitude getters.
function parseCoords(raw) {
if (!raw) return null
const lat = raw.latitude ?? raw.lat ?? null
const lng = raw.longitude ?? raw.lng ?? null
if (lat == null || lng == null) return null
return { lat: Number(lat), lng: Number(lng) }
}
// ─── Inline SVGs ─────────────────────────────────────────────────────────────
function BellIcon({ size = 13, color = 'currentColor' }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none"
stroke={color} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"
aria-hidden="true">
<path d="M18 8A6 6 0 006 8c0 7-3 9-3 9h18s-3-2-3-9" />
<path d="M13.73 21a2 2 0 01-3.46 0" />
</svg>
)
}
function ClockIcon({ size = 13, color = 'currentColor' }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none"
stroke={color} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"
aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<polyline points="12 6 12 12 16 14" />
</svg>
)
}
function AlertTriangleIcon({ size = 13, color = 'currentColor' }) {
return (
<svg width={size} height={size} viewBox="0 0 24 24" fill="none"
stroke={color} strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"
aria-hidden="true">
<path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
<line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
)
}
// ─── Real OSM tile map background ────────────────────────────────────────────
// Renders a 3×3 grid of OSM tiles centred on device_location_coordinates,
// tinted dark to match the card theme, with a left-fade gradient overlay.
function MapBackground({ coords }) {
const ZOOM = 13
const { tiles, markerOffset } = useMemo(() => {
if (!coords) return { tiles: null, markerOffset: null }
return buildTileGrid(coords.lat, coords.lng, ZOOM)
}, [coords])
return (
<div className="dcard__map-bg" aria-hidden="true">
{tiles ? (
// 4×3 tile grid. Anchored so markerOffset lands at exactly 80%/60% of
// the card. The grid is 1024px wide so it always covers the full card.
<div
className="dcard__map-tiles"
style={{
top: `calc(60% - ${markerOffset.y}px)`,
left: `calc(80% - ${markerOffset.x}px)`,
}}
>
{tiles.map((t, i) => (
<img
key={i}
src={t.url}
alt=""
className="dcard__map-tile"
style={{ gridColumn: t.col, gridRow: t.row }}
draggable={false}
/>
))}
</div>
) : (
<div className="dcard__map-fallback" />
)}
{/* Marker pinned at exactly 80%/60% of the card */}
{tiles && markerOffset && (
<div aria-hidden="true" style={{
position: 'absolute',
top: '60%',
left: '80%',
width: 0,
height: 0,
zIndex: 10,
pointerEvents: 'none',
}}>
<div style={{
position: 'absolute',
width: 9,
height: 9,
borderRadius: '50%',
background: 'rgba(250,204,21,1)',
boxShadow: '0 0 0 2px rgba(8,12,18,0.95), 0 0 12px rgba(250,204,21,0.8)',
top: -4.5,
left: -4.5,
}} />
<div style={{
position: 'absolute',
width: 24,
height: 24,
borderRadius: '50%',
border: '1.5px solid rgba(250,204,21,0.6)',
top: -12,
left: -12,
animation: 'dcard-marker-pulse 2.2s ease-out infinite',
}} />
</div>
)}
<div className="dcard__map-tint" />
<div className="dcard__map-fade" />
</div>
)
}
// ─── Online status block (rectangular, spans both identity rows) ──────────────
function OnlineBlock({ online }) {
return (
<div
className={`dcard__online-block ${online ? 'dcard__online-block--on' : 'dcard__online-block--off'}`}
aria-label={online ? 'Online' : 'Offline'}
>
<span className="dcard__online-block-dot" aria-hidden="true" />
<span className="dcard__online-block-label">{online ? 'Online' : 'Offline'}</span>
</div>
)
}
// ─── Inline pill (used for tier, warranty, clock, bells) ─────────────────────
function InlinePill({ icon, label, variant = 'default', title }) {
return (
<div className={`dcard__pill dcard__pill--${variant}`} title={title || label}>
{icon && <span className="dcard__pill-icon" aria-hidden="true">{icon}</span>}
<span className="dcard__pill-label">{label}</span>
</div>
)
}
// ─── Warning count badge ──────────────────────────────────────────────────────
function WarningsBadge({ count }) {
if (!count) return null
return (
<div className="dcard__warn-badge" title={`${count} warning${count > 1 ? 's' : ''} given`}>
<AlertTriangleIcon size={11} />
<span>{count}</span>
</div>
)
}
// ─── Single Device Card ───────────────────────────────────────────────────────
function DeviceCard({ device, mqttStatusMap, onView, onMiddleClick }) {
const attr = device.device_attributes || {}
const sub = device.device_subscription || {}
const stats = device.device_stats || {}
const sn = device.serial_number || device.device_id || ''
const mqtt = mqttStatusMap[sn]
const isOnline = mqtt ? mqtt.online : device.is_Online
const name = device.device_name || 'Unnamed Device'
const location = device.device_location
const coords = useMemo(() => parseCoords(device.device_location_coordinates), [device.device_location_coordinates])
const tierLabel = getTierLabel(sub.subscrTier)
const hasClock = !!attr.hasClock
const hasBells = !!attr.hasBells
const totalWarnings = stats.totalWarningsGiven ?? 0
return (
<article
className={`dcard ${isOnline ? 'dcard--online' : 'dcard--offline'}`}
onClick={onView}
onMouseDown={(e) => { if (e.button === 1) { e.preventDefault(); onMiddleClick?.(e) } }}
>
{/* ── Tier badge — absolute top-right corner ── */}
<div className="dcard__tier-badge">{tierLabel}</div>
{/* ── Card content (above map) ── */}
<div className="dcard__content">
{/* ── Real OSM map background — fills card, pinned top-left ── */}
<MapBackground coords={coords} />
{/* ── Header: status block + identity ── */}
<header className="dcard__header">
<OnlineBlock online={isOnline} />
<div className="dcard__identity">
<div className="dcard__name-row">
<span className="dcard__name">{name}</span>
</div>
<div className="dcard__serial-row">
<span className="dcard__serial-hash">#</span>
<span className="dcard__serial">{sn || '—'}</span>
{totalWarnings > 0 && <WarningsBadge count={totalWarnings} />}
</div>
</div>
</header>
{/* ── Feature pills: clock + bells — absolute bottom-left ── */}
<div className="dcard__pills">
{hasClock && (
<InlinePill icon={<ClockIcon size={11} />} label="Clock" variant="feature" title="Has Clock" />
)}
{hasBells && (
<InlinePill icon={<BellIcon size={11} />} label="Bells" variant="feature" title="Has Bells" />
)}
</div>
{/* ── Location label — under marker at 80%/60%, or bottom-right corner ── */}
{location && (
<div
className="dcard__location"
style={coords
? { top: 'calc(60% + 16px)', left: '80%', transform: 'translateX(-50%)' }
: { bottom: 'var(--space-4)', right: 'var(--space-4)' }
}
aria-label={`Location: ${location}`}
>
<span className="dcard__location-label">{location}</span>
</div>
)}
</div>
</article>
)
}
// ─── Skeleton card ────────────────────────────────────────────────────────────
function SkeletonCard() {
return (
<div className="dcard dcard--offline dcard--skeleton" aria-hidden="true">
<div className="dcard__content">
<div className="dcard__header">
<div className="dcard-skel" style={{ width: 56, alignSelf: 'stretch', borderRadius: 8, flexShrink: 0 }} />
<div className="dcard__identity">
<div className="dcard__name-row">
<div className="dcard-skel" style={{ flex: 1, height: 22 }} />
</div>
<div className="dcard__serial-row">
<div className="dcard-skel" style={{ width: '65%', height: 14 }} />
</div>
</div>
</div>
<div className="dcard__pills">
{[1, 2, 3].map((i) => (
<div key={i} className="dcard-skel" style={{ width: 64, height: 26, borderRadius: 999 }} />
))}
</div>
</div>
</div>
)
}
// ─── DeviceListCardView (exported) ────────────────────────────────────────────
export default function DeviceListCardView({
devices,
loading,
mqttStatusMap,
onView,
onMiddleClick,
}) {
if (loading) {
return (
<>
<style>{CARD_STYLES}</style>
<div className="dcard-grid">
{Array.from({ length: 9 }).map((_, i) => <SkeletonCard key={i} />)}
</div>
</>
)
}
if (!devices.length) {
return (
<>
<style>{CARD_STYLES}</style>
<div className="dcard-empty">
<div className="dcard-empty__icon" aria-hidden="true">
<Icon name="devices" size={36} color="var(--color-text-muted)" />
</div>
<p className="dcard-empty__title">No devices found</p>
<p className="dcard-empty__sub">Try adjusting your search or filters.</p>
</div>
</>
)
}
return (
<>
<style>{CARD_STYLES}</style>
<div className="dcard-grid">
{devices.map((device) => (
<DeviceCard
key={device.id}
device={device}
mqttStatusMap={mqttStatusMap}
onView={() => onView(device)}
onMiddleClick={onMiddleClick ? (e) => onMiddleClick(device, e) : undefined}
/>
))}
</div>
</>
)
}
// ─── Styles ───────────────────────────────────────────────────────────────────
const CARD_STYLES = `
/* ── Grid ─────────────────────────────────────────────────────────────────── */
.dcard-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
gap: var(--space-4);
align-items: flex-start;
}
/* ── Card wrapper — gradient border that changes with online state ────────── */
.dcard {
position: relative;
display: flex;
flex-direction: column;
border-radius: 16px;
padding: 1px; /* the 1px holds the gradient border colour */
cursor: pointer;
user-select: none;
box-sizing: border-box;
transition: transform 220ms ease, box-shadow 220ms ease, background-image 220ms ease;
/* min-height ensures border shows on all 4 sides even with short content */
min-height: 200px;
}
/* Online — green glow border */
.dcard--online {
background-image: linear-gradient(
135deg,
rgba(74,222,128,0.55) 0%,
rgba(255,255,255,0.08) 40%,
rgba(255,255,255,0.05) 65%,
rgba(74,222,128,0.70) 100%
);
box-shadow:
0 8px 32px rgba(0,0,0,0.45),
0 0 28px rgba(74,222,128,0.10);
}
.dcard--online:hover {
background-image: linear-gradient(
135deg,
rgba(74,222,128,0.80) 0%,
rgba(255,255,255,0.10) 40%,
rgba(255,255,255,0.07) 65%,
rgba(74,222,128,0.95) 100%
);
box-shadow:
0 12px 40px rgba(0,0,0,0.55),
0 0 48px rgba(74,222,128,0.18);
}
/* Offline — neutral grey border */
.dcard--offline {
background-image: linear-gradient(
135deg,
rgba(120,130,145,0.35) 0%,
rgba(255,255,255,0.05) 40%,
rgba(255,255,255,0.03) 65%,
rgba(90,100,115,0.45) 100%
);
box-shadow:
0 8px 32px rgba(0,0,0,0.45),
0 0 20px rgba(100,110,125,0.06);
}
.dcard--offline:hover {
background-image: linear-gradient(
135deg,
rgba(140,155,175,0.50) 0%,
rgba(255,255,255,0.08) 40%,
rgba(255,255,255,0.05) 65%,
rgba(110,125,145,0.60) 100%
);
box-shadow:
0 12px 40px rgba(0,0,0,0.55),
0 0 32px rgba(120,135,155,0.10);
}
.dcard:active { transform: translateY(0) !important; }
.dcard:hover { transform: translateY(-2px); }
/* ── Card inner surface ──────────────────────────────────────────────────── */
.dcard__content {
position: relative;
z-index: 1;
display: flex;
flex-direction: column;
gap: var(--space-4);
background: rgba(10, 15, 22, 0.92);
border-radius: 15px;
padding: var(--space-5) var(--space-5) var(--space-4);
overflow: hidden;
/* flex: 1 makes content fill the full card height so all 4 border edges show */
flex: 1;
min-height: 210px;
}
/* ── Real OSM tile map background — full card width, fade handles transition ── */
.dcard__map-bg {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 0;
overflow: hidden;
border-radius: 15px;
}
/* 4×3 tile grid — anchored via inline style so the coordinate lands at 80%/60%.
1024px wide guarantees full card coverage regardless of sub-tile offset. */
.dcard__map-tiles {
display: grid;
grid-template-columns: repeat(4, 256px);
grid-template-rows: repeat(3, 256px);
position: absolute;
width: 1024px;
height: 768px;
}
.dcard__map-tile {
width: 256px;
height: 256px;
display: block;
/* Stamen Toner is already B&W — invert so roads are dark lines on dark bg,
then reduce brightness so it sits quietly behind the card content */
filter: invert(1) brightness(0.30);
pointer-events: none;
user-select: none;
}
/* Fallback grid pattern when no coordinates */
.dcard__map-fallback {
position: absolute;
inset: 0;
background-image:
linear-gradient(rgba(99,179,237,0.07) 1px, transparent 1px),
linear-gradient(90deg, rgba(99,179,237,0.07) 1px, transparent 1px);
background-size: 32px 32px;
}
/* Tint — very light, map is meant to be visible */
.dcard__map-tint {
position: absolute;
inset: 0;
background: rgba(10, 15, 22, 0.05);
}
/* Fade: solid left edge, starts dissolving after 15% */
.dcard__map-fade {
position: absolute;
inset: 0;
background: linear-gradient(
to right,
rgba(10, 15, 22, 1) 0%,
rgba(10, 15, 22, 1) 15%,
rgba(10, 15, 22, 0.60) 40%,
rgba(10, 15, 22, 0.15) 65%,
rgba(10, 15, 22, 0) 80%
);
}
@keyframes dcard-marker-pulse {
0% { transform: scale(0.5); opacity: 1; }
70% { transform: scale(1.6); opacity: 0; }
100% { transform: scale(1.6); opacity: 0; }
}
/* ── Header ──────────────────────────────────────────────────────────────── */
.dcard__header {
display: flex;
align-items: stretch;
gap: var(--space-3);
position: relative;
z-index: 2;
}
.dcard__identity {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 7px;
justify-content: center;
}
.dcard__name-row {
display: flex;
align-items: center;
gap: var(--space-2);
min-width: 0;
}
.dcard__name {
flex: 1;
min-width: 0;
font-family: var(--font-family-display);
font-size: var(--font-size-xl, 1.25rem);
font-weight: var(--font-weight-bold);
color: var(--color-text-primary);
letter-spacing: -0.01em;
line-height: 1.2;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* ── Serial row ──────────────────────────────────────────────────────────── */
.dcard__serial-row {
display: flex;
align-items: center;
gap: 5px;
min-width: 0;
}
.dcard__serial-hash {
font-size: var(--font-size-sm);
font-weight: var(--font-weight-semibold);
color: var(--color-text-muted);
line-height: 1;
flex-shrink: 0;
}
.dcard__serial {
font-family: var(--font-family-mono);
font-size: var(--font-size-sm);
font-weight: var(--font-weight-medium);
color: rgba(99, 179, 237, 0.80);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-width: 0;
letter-spacing: 0.04em;
}
/* ── Online status block ─────────────────────────────────────────────────── */
.dcard__online-block {
flex-shrink: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
width: 58px;
border-radius: 10px;
border: 1px solid transparent;
padding: var(--space-2) var(--space-1);
transition: background 200ms ease;
}
.dcard__online-block--on {
background: rgba(74, 222, 128, 0.09);
border-color: rgba(74, 222, 128, 0.28);
}
.dcard__online-block--off {
background: rgba(255, 255, 255, 0.03);
border-color: rgba(255, 255, 255, 0.09);
}
.dcard__online-block-dot {
display: block;
width: 10px;
height: 10px;
border-radius: 50%;
flex-shrink: 0;
}
.dcard__online-block--on .dcard__online-block-dot {
background: #4ade80;
box-shadow: 0 0 8px rgba(74,222,128,0.75);
animation: dcard-pulse 2s ease-out infinite;
}
.dcard__online-block--off .dcard__online-block-dot {
background: rgba(160,170,185,0.40);
}
.dcard__online-block-label {
font-size: 9px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
line-height: 1;
white-space: nowrap;
}
.dcard__online-block--on .dcard__online-block-label { color: #4ade80; }
.dcard__online-block--off .dcard__online-block-label { color: rgba(160,170,185,0.55); }
@keyframes dcard-pulse {
0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.65); }
70% { box-shadow: 0 0 0 8px rgba(74, 222, 128, 0); }
100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }
}
/* ── Warning badge ───────────────────────────────────────────────────────── */
.dcard__warn-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px var(--space-2);
background: var(--color-warning-bg);
border: 1px solid rgba(251, 191, 36, 0.20);
border-radius: var(--radius-sm);
font-size: var(--font-size-xs);
font-weight: var(--font-weight-semibold);
color: var(--color-warning);
flex-shrink: 0;
}
/* ── Tier badge — absolute top-right of card ─────────────────────────────── */
/* Uses var(--space-4) = 16px to match the bottom-left pills and bottom-right
location corner — all three shared the same corner inset. */
.dcard__tier-badge {
position: absolute;
top: var(--space-4);
right: var(--space-4);
z-index: 10;
padding: 3px 10px;
border-radius: 999px;
font-size: 10px;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
background: rgba(255,255,255,0.07);
border: 1px solid rgba(255,255,255,0.15);
color: rgba(200,210,220,0.85);
white-space: nowrap;
backdrop-filter: blur(4px);
pointer-events: none;
}
/* ── Pills row — absolute bottom-left, same inset as tier badge and location corner ── */
.dcard__pills {
position: absolute;
bottom: var(--space-4);
left: var(--space-4);
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
z-index: 2;
pointer-events: none;
}
/* Base pill style */
.dcard__pill {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 11px;
border-radius: 999px;
font-size: 11px;
font-weight: 500;
border: 1px solid transparent;
white-space: nowrap;
line-height: 1;
transition: border-color 150ms ease, background 150ms ease;
}
.dcard__pill-icon {
display: flex;
align-items: center;
flex-shrink: 0;
}
.dcard__pill-label { line-height: 1; }
/* Tier pill — subtle neutral */
.dcard__pill--tier {
background: rgba(255,255,255,0.05);
border-color: rgba(255,255,255,0.12);
color: rgba(200,210,220,0.80);
}
/* Feature pills (clock, bells) — cyan/blue */
.dcard__pill--feature {
background: rgba(99,179,237,0.07);
border-color: rgba(99,179,237,0.28);
color: rgba(99,179,237,0.90);
}
.dcard__pill--feature:hover {
background: rgba(99,179,237,0.13);
border-color: rgba(99,179,237,0.50);
}
/* Warranty active — soft green */
.dcard__pill--warranty-on {
background: rgba(74,222,128,0.07);
border-color: rgba(74,222,128,0.28);
color: rgba(74,222,128,0.90);
}
/* No warranty — muted red/amber */
.dcard__pill--warranty-off {
background: rgba(251,113,133,0.06);
border-color: rgba(251,113,133,0.22);
color: rgba(251,113,133,0.80);
}
/* ── Location label ───────────────────────────────────────────────────────── */
/* Position set via inline style in JSX — follows the marker when coords exist,
falls back to bottom-right corner otherwise. */
.dcard__location {
position: absolute;
z-index: 3;
pointer-events: none;
max-width: 170px;
}
.dcard__location-label {
display: inline-block;
padding: 3px 9px;
border-radius: 999px;
background: rgba(8, 12, 18, 0.72);
border: 1px solid rgba(250, 204, 21, 0.22);
backdrop-filter: blur(4px);
font-size: 12px;
font-weight: 600;
color: rgba(250, 204, 21, 0.88);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
letter-spacing: 0.02em;
line-height: 1.4;
}
/* ── Empty state ──────────────────────────────────────────────────────────── */
.dcard-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: var(--space-3);
padding: var(--space-16) var(--space-8);
text-align: center;
width: 100%;
}
.dcard-empty__icon {
display: flex;
align-items: center;
justify-content: center;
width: 64px;
height: 64px;
border-radius: var(--radius-xl);
background: var(--color-bg-elevated);
margin-bottom: var(--space-2);
}
.dcard-empty__title {
font-size: var(--font-size-base);
font-weight: var(--font-weight-semibold);
color: var(--color-text-secondary);
margin: 0;
}
.dcard-empty__sub {
font-size: var(--font-size-sm);
color: var(--color-text-muted);
margin: 0;
}
/* ── Skeleton shimmer ─────────────────────────────────────────────────────── */
.dcard--skeleton {
cursor: default;
pointer-events: none;
}
.dcard-skel {
background: linear-gradient(
90deg,
rgba(255,255,255,0.04) 0%,
rgba(255,255,255,0.09) 50%,
rgba(255,255,255,0.04) 100%
);
background-size: 200% 100%;
animation: dcard-shimmer 1.4s ease-in-out infinite;
border-radius: var(--radius-sm);
}
@keyframes dcard-shimmer {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
/* ── Responsive ───────────────────────────────────────────────────────────── */
@media (max-width: 768px) {
.dcard-grid {
grid-template-columns: 1fr;
gap: var(--space-3);
}
}
`
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
// frontend/src/pages/bellcloud/devices/DeviceMapPage.jsx
//
// Standalone route for the map view while it's under construction.
// Access via /devices/map-preview — not linked from the main UI.
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import DeviceListMapView from './DeviceListMapView'
export default function DeviceMapPage() {
const navigate = useNavigate()
const [devices, setDevices] = useState([])
const [mqttStatusMap, setMqttStatusMap] = useState({})
const [loading, setLoading] = useState(true)
useEffect(() => {
api.get('/devices').then((data) => {
setDevices(data.devices ?? [])
api.get('/mqtt/status').then((mqttData) => {
if (mqttData?.devices) {
const map = {}
for (const s of mqttData.devices) map[s.device_serial] = s
setMqttStatusMap(map)
}
setLoading(false)
}).catch(() => setLoading(false))
}).catch(() => setLoading(false))
}, [])
return (
<DeviceListMapView
devices={devices}
loading={loading}
mqttStatusMap={mqttStatusMap}
onView={(device) => navigate(`/devices/${device.id}`)}
/>
)
}
@@ -0,0 +1,504 @@
// frontend/src/pages/bellcloud/devices/tabs/BellsTab.jsx
// Bell Mechanisms tab — displays Bell Commander/Guard status, connected bell count,
// master switch, and per-bell glass cards with output, timing, size, and strike stats.
import { useState, useCallback } from 'react'
import api from '@/lib/api'
import { useToast } from '@/components/ui/Toast'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import Icon from '@/components/ui/Icon'
import ConfirmDialog from '@/components/ui/ConfirmDialog'
import certificationImg from '@/assets/striker-mechanisms/certification.png'
import strikerSize1 from '@/assets/striker-mechanisms/size-1.jpg'
import strikerSize2 from '@/assets/striker-mechanisms/size-2.jpg'
import strikerSize3 from '@/assets/striker-mechanisms/size-3.jpg'
import strikerSize4 from '@/assets/striker-mechanisms/size-4.jpg'
import strikerSize5 from '@/assets/striker-mechanisms/size-5.jpg'
import strikerSize6 from '@/assets/striker-mechanisms/size-6.jpg'
const STRIKER_IMAGES = { 1: strikerSize1, 2: strikerSize2, 3: strikerSize3, 4: strikerSize4, 5: strikerSize5, 6: strikerSize6 }
// ─── Timing → Size mapping (from archive) ────────────────────────────────────
function getStrikerSize(ms) {
if (!Number.isFinite(ms)) return null
if (ms <= 89) return 1
if (ms <= 94) return 2
if (ms <= 99) return 3
if (ms <= 109) return 4
if (ms <= 119) return 5
return 6
}
const ORDINAL_NAMES = [
'First', 'Second', 'Third', 'Fourth', 'Fifth',
'Sixth', 'Seventh', 'Eighth', 'Ninth', 'Tenth',
]
// ─── Indicator pill ───────────────────────────────────────────────────────────
function Indicator({ label, value, yesLabel = 'Operational', noLabel = 'Disabled' }) {
const isUnknown = typeof value !== 'boolean'
const variant = isUnknown ? 'neutral' : value ? 'success' : 'danger'
const text = isUnknown ? 'Unknown' : value ? yesLabel : noLabel
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)', alignItems: 'flex-start' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-muted)',
textTransform: 'uppercase',
letterSpacing: 'var(--tracking-wide)',
}}>
{label}
</span>
<StatusBadge variant={variant}>{text}</StatusBadge>
</div>
)
}
// ─── Bell card (glass) ────────────────────────────────────────────────────────
const BELL_GLASS_CARD = {
background: 'rgba(28, 32, 38, 0.30)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-xl)',
boxShadow: 'var(--shadow-card), var(--shadow-md)',
display: 'flex',
flexDirection: 'column',
breakInside: 'avoid',
}
const SPEC_TILE = {
background: 'rgba(28, 32, 38, 0.40)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
borderRadius: 'var(--radius-md)',
padding: 'var(--space-3)',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 'var(--space-1)',
textAlign: 'center',
flex: 1,
}
function BellCard({ index, output, hammingMs, strikeCount, requestingCounters, isBellSystems }) {
const ordinal = ORDINAL_NAMES[index] ?? `${index + 1}th`
const strikerSize = getStrikerSize(hammingMs)
const isDisabled = Number.isFinite(output) && Number(output) === 0
const [hovered, setHovered] = useState(false)
const strikerImg = strikerSize ? STRIKER_IMAGES[strikerSize] : null
return (
<article
style={{
...BELL_GLASS_CARD,
boxShadow: hovered
? 'var(--shadow-card), var(--shadow-lg), 0 0 0 1px rgba(192, 193, 255, 0.35), 0 0 32px rgba(192, 193, 255, 0.22)'
: 'var(--shadow-card), var(--shadow-md)',
transition: 'box-shadow 0.25s ease',
}}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
{/* Hero image — fades into card body */}
<div style={{
position: 'relative',
height: '220px',
background: 'rgba(10, 14, 20, 0.80)',
overflow: 'hidden',
flexShrink: 0,
borderRadius: 'var(--radius-xl) var(--radius-xl) 0 0',
}}>
{strikerImg ? (
<img
src={strikerImg}
alt={`Size ${strikerSize} striker mechanism`}
style={{
width: '100%',
height: '100%',
objectFit: 'cover',
objectPosition: 'center bottom',
opacity: 1,
transform: hovered ? 'scale(1.15)' : 'scale(1.05)',
transition: 'transform 0.4s ease',
}}
/>
) : (
<div style={{
width: '100%',
height: '100%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<Icon name="bell" size={48} color="var(--color-text-muted)" />
</div>
)}
{/* Bottom fade — bleeds over the name below */}
<div style={{
position: 'absolute',
inset: 0,
background: 'linear-gradient(to top, rgba(28, 32, 38, 1) 0%, rgba(28, 32, 38, 0.55) 40%, transparent 70%)',
pointerEvents: 'none',
}} />
{/* Name overlaid at the bottom of the image */}
<div style={{
position: 'absolute',
bottom: 'var(--space-4)',
left: 'var(--space-4)',
right: 'var(--space-4)',
}}>
<h3 style={{
fontFamily: 'var(--font-family-display)',
letterSpacing: 'var(--tracking-tight)',
color: 'var(--color-text-primary)',
lineHeight: 1.2,
margin: 0,
}}>
<span style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-medium)' }}>
{strikerSize ? 'Size ' : (isBellSystems ? 'Striker' : `${ordinal} Bell`)}
</span>
{strikerSize && (
<span style={{ fontSize: 'var(--font-size-xl)', fontWeight: 'var(--font-weight-bold)' }}>
{strikerSize}
</span>
)}
{strikerSize && (
<span style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-medium)' }}>
{' Striker'}
</span>
)}
</h3>
<p style={{
fontSize: 'var(--font-size-sm)',
color: 'var(--color-text-muted)',
marginTop: '2px',
}}>
{ordinal} Bell
</p>
</div>
</div>
{/* Card body */}
<div style={{ padding: 'var(--space-4)', display: 'flex', flexDirection: 'column', gap: 'var(--space-4)', flex: 1 }}>
{/* Spec tiles: Output · Timing · Size */}
<div style={{ display: 'flex', gap: 'var(--space-2)' }}>
<div style={SPEC_TILE}>
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
Output
</span>
<span style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-bold)', color: isDisabled ? 'var(--color-danger)' : 'var(--color-text-secondary)' }}>
{isDisabled ? 'Disabled' : Number.isFinite(output) ? `Out ${output}` : '—'}
</span>
</div>
<div style={SPEC_TILE}>
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
Timing
</span>
<span style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-bold)', color: 'var(--color-text-secondary)', fontFamily: 'var(--font-family-mono)' }}>
{Number.isFinite(hammingMs) ? `${hammingMs} ms` : '—'}
</span>
</div>
<div style={SPEC_TILE}>
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-muted)', textTransform: 'uppercase', letterSpacing: 'var(--tracking-wide)' }}>
Size
</span>
<span style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-bold)', color: 'var(--color-text-secondary)' }}>
{strikerSize ? `Size ${strikerSize}` : '—'}
</span>
</div>
</div>
{/* Strike count footer */}
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}}>
<div style={{ display: 'flex', flexDirection: 'column', gap: '2px' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-more-muted)',
textTransform: 'uppercase',
letterSpacing: 'var(--tracking-wide)',
opacity: 0.7,
}}>
Lifetime Strikes
</span>
{requestingCounters ? (
<span style={{ fontSize: 'var(--font-size-base)', color: 'var(--color-text-muted)', fontFamily: 'var(--font-family-mono)' }}>…</span>
) : Number.isFinite(strikeCount) ? (
<span style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', fontFamily: 'var(--font-family-mono)' }}>
{strikeCount.toLocaleString()}
</span>
) : (
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
No data available
</span>
)}
</div>
{isBellSystems && (
<img
src={certificationImg}
alt="BellSystems Certified"
style={{ width: 36, height: 36, objectFit: 'contain', opacity: 0.90 }}
/>
)}
</div>
</div>
</article>
)
}
// ─── BellsTab ─────────────────────────────────────────────────────────────────
export default function BellsTab({
device,
attr,
canEdit,
loadDevice,
sendMqttCommand,
onEditBellOutputs,
}) {
const { toast } = useToast()
const [togglingCommander, setTogglingCommander] = useState(false)
const [requestingCounters, setRequestingCounters] = useState(false)
const [liveCounters] = useState(null)
const [confirmDisable, setConfirmDisable] = useState(false)
// Derived data
const bellOutputs = attr?.bellOutputs || []
const hammerTimings = attr?.hammerTimings || []
const totalBells = attr?.totalBells || 0
const hasBells = attr?.hasBells ?? false
const bellGuardOn = attr?.bellGuardOn ?? false
// Request strike counters via MQTT
const requestStrikeCounters = useCallback(async () => {
if (!sendMqttCommand) return
setRequestingCounters(true)
try {
await sendMqttCommand('system_info', { action: 'report_status' })
} finally {
// Will be cleared when live data arrives, or after timeout
setTimeout(() => setRequestingCounters(false), 8000)
}
}, [sendMqttCommand])
// Toggle Bell Commander (master switch)
const handleToggleCommander = async (newVal) => {
setTogglingCommander(true)
try {
await api.put(`/devices/${device.id || device.device_id}`, {
device_attributes: { hasBells: newVal },
})
await loadDevice()
toast.success(
newVal ? 'Bell Commander Enabled' : 'Bell Commander Disabled',
newVal ? 'All bell mechanisms are now active.' : 'All bell mechanisms have been disabled.'
)
} catch (err) {
toast.danger('Error', err.message || 'Failed to update Bell Commander.')
} finally {
setTogglingCommander(false)
}
}
const handleCommanderToggleRequest = () => {
if (hasBells) {
// Disabling — confirm first
setConfirmDisable(true)
} else {
handleToggleCommander(true)
}
}
const hasData = bellOutputs.length > 0
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
{/* ── Status overview bar ───────────────────────────────────────────── */}
<div style={{
background: 'rgba(28, 32, 38, 0.30)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-xl)',
boxShadow: 'var(--shadow-card)',
padding: 'var(--space-5) var(--space-6)',
display: 'flex',
alignItems: 'center',
flexWrap: 'wrap',
gap: 'var(--space-6)',
}}>
{/* Indicators */}
<div style={{ display: 'flex', gap: 'var(--space-12)', flex: 1, flexWrap: 'wrap' }}>
<Indicator label="Bell Commander" value={hasBells} yesLabel="Operational" noLabel="Disabled" />
<Indicator label="Bell Guard" value={bellGuardOn} yesLabel="Operational" noLabel="Disabled" />
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)', alignItems: 'flex-start' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-muted)',
textTransform: 'uppercase',
letterSpacing: 'var(--tracking-wide)',
}}>
Connected Bells
</span>
<span style={{
fontSize: 'var(--font-size-base)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-primary)',
}}>
{Number.isFinite(totalBells) ? (totalBells === 1 ? '1 Bell' : `${totalBells} Bells`) : '—'}
</span>
</div>
</div>
{/* Actions */}
{canEdit && (
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexShrink: 0 }}>
{/* Master toggle */}
<Button
variant={hasBells ? 'danger' : 'success'}
size="md"
loading={togglingCommander}
onClick={handleCommanderToggleRequest}
>
{hasBells ? 'Disable Commander' : 'Enable Commander'}
</Button>
{/* Edit Outputs */}
<Button variant="primary" size="md" onClick={onEditBellOutputs}>
Edit Outputs
</Button>
</div>
)}
</div>
{/* ── Bell cards ────────────────────────────────────────────────────── */}
{!hasData ? (
/* Empty state */
<div style={{
background: 'rgba(28, 32, 38, 0.30)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-xl)',
padding: 'var(--space-12)',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 'var(--space-4)',
textAlign: 'center',
}}>
<div style={{
width: 56,
height: 56,
borderRadius: 'var(--radius-full)',
background: 'var(--color-bg-elevated)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<Icon name="bell" size={24} color="var(--color-text-muted)" />
</div>
<div>
<p style={{ fontSize: 'var(--font-size-md)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-secondary)' }}>
No Bell Mechanisms Configured
</p>
<p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 'var(--space-1)' }}>
Use Edit Outputs to assign bells and configure their output channels.
</p>
</div>
{canEdit && (
<Button variant="primary" size="sm" onClick={onEditBellOutputs}>
Configure Bell Outputs
</Button>
)}
</div>
) : (
<div>
{/* Strike counter refresh */}
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 'var(--space-4)',
}}>
<h2 style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-xl)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-tight)',
color: 'var(--color-text-primary)',
}}>
Bell Mechanisms
</h2>
<Button
variant="ghost"
size="sm"
onClick={requestStrikeCounters}
loading={requestingCounters}
>
Refresh Strike Counts
</Button>
</div>
{/* Grid of bell cards */}
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))',
gap: 'var(--space-5)',
}}>
{bellOutputs.map((output, i) => (
<BellCard
key={i}
index={i}
output={output}
hammingMs={hammerTimings[i]}
strikeCount={liveCounters?.[i] ?? null}
requestingCounters={requestingCounters}
isBellSystems={true}
/>
))}
</div>
</div>
)}
{/* ── Confirm disable dialog ────────────────────────────────────────── */}
<ConfirmDialog
open={confirmDisable}
variant="danger"
title="Disable Bell Commander"
message="Are you sure you want to disable the Bell Commander? This will deactivate all bell mechanisms on this device."
confirmLabel="Disable"
onConfirm={() => {
setConfirmDisable(false)
handleToggleCommander(false)
}}
onCancel={() => setConfirmDisable(false)}
loading={togglingCommander}
/>
</div>
)
}
@@ -0,0 +1,643 @@
// frontend/src/pages/bellcloud/devices/tabs/ClockTab.jsx
import { useState, useEffect, useRef } from 'react'
import api from '@/lib/api'
import Card from '@/components/ui/Card'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import { useToast } from '@/components/ui/Toast'
import SyncClockModal from '@/modals/bellcloud/devices/SyncClockModal'
// ─── Helpers ──────────────────────────────────────────────────────────────────
function extractTime(tsStr) {
if (!tsStr) return null
const d = new Date(
tsStr.replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+(\d{4})/, 'UTC')
)
if (!isNaN(d.getTime())) {
return `${d.getUTCHours().toString().padStart(2, '0')}:${d.getUTCMinutes().toString().padStart(2, '0')}`
}
const match = tsStr.match(/(\d{1,2}):(\d{2})/)
return match ? `${match[1].padStart(2, '0')}:${match[2]}` : null
}
function msToSeconds(ms) {
if (ms == null || ms === 0) return null
return `${(ms / 1000).toFixed(1)}s`
}
function bellLabel(n) {
if (!n || n === 0) return 'Disabled'
return `Bell ${n}`
}
function outputLabel(n) {
if (!n || n === 0) return 'Disabled'
return `Output ${n}`
}
function silenceLabel(isOn, from, to) {
if (!isOn) return 'Off'
const f = extractTime(from)
const t = extractTime(to)
if (f && t) return `${f} – ${t}`
return 'On'
}
// ─── Analog Clock Face ────────────────────────────────────────────────────────
function AnalogClock({ time, label, variant = 'primary' }) {
const canvasRef = useRef(null)
useEffect(() => {
const canvas = canvasRef.current
if (!canvas) return
const ctx = canvas.getContext('2d')
const size = canvas.width
const cx = size / 2
const cy = size / 2
const r = size / 2 - 4
const h = time.getHours() % 12
const m = time.getMinutes()
const s = time.getSeconds()
const isPrimary = variant === 'primary'
const accentColor = isPrimary ? 'rgba(192,193,255,0.9)' : 'rgba(192,193,255,0.35)'
const faceColor = isPrimary ? 'rgba(192,193,255,0.06)' : 'rgba(192,193,255,0.03)'
const rimColor = isPrimary ? 'rgba(192,193,255,0.25)' : 'rgba(192,193,255,0.10)'
const tickColor = isPrimary ? 'rgba(192,193,255,0.30)' : 'rgba(192,193,255,0.12)'
const hourHandColor = isPrimary ? 'rgba(192,193,255,1)' : 'rgba(192,193,255,0.45)'
const minuteHandColor = isPrimary ? 'rgba(210,187,255,0.85)' : 'rgba(210,187,255,0.35)'
const secondHandColor = isPrimary ? 'rgba(255,92,92,0.85)' : 'rgba(255,92,92,0.4)'
const centerDotColor = isPrimary ? '#c0c1ff' : 'rgba(192,193,255,0.4)'
ctx.clearRect(0, 0, size, size)
// Face
ctx.beginPath()
ctx.arc(cx, cy, r, 0, Math.PI * 2)
ctx.fillStyle = faceColor
ctx.fill()
// Outer glow for primary
if (isPrimary) {
const grad = ctx.createRadialGradient(cx, cy, r - 2, cx, cy, r + 8)
grad.addColorStop(0, 'rgba(192,193,255,0.12)')
grad.addColorStop(1, 'rgba(192,193,255,0)')
ctx.beginPath()
ctx.arc(cx, cy, r + 4, 0, Math.PI * 2)
ctx.fillStyle = grad
ctx.fill()
}
// Rim
ctx.beginPath()
ctx.arc(cx, cy, r, 0, Math.PI * 2)
ctx.strokeStyle = rimColor
ctx.lineWidth = isPrimary ? 1.5 : 1
ctx.stroke()
// Ticks
for (let i = 0; i < 60; i++) {
const angle = (i / 60) * Math.PI * 2 - Math.PI / 2
const isHour = i % 5 === 0
const inner = isHour ? r - 12 : r - 7
ctx.beginPath()
ctx.moveTo(cx + Math.cos(angle) * inner, cy + Math.sin(angle) * inner)
ctx.lineTo(cx + Math.cos(angle) * (r - 2), cy + Math.sin(angle) * (r - 2))
ctx.strokeStyle = isHour ? accentColor : tickColor
ctx.lineWidth = isHour ? 1.5 : 0.75
ctx.stroke()
}
// Hour hand
const hourAngle = ((h + m / 60) / 12) * Math.PI * 2 - Math.PI / 2
ctx.beginPath()
ctx.moveTo(cx, cy)
ctx.lineTo(cx + Math.cos(hourAngle) * r * 0.52, cy + Math.sin(hourAngle) * r * 0.52)
ctx.strokeStyle = hourHandColor
ctx.lineWidth = isPrimary ? 3 : 2
ctx.lineCap = 'round'
ctx.stroke()
// Minute hand
const minAngle = ((m + s / 60) / 60) * Math.PI * 2 - Math.PI / 2
ctx.beginPath()
ctx.moveTo(cx, cy)
ctx.lineTo(cx + Math.cos(minAngle) * r * 0.72, cy + Math.sin(minAngle) * r * 0.72)
ctx.strokeStyle = minuteHandColor
ctx.lineWidth = isPrimary ? 2 : 1.5
ctx.lineCap = 'round'
ctx.stroke()
// Second hand
const secAngle = (s / 60) * Math.PI * 2 - Math.PI / 2
ctx.beginPath()
ctx.moveTo(cx, cy)
ctx.lineTo(cx + Math.cos(secAngle) * r * 0.82, cy + Math.sin(secAngle) * r * 0.82)
ctx.strokeStyle = secondHandColor
ctx.lineWidth = 1
ctx.lineCap = 'round'
ctx.stroke()
// Center dot
ctx.beginPath()
ctx.arc(cx, cy, isPrimary ? 4 : 3, 0, Math.PI * 2)
ctx.fillStyle = centerDotColor
ctx.fill()
}, [time, variant])
const digitalTime = `${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}:${time.getSeconds().toString().padStart(2, '0')}`
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'var(--space-3)' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
color: variant === 'primary' ? 'var(--color-primary)' : 'var(--color-text-muted)',
}}>
{label}
</span>
<canvas
ref={canvasRef}
width={160}
height={160}
style={{ display: 'block' }}
aria-label={`${label}: ${digitalTime}`}
/>
<div style={{
fontFamily: 'var(--font-family-mono)',
fontSize: 'var(--font-size-base)',
fontWeight: 'var(--font-weight-medium)',
color: variant === 'primary' ? 'var(--color-text-primary)' : 'var(--color-text-muted)',
letterSpacing: '0.04em',
}}>
{digitalTime}
</div>
</div>
)
}
// ─── SettingRow ───────────────────────────────────────────────────────────────
function SettingRow({ label, value, mono = false, badge }) {
return (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 'var(--space-3)', minHeight: 32 }}>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', flexShrink: 0 }}>
{label}
</span>
<span style={{
fontSize: 'var(--font-size-sm)',
color: value === '—' || value === 'Disabled' || value === 'Off' ? 'var(--color-text-muted)' : 'var(--color-text-primary)',
fontFamily: mono ? 'var(--font-family-mono)' : 'inherit',
fontWeight: 'var(--font-weight-medium)',
textAlign: 'right',
}}>
{badge ? badge : value ?? '—'}
</span>
</div>
)
}
function Divider() {
return (
<div style={{ height: 1, backgroundColor: 'var(--color-border)', margin: 'var(--space-1) 0' }} />
)
}
// ─── HeroTile ─────────────────────────────────────────────────────────────────
function HeroTile({ label, value, flash = false }) {
return (
<div style={{
backgroundColor: 'rgba(28, 32, 38, 0.40)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
border: `1px solid ${flash ? 'var(--color-warning)' : 'var(--color-border)'}`,
borderRadius: 'var(--radius-lg)',
padding: 'var(--space-3) var(--space-4)',
display: 'flex',
flexDirection: 'column',
gap: 'var(--space-1)',
transition: 'border-color 0.3s',
animation: flash ? 'tile-flash 0.6s ease 3' : 'none',
}}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
color: flash ? 'var(--color-warning)' : 'var(--color-text-muted)',
transition: 'color 0.3s',
}}>
{label}
</span>
<span style={{
fontSize: 'var(--font-size-xl)',
fontWeight: 'var(--font-weight-bold)',
color: value ? 'var(--color-text-primary)' : 'var(--color-text-muted)',
fontFamily: 'var(--font-family-display)',
letterSpacing: 'var(--tracking-tight)',
lineHeight: 1.1,
fontStyle: value ? 'normal' : 'italic',
}}>
{value ?? 'not set'}
</span>
</div>
)
}
// ─── ClockTab ─────────────────────────────────────────────────────────────────
export default function ClockTab({
device,
canEdit,
clock,
attr,
onEditClockSettings,
onEditAlerts,
onEditBacklight,
onDeviceUpdated,
}) {
const [now, setNow] = useState(new Date())
const [showSync, setShowSync] = useState(false)
const [flashFields, setFlashFields] = useState(false)
const [togglingClock, setTogglingClock] = useState(false)
const { toast } = useToast()
useEffect(() => {
const id = setInterval(() => setNow(new Date()), 1000)
return () => clearInterval(id)
}, [])
// ── Derived values ────────────────────────────────────────────────────────
const hasClock = attr?.hasClock ?? false
const clockOutputs = clock?.clockOutputs || []
const clockTimings = clock?.clockTimings || []
const oddOut = clockOutputs[0] || 0
const evenOut = clockOutputs[1] || 0
const runPulse = clockTimings[0]
const pauseTime = clockTimings[1]
const alertType = clock?.ringAlerts || 'disabled'
const alertMasterOn = clock?.ringAlertsMasterOn ?? false
const ringIntervals = clock?.ringIntervals
const hourBell = clock?.hourAlertsBell || 0
const halfBell = clock?.halfhourAlertsBell || 0
const quarterBell = clock?.quarterAlertsBell || 0
const isDaySilenceOn = clock?.isDaySilenceOn ?? false
const isNightSilenceOn = clock?.isNightSilenceOn ?? false
const backlightOn = clock?.isBacklightAutomationOn ?? false
const backlightOutput = clock?.backlightOutput || 0
const backlightOnTime = extractTime(clock?.backlightTurnOnTime)
const backlightOffTime = extractTime(clock?.backlightTurnOffTime)
const timezone = attr?.timezone || device?.timezone || null
const ntpServer = attr?.ntpServer || attr?.networkSettings?.ntpServer || null
const autoDst = attr?.autoDST ?? false
const alertTypeLabel =
alertType === 'single' ? 'Single Fire' :
alertType === 'multi' ? 'Hour Indicating' :
'Disabled'
const alertVariant = alertMasterOn ? 'success' : 'neutral'
// All 4 hero fields must be set before ENABLING the master switch
const allFieldsSet = oddOut > 0 && evenOut > 0 && runPulse > 0 && pauseTime > 0
const handleMasterToggleClick = async () => {
if (!canEdit || togglingClock) return
// Trying to enable but required fields are missing — flash tiles and block
if (!hasClock && !allFieldsSet) {
setFlashFields(true)
setTimeout(() => setFlashFields(false), 2200)
return
}
const deviceId = device?.id || device?.device_id
const newValue = !hasClock
setTogglingClock(true)
try {
const updated = await api.put(`/devices/${deviceId}`, {
device_attributes: { ...(attr || {}), hasClock: newValue },
})
if (onDeviceUpdated) {
// If API returns the full device object, use it; otherwise patch manually
if (updated?.device_attributes !== undefined) {
onDeviceUpdated(updated)
} else {
onDeviceUpdated(prev => ({
...prev,
device_attributes: { ...(prev?.device_attributes || {}), hasClock: newValue },
}))
}
}
toast.success(newValue ? 'Clock enabled' : 'Clock disabled', '')
} catch (err) {
toast.danger('Error', err.message || 'Failed to update clock status.')
} finally {
setTogglingClock(false)
}
}
// Backlight period string
const backlightPeriod = backlightOn && backlightOnTime && backlightOffTime
? `${backlightOnTime} – ${backlightOffTime}`
: null
// ── Render ─────────────────────────────────────────────────────────────────
return (
<>
{/* Flash keyframe injected once */}
<style>{`
@keyframes tile-flash {
0%, 100% { border-color: var(--color-border); }
50% { border-color: var(--color-warning); box-shadow: 0 0 0 2px rgba(251,191,36,0.18); }
}
`}</style>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
{/* ── Hero ──────────────────────────────────────────────────────────── */}
<div style={{
position: 'relative',
borderRadius: 'var(--radius-xl)',
backgroundColor: 'rgba(28, 32, 38, 0.30)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
border: '1px solid var(--color-border)',
boxShadow: 'var(--shadow-card), var(--shadow-md)',
overflow: 'hidden',
padding: 'var(--space-6) var(--space-8)',
}}>
<div aria-hidden="true" style={{
position: 'absolute', inset: 0, pointerEvents: 'none',
background: 'radial-gradient(ellipse 50% 80% at 85% 50%, rgba(192,193,255,0.05) 0%, transparent 70%)',
}} />
<div style={{
position: 'relative',
display: 'flex',
alignItems: 'center',
gap: 'var(--space-8)',
flexWrap: 'wrap',
}}>
{/* Left — settings panel */}
<div style={{ flex: 1, minWidth: 260, display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
{/* Title + toggle */}
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
<span style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-xl)',
fontWeight: 'var(--font-weight-bold)',
letterSpacing: 'var(--tracking-tight)',
color: 'var(--color-text-primary)',
}}>
Master Control
</span>
<button
type="button"
role="switch"
aria-checked={hasClock}
aria-label="Toggle clock"
onClick={handleMasterToggleClick}
disabled={togglingClock}
style={{
position: 'relative',
width: 36,
height: 20,
borderRadius: 'var(--radius-full)',
backgroundColor: hasClock ? 'var(--color-success)' : 'var(--color-bg-island)',
border: `1px solid ${hasClock ? 'var(--color-success)' : 'var(--color-border-strong)'}`,
flexShrink: 0,
cursor: canEdit && !togglingClock ? 'pointer' : 'default',
transition: 'background-color 0.2s, border-color 0.2s',
padding: 0,
opacity: togglingClock ? 0.6 : 1,
}}
>
<div style={{
position: 'absolute',
top: 2,
left: hasClock ? 17 : 2,
width: 14,
height: 14,
borderRadius: 'var(--radius-full)',
backgroundColor: hasClock ? 'var(--color-text-inverse)' : 'var(--color-text-muted)',
transition: 'left 0.2s',
}} />
</button>
<span style={{
fontSize: 'var(--font-size-sm)',
color: hasClock ? 'var(--color-success)' : 'var(--color-text-muted)',
fontWeight: 'var(--font-weight-medium)',
}}>
{hasClock ? 'Active' : 'Inactive'}
</span>
</div>
{/* 2×2 tile grid */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
<HeroTile label="Pulse Duration" value={msToSeconds(runPulse)} flash={flashFields && !runPulse} />
<HeroTile label="Pause Duration" value={msToSeconds(pauseTime)} flash={flashFields && !pauseTime} />
<HeroTile label="ODD Output" value={oddOut ? outputLabel(oddOut) : null} flash={flashFields && !oddOut} />
<HeroTile label="EVEN Output" value={evenOut ? outputLabel(evenOut) : null} flash={flashFields && !evenOut} />
</div>
{/* Actions row */}
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
{canEdit && (
<Button variant="ghost" size="sm" onClick={onEditClockSettings}>Edit Settings</Button>
)}
<button
type="button"
onClick={() => setShowSync(true)}
style={{
background: 'none', border: 'none',
padding: '0 var(--space-1)',
fontSize: 'var(--font-size-sm)',
color: 'var(--color-primary)',
cursor: 'pointer',
opacity: 0.75,
transition: 'opacity 0.15s',
}}
onMouseEnter={e => (e.currentTarget.style.opacity = 1)}
onMouseLeave={e => (e.currentTarget.style.opacity = 0.75)}
>
Sync Clocktower Time
</button>
</div>
</div>
{/* Right — clocks, with equal breathing room on all sides */}
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 'var(--space-12)', padding: '0 var(--space-8)' }}>
<AnalogClock time={now} label="RTC Time" variant="primary" />
<AnalogClock time={now} label="Clocktower" variant="primary" />
</div>
</div>
</div>
{/* ── Cards grid — 3 columns ────────────────────────────────────────── */}
<div className="masonry-grid masonry-grid--3">
{/* Alert Settings */}
<Card
title="Alert Settings"
action={canEdit && (
<Button variant="ghost" size="sm" onClick={onEditAlerts}>Edit</Button>
)}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
{/* Master + type inline */}
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexWrap: 'wrap' }}>
<StatusBadge variant={alertVariant}>{alertMasterOn ? 'Enabled' : 'Disabled'}</StatusBadge>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>·</span>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', fontWeight: 'var(--font-weight-medium)' }}>
{alertTypeLabel}
</span>
{alertType === 'multi' && ringIntervals && (
<>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>·</span>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
Tempo {msToSeconds(ringIntervals)}
</span>
</>
)}
</div>
<Divider />
{/* Bell assignments + silence periods — shared 3-column grid */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 'var(--space-2) var(--space-2)', rowGap: 'var(--space-4)' }}>
{[
{ label: 'Hours', value: bellLabel(hourBell) },
{ label: 'Half-Hours', value: bellLabel(halfBell) },
{ label: 'Quarters', value: bellLabel(quarterBell) },
].map(({ label, value }) => (
<div key={label} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
}}>
{label}
</span>
<span style={{
fontSize: 'var(--font-size-base)',
fontWeight: 'var(--font-weight-semibold)',
color: value === 'Disabled' ? 'var(--color-text-muted)' : 'var(--color-text-primary)',
fontFamily: 'var(--font-family-display)',
letterSpacing: 'var(--tracking-tight)',
}}>
{value}
</span>
</div>
))}
{/* Silence periods in cols 1–2, col 3 intentionally empty */}
{[
{ label: 'Day Silence', isOn: isDaySilenceOn, from: clock?.daySilenceFrom, to: clock?.daySilenceTo },
{ label: 'Night Silence', isOn: isNightSilenceOn, from: clock?.nightSilenceFrom, to: clock?.nightSilenceTo },
].map(({ label, isOn, from, to }) => (
<div key={label} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
<span style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
}}>
{label}
</span>
<span style={{
fontSize: 'var(--font-size-base)',
fontWeight: 'var(--font-weight-semibold)',
color: isOn ? 'var(--color-text-primary)' : 'var(--color-text-muted)',
fontFamily: isOn ? 'var(--font-family-mono)' : 'inherit',
letterSpacing: isOn ? '0.03em' : 0,
}}>
{silenceLabel(isOn, from, to)}
</span>
</div>
))}
</div>
</div>
</Card>
{/* Backlight Automation */}
<Card
title="Backlight Automation"
action={canEdit && (
<Button variant="ghost" size="sm" onClick={onEditBacklight}>Edit</Button>
)}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
<SettingRow
label="Automation"
badge={<StatusBadge variant={backlightOn ? 'success' : 'neutral'}>{backlightOn ? 'Automated' : 'Disabled'}</StatusBadge>}
/>
<SettingRow label="Output" value={outputLabel(backlightOutput)} />
{backlightOn && (
<SettingRow
label="Period"
value={backlightPeriod || '—'}
mono={!!backlightPeriod}
/>
)}
</div>
</Card>
{/* Network & Time */}
<Card title="Network & Time">
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
<SettingRow label="Timezone" value={timezone || '—'} mono={!!timezone} />
<SettingRow label="NTP Server" value={ntpServer || '—'} mono={!!ntpServer} />
<SettingRow
label="Auto-DST"
badge={
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
<StatusBadge variant="neutral">{autoDst ? 'Enabled' : 'Disabled'}</StatusBadge>
<span style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
backgroundColor: 'rgba(28, 32, 38, 0.40)',
padding: '2px var(--space-2)',
borderRadius: 'var(--radius-sm)',
border: '1px solid var(--color-border)',
}}>
Coming Soon
</span>
</div>
}
/>
</div>
{canEdit && (
<div style={{ marginTop: 'var(--space-4)', paddingTop: 'var(--space-4)', borderTop: '1px solid var(--color-border)' }}>
<p style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
Timezone and NTP configuration are managed via device attributes. Auto-DST adjustment is pending implementation.
</p>
</div>
)}
</Card>
</div>
</div>
<SyncClockModal open={showSync} onClose={() => setShowSync(false)} device={device} />
</>
)
}
@@ -0,0 +1,5 @@
// frontend/src/pages/bellcloud/devices/tabs/ControlTab.jsx
export default function ControlTab({ device, canEdit, onDeviceUpdated }) {
return null
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,683 @@
// frontend/src/pages/bellcloud/devices/tabs/ManageTab.jsx
// Manage tab — Device Users + Device Notes + Linked Issues
import { useState, useEffect, 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 ConfirmDialog from '@/components/ui/ConfirmDialog'
import Icon from '@/components/ui/Icon'
import { fmtDateMedium, fmtRelative } from '@/lib/formatters'
import AddDeviceUserModal from '@/modals/bellcloud/devices/AddDeviceUserModal'
import DeviceNoteModal from '@/modals/bellcloud/devices/DeviceNoteModal'
import EntryFormModal from '@/modals/crm/helpdesk/EntryFormModal'
// ─── Visual constants (match OverviewTab's GlassCard aesthetic) ───────────────
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.55)'
const BLUR = 'blur(12px)'
// ─── Status/severity maps (match IssuesTab constants) ─────────────────────────
const STATUS_META = {
open: { label: 'Open', color: 'var(--color-danger)', bg: 'var(--color-danger-bg)' },
researching: { label: 'Researching', color: 'var(--color-warning)', bg: 'var(--color-warning-bg)' },
resolved: { label: 'Resolved', color: 'var(--color-success)', bg: 'var(--color-success-bg)' },
}
const SEVERITY_META = {
low: { label: 'Low', color: 'var(--color-info)' },
medium: { label: 'Medium', color: 'var(--color-warning)' },
high: { label: 'High', color: 'var(--color-danger)' },
critical: { label: 'Critical', color: 'var(--color-danger)', breathe: true },
}
// ─── Sub-components ───────────────────────────────────────────────────────────
function SectionLabel({ children }) {
return (
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-muted)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
}}>
{children}
</span>
)
}
function GlassCard({ children, style = {} }) {
return (
<div style={{
background: GLASS,
backdropFilter: BLUR,
WebkitBackdropFilter: BLUR,
border: '1px solid var(--color-border)',
borderRadius: 'var(--radius-xl)',
boxShadow: 'var(--shadow-card), var(--shadow-md)',
...style,
}}>
{children}
</div>
)
}
function CardHeader({ label, count, action }) {
return (
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: 'var(--space-4) var(--space-5)',
borderBottom: '1px solid var(--color-border)',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
<SectionLabel>{label}</SectionLabel>
{count != null && (
<span style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
background: GLASS_INNER,
padding: '2px var(--space-2)',
borderRadius: 'var(--radius-full)',
border: '1px solid var(--color-border)',
lineHeight: 1.4,
}}>
{count}
</span>
)}
</div>
{action}
</div>
)
}
function EmptySlate({ icon, message, action }) {
return (
<div style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 'var(--space-3)',
padding: 'var(--space-8) var(--space-6)',
color: 'var(--color-text-muted)',
}}>
<div style={{ opacity: 0.35 }}>{icon}</div>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', textAlign: 'center' }}>{message}</p>
{action}
</div>
)
}
function StatusPill({ status }) {
const m = STATUS_META[status] || { label: status, color: 'var(--color-text-muted)', bg: 'var(--color-bg-elevated)' }
return (
<span style={{
display: 'inline-flex', alignItems: 'center', gap: 5,
padding: '2px 8px',
borderRadius: 'var(--radius-full)',
backgroundColor: m.bg,
border: `1px solid ${m.color}33`,
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: m.color,
whiteSpace: 'nowrap',
flexShrink: 0,
}}>
<span style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: m.color, flexShrink: 0 }} />
{m.label}
</span>
)
}
function SeverityBars({ severity }) {
if (!severity) return null
const m = SEVERITY_META[severity] || { label: severity, color: 'var(--color-text-muted)' }
const bars = { low: 1, medium: 2, high: 3, critical: 4 }[severity] || 1
return (
<span
className={m.breathe ? 'severity-critical' : undefined}
style={{ display: 'inline-flex', alignItems: 'center', gap: 4, flexShrink: 0 }}
>
<span style={{ display: 'flex', alignItems: 'flex-end', gap: 2, height: 12 }}>
{[1, 2, 3, 4].map(b => (
<span key={b} style={{
width: 3,
height: 2 + b * 2,
borderRadius: 1,
backgroundColor: b <= bars ? m.color : 'var(--color-bg-island)',
display: 'block',
}} />
))}
</span>
<span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: m.color }}>
{m.label}
</span>
</span>
)
}
// ─── ManageTab ────────────────────────────────────────────────────────────────
export default function ManageTab({ device, canEdit, deviceUsers: propUsers, usersLoading: propUsersLoading }) {
const navigate = useNavigate()
const { toast } = useToast()
const id = device?.id || device?.device_id
// ── Users state ────────────────────────────────────────────────────────────
// We manage our own copy so we can add/remove without refetching the entire device
const [users, setUsers] = useState(propUsers || [])
const [usersLoading, setUsersLoading] = useState(propUsersLoading || false)
const [removingUser, setRemovingUser] = useState(null)
const [confirmRemoveUser, setConfirmRemoveUser] = useState(null)
const [showAddUser, setShowAddUser] = useState(false)
// Sync from parent prop on mount / prop change
useEffect(() => {
if (propUsers) setUsers(propUsers)
}, [propUsers])
useEffect(() => {
setUsersLoading(propUsersLoading)
}, [propUsersLoading])
const reloadUsers = useCallback(async () => {
if (!id) return
setUsersLoading(true)
try {
const data = await api.get(`/devices/${id}/users`)
setUsers(data.users || [])
} catch {
// silent — parent has already shown this device's users
} finally {
setUsersLoading(false)
}
}, [id])
const handleUserAdded = (user) => {
setUsers(prev => [...prev, user])
toast.success('User added', `${user.display_name || user.email} now has access.`)
}
const handleRemoveUser = async () => {
if (!confirmRemoveUser) return
const targetId = confirmRemoveUser.user_id || confirmRemoveUser.id
setRemovingUser(targetId)
try {
await api.delete(`/devices/${id}/user-list/${targetId}`)
setUsers(prev => prev.filter(u => (u.user_id || u.id) !== targetId))
toast.success('Removed', `${confirmRemoveUser.display_name || confirmRemoveUser.email} removed.`)
} catch (err) {
toast.danger('Error', err.message || 'Failed to remove user.')
} finally {
setRemovingUser(null)
setConfirmRemoveUser(null)
}
}
// ── Device notes (Firestore) ──────────────────────────────────────────────
const [notes, setNotes] = useState([])
const [notesLoading, setNotesLoading] = useState(false)
const [noteModal, setNoteModal] = useState({ open: false, note: null })
const [deletingNote, setDeletingNote] = useState(null)
const [confirmDeleteNote, setConfirmDeleteNote] = useState(null)
const loadNotes = useCallback(async () => {
if (!id) return
setNotesLoading(true)
try {
const data = await api.get(`/devices/${id}/notes`)
setNotes((data.notes || []).slice().reverse()) // newest first
} catch {
setNotes([])
} finally {
setNotesLoading(false)
}
}, [id])
useEffect(() => { loadNotes() }, [loadNotes])
const handleNoteSaved = () => {
setNoteModal({ open: false, note: null })
loadNotes()
}
const handleDeleteNote = async () => {
if (!confirmDeleteNote) return
setDeletingNote(confirmDeleteNote.id)
try {
await api.delete(`/devices/${id}/notes/${confirmDeleteNote.id}`)
setNotes(prev => prev.filter(n => n.id !== confirmDeleteNote.id))
toast.success('Deleted', 'Note removed.')
} catch (err) {
toast.danger('Error', err.message || 'Failed to delete note.')
} finally {
setDeletingNote(null)
setConfirmDeleteNote(null)
}
}
// ── Linked issues (global /notes system, entity_type=device) ─────────────
const [issues, setIssues] = useState([])
const [issuesLoading, setIssuesLoading] = useState(false)
const [issueModal, setIssueModal] = useState({ open: false, entry: null })
const [confirmDeleteIssue, setConfirmDeleteIssue] = useState(null)
const [deletingIssue, setDeletingIssue] = 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 openNewIssue = () => setIssueModal({ open: true, entry: null })
const openEditIssue = (entry) => setIssueModal({ open: true, entry })
const handleIssueSaved = () => {
setIssueModal({ open: false, entry: null })
loadIssues()
}
const handleDeleteIssue = async () => {
if (!confirmDeleteIssue) return
setDeletingIssue(true)
try {
await api.delete(`/notes/${confirmDeleteIssue}`)
toast.success('Deleted', 'Issue removed.')
setConfirmDeleteIssue(null)
loadIssues()
} catch (err) {
toast.danger('Error', err.message || 'Failed to delete issue.')
} finally {
setDeletingIssue(false)
}
}
const sn = device?.serial_number || device?.device_id
const existingUserIds = users.map(u => u.user_id || u.id).filter(Boolean)
// ── Render ─────────────────────────────────────────────────────────────────
return (
<>
<style>{`
.manage-user-row:hover .manage-user-remove { opacity: 1; }
.manage-user-row .manage-user-remove { opacity: 0; transition: opacity 0.15s; }
.manage-issue-row { cursor: pointer; transition: background 0.12s; }
.manage-issue-row:hover { background: ${GLASS_HOVER} !important; }
.manage-note-card { transition: box-shadow 0.15s; }
.manage-note-card:hover { box-shadow: var(--shadow-md) !important; }
@keyframes severity-critical-glow {
0%, 100% { filter: drop-shadow(0 0 0px var(--color-danger)); }
50% { filter: drop-shadow(0 0 5px var(--color-danger)); }
}
.severity-critical { animation: severity-critical-glow 0.9s ease-in-out infinite; }
`}</style>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
{/* ── 1. DEVICE ACCESS (Users) ──────────────────────────────────────── */}
<GlassCard>
<CardHeader
label="Device Access"
count={users.length || undefined}
action={canEdit && (
<Button variant="secondary" size="sm" onClick={() => setShowAddUser(true)}>
+ Add User
</Button>
)}
/>
<div style={{ padding: 'var(--space-4) var(--space-5)', display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
{usersLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-6)' }}>
<Spinner size="sm" />
</div>
) : users.length === 0 ? (
<EmptySlate
icon={
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
<circle cx="9" cy="7" r="4"/>
<path d="M23 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75"/>
</svg>
}
message="No users have access to this device."
action={canEdit && (
<Button variant="secondary" size="sm" onClick={() => setShowAddUser(true)}>Add first user</Button>
)}
/>
) : (
users.map((user) => {
const userId = user.user_id || user.id
const initials = (user.display_name || user.email || '?').charAt(0).toUpperCase()
return (
<div
key={userId}
className="manage-user-row"
style={{
display: 'flex', alignItems: 'center', gap: 'var(--space-3)',
padding: 'var(--space-3)',
borderRadius: 'var(--radius-md)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
cursor: userId ? 'pointer' : 'default',
transition: 'background 0.15s',
}}
onClick={() => userId && navigate(`/users/${userId}`)}
onMouseEnter={e => e.currentTarget.style.background = GLASS_HOVER}
onMouseLeave={e => e.currentTarget.style.background = GLASS_INNER}
>
<div style={{
width: 36, height: 36, borderRadius: '50%', overflow: 'hidden',
background: 'var(--color-primary-subtle)', flexShrink: 0,
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-primary)', border: '1px solid rgba(192,193,255,0.20)',
}}>
{user.photo_url ? <img src={user.photo_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} /> : initials}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{user.display_name || user.email || 'Unknown User'}
</p>
{user.email && user.display_name && (
<p style={{ margin: 0, fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{user.email}
</p>
)}
</div>
{user.role && <StatusBadge variant="info">{user.role}</StatusBadge>}
{canEdit && (
<button
className="manage-user-remove"
onClick={e => { e.stopPropagation(); setConfirmRemoveUser(user) }}
disabled={removingUser === userId}
title="Remove access" aria-label="Remove user"
style={{
width: 28, height: 28, borderRadius: 'var(--radius-md)',
border: '1px solid var(--color-border-strong)',
background: 'var(--color-danger-bg)', color: 'var(--color-danger)',
cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0, transition: 'background 0.12s',
}}
onMouseEnter={e => e.currentTarget.style.background = 'var(--color-danger)'}
onMouseLeave={e => e.currentTarget.style.background = 'var(--color-danger-bg)'}
>
<Icon name="delete" size={13} />
</button>
)}
</div>
)
})
)}
</div>
</GlassCard>
{/* ── 2. DEVICE NOTES ───────────────────────────────────────────────── */}
<GlassCard>
<CardHeader
label="Device Notes"
count={notes.length || undefined}
action={canEdit && (
<Button variant="secondary" size="sm" onClick={() => setNoteModal({ open: true, note: null })}>
+ Add Note
</Button>
)}
/>
<div style={{ padding: notesLoading || notes.length === 0 ? 0 : 'var(--space-4) var(--space-5)' }}>
{notesLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
<Spinner size="sm" />
</div>
) : notes.length === 0 ? (
<EmptySlate
icon={
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
<line x1="16" y1="13" x2="8" y2="13"/>
<line x1="16" y1="17" x2="8" y2="17"/>
<polyline points="10 9 9 9 8 9"/>
</svg>
}
message="No notes recorded for this device yet."
action={canEdit && (
<Button variant="secondary" size="sm" onClick={() => setNoteModal({ open: true, note: null })}>
Add first note
</Button>
)}
/>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 'var(--space-3)' }}>
{notes.map(note => (
<div
key={note.id}
className="manage-note-card"
style={{
display: 'flex', flexDirection: 'column', gap: 'var(--space-3)',
padding: 'var(--space-4)',
borderRadius: 'var(--radius-lg)',
background: GLASS_INNER,
border: '1px solid var(--color-border)',
boxShadow: 'var(--shadow-sm)',
}}
>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', color: 'var(--color-text-primary)', lineHeight: 1.6, whiteSpace: 'pre-wrap', flex: 1 }}>
{note.content || '—'}
</p>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-2)' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }} title={fmtDateMedium(note.created_at)}>
{fmtRelative(note.created_at)}
</span>
{note.created_by && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{note.created_by}
</span>
)}
</div>
{canEdit && (
<div style={{ display: 'flex', gap: 'var(--space-1)', flexShrink: 0 }}>
<button onClick={() => setNoteModal({ open: true, note })} title="Edit note" aria-label="Edit note"
style={{ width: 26, height: 26, borderRadius: 'var(--radius-sm)', border: '1px solid transparent', background: 'none', color: 'var(--color-text-muted)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'color 0.12s, background 0.12s, border-color 0.12s' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-primary)'; e.currentTarget.style.background = 'var(--color-primary-subtle)'; e.currentTarget.style.borderColor = 'rgba(192,193,255,0.25)' }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'none'; e.currentTarget.style.borderColor = 'transparent' }}
>
<Icon name="edit" size={13} />
</button>
<button onClick={() => setConfirmDeleteNote(note)} title="Delete note" aria-label="Delete note"
style={{ width: 26, height: 26, borderRadius: 'var(--radius-sm)', border: '1px solid transparent', background: 'none', color: 'var(--color-text-muted)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'color 0.12s, background 0.12s, border-color 0.12s' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.background = 'var(--color-danger-bg)'; e.currentTarget.style.borderColor = 'var(--color-danger)' }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'none'; e.currentTarget.style.borderColor = 'transparent' }}
>
<Icon name="delete" size={13} />
</button>
</div>
)}
</div>
</div>
))}
</div>
)}
</div>
</GlassCard>
{/* ── 3. LINKED ISSUES ──────────────────────────────────────────────── */}
<GlassCard>
<CardHeader
label="Linked Issues"
count={
issues.filter(i => i.status !== 'resolved').length > 0
? `${issues.filter(i => i.status !== 'resolved').length} open`
: issues.length > 0 ? `${issues.length} total` : undefined
}
action={canEdit && (
<Button variant="secondary" size="sm" onClick={openNewIssue}>
+ New Issue
</Button>
)}
/>
<div style={{ display: 'flex', flexDirection: 'column' }}>
{issuesLoading ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-8)' }}>
<Spinner size="sm" />
</div>
) : issues.length === 0 ? (
<EmptySlate
icon={
<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>
</svg>
}
message="No issues linked to this device."
action={canEdit && (
<Button variant="secondary" size="sm" onClick={openNewIssue}>Log first issue</Button>
)}
/>
) : (
issues.map((issue, idx) => (
<div
key={issue.id}
className="manage-issue-row"
style={{
display: 'grid',
gridTemplateColumns: 'auto 1fr auto auto auto',
alignItems: 'center',
gap: 'var(--space-3)',
padding: 'var(--space-3) var(--space-5)',
borderBottom: idx < issues.length - 1 ? '1px solid var(--color-border)' : 'none',
}}
onClick={() => canEdit && openEditIssue(issue)}
>
<StatusPill status={issue.status} />
<div style={{ minWidth: 0 }}>
<p style={{ margin: 0, fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{issue.title}
</p>
{issue.body && (
<p style={{ margin: '2px 0 0', fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{issue.body.replace(/<[^>]*>/g, '').slice(0, 90)}
</p>
)}
</div>
<SeverityBars severity={issue.severity} />
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', whiteSpace: 'nowrap', flexShrink: 0 }} title={fmtDateMedium(issue.created_at)}>
{fmtRelative(issue.created_at)}
</span>
{canEdit && (
<button
onClick={e => { e.stopPropagation(); setConfirmDeleteIssue(issue.id) }}
title="Delete issue" aria-label="Delete issue"
style={{ width: 26, height: 26, borderRadius: 'var(--radius-sm)', border: '1px solid transparent', background: 'none', color: 'var(--color-text-muted)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'color 0.12s, background 0.12s, border-color 0.12s' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--color-danger)'; e.currentTarget.style.background = 'var(--color-danger-bg)'; e.currentTarget.style.borderColor = 'var(--color-danger)' }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--color-text-muted)'; e.currentTarget.style.background = 'none'; e.currentTarget.style.borderColor = 'transparent' }}
>
<Icon name="delete" size={13} />
</button>
)}
</div>
))
)}
</div>
</GlassCard>
</div>
{/* ── Modals ─────────────────────────────────────────────────────────── */}
<AddDeviceUserModal
open={showAddUser}
deviceId={id}
existingUserIds={existingUserIds}
onClose={() => setShowAddUser(false)}
onAdded={handleUserAdded}
/>
<DeviceNoteModal
open={noteModal.open}
deviceId={id}
note={noteModal.note}
onClose={() => setNoteModal({ open: false, note: null })}
onSaved={handleNoteSaved}
/>
{/* Issue form — pre-link to this device (locked — cannot be removed) */}
<EntryFormModal
open={issueModal.open}
entry={issueModal.entry}
defaultType="issue"
prefilledLinks={issueModal.entry
? undefined
: [{ entity_type: 'device', entity_id: id, display_name: device?.device_name || sn, locked: true }]
}
knownEntities={id ? { [id]: device?.device_name || sn } : undefined}
onClose={() => setIssueModal({ open: false, entry: null })}
onSaved={handleIssueSaved}
onDelete={canEdit ? (entryId) => {
setIssueModal({ open: false, entry: null })
setConfirmDeleteIssue(entryId)
} : null}
/>
{/* Confirm: remove user */}
<ConfirmDialog
open={!!confirmRemoveUser}
variant="danger"
title="Remove Access"
message={`Remove ${confirmRemoveUser?.display_name || confirmRemoveUser?.email || 'this user'} from the device?`}
confirmLabel="Remove"
onConfirm={handleRemoveUser}
onClose={() => setConfirmRemoveUser(null)}
loading={!!removingUser}
/>
{/* Confirm: delete note */}
<ConfirmDialog
open={!!confirmDeleteNote}
variant="danger"
title="Delete Note"
message="This note will be permanently deleted."
confirmLabel="Delete"
onConfirm={handleDeleteNote}
onClose={() => setConfirmDeleteNote(null)}
loading={deletingNote === confirmDeleteNote?.id}
/>
{/* Confirm: delete issue */}
<ConfirmDialog
open={!!confirmDeleteIssue}
variant="danger"
title="Delete Issue"
message="This issue and all its entity links will be permanently removed."
confirmLabel="Delete"
onConfirm={handleDeleteIssue}
onClose={() => setConfirmDeleteIssue(null)}
loading={deletingIssue}
/>
</>
)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,857 @@
// frontend/src/pages/bellcloud/devices/tabs/WarrantyTab.jsx
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import { fmtDateMedium, fmtDateLong } from '@/lib/formatters'
// ─── Helpers ──────────────────────────────────────────────────────────────────
function parseDate(val) {
if (!val) return null
// Firestore Timestamp object
if (typeof val === 'object' && typeof val.seconds === 'number') {
return new Date(val.seconds * 1000)
}
const d = new Date(val)
return isNaN(d.getTime()) ? null : d
}
function addDays(date, days) {
if (!date || !days) return null
const d = new Date(date)
d.setDate(d.getDate() + Number(days))
return d
}
function daysUntil(date) {
if (!date) return null
return Math.ceil((date.getTime() - Date.now()) / 86400000)
}
/** 0–100 how much of the period has ELAPSED */
function calcProgress(start, end) {
if (!start || !end) return null
const total = end.getTime() - start.getTime()
if (total <= 0) return 100
const elapsed = Date.now() - start.getTime()
return Math.min(100, Math.max(0, Math.round((elapsed / total) * 100)))
}
/** Remaining portion (inverse of elapsed) */
function calcRemaining(start, end) {
const p = calcProgress(start, end)
return p === null ? null : 100 - p
}
function daysLabel(days) {
if (days == null || days === 0) return '—'
if (days % 365 === 0) {
const y = days / 365
return `${y} year${y !== 1 ? 's' : ''}`
}
if (days % 30 === 0) {
const m = days / 30
return `${m} month${m !== 1 ? 's' : ''}`
}
return `${days} day${days !== 1 ? 's' : ''}`
}
// ─── Glass surface styles ─────────────────────────────────────────────────────
const GLASS = {
background: 'rgba(28, 32, 38, 0.30)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
border: '1px solid var(--color-border)',
boxShadow: 'var(--shadow-card), var(--shadow-md)',
borderRadius: 'var(--radius-xl)',
}
const GLASS_ELEVATED = {
background: 'rgba(28, 32, 38, 0.40)',
backdropFilter: 'var(--blur-modal)',
WebkitBackdropFilter: 'var(--blur-modal)',
border: '1px solid var(--color-border)',
boxShadow: 'var(--shadow-sm)',
borderRadius: 'var(--radius-lg)',
}
// ─── Primitives ───────────────────────────────────────────────────────────────
function SectionLabel({ children }) {
return (
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-wide)',
textTransform: 'uppercase',
color: 'var(--color-text-muted)',
}}>
{children}
</span>
)
}
function InfoCell({ label, children }) {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
<SectionLabel>{label}</SectionLabel>
<span style={{
fontSize: 'var(--font-size-base)',
fontWeight: 'var(--font-weight-medium)',
color: 'var(--color-text-primary)',
marginTop: 'var(--space-1)',
}}>
{children ?? '—'}
</span>
</div>
)
}
function ProgressBar({ value, color = 'var(--color-primary)', label, showPct = true }) {
const pct = Math.max(0, Math.min(100, value ?? 0))
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
{(label || showPct) && (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
{label && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
{label}
</span>
)}
{showPct && (
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-secondary)',
}}>
{pct}%
</span>
)}
</div>
)}
<div style={{
height: 6,
borderRadius: 'var(--radius-full)',
backgroundColor: 'var(--color-bg-island)',
overflow: 'hidden',
}}>
<div style={{
height: '100%',
width: `${pct}%`,
backgroundColor: color,
borderRadius: 'var(--radius-full)',
transition: 'width 0.6s ease',
boxShadow: `0 0 8px ${color}60`,
}} />
</div>
</div>
)
}
function Divider() {
return <div style={{ height: 1, backgroundColor: 'var(--color-border)', margin: 'var(--space-1) 0' }} />
}
function DetailRow({ label, value, valueColor }) {
return (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 'var(--space-4)', minHeight: 28 }}>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', flexShrink: 0 }}>
{label}
</span>
<span style={{
fontSize: 'var(--font-size-sm)',
fontWeight: 'var(--font-weight-medium)',
color: valueColor ?? (!value || value === '—' ? 'var(--color-text-muted)' : 'var(--color-text-primary)'),
textAlign: 'right',
}}>
{value ?? '—'}
</span>
</div>
)
}
// ─── Subscription Hero ────────────────────────────────────────────────────────
function SubscriptionHero({ sub, canEdit, onEditSubscription, deviceUsers }) {
const subscrStart = parseDate(sub?.subscrStart)
const subscrEnd = addDays(subscrStart, sub?.subscrDuration)
const daysLeft = daysUntil(subscrEnd)
const remaining = calcRemaining(subscrStart, subscrEnd)
const isActive = daysLeft === null || daysLeft > 0
const tier = sub?.subscrTier || null
const progressColor = daysLeft === null
? 'var(--color-primary)'
: daysLeft > 60
? 'var(--color-success)'
: daysLeft > 14
? 'var(--color-warning)'
: 'var(--color-danger)'
// Registered users = actual device users count passed from parent
const regUsers = Array.isArray(deviceUsers) ? deviceUsers.length : null
const maxUsers = sub?.maxUsers ?? null
const hwOutputs = sub?.hw_outputs ?? null
const maxOutputs = sub?.maxOutputs ?? null
return (
<div style={{
...GLASS,
padding: 'var(--space-6) var(--space-8)',
position: 'relative',
overflow: 'hidden',
borderLeft: '3px solid var(--color-primary)',
}}>
{/* Left accent glow */}
<div aria-hidden="true" style={{
position: 'absolute',
left: 0, top: 0, bottom: 0,
width: 140,
pointerEvents: 'none',
background: 'linear-gradient(90deg, rgba(192,193,255,0.06) 0%, transparent 100%)',
}} />
{/* Right ambient glow */}
<div aria-hidden="true" style={{
position: 'absolute', inset: 0, pointerEvents: 'none',
background: 'radial-gradient(ellipse 60% 120% at 90% 50%, rgba(192,193,255,0.03) 0%, transparent 70%)',
}} />
<div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 'var(--space-6)', flexWrap: 'wrap' }}>
{/* ── Column 1: Tier ── */}
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-4)', minWidth: 180, flexShrink: 0 }}>
<div style={{
width: 48, height: 48,
borderRadius: 'var(--radius-lg)',
backgroundColor: 'var(--color-primary-subtle)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0,
}}>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--color-primary)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
</svg>
</div>
<div>
<div style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-lg)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-tight)',
color: 'var(--color-text-primary)',
textTransform: 'capitalize',
}}>
{tier ? `${tier} Tier` : 'No Subscription'}
</div>
<div style={{ marginTop: 4 }}>
<StatusBadge variant={isActive ? 'success' : 'danger'}>
{isActive ? 'Active License' : 'Expired'}
</StatusBadge>
</div>
</div>
</div>
{/* ── Column 2: Progress bar ── */}
<div style={{
flex: 1, minWidth: 220,
paddingLeft: 'var(--space-6)',
borderLeft: '1px solid var(--color-border)',
display: 'flex', flexDirection: 'column', gap: 'var(--space-3)',
}}>
{/* Top label row */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
<span style={{
fontSize: 'var(--font-size-sm)',
fontWeight: 'var(--font-weight-medium)',
color: 'var(--color-text-primary)',
}}>
{daysLeft === null
? 'No expiry set'
: daysLeft <= 0
? 'Subscription expired'
: `${daysLeft} days remaining`}
</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
{daysLabel(sub?.subscrDuration)} plan
</span>
</div>
{/* Progress bar */}
<ProgressBar value={remaining ?? 0} color={progressColor} showPct={false} />
{/* Bottom: inline Start / Renewal */}
<div style={{ display: 'flex', gap: 'var(--space-8)', alignItems: 'center' }}>
{subscrStart && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
Start:{' '}
<span style={{ color: 'var(--color-text-secondary)', fontWeight: 'var(--font-weight-medium)' }}>
{fmtDateMedium(subscrStart.toISOString())}
</span>
</span>
)}
{subscrEnd && (
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
Renewal:{' '}
<span style={{ color: 'var(--color-text-secondary)', fontWeight: 'var(--font-weight-medium)' }}>
{fmtDateMedium(subscrEnd.toISOString())}
</span>
</span>
)}
</div>
</div>
{/* ── Column 3: Users + Outputs + Edit — side by side ── */}
<div style={{
display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 'var(--space-6)',
paddingLeft: 'var(--space-6)',
borderLeft: '1px solid var(--color-border)',
flexShrink: 0,
}}>
{/* Users block */}
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-4)' }}>
<div style={{
width: 48, height: 48,
borderRadius: 'var(--radius-lg)',
backgroundColor: 'var(--color-primary-subtle)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0,
}}>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--color-primary)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-secondary)',
}}>
Device Users
</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
Max:{' '}
<span style={{ color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-medium)' }}>
{maxUsers ?? '—'}
</span>
{regUsers !== null && (
<>
{' '}<span style={{ color: 'var(--color-border-strong)' }}>|</span>{' '}
Reg:{' '}
<span style={{ color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-medium)' }}>
{regUsers}
</span>
</>
)}
</span>
</div>
</div>
{/* Outputs block */}
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-4)' }}>
<div style={{
width: 48, height: 48,
borderRadius: 'var(--radius-lg)',
backgroundColor: 'var(--color-primary-subtle)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0,
}}>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--color-primary)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="3" />
<path d="M19.07 4.93a10 10 0 010 14.14M4.93 4.93a10 10 0 000 14.14" />
</svg>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
<span style={{
fontSize: 'var(--font-size-xs)',
fontWeight: 'var(--font-weight-semibold)',
color: 'var(--color-text-secondary)',
}}>
Outputs
</span>
<span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
HW:{' '}
<span style={{ color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-medium)' }}>
{hwOutputs ?? '—'}
</span>
{maxOutputs !== null && (
<>
{' '}<span style={{ color: 'var(--color-border-strong)' }}>|</span>{' '}
Max:{' '}
<span style={{ color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-medium)' }}>
{maxOutputs}
</span>
</>
)}
</span>
</div>
</div>
{/* Edit pencil icon button */}
{canEdit && (
<button
type="button"
onClick={onEditSubscription}
aria-label="Edit subscription plan"
title="Edit subscription plan"
style={{
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
width: 40,
height: 40,
borderRadius: 'var(--radius-md)',
border: 'none',
background: 'transparent',
color: 'var(--color-text-muted)',
cursor: 'pointer',
transition: 'background 0.15s, color 0.15s',
flexShrink: 0,
}}
onMouseEnter={e => {
e.currentTarget.style.background = 'rgba(49,53,60,0.50)'
e.currentTarget.style.color = 'var(--color-text-primary)'
}}
onMouseLeave={e => {
e.currentTarget.style.background = 'transparent'
e.currentTarget.style.color = 'var(--color-text-muted)'
}}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" />
<path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" />
</svg>
</button>
)}
</div>
</div>
</div>
)
}
// ─── Warranty Card ────────────────────────────────────────────────────────────
function WarrantyCard({ stats, canEdit, onEditWarranty }) {
const warrantyStart = parseDate(stats?.warrantyStart)
const warrantyEnd = addDays(warrantyStart, stats?.warrantyPeriod)
const daysLeft = daysUntil(warrantyEnd)
const remaining = calcRemaining(warrantyStart, warrantyEnd)
const isVoid = stats?.warrantyActive === false
const isExpired = !isVoid && daysLeft !== null && daysLeft <= 0
const isActive = !isVoid && !isExpired && (daysLeft === null || daysLeft > 0)
const statusLabel = isVoid ? 'Warranty Void' : isExpired ? 'Expired' : isActive ? 'Active' : '—'
const statusVariant = isVoid ? 'warning' : isExpired ? 'danger' : isActive ? 'success' : 'neutral'
const borderAccent = isVoid
? 'var(--color-warning)'
: isExpired
? 'var(--color-danger)'
: 'var(--color-success)'
const progressColor = isVoid || isExpired ? 'var(--color-danger)' : 'var(--color-success)'
return (
<div style={{
...GLASS,
padding: 'var(--space-6)',
borderLeft: `3px solid ${borderAccent}`,
position: 'relative',
overflow: 'hidden',
}}>
{/* Accent side glow */}
<div aria-hidden="true" style={{
position: 'absolute',
left: 0, top: 0, bottom: 0,
width: 140,
pointerEvents: 'none',
background: `linear-gradient(90deg, ${borderAccent}12 0%, transparent 100%)`,
}} />
<div style={{ position: 'relative', display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
{/* Header */}
<div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 'var(--space-4)', flexWrap: 'wrap' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-4)' }}>
<div style={{
width: 44, height: 44,
borderRadius: 'var(--radius-full)',
backgroundColor: `${borderAccent}18`,
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0,
}}>
{isActive ? (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={borderAccent} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
<polyline points="9 12 11 14 15 10" />
</svg>
) : (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={borderAccent} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
<line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
)}
</div>
<div>
<div style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-lg)',
fontWeight: 'var(--font-weight-bold)',
letterSpacing: 'var(--tracking-tight)',
color: borderAccent,
}}>
{statusLabel}
</div>
<div style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', marginTop: 3 }}>
{isVoid
? 'Warranty has been manually voided'
: isExpired
? warrantyEnd
? `Coverage ended on ${fmtDateLong(warrantyEnd.toISOString())}`
: 'Coverage has expired'
: warrantyEnd
? `Active until ${fmtDateMedium(warrantyEnd.toISOString())}`
: 'Warranty is currently active'}
</div>
</div>
</div>
{canEdit && (
<Button variant="ghost" size="sm" onClick={onEditWarranty}>
Edit Warranty
</Button>
)}
</div>
{/* Progress */}
<ProgressBar
value={remaining ?? 0}
color={progressColor}
label={
daysLeft === null
? 'Coverage period'
: daysLeft <= 0
? 'Coverage elapsed'
: `${daysLeft} day${daysLeft !== 1 ? 's' : ''} remaining`
}
/>
{/* Detail grid */}
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))',
gap: 'var(--space-4) var(--space-6)',
}}>
<InfoCell label="Start Date">
{warrantyStart ? fmtDateMedium(warrantyStart.toISOString()) : '—'}
</InfoCell>
<InfoCell label="Expiry Date">
{warrantyEnd ? fmtDateMedium(warrantyEnd.toISOString()) : '—'}
</InfoCell>
<InfoCell label="Coverage Period">
{daysLabel(stats?.warrantyPeriod)}
</InfoCell>
<InfoCell label="Status">
<StatusBadge variant={statusVariant}>{statusLabel}</StatusBadge>
</InfoCell>
</div>
</div>
</div>
)
}
// ─── Maintenance Card ─────────────────────────────────────────────────────────
function MaintenanceCard({ stats }) {
const maintainedOn = parseDate(stats?.maintainedOn)
const nextMaint = addDays(maintainedOn, stats?.maintainancePeriod)
const daysLeft = daysUntil(nextMaint)
const remaining = calcRemaining(maintainedOn, nextMaint)
const isOverdue = daysLeft !== null && daysLeft <= 0
const isDueSoon = daysLeft !== null && daysLeft > 0 && daysLeft <= 30
const statusVariant = isOverdue ? 'danger' : isDueSoon ? 'warning' : 'neutral'
const progressColor = isOverdue
? 'var(--color-danger)'
: isDueSoon
? 'var(--color-warning)'
: 'var(--color-info)'
return (
<div style={{ ...GLASS, padding: 'var(--space-6)', display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
{/* Title */}
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', flexWrap: 'wrap' }}>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-muted)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M14.7 6.3a1 1 0 000 1.4l1.6 1.6a1 1 0 001.4 0l3.77-3.77a6 6 0 01-7.94 7.94l-6.91 6.91a2.12 2.12 0 01-3-3l6.91-6.91a6 6 0 017.94-7.94l-3.76 3.76z" />
</svg>
<span style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-md)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-tight)',
color: 'var(--color-text-primary)',
}}>
Maintenance Schedule
</span>
{(isOverdue || isDueSoon) && (
<StatusBadge variant={statusVariant}>
{isOverdue ? 'Overdue' : 'Due Soon'}
</StatusBadge>
)}
</div>
{/* Next service highlight */}
{nextMaint ? (
<div style={{
...GLASS_ELEVATED,
padding: 'var(--space-4)',
display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 'var(--space-4)', flexWrap: 'wrap',
}}>
<div>
<SectionLabel>Next Scheduled Service</SectionLabel>
<div style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-xl)',
fontWeight: 'var(--font-weight-bold)',
letterSpacing: 'var(--tracking-tight)',
color: isOverdue ? 'var(--color-danger)' : isDueSoon ? 'var(--color-warning)' : 'var(--color-text-primary)',
marginTop: 'var(--space-1)',
}}>
{fmtDateLong(nextMaint.toISOString())}
</div>
</div>
<div style={{ textAlign: 'right', flexShrink: 0 }}>
<SectionLabel>{isOverdue ? 'Overdue by' : 'In'}</SectionLabel>
<div style={{
fontSize: 'var(--font-size-lg)',
fontWeight: 'var(--font-weight-bold)',
color: isOverdue ? 'var(--color-danger)' : isDueSoon ? 'var(--color-warning)' : 'var(--color-text-secondary)',
marginTop: 'var(--space-1)',
}}>
{daysLeft != null ? `${Math.abs(daysLeft)} day${Math.abs(daysLeft) !== 1 ? 's' : ''}` : '—'}
</div>
</div>
</div>
) : (
<div style={{
...GLASS_ELEVATED,
padding: 'var(--space-4)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
No maintenance schedule set
</span>
</div>
)}
{/* Progress bar */}
<ProgressBar
value={remaining ?? 0}
color={progressColor}
label="Progress to next service"
/>
{/* Detail rows */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
<DetailRow
label="Last Maintained"
value={maintainedOn ? fmtDateMedium(maintainedOn.toISOString()) : null}
/>
<Divider />
<DetailRow
label="Service Interval"
value={daysLabel(stats?.maintainancePeriod)}
/>
<Divider />
<DetailRow
label="Next Service"
value={nextMaint ? fmtDateMedium(nextMaint.toISOString()) : null}
valueColor={isOverdue ? 'var(--color-danger)' : isDueSoon ? 'var(--color-warning)' : undefined}
/>
</div>
</div>
)
}
// ─── Performance Metrics ──────────────────────────────────────────────────────
function MetricTile({ icon, label, value, accent = 'var(--color-primary)', tag, tagVariant = 'info' }) {
return (
<div style={{
...GLASS_ELEVATED,
padding: 'var(--space-5)',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
gap: 'var(--space-4)',
minHeight: 100,
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<div style={{ color: accent, display: 'flex', alignItems: 'center' }}>
{icon}
</div>
{tag != null && (
<StatusBadge variant={tagVariant}>{tag}</StatusBadge>
)}
</div>
<div>
<div style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-2xl)',
fontWeight: 'var(--font-weight-bold)',
letterSpacing: 'var(--tracking-display)',
color: 'var(--color-text-primary)',
lineHeight: 1,
}}>
{value}
</div>
<div style={{
fontSize: 'var(--font-size-xs)',
color: 'var(--color-text-muted)',
fontWeight: 'var(--font-weight-medium)',
marginTop: 'var(--space-1)',
}}>
{label}
</div>
</div>
</div>
)
}
function PerformanceMetrics({ device, stats }) {
const totalWarnings = Number.isFinite(stats?.totalWarningsGiven) ? stats.totalWarningsGiven : null
const melodiesCount = Array.isArray(device?.device_melodies_all) ? device.device_melodies_all.length : null
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-muted)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<polyline points="22 12 18 12 15 21 9 3 6 12 2 12" />
</svg>
<span style={{
fontFamily: 'var(--font-family-display)',
fontSize: 'var(--font-size-md)',
fontWeight: 'var(--font-weight-semibold)',
letterSpacing: 'var(--tracking-tight)',
color: 'var(--color-text-primary)',
}}>
Device Performance
</span>
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 'var(--space-3)' }}>
{/* System Warnings */}
<MetricTile
accent={totalWarnings !== null && totalWarnings > 0 ? 'var(--color-danger)' : 'var(--color-success)'}
tag={totalWarnings !== null ? (totalWarnings === 0 ? 'Clean' : 'Flagged') : null}
tagVariant={totalWarnings === 0 ? 'success' : 'danger'}
value={totalWarnings !== null ? totalWarnings : '—'}
label="System Warnings"
icon={
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
<line x1="12" y1="9" x2="12" y2="13" />
<line x1="12" y1="17" x2="12.01" y2="17" />
</svg>
}
/>
{/* On-board Melodies */}
<MetricTile
accent="var(--color-info)"
tag={melodiesCount !== null ? 'Loaded' : null}
tagVariant="info"
value={melodiesCount !== null ? melodiesCount : '—'}
label="On-board Melodies"
icon={
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M9 18V5l12-2v13" />
<circle cx="6" cy="18" r="3" />
<circle cx="18" cy="16" r="3" />
</svg>
}
/>
{/* Firmware Version */}
<MetricTile
accent="var(--color-primary)"
tag={device?.device_firmware_version ? 'Current' : null}
tagVariant="neutral"
value={device?.device_firmware_version ?? '—'}
label="Firmware Version"
icon={
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<rect x="4" y="4" width="16" height="16" rx="2" />
<rect x="9" y="9" width="6" height="6" />
<path d="M15 2v2M9 2v2M15 20v2M9 20v2M20 9h2M20 14h2M2 9h2M2 14h2" />
</svg>
}
/>
{/* Total Melodies (favorites) */}
<MetricTile
accent="var(--color-warning)"
tag={Array.isArray(device?.device_melodies_favorites) && device.device_melodies_favorites.length > 0 ? 'Saved' : null}
tagVariant="warning"
value={Array.isArray(device?.device_melodies_favorites) ? device.device_melodies_favorites.length : '—'}
label="Favourite Melodies"
icon={
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z" />
</svg>
}
/>
</div>
</div>
)
}
// ─── WarrantyTab ──────────────────────────────────────────────────────────────
export default function WarrantyTab({
device,
canEdit,
sub,
stats,
deviceUsers,
onEditSubscription,
onEditWarranty,
}) {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)', width: '100%', maxWidth: 2000, margin: '0 auto' }}>
{/* Subscription hero — no section label above */}
<SubscriptionHero
sub={sub}
canEdit={canEdit}
onEditSubscription={onEditSubscription}
deviceUsers={deviceUsers}
/>
{/* Warranty card — no section label above */}
<WarrantyCard stats={stats} canEdit={canEdit} onEditWarranty={onEditWarranty} />
{/* Masonry: Maintenance + Metrics side by side */}
<div className="masonry-grid masonry-grid--2">
<MaintenanceCard stats={stats} />
<div style={{ ...GLASS, padding: 'var(--space-6)' }}>
<PerformanceMetrics device={device} stats={stats} />
</div>
</div>
</div>
)
}
@@ -0,0 +1,171 @@
// frontend/src/pages/bellcloud/devices/tabs/shared.jsx
// Shared helpers, sub-components, and constants used across device tabs
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
// ─── Date / time helpers ──────────────────────────────────────────────────────
export function parseFirestoreDate(str) {
if (!str) return null
if (typeof str === 'object') {
const secs = str._seconds ?? str.seconds
if (typeof secs === 'number') return new Date(secs * 1000)
return null
}
const cleaned = str.replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+(\d{4})/, 'UTC')
const d = new Date(cleaned)
return isNaN(d.getTime()) ? null : d
}
export function formatDate(str) {
const d = parseFirestoreDate(str)
if (!d) return str || '—'
const day = d.getUTCDate().toString().padStart(2, '0')
const month = (d.getUTCMonth() + 1).toString().padStart(2, '0')
return `${day}-${month}-${d.getUTCFullYear()}`
}
export function formatDateNice(d) {
if (!d) return '—'
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`
}
export function daysUntil(targetDate) {
return Math.ceil((targetDate.getTime() - Date.now()) / 86400000)
}
export function addDays(date, days) {
return new Date(date.getTime() + days * 86400000)
}
export function daysToDisplay(days) {
if (days >= 365 && days % 365 === 0) return `${days / 365} year${days / 365 > 1 ? 's' : ''} (${days} days)`
if (days >= 30) {
const months = Math.floor(days / 30)
const rem = days % 30
if (rem === 0) return `${months} month${months > 1 ? 's' : ''} (${days} days)`
return `${days} days (~${months} month${months > 1 ? 's' : ''})`
}
return `${days} days`
}
export function formatTimestamp(str) {
if (!str) return '—'
const d = parseFirestoreDate(str)
if (d) return `${d.getUTCHours().toString().padStart(2, '0')}:${d.getUTCMinutes().toString().padStart(2, '0')}`
const match = str.match(/(\d{1,2}):(\d{2})/)
return match ? `${match[1].padStart(2, '0')}:${match[2]}` : str
}
export function parseCoordinates(coordStr) {
if (!coordStr) return null
if (typeof coordStr === 'object') {
const lat = parseFloat(coordStr.lat ?? coordStr.latitude)
const lng = parseFloat(coordStr.lng ?? coordStr.longitude)
if (!isNaN(lat) && !isNaN(lng)) return { lat, lng }
return null
}
const numbers = coordStr.match(/-?\d+(?:\.\d+)?/g)
if (numbers?.length >= 2) {
let lat = parseFloat(numbers[0])
let lng = parseFloat(numbers[1])
if (!isNaN(lat) && !isNaN(lng)) {
if (/\bS\b/.test(coordStr)) lat = -Math.abs(lat)
if (/\bW\b/.test(coordStr)) lng = -Math.abs(lng)
return { lat, lng }
}
}
return null
}
export function formatCoordinates(coords) {
if (!coords) return '—'
const latDir = coords.lat >= 0 ? 'N' : 'S'
const lngDir = coords.lng >= 0 ? 'E' : 'W'
return `${Math.abs(coords.lat).toFixed(6)}° ${latDir}, ${Math.abs(coords.lng).toFixed(6)}° ${lngDir}`
}
export function formatLocale(v) {
if (!v || v === 'all') return 'Global'
if (v === 'orthodox') return 'Orthodox'
if (v === 'catholic') return 'Catholic'
return v
}
// ─── Constants ────────────────────────────────────────────────────────────────
export const LOG_LEVEL_LABELS = { 0: 'Disabled', 1: 'Error', 2: 'Warning', 3: 'Info', 4: 'Debug', 5: 'Verbose' }
export const LOG_LEVEL_VARIANTS = { 0: 'neutral', 1: 'danger', 2: 'warning', 3: 'info', 4: 'neutral', 5: 'neutral' }
// ─── Shared sub-components ────────────────────────────────────────────────────
export function Field({ label, children, mono = false }) {
const isEmpty = children == null || children === ''
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
<dt style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>
{label}
</dt>
<dd style={{
fontSize: 'var(--font-size-base)',
color: isEmpty ? 'var(--color-text-muted)' : 'var(--color-text-primary)',
fontFamily: mono ? 'var(--font-family-mono)' : 'inherit',
}}>
{isEmpty ? '—' : children}
</dd>
</div>
)
}
export function FieldGrid({ children, cols = 2 }) {
return (
<dl style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gap: 'var(--space-4)' }}>
{children}
</dl>
)
}
export function SectionTitle({ title, onEdit, canEdit }) {
return (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 'var(--space-4)' }}>
<h3 style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
{title}
</h3>
{canEdit && onEdit && (
<Button variant="ghost" size="sm" onClick={onEdit}>Edit</Button>
)}
</div>
)
}
export function KpiCard({ label, value, variant }) {
const valueColor = variant === 'success'
? 'var(--color-success)'
: variant === 'danger'
? 'var(--color-danger)'
: variant === 'warning'
? 'var(--color-warning)'
: 'var(--color-text-primary)'
return (
<Card padding>
<div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
<span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>{label}</span>
<span style={{ fontSize: 'var(--font-size-2xl)', fontWeight: 'var(--font-weight-bold)', letterSpacing: 'var(--tracking-display)', color: valueColor, lineHeight: 1, fontFamily: 'var(--font-family-display)' }}>
{value}
</span>
</div>
</Card>
)
}
export function ProgressBar({ value, variant = 'primary' }) {
const width = 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 (
<div style={{ height: '6px', borderRadius: 'var(--radius-full)', backgroundColor: 'var(--color-bg-elevated)', overflow: 'hidden' }}>
<div style={{ height: '100%', width: `${width}%`, backgroundColor: color, borderRadius: 'var(--radius-full)', transition: 'width 0.3s' }} />
</div>
)
}