Scaffold plant app - MQTT monitoring for boiler-room equipment

Read-only monitoring/alerting for boilers, water softener, calorifiers
and pumps via a generic MQTT-topic-prefix asset model, so new
equipment can be onboarded without new ingestion code. Threshold and
stale-data alert rules with email + in-app notification.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
jtricerolph 2026-07-28 21:16:02 +00:00
commit 503b397dff
38 changed files with 5044 additions and 0 deletions

13
frontend/Dockerfile Normal file
View file

@ -0,0 +1,13 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json .
RUN npm install
COPY . .
ARG VITE_HOTEL_NAME
ENV VITE_HOTEL_NAME=$VITE_HOTEL_NAME
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html/plant
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80

16
frontend/index.html Normal file
View file

@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="theme-color" content="#0e7490" />
<title>Plant Room</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

40
frontend/nginx.conf Normal file
View file

@ -0,0 +1,40 @@
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
client_max_body_size 12m;
location /plant/api/auth/ {
proxy_pass http://10.10.10.101:3001/api/auth/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /plant/api/ {
proxy_pass http://backend:3001/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header Cache-Control "no-store";
}
location /plant/health {
proxy_pass http://backend:3001/health;
}
location ~* /plant/.*\.(js|css|png|ico|svg|woff2?)$ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
location /plant/ {
add_header Cache-Control "no-cache" always;
try_files $uri /plant/index.html;
}
location = / {
return 301 /plant/;
}
}

1901
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

24
frontend/package.json Normal file
View file

@ -0,0 +1,24 @@
{
"name": "hnf-plant-frontend",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"lucide-react": "^0.468.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.28.0"
},
"devDependencies": {
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.4",
"typescript": "^5.7.2",
"vite": "^6.0.5"
}
}

35
frontend/src/App.tsx Normal file
View file

@ -0,0 +1,35 @@
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import AuthGate, { useAuth } from './components/AuthGate'
import Layout from './components/Layout'
import Dashboard from './pages/Dashboard'
import Assets from './pages/Assets'
import Alerts from './pages/Alerts'
import Settings from './pages/Settings'
import { can } from './types'
function Home() {
const { user } = useAuth()
if (can(user, 'view')) return <Navigate to="/dashboard" replace />
if (can(user, 'manage_assets')) return <Navigate to="/assets" replace />
if (can(user, 'settings')) return <Navigate to="/settings" replace />
return <div className="page"><p className="muted">You don't have access to any Plant Room pages yet.</p></div>
}
export default function App() {
return (
<BrowserRouter basename="/plant">
<AuthGate>
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/assets" element={<Assets />} />
<Route path="/alerts" element={<Alerts />} />
<Route path="/settings" element={<Settings />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Layout>
</AuthGate>
</BrowserRouter>
)
}

112
frontend/src/api.ts Normal file
View file

@ -0,0 +1,112 @@
import type {
PlantAsset, AssetStatus, AssetPhoto, AlertRule, PlantAlert, AppSetting, PhotoType,
} from './types'
const BASE = '/plant/api'
async function request<T>(path: string, opts: RequestInit = {}): Promise<T> {
const res = await fetch(`${BASE}${path}`, {
credentials: 'include',
headers: { 'Content-Type': 'application/json', ...opts.headers },
...opts,
})
if (res.status === 401) {
;(window.top ?? window).location.href = '/login'
throw new Error('Unauthenticated')
}
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || `Request failed: ${res.status}`)
}
return res.json()
}
// Assets
export function fetchAssets(): Promise<PlantAsset[]> {
return request('/assets')
}
export function createAsset(body: Partial<PlantAsset>): Promise<PlantAsset> {
return request('/assets', { method: 'POST', body: JSON.stringify(body) })
}
export function updateAsset(id: number, body: Partial<PlantAsset>): Promise<PlantAsset> {
return request(`/assets/${id}`, { method: 'PATCH', body: JSON.stringify(body) })
}
// Asset photos — multipart, so no JSON content-type header
export async function uploadAssetPhoto(assetId: number, file: File, photoType: PhotoType): Promise<AssetPhoto> {
const form = new FormData()
form.append('photo_type', photoType)
form.append('file', file)
const res = await fetch(`${BASE}/assets/${assetId}/photos`, { method: 'POST', credentials: 'include', body: form })
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || `Upload failed: ${res.status}`)
}
return res.json()
}
export function fetchAssetPhotos(assetId: number): Promise<AssetPhoto[]> {
return request(`/assets/${assetId}/photos`)
}
export function deleteAssetPhoto(id: number): Promise<{ ok: boolean }> {
return request(`/photos/${id}`, { method: 'DELETE' })
}
export function photoUrl(filePath: string): string {
return `${BASE}/uploads${filePath}`
}
// Status (dashboard)
export function fetchStatus(): Promise<{ open_alerts: number; mqtt_connected: boolean; assets: AssetStatus[] }> {
return request('/status')
}
// Alerts
export function fetchAlerts(filters: { status?: string; severity?: string } = {}): Promise<PlantAlert[]> {
const params = new URLSearchParams()
if (filters.status) params.set('status', filters.status)
if (filters.severity) params.set('severity', filters.severity)
const qs = params.toString()
return request(`/alerts${qs ? `?${qs}` : ''}`)
}
export function acknowledgeAlert(id: number): Promise<PlantAlert> {
return request(`/alerts/${id}`, { method: 'PATCH', body: JSON.stringify({ action: 'acknowledge' }) })
}
export function resolveAlert(id: number): Promise<PlantAlert> {
return request(`/alerts/${id}`, { method: 'PATCH', body: JSON.stringify({ action: 'resolve' }) })
}
// Alert rules — threshold/asset_id/asset_type are write-side numbers/nulls,
// distinct enough from AlertRule's read-side (string threshold) shape that a
// plain object type is simpler than fighting Partial<AlertRule> here.
export interface AlertRuleInput {
asset_id?: number | null
asset_type?: AlertRule['asset_type']
field_key?: string
condition?: AlertRule['condition']
threshold?: number
severity?: AlertRule['severity']
active?: boolean
}
export function fetchAlertRules(): Promise<AlertRule[]> {
return request('/alert-rules')
}
export function createAlertRule(body: AlertRuleInput): Promise<AlertRule> {
return request('/alert-rules', { method: 'POST', body: JSON.stringify(body) })
}
export function updateAlertRule(id: number, body: AlertRuleInput): Promise<AlertRule> {
return request(`/alert-rules/${id}`, { method: 'PATCH', body: JSON.stringify(body) })
}
export function deleteAlertRule(id: number): Promise<{ ok: boolean }> {
return request(`/alert-rules/${id}`, { method: 'DELETE' })
}
// Settings
export function getSettings(): Promise<{ settings: AppSetting[] }> {
return request('/settings')
}
export function saveSettings(settings: { key: string; value: string }[]): Promise<{ ok: boolean }> {
return request('/settings', { method: 'PUT', body: JSON.stringify({ settings }) })
}
export function fetchMqttStatus(): Promise<{ connected: boolean; note: string }> {
return request('/settings/mqtt-status')
}

View file

@ -0,0 +1,93 @@
import { useRef, useState } from 'react'
import { Camera, Image as ImageIcon, Loader2, X } from 'lucide-react'
import type { AssetPhoto, PhotoType } from '../types'
import { uploadAssetPhoto, deleteAssetPhoto, photoUrl } from '../api'
// Camera/library capture split: one input with capture="environment" (opens the
// device camera directly on mobile), one plain file input (opens the photo
// library/file picker) — same split as hvac's DevicePhotoUpload.
export default function AssetPhotoUpload({ assetId, photoType, photos, onChanged, canDelete }: {
assetId: number
photoType: PhotoType
photos: AssetPhoto[]
onChanged: () => void
canDelete: boolean
}) {
const [uploading, setUploading] = useState(false)
const [error, setError] = useState('')
const [lightbox, setLightbox] = useState<string | null>(null)
const cameraInput = useRef<HTMLInputElement>(null)
const libraryInput = useRef<HTMLInputElement>(null)
const slotPhotos = photos.filter(p => p.photo_type === photoType)
async function handleFile(file: File | undefined) {
if (!file) return
setUploading(true); setError('')
try {
await uploadAssetPhoto(assetId, file, photoType)
onChanged()
} catch (e) {
setError(e instanceof Error ? e.message : 'Upload failed')
} finally {
setUploading(false)
}
}
async function remove(id: number) {
await deleteAssetPhoto(id).catch(() => {})
onChanged()
}
return (
<div style={{ marginBottom: 10 }}>
<div className="photo-grid">
{slotPhotos.map(p => (
<div key={p.id} className="photo-thumb-wrap">
<img className="photo-thumb" src={photoUrl(p.file_path)} onClick={() => setLightbox(photoUrl(p.file_path))} />
{canDelete && (
<button className="photo-del" onClick={() => remove(p.id)} title="Delete photo">
<X size={12} strokeWidth={2} />
</button>
)}
</div>
))}
{uploading && (
<div className="photo-thumb-wrap">
<div className="photo-thumb photo-thumb-uploading">
<Loader2 size={20} strokeWidth={1.75} className="spin" />
</div>
</div>
)}
</div>
{error && <div className="error-banner">{error}</div>}
<div style={{ display: 'flex', gap: 8 }}>
<button type="button" className="btn btn-sm" onClick={() => cameraInput.current?.click()}>
<Camera size={14} strokeWidth={1.75} /> Take photo
</button>
<input
ref={cameraInput}
type="file" accept="image/*" capture="environment" style={{ display: 'none' }}
onChange={e => { handleFile(e.target.files?.[0]); e.target.value = '' }}
/>
<button type="button" className="btn btn-sm" onClick={() => libraryInput.current?.click()}>
<ImageIcon size={14} strokeWidth={1.75} /> Choose from library
</button>
<input
ref={libraryInput}
type="file" accept="image/*" style={{ display: 'none' }}
onChange={e => { handleFile(e.target.files?.[0]); e.target.value = '' }}
/>
</div>
{lightbox && (
<div className="lightbox-overlay" onClick={() => setLightbox(null)}>
<img className="lightbox-img" src={lightbox} />
<button className="lightbox-close" onClick={() => setLightbox(null)}><X size={20} strokeWidth={1.75} /></button>
</div>
)}
</div>
)
}

View file

@ -0,0 +1,166 @@
import { useEffect, useRef, useState, createContext, useContext } from 'react'
import type { User } from '../types'
function getInactivityMs(): number | null {
if (window.matchMedia('(display-mode: standalone)').matches) return null
const c = document.cookie.split(';').map(s => s.trim()).find(s => s.startsWith('hnf_inactivity_mins='))
if (!c) return null
const mins = parseInt(c.split('=')[1])
return isNaN(mins) || mins <= 0 ? null : mins * 60 * 1000
}
// Only bounce to the central login when actually embedded in the portal shell.
// A directly-opened browser tab must never navigate away from its own scope.
function isEmbedded() {
return window.top !== window
}
interface AuthCtx { user: User }
const Ctx = createContext<AuthCtx | null>(null)
export function useAuth() {
const ctx = useContext(Ctx)
if (!ctx) throw new Error('useAuth must be used inside AuthGate')
return ctx
}
export default function AuthGate({ children }: { children: React.ReactNode }) {
const [state, setState] = useState<'checking' | 'authed' | 'login'>('checking')
const [user, setUser] = useState<User | null>(null)
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
fetch('/api/auth/verify?app=plant', { credentials: 'include' })
.then(async r => {
if (r.ok) {
setUser(await r.json())
setState('authed')
} else if (isEmbedded()) {
window.top!.location.href = `/login?from=${encodeURIComponent('/app/plant')}`
} else {
setState('login')
}
})
.catch(() => { if (!isEmbedded()) setState('login') })
}, [])
// Inactivity auto-logout — configurable per device (Admin Settings → Device).
useEffect(() => {
const ms = getInactivityMs()
if (state !== 'authed' || !ms) return
const timeoutMs: number = ms
async function forceLogout() {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {})
setUser(null)
setState('login')
}
function reset() {
if (timerRef.current) clearTimeout(timerRef.current)
timerRef.current = setTimeout(forceLogout, timeoutMs)
}
const events = ['mousemove', 'keydown', 'click', 'touchstart'] as const
events.forEach(e => window.addEventListener(e, reset, { passive: true }))
reset()
return () => {
if (timerRef.current) clearTimeout(timerRef.current)
events.forEach(e => window.removeEventListener(e, reset))
}
}, [state])
async function login(e: React.FormEvent) {
e.preventDefault()
setLoading(true)
setError('')
try {
const res = await fetch('/api/auth/login', {
method: 'POST', credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
})
if (!res.ok) { setError('Invalid email or password'); return }
const verify = await fetch('/api/auth/verify?app=plant', { credentials: 'include' })
if (verify.ok) {
setUser(await verify.json())
setState('authed')
} else {
setError("You don't have access to this app.")
}
} catch {
setError('Connection error — please try again')
} finally {
setLoading(false)
}
}
if (state === 'checking') {
return (
<div style={{
display: 'flex', alignItems: 'center', justifyContent: 'center',
height: '100vh', fontFamily: 'var(--font)', color: 'var(--text-mid)'
}}>
Loading
</div>
)
}
if (state === 'login') {
return (
<div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center',
justifyContent: 'center', height: '100dvh', padding: '1.5rem',
background: 'var(--navy-dark)',
}}>
<div style={{
background: 'var(--navy)', borderRadius: 'var(--radius)',
padding: '2rem', width: '100%', maxWidth: '360px',
border: '1px solid var(--surface-2)',
}}>
<h1 style={{ fontSize: '1.4rem', marginBottom: '1.5rem', color: 'var(--gold)' }}>
Plant Room
</h1>
<form onSubmit={login} style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
<input
type="email" value={email} onChange={e => setEmail(e.target.value)}
placeholder="Email" required autoComplete="email"
style={inputStyle}
/>
<input
type="password" value={password} onChange={e => setPassword(e.target.value)}
placeholder="Password" required autoComplete="current-password"
style={inputStyle}
/>
{error && <p style={{ color: 'var(--danger)', fontSize: '0.875rem' }}>{error}</p>}
<button type="submit" disabled={loading} style={{
background: loading ? 'var(--surface-2)' : 'var(--gold)',
color: loading ? 'var(--text-muted)' : 'var(--navy-dark)',
border: 'none', borderRadius: '6px', padding: '0.625rem',
fontSize: '1rem', fontWeight: 600, marginTop: '0.25rem',
}}>
{loading ? 'Signing in…' : 'Sign in'}
</button>
</form>
</div>
</div>
)
}
return (
<Ctx.Provider value={{ user: user! }}>
{children}
</Ctx.Provider>
)
}
const inputStyle: React.CSSProperties = {
background: 'var(--navy-dark)', border: '1px solid var(--surface-2)',
borderRadius: '6px', color: 'var(--text)', padding: '0.625rem 0.75rem',
fontSize: '1rem', width: '100%', outline: 'none',
}

View file

@ -0,0 +1,73 @@
import { useState, useEffect } from 'react'
import { NavLink, useLocation } from 'react-router-dom'
import { Gauge, LayoutGrid, Wrench, Bell, Settings, Menu, LogOut } from 'lucide-react'
import { useAuth } from './AuthGate'
import { can } from '../types'
const ICON_PROPS = { size: 16, strokeWidth: 1.75 }
const NAV = [
{ to: '/dashboard', label: 'Dashboard', icon: LayoutGrid, cap: 'view' },
{ to: '/assets', label: 'Assets', icon: Wrench, cap: 'manage_assets' },
{ to: '/alerts', label: 'Alerts', icon: Bell, cap: 'view' },
{ to: '/settings', label: 'Settings', icon: Settings, cap: 'settings' },
]
export default function Layout({ children }: { children: React.ReactNode }) {
const { user } = useAuth()
const items = NAV.filter(n => can(user, n.cap))
const location = useLocation()
const [menuOpen, setMenuOpen] = useState(false)
async function logout() {
await fetch('/plant/api/auth/logout', { method: 'POST', credentials: 'include' })
window.location.reload()
}
useEffect(() => { setMenuOpen(false) }, [location.pathname])
return (
<div className={`app-shell${menuOpen ? ' menu-open' : ''}`}>
<aside className="sidebar">
<div className="sidebar-logo">
<Gauge size={18} strokeWidth={1.75} />
Plant Room
</div>
<nav className="sidebar-nav">
{items.map(({ to, label, icon: Icon }) => (
<NavLink key={to} to={to} className={({ isActive }) => isActive ? 'active' : ''}>
<Icon {...ICON_PROPS} />
{label}
</NavLink>
))}
</nav>
<div className="sidebar-user" style={{ whiteSpace: 'normal' }}>
<div style={{ fontWeight: 600, color: 'var(--text)', fontSize: '12px', marginBottom: '2px' }}>{user.name}</div>
<div style={{ fontSize: '11px', marginBottom: '8px' }}>{user.email}</div>
<button onClick={logout} style={{
display: 'flex', alignItems: 'center', gap: '6px',
background: 'none', border: 'none', color: 'inherit',
fontSize: '12px', padding: 0, cursor: 'pointer',
}}>
<LogOut size={13} strokeWidth={1.75} />
Sign out
</button>
</div>
</aside>
{menuOpen && <div className="menu-backdrop" onClick={() => setMenuOpen(false)} />}
<header className="top-bar">
<button className="top-bar-burger" onClick={() => setMenuOpen(o => !o)}>
<Menu size={20} strokeWidth={1.75} />
</button>
<Gauge size={18} strokeWidth={1.75} color="var(--gold)" />
<span className="top-bar-title">Plant Room</span>
</header>
<main className="page-content">
{children}
</main>
</div>
)
}

374
frontend/src/index.css Normal file
View file

@ -0,0 +1,374 @@
/* Stack design system tokens — include verbatim in every app */
:root {
--navy: #1a1a2e;
--navy-dark: #0f0f20;
--gold: #c9a84c;
--gold-light: #e8c96d;
--surface: rgba(255,255,255,0.07);
--surface-2: rgba(255,255,255,0.08);
--text: rgba(255,255,255,0.88);
--text-muted: rgba(255,255,255,0.48);
--body-bg: #f4f5f7;
--card-bg: #ffffff;
--card-border: #e4e8ee;
--text-dark: #1e293b;
--text-mid: #64748b;
--shadow-sm: 0 1px 3px rgba(0,0,0,0.07), 0 1px 2px rgba(0,0,0,0.04);
--shadow-md: 0 4px 12px rgba(0,0,0,0.08);
--danger: #dc2626;
--radius: 10px;
--font: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
}
body { background: var(--body-bg); color: var(--text-dark); font-family: var(--font); }
/* App theme + semantic tokens */
:root {
--app-primary: #0e7490;
--app-primary-light: #0891b2;
--sev-warning: #d97706;
--sev-critical: #dc2626;
--sev-ok: #16a34a;
--danger-bg: #fef2f2;
--warn-bg: #fffbeb;
--ok-bg: #f0fdf4;
--sidebar-w: 240px;
--topbar-h: 56px;
}
*, *::before, *::after { box-sizing: border-box; }
html, body, #root { height: 100%; margin: 0; font-size: 14px; }
::-webkit-scrollbar { width: 4px; height: 4px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--card-border); border-radius: 2px; }
/* ── App shell ─────────────────────────────────────────────── */
.app-shell { display: flex; height: 100vh; overflow: hidden; }
.sidebar {
width: var(--sidebar-w);
background: var(--navy);
display: flex;
flex-direction: column;
flex-shrink: 0;
overflow-y: auto;
}
.sidebar-logo {
padding: 20px 16px 12px;
color: var(--gold);
font-size: 13px;
font-weight: 600;
letter-spacing: .05em;
text-transform: uppercase;
display: flex;
align-items: center;
gap: 8px;
}
.sidebar-logo svg { opacity: .8; }
.sidebar-nav { flex: 1; padding: 8px 0; }
.sidebar-nav a {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
color: var(--text-muted);
text-decoration: none;
font-size: 13.5px;
transition: background .15s, color .15s;
}
.sidebar-nav a:hover { background: var(--surface); color: var(--text); }
.sidebar-nav a.active { background: rgba(201,168,76,.1); color: var(--gold); }
.sidebar-user {
padding: 12px 16px;
border-top: 1px solid var(--surface-2);
color: var(--text-muted);
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.top-bar {
display: none;
height: var(--topbar-h);
background: var(--navy);
color: var(--text);
align-items: center;
padding: 0 12px;
gap: 10px;
flex-shrink: 0;
}
.top-bar-title { flex: 1; font-size: 15px; font-weight: 600; color: var(--gold); }
.page-content { flex: 1; overflow-y: auto; display: flex; flex-direction: column; }
@media (max-width: 768px) {
.sidebar {
position: fixed;
top: 0; left: 0; bottom: 0;
z-index: 200;
transform: translateX(calc(-1 * var(--sidebar-w)));
transition: transform 0.25s ease;
}
.app-shell.menu-open .sidebar { transform: translateX(0); }
.top-bar { display: flex; }
.app-shell { flex-direction: column; }
.field-row { flex-direction: column; }
}
.menu-backdrop {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.5);
z-index: 199;
}
.top-bar-burger {
background: none;
border: none;
color: var(--text);
cursor: pointer;
display: flex;
align-items: center;
padding: 4px;
flex-shrink: 0;
}
/* ── Page chrome ───────────────────────────────────────────── */
.page { padding: 20px; max-width: 1100px; width: 100%; margin: 0 auto; }
.page-header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
.page-header h1 { font-size: 18px; margin: 0; flex: 1; }
/* ── Buttons ───────────────────────────────────────────────── */
.btn {
display: inline-flex;
align-items: center;
gap: 6px;
border: 1px solid var(--card-border);
background: var(--card-bg);
color: var(--text-dark);
border-radius: var(--radius);
padding: 7px 14px;
font-size: 13px;
cursor: pointer;
font-family: var(--font);
transition: background .12s, border-color .12s;
}
.btn:hover { border-color: var(--text-mid); }
.btn:disabled { opacity: .5; cursor: default; }
.btn-primary { background: var(--gold); border-color: var(--gold); color: var(--navy); font-weight: 600; }
.btn-primary:hover { background: var(--gold-light); border-color: var(--gold-light); }
.btn-danger { background: var(--danger); border-color: var(--danger); color: #fff; }
.btn-sm { padding: 4px 10px; font-size: 12px; border-radius: 8px; }
/* ── Forms ─────────────────────────────────────────────────── */
.field { margin-bottom: 12px; }
.field label { display: block; font-size: 12px; font-weight: 600; color: var(--text-mid); margin-bottom: 4px; }
.field input[type="text"], .field input[type="email"], .field input[type="date"],
.field input[type="number"], .field select, .field textarea {
width: 100%;
border: 1px solid var(--card-border);
border-radius: 8px;
padding: 8px 10px;
font-size: 13.5px;
font-family: var(--font);
color: var(--text-dark);
background: var(--card-bg);
}
.field textarea { min-height: 72px; resize: vertical; }
.field-row { display: flex; gap: 12px; }
.field-row > .field { flex: 1; }
.field-check { display: flex; align-items: center; gap: 8px; font-size: 13.5px; cursor: pointer; }
.field-check input { width: 16px; height: 16px; accent-color: var(--gold); }
.field-hint { font-size: 11.5px; color: var(--text-mid); margin-top: 3px; }
/* ── Cards ─────────────────────────────────────────────────── */
.card {
background: var(--card-bg);
border: 1px solid var(--card-border);
border-radius: var(--radius);
box-shadow: var(--shadow-sm);
padding: 14px 16px;
margin-bottom: 10px;
}
/* ── Asset grid / cards ────────────────────────────────────── */
.asset-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; }
.asset-card {
border-left: 4px solid var(--sev-ok);
}
.asset-card.sev-warning { border-left-color: var(--sev-warning); }
.asset-card.sev-critical { border-left-color: var(--sev-critical); }
.asset-card-title { font-weight: 600; font-size: 14px; margin-bottom: 4px; display: flex; align-items: center; gap: 6px; justify-content: space-between; }
.asset-card-meta { font-size: 12px; color: var(--text-mid); margin-bottom: 8px; }
.asset-field-list { display: flex; flex-direction: column; gap: 4px; }
.asset-field-row { display: flex; justify-content: space-between; gap: 8px; font-size: 12.5px; }
.asset-field-key { color: var(--text-mid); }
.asset-field-value { font-weight: 600; color: var(--text-dark); }
/* ── Badges ────────────────────────────────────────────────── */
.badge {
display: inline-flex;
align-items: center;
gap: 4px;
border-radius: 20px;
padding: 2px 9px;
font-size: 11px;
font-weight: 600;
color: #fff;
white-space: nowrap;
}
.badge-sev-warning { background: var(--sev-warning); }
.badge-sev-critical { background: var(--sev-critical); }
.badge-sev-ok { background: var(--sev-ok); }
.badge-status-open { background: var(--sev-critical); }
.badge-status-acknowledged { background: var(--sev-warning); }
.badge-status-resolved { background: var(--sev-ok); }
.badge-outline {
background: transparent;
border: 1px solid var(--card-border);
color: var(--text-mid);
font-weight: 500;
}
/* ── Modal ─────────────────────────────────────────────────── */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(15,15,32,.55);
display: flex;
align-items: flex-start;
justify-content: center;
padding: 24px 12px;
z-index: 100;
overflow-y: auto;
}
.modal {
background: var(--card-bg);
border-radius: var(--radius);
box-shadow: var(--shadow-md);
width: 100%;
max-width: 680px;
padding: 20px;
margin: auto 0;
}
.modal-header { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 14px; }
.modal-header h2 { font-size: 16px; margin: 0; flex: 1; }
.modal-close {
background: none;
border: none;
cursor: pointer;
color: var(--text-mid);
padding: 2px;
display: flex;
}
.modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; flex-wrap: wrap; }
/* ── Photos ────────────────────────────────────────────────── */
.photo-grid { display: flex; gap: 8px; flex-wrap: wrap; margin: 8px 0; }
.photo-thumb {
width: 84px;
height: 84px;
border-radius: 8px;
object-fit: cover;
border: 1px solid var(--card-border);
cursor: pointer;
}
.photo-thumb-uploading {
display: flex; align-items: center; justify-content: center;
background: var(--card-border); color: var(--text-mid);
}
@keyframes spin { to { transform: rotate(360deg); } }
.spin { animation: spin .75s linear infinite; }
.photo-thumb-wrap { position: relative; }
.photo-del {
position: absolute;
top: -6px;
right: -6px;
background: var(--danger);
color: #fff;
border: none;
border-radius: 50%;
width: 20px;
height: 20px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
}
.lightbox-overlay {
position: fixed; inset: 0; z-index: 200;
background: rgba(0,0,0,.92);
display: flex; align-items: center; justify-content: center;
padding: 16px;
}
.lightbox-img { max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 4px; }
.lightbox-close {
position: absolute; top: 16px; right: 16px;
background: rgba(255,255,255,.15); border: none; border-radius: 50%;
width: 38px; height: 38px; display: flex; align-items: center; justify-content: center;
cursor: pointer; color: #fff; transition: background .12s;
}
.lightbox-close:hover { background: rgba(255,255,255,.28); }
/* ── Tables ────────────────────────────────────────────────── */
.table-wrap { overflow-x: auto; background: var(--card-bg); border: 1px solid var(--card-border); border-radius: var(--radius); box-shadow: var(--shadow-sm); }
table.data { width: 100%; border-collapse: collapse; font-size: 13px; }
table.data th {
text-align: left;
padding: 9px 12px;
font-size: 11.5px;
text-transform: uppercase;
letter-spacing: .04em;
color: var(--text-mid);
border-bottom: 1px solid var(--card-border);
white-space: nowrap;
}
table.data td { padding: 9px 12px; border-bottom: 1px solid var(--card-border); vertical-align: top; }
table.data tr:last-child td { border-bottom: none; }
table.data tr.clickable { cursor: pointer; }
/* ── Misc ──────────────────────────────────────────────────── */
.empty-state { text-align: center; color: var(--text-mid); padding: 40px 16px; font-size: 13.5px; }
.error-banner {
background: var(--danger-bg);
border: 1px solid var(--danger);
color: var(--danger);
border-radius: var(--radius);
padding: 10px 14px;
margin-bottom: 12px;
font-size: 13px;
}
.ok-banner {
background: var(--ok-bg);
border: 1px solid var(--sev-ok);
color: var(--sev-ok);
border-radius: var(--radius);
padding: 10px 14px;
margin-bottom: 12px;
font-size: 13px;
}
.warn-banner {
background: var(--warn-bg);
border: 1px solid var(--sev-warning);
color: var(--sev-warning);
border-radius: var(--radius);
padding: 10px 14px;
margin-bottom: 12px;
font-size: 13px;
}
.section-title { font-size: 13px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; color: var(--text-mid); margin: 18px 0 8px; }
.muted { color: var(--text-mid); }
/* Sidebar scrollbar */
.sidebar::-webkit-scrollbar, .sidebar-nav::-webkit-scrollbar { width: 4px; }
.sidebar::-webkit-scrollbar-track, .sidebar-nav::-webkit-scrollbar-track { background: transparent; }
.sidebar::-webkit-scrollbar-thumb, .sidebar-nav::-webkit-scrollbar-thumb { background: rgba(201,168,76,0.35); border-radius: 2px; }
.sidebar::-webkit-scrollbar-thumb:hover, .sidebar-nav::-webkit-scrollbar-thumb:hover { background: rgba(201,168,76,0.65); }
.sidebar, .sidebar-nav { scrollbar-width: thin; scrollbar-color: rgba(201,168,76,0.35) transparent; }

10
frontend/src/main.tsx Normal file
View file

@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)

View file

@ -0,0 +1,146 @@
import { useEffect, useState, useCallback } from 'react'
import { Check, CheckCheck } from 'lucide-react'
import { fetchAlerts, acknowledgeAlert, resolveAlert } from '../api'
import type { PlantAlert, AlertStatus, AlertSeverity } from '../types'
import { CONDITION_LABELS } from '../types'
import { useAuth } from '../components/AuthGate'
import { can } from '../types'
const STATUS_OPTIONS: { value: AlertStatus | ''; label: string }[] = [
{ value: '', label: 'All statuses' },
{ value: 'open', label: 'Open' },
{ value: 'acknowledged', label: 'Acknowledged' },
{ value: 'resolved', label: 'Resolved' },
]
const SEVERITY_OPTIONS: { value: AlertSeverity | ''; label: string }[] = [
{ value: '', label: 'All severities' },
{ value: 'warning', label: 'Warning' },
{ value: 'critical', label: 'Critical' },
]
export default function Alerts() {
const { user } = useAuth()
const canAck = can(user, 'acknowledge_alerts')
const [alerts, setAlerts] = useState<PlantAlert[]>([])
const [status, setStatus] = useState<AlertStatus | ''>('open')
const [severity, setSeverity] = useState<AlertSeverity | ''>('')
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [busyId, setBusyId] = useState<number | null>(null)
const load = useCallback(() => {
setLoading(true)
fetchAlerts({ status: status || undefined, severity: severity || undefined })
.then(setAlerts)
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load alerts'))
.finally(() => setLoading(false))
}, [status, severity])
useEffect(() => { load() }, [load])
async function ack(id: number) {
setBusyId(id); setError('')
try {
await acknowledgeAlert(id)
load()
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to acknowledge')
} finally {
setBusyId(null)
}
}
async function resolve(id: number) {
setBusyId(id); setError('')
try {
await resolveAlert(id)
load()
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to resolve')
} finally {
setBusyId(null)
}
}
return (
<div className="page">
<div className="page-header">
<h1>Alerts</h1>
</div>
{error && <div className="error-banner">{error}</div>}
<div className="field-row" style={{ marginBottom: 16, maxWidth: 420 }}>
<div className="field">
<label>Status</label>
<select value={status} onChange={e => setStatus(e.target.value as AlertStatus | '')}>
{STATUS_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
</div>
<div className="field">
<label>Severity</label>
<select value={severity} onChange={e => setSeverity(e.target.value as AlertSeverity | '')}>
{SEVERITY_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
</div>
</div>
{loading ? (
<p className="muted">Loading</p>
) : alerts.length === 0 ? (
<div className="empty-state">No alerts match this filter.</div>
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Asset</th>
<th>Field</th>
<th>Condition</th>
<th>Value at trigger</th>
<th>Severity</th>
<th>Status</th>
<th>Triggered</th>
{canAck && <th>Actions</th>}
</tr>
</thead>
<tbody>
{alerts.map(a => (
<tr key={a.id}>
<td>{a.asset_name}</td>
<td>{a.field_key.replace(/_/g, ' ')}</td>
<td>{CONDITION_LABELS[a.condition]} {a.threshold}</td>
<td>{a.value_at_trigger ?? '—'}</td>
<td><span className={`badge badge-sev-${a.severity}`}>{a.severity}</span></td>
<td><span className={`badge badge-status-${a.status}`}>{a.status}</span></td>
<td>{new Date(a.triggered_at).toLocaleString('en-GB')}</td>
{canAck && (
<td>
{a.status === 'open' && (
<div style={{ display: 'flex', gap: 6 }}>
<button className="btn btn-sm" disabled={busyId === a.id} onClick={() => ack(a.id)}>
<Check size={12} strokeWidth={1.75} /> Ack
</button>
<button className="btn btn-sm" disabled={busyId === a.id} onClick={() => resolve(a.id)}>
<CheckCheck size={12} strokeWidth={1.75} /> Resolve
</button>
</div>
)}
{a.status === 'acknowledged' && (
<button className="btn btn-sm" disabled={busyId === a.id} onClick={() => resolve(a.id)}>
<CheckCheck size={12} strokeWidth={1.75} /> Resolve
</button>
)}
{a.status === 'resolved' && <span className="muted" style={{ fontSize: 12 }}></span>}
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)
}

View file

@ -0,0 +1,291 @@
import { Fragment, useEffect, useState } from 'react'
import { ChevronDown, ChevronRight, Plus } from 'lucide-react'
import { fetchAssets, createAsset, updateAsset, fetchAssetPhotos } from '../api'
import type { PlantAsset, AssetPhoto } from '../types'
import { ASSET_TYPES, ASSET_TYPE_LABELS } from '../types'
import AssetPhotoUpload from '../components/AssetPhotoUpload'
import { useAuth } from '../components/AuthGate'
import { can } from '../types'
const BLANK_FORM = {
name: '', asset_type: 'boiler' as PlantAsset['asset_type'], location: '', make_model: '',
serial_no: '', install_date: '', notes: '', mqtt_topic_prefix: '',
}
export default function Assets() {
const { user } = useAuth()
const canManage = can(user, 'manage_assets')
const [assets, setAssets] = useState<PlantAsset[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [msg, setMsg] = useState('')
const [expanded, setExpanded] = useState<number | null>(null)
const [photosByAsset, setPhotosByAsset] = useState<Record<number, AssetPhoto[]>>({})
const [editForm, setEditForm] = useState<Record<string, string>>({})
const [showNew, setShowNew] = useState(false)
const [newForm, setNewForm] = useState(BLANK_FORM)
const [creating, setCreating] = useState(false)
function load() {
fetchAssets()
.then(setAssets)
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load'))
.finally(() => setLoading(false))
}
useEffect(load, [])
async function toggleExpand(a: PlantAsset) {
if (expanded === a.id) { setExpanded(null); return }
setExpanded(a.id)
setEditForm({
name: a.name, asset_type: a.asset_type, location: a.location || '', make_model: a.make_model || '',
serial_no: a.serial_no || '', install_date: a.install_date ? a.install_date.slice(0, 10) : '',
notes: a.notes || '', mqtt_topic_prefix: a.mqtt_topic_prefix || '', active: String(a.active),
})
if (!photosByAsset[a.id]) {
const photos = await fetchAssetPhotos(a.id).catch(() => [])
setPhotosByAsset(prev => ({ ...prev, [a.id]: photos }))
}
}
async function reloadPhotos(id: number) {
const photos = await fetchAssetPhotos(id).catch(() => [])
setPhotosByAsset(prev => ({ ...prev, [id]: photos }))
}
async function saveEdit(id: number) {
setError(''); setMsg('')
try {
await updateAsset(id, {
name: editForm.name,
asset_type: editForm.asset_type as PlantAsset['asset_type'],
location: editForm.location || null,
make_model: editForm.make_model || null,
serial_no: editForm.serial_no || null,
install_date: editForm.install_date || null,
notes: editForm.notes || null,
mqtt_topic_prefix: editForm.mqtt_topic_prefix || null,
active: editForm.active === 'true',
})
setMsg('Saved')
setTimeout(() => setMsg(''), 2000)
load()
} catch (e) {
setError(e instanceof Error ? e.message : 'Save failed')
}
}
async function handleCreate(e: React.FormEvent) {
e.preventDefault()
if (!newForm.name.trim()) return
setCreating(true); setError(''); setMsg('')
try {
await createAsset({
name: newForm.name.trim(),
asset_type: newForm.asset_type,
location: newForm.location || null,
make_model: newForm.make_model || null,
serial_no: newForm.serial_no || null,
install_date: newForm.install_date || null,
notes: newForm.notes || null,
mqtt_topic_prefix: newForm.mqtt_topic_prefix || null,
})
setNewForm(BLANK_FORM)
setShowNew(false)
setMsg('Asset created')
load()
} catch (e) {
setError(e instanceof Error ? e.message : 'Create failed')
} finally {
setCreating(false)
}
}
if (loading) return <div className="page"><p className="muted">Loading</p></div>
return (
<div className="page">
<div className="page-header">
<h1>Assets</h1>
{canManage && (
<button className="btn btn-primary" onClick={() => setShowNew(s => !s)}>
<Plus size={14} strokeWidth={1.75} /> {showNew ? 'Cancel' : 'Add asset'}
</button>
)}
</div>
{error && <div className="error-banner">{error}</div>}
{msg && <div className="ok-banner">{msg}</div>}
{showNew && canManage && (
<form onSubmit={handleCreate} className="card" style={{ marginBottom: 16 }}>
<div className="field-row">
<div className="field">
<label>Name</label>
<input type="text" value={newForm.name} onChange={e => setNewForm({ ...newForm, name: e.target.value })} required />
</div>
<div className="field">
<label>Type</label>
<select value={newForm.asset_type} onChange={e => setNewForm({ ...newForm, asset_type: e.target.value as PlantAsset['asset_type'] })}>
{ASSET_TYPES.map(t => <option key={t} value={t}>{ASSET_TYPE_LABELS[t]}</option>)}
</select>
</div>
</div>
<div className="field-row">
<div className="field">
<label>Location</label>
<input type="text" value={newForm.location} onChange={e => setNewForm({ ...newForm, location: e.target.value })} placeholder="Plant room, roof, ..." />
</div>
<div className="field">
<label>MQTT topic prefix</label>
<input type="text" value={newForm.mqtt_topic_prefix} onChange={e => setNewForm({ ...newForm, mqtt_topic_prefix: e.target.value })} placeholder="plant/water-softener" />
</div>
</div>
<div className="field-row">
<div className="field">
<label>Make / model</label>
<input type="text" value={newForm.make_model} onChange={e => setNewForm({ ...newForm, make_model: e.target.value })} />
</div>
<div className="field">
<label>Serial no.</label>
<input type="text" value={newForm.serial_no} onChange={e => setNewForm({ ...newForm, serial_no: e.target.value })} />
</div>
<div className="field">
<label>Install date</label>
<input type="date" value={newForm.install_date} onChange={e => setNewForm({ ...newForm, install_date: e.target.value })} />
</div>
</div>
<div className="field">
<label>Notes</label>
<textarea value={newForm.notes} onChange={e => setNewForm({ ...newForm, notes: e.target.value })} />
</div>
<button className="btn btn-primary" type="submit" disabled={creating}>
{creating ? 'Creating…' : 'Create asset'}
</button>
</form>
)}
{assets.length === 0 ? (
<div className="empty-state">No assets yet add the first one above.</div>
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Type</th>
<th>Location</th>
<th>MQTT prefix</th>
<th>Active</th>
<th>Photos</th>
</tr>
</thead>
<tbody>
{assets.map(a => (
<Fragment key={a.id}>
<tr className="clickable" onClick={() => toggleExpand(a)}>
<td>{expanded === a.id ? <ChevronDown size={14} strokeWidth={1.75} /> : <ChevronRight size={14} strokeWidth={1.75} />}</td>
<td>{a.name}</td>
<td>{ASSET_TYPE_LABELS[a.asset_type]}</td>
<td>{a.location || <span className="muted"></span>}</td>
<td>{a.mqtt_topic_prefix || <span className="muted">not wired</span>}</td>
<td><span className={`badge ${a.active ? 'badge-sev-ok' : 'badge-outline'}`}>{a.active ? 'Active' : 'Inactive'}</span></td>
<td>{a.photo_count ?? 0}</td>
</tr>
{expanded === a.id && (
<tr>
<td colSpan={7}>
{canManage ? (
<>
<div className="field-row">
<div className="field">
<label>Name</label>
<input type="text" value={editForm.name || ''} onChange={e => setEditForm({ ...editForm, name: e.target.value })} />
</div>
<div className="field">
<label>Type</label>
<select value={editForm.asset_type || ''} onChange={e => setEditForm({ ...editForm, asset_type: e.target.value })}>
{ASSET_TYPES.map(t => <option key={t} value={t}>{ASSET_TYPE_LABELS[t]}</option>)}
</select>
</div>
<div className="field">
<label>Active</label>
<select value={editForm.active || 'true'} onChange={e => setEditForm({ ...editForm, active: e.target.value })}>
<option value="true">Active</option>
<option value="false">Inactive</option>
</select>
</div>
</div>
<div className="field-row">
<div className="field">
<label>Location</label>
<input type="text" value={editForm.location || ''} onChange={e => setEditForm({ ...editForm, location: e.target.value })} />
</div>
<div className="field">
<label>MQTT topic prefix</label>
<input type="text" value={editForm.mqtt_topic_prefix || ''} onChange={e => setEditForm({ ...editForm, mqtt_topic_prefix: e.target.value })} placeholder="plant/water-softener" />
</div>
</div>
<div className="field-row">
<div className="field">
<label>Make / model</label>
<input type="text" value={editForm.make_model || ''} onChange={e => setEditForm({ ...editForm, make_model: e.target.value })} />
</div>
<div className="field">
<label>Serial no.</label>
<input type="text" value={editForm.serial_no || ''} onChange={e => setEditForm({ ...editForm, serial_no: e.target.value })} />
</div>
<div className="field">
<label>Install date</label>
<input type="date" value={editForm.install_date || ''} onChange={e => setEditForm({ ...editForm, install_date: e.target.value })} />
</div>
</div>
<div className="field">
<label>Notes</label>
<textarea value={editForm.notes || ''} onChange={e => setEditForm({ ...editForm, notes: e.target.value })} />
</div>
<button className="btn btn-primary btn-sm" onClick={() => saveEdit(a.id)} style={{ marginBottom: 12 }}>
Save changes
</button>
</>
) : (
<div className="field-hint" style={{ marginBottom: 8 }}>
{a.make_model || 'No make/model set'} · {a.serial_no || 'No serial recorded'}
</div>
)}
<div className="field-row">
<div style={{ flex: 1 }}>
<div className="field-hint" style={{ marginBottom: 4 }}>Asset photo</div>
<AssetPhotoUpload
assetId={a.id} photoType="asset"
photos={photosByAsset[a.id] || []}
onChanged={() => reloadPhotos(a.id)}
canDelete={canManage}
/>
</div>
<div style={{ flex: 1 }}>
<div className="field-hint" style={{ marginBottom: 4 }}>Serial / model plate photo</div>
<AssetPhotoUpload
assetId={a.id} photoType="serial_plate"
photos={photosByAsset[a.id] || []}
onChanged={() => reloadPhotos(a.id)}
canDelete={canManage}
/>
</div>
</div>
</td>
</tr>
)}
</Fragment>
))}
</tbody>
</table>
</div>
)}
</div>
)
}

View file

@ -0,0 +1,118 @@
import { useEffect, useState, useCallback } from 'react'
import { AlertTriangle, WifiOff } from 'lucide-react'
import { fetchStatus } from '../api'
import type { AssetStatus, AssetType } from '../types'
import { ASSET_TYPES, ASSET_TYPE_LABELS } from '../types'
const POLL_MS = 30000
function fieldLabel(key: string): string {
return key.replace(/_/g, ' ')
}
function fieldValue(f: { value_numeric: string | null; value_text: string | null }): string {
if (f.value_text !== null && f.value_text !== '' && isNaN(Number(f.value_text))) return f.value_text
if (f.value_numeric !== null) return f.value_numeric
return f.value_text ?? '—'
}
function AssetCard({ asset }: { asset: AssetStatus }) {
const sevClass = asset.max_severity ? `sev-${asset.max_severity}` : ''
return (
<div className={`card asset-card ${sevClass}`}>
<div className="asset-card-title">
<span>{asset.name}</span>
{asset.max_severity && (
<span className={`badge badge-sev-${asset.max_severity}`}>
{asset.open_alert_count} open
</span>
)}
</div>
<div className="asset-card-meta">
{asset.location || 'No location set'}
{asset.mqtt_topic_prefix ? '' : ' · not wired to MQTT yet'}
</div>
{asset.latest.length === 0 ? (
<div className="muted" style={{ fontSize: 12.5 }}>No telemetry received yet.</div>
) : (
<div className="asset-field-list">
{asset.latest.map(f => (
<div key={f.field_key} className="asset-field-row">
<span className="asset-field-key">{fieldLabel(f.field_key)}</span>
<span className="asset-field-value">{fieldValue(f)}</span>
</div>
))}
</div>
)}
</div>
)
}
export default function Dashboard() {
const [assets, setAssets] = useState<AssetStatus[]>([])
const [openAlerts, setOpenAlerts] = useState(0)
const [mqttConnected, setMqttConnected] = useState(true)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const load = useCallback(() => {
fetchStatus()
.then(res => {
setAssets(res.assets)
setOpenAlerts(res.open_alerts)
setMqttConnected(res.mqtt_connected)
setError('')
})
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load status'))
.finally(() => setLoading(false))
}, [])
useEffect(() => {
load()
const t = setInterval(load, POLL_MS)
return () => clearInterval(t)
}, [load])
if (loading) return <div className="page"><p className="muted">Loading</p></div>
const byType = (t: AssetType) => assets.filter(a => a.asset_type === t)
return (
<div className="page">
<div className="page-header">
<h1>Dashboard</h1>
</div>
{error && <div className="error-banner">{error}</div>}
{!mqttConnected && (
<div className="warn-banner" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<WifiOff size={14} strokeWidth={1.75} />
MQTT broker not connected asset telemetry may be stale.
</div>
)}
{openAlerts > 0 && (
<div className="error-banner" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<AlertTriangle size={14} strokeWidth={1.75} />
{openAlerts} open alert{openAlerts === 1 ? '' : 's'} see the Alerts page.
</div>
)}
{assets.length === 0 ? (
<div className="empty-state">No active assets yet add one on the Assets page.</div>
) : (
ASSET_TYPES.map(type => {
const group = byType(type)
if (group.length === 0) return null
return (
<div key={type}>
<div className="section-title">{ASSET_TYPE_LABELS[type]}</div>
<div className="asset-grid">
{group.map(a => <AssetCard key={a.id} asset={a} />)}
</div>
</div>
)
})
)}
</div>
)
}

View file

@ -0,0 +1,267 @@
import { useEffect, useState } from 'react'
import { Wifi, WifiOff, Plus, Trash2 } from 'lucide-react'
import {
getSettings, saveSettings, fetchMqttStatus, fetchAssets,
fetchAlertRules, createAlertRule, updateAlertRule, deleteAlertRule,
} from '../api'
import type { PlantAsset, AlertRule, AlertCondition, AlertSeverity } from '../types'
import { ASSET_TYPES, ASSET_TYPE_LABELS, CONDITION_LABELS } from '../types'
const SETTING_LABELS: Record<string, { label: string; hint: string; placeholder?: string }> = {
alert_notify_email: {
label: 'Alert notification email',
hint: 'Address that receives an email whenever a new alert is triggered. Leave blank to disable alert emails.',
placeholder: 'maintenance@example.com',
},
}
const CONDITIONS: AlertCondition[] = ['lt', 'gt', 'eq', 'stale_minutes']
const SEVERITIES: AlertSeverity[] = ['warning', 'critical']
const BLANK_RULE = {
scope: 'asset_type' as 'asset' | 'asset_type',
asset_id: '' as string,
asset_type: 'boiler' as PlantAsset['asset_type'],
field_key: '',
condition: 'lt' as AlertCondition,
threshold: '',
severity: 'warning' as AlertSeverity,
}
export default function Settings() {
const [values, setValues] = useState<Record<string, string>>({})
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [msg, setMsg] = useState('')
const [mqttConnected, setMqttConnected] = useState<boolean | null>(null)
const [mqttNote, setMqttNote] = useState('')
const [assets, setAssets] = useState<PlantAsset[]>([])
const [rules, setRules] = useState<AlertRule[]>([])
const [showNewRule, setShowNewRule] = useState(false)
const [newRule, setNewRule] = useState(BLANK_RULE)
const [creatingRule, setCreatingRule] = useState(false)
function loadSettings() {
getSettings()
.then(({ settings }) => {
const v: Record<string, string> = {}
for (const s of settings) v[s.key] = s.value
setValues(v)
})
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load settings'))
.finally(() => setLoading(false))
}
function loadRules() {
fetchAlertRules().then(setRules).catch(() => {})
}
useEffect(() => {
loadSettings()
loadRules()
fetchAssets().then(setAssets).catch(() => {})
fetchMqttStatus().then(s => { setMqttConnected(s.connected); setMqttNote(s.note) }).catch(() => {})
}, [])
async function handleSaveSettings() {
setSaving(true); setError(''); setMsg('')
try {
await saveSettings(Object.entries(values).map(([key, value]) => ({ key, value })))
setMsg('Settings saved'); setTimeout(() => setMsg(''), 2500)
} catch (e) {
setError(e instanceof Error ? e.message : 'Save failed')
} finally {
setSaving(false)
}
}
async function handleCreateRule(e: React.FormEvent) {
e.preventDefault()
if (!newRule.field_key.trim() || newRule.threshold === '') return
setCreatingRule(true); setError(''); setMsg('')
try {
await createAlertRule({
asset_id: newRule.scope === 'asset' && newRule.asset_id ? Number(newRule.asset_id) : null,
asset_type: newRule.scope === 'asset_type' ? newRule.asset_type : null,
field_key: newRule.field_key.trim(),
condition: newRule.condition,
threshold: Number(newRule.threshold),
severity: newRule.severity,
})
setNewRule(BLANK_RULE)
setShowNewRule(false)
loadRules()
setMsg('Alert rule created')
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to create rule')
} finally {
setCreatingRule(false)
}
}
async function toggleRuleActive(rule: AlertRule) {
try {
await updateAlertRule(rule.id, { active: !rule.active })
loadRules()
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to update rule')
}
}
async function removeRule(id: number) {
try {
await deleteAlertRule(id)
loadRules()
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to delete rule')
}
}
if (loading) return <div className="page"><p className="muted">Loading</p></div>
return (
<div className="page">
<div className="page-header">
<h1>Settings</h1>
</div>
{error && <div className="error-banner">{error}</div>}
{msg && <div className="ok-banner">{msg}</div>}
<div className="section-title">MQTT Broker</div>
<div className="card" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{mqttConnected ? <Wifi size={16} strokeWidth={1.75} color="var(--sev-ok)" /> : <WifiOff size={16} strokeWidth={1.75} color="var(--danger)" />}
<span>{mqttNote || 'Checking…'}</span>
</div>
<div className="section-title">Notifications</div>
{Object.entries(SETTING_LABELS).map(([key, meta]) => (
<div className="field" key={key} style={{ maxWidth: 420 }}>
<label>{meta.label}</label>
<input
type="text"
value={values[key] ?? ''}
placeholder={meta.placeholder}
onChange={e => setValues(v => ({ ...v, [key]: e.target.value }))}
/>
<div className="field-hint">{meta.hint}</div>
</div>
))}
<button className="btn btn-primary" disabled={saving} onClick={handleSaveSettings} style={{ marginBottom: 24 }}>
{saving ? 'Saving…' : 'Save Settings'}
</button>
<div className="section-title" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<span>Alert Rules</span>
<button className="btn btn-sm" onClick={() => setShowNewRule(s => !s)}>
<Plus size={13} strokeWidth={1.75} /> {showNewRule ? 'Cancel' : 'Add rule'}
</button>
</div>
{showNewRule && (
<form onSubmit={handleCreateRule} className="card" style={{ marginBottom: 16 }}>
<div className="field-row">
<div className="field">
<label>Applies to</label>
<select value={newRule.scope} onChange={e => setNewRule({ ...newRule, scope: e.target.value as 'asset' | 'asset_type' })}>
<option value="asset_type">Every asset of a type</option>
<option value="asset">A specific asset</option>
</select>
</div>
{newRule.scope === 'asset_type' ? (
<div className="field">
<label>Asset type</label>
<select value={newRule.asset_type} onChange={e => setNewRule({ ...newRule, asset_type: e.target.value as PlantAsset['asset_type'] })}>
{ASSET_TYPES.map(t => <option key={t} value={t}>{ASSET_TYPE_LABELS[t]}</option>)}
</select>
</div>
) : (
<div className="field">
<label>Asset</label>
<select value={newRule.asset_id} onChange={e => setNewRule({ ...newRule, asset_id: e.target.value })} required>
<option value="">Select an asset</option>
{assets.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
</select>
</div>
)}
</div>
<div className="field-row">
<div className="field">
<label>Field key</label>
<input
type="text" value={newRule.field_key}
onChange={e => setNewRule({ ...newRule, field_key: e.target.value })}
placeholder="salt_level_pct" required
/>
</div>
<div className="field">
<label>Condition</label>
<select value={newRule.condition} onChange={e => setNewRule({ ...newRule, condition: e.target.value as AlertCondition })}>
{CONDITIONS.map(c => <option key={c} value={c}>{CONDITION_LABELS[c]}</option>)}
</select>
</div>
<div className="field">
<label>Threshold</label>
<input
type="number" value={newRule.threshold}
onChange={e => setNewRule({ ...newRule, threshold: e.target.value })}
required
/>
</div>
<div className="field">
<label>Severity</label>
<select value={newRule.severity} onChange={e => setNewRule({ ...newRule, severity: e.target.value as AlertSeverity })}>
{SEVERITIES.map(s => <option key={s} value={s}>{s}</option>)}
</select>
</div>
</div>
<button className="btn btn-primary" type="submit" disabled={creatingRule}>
{creatingRule ? 'Creating…' : 'Create rule'}
</button>
</form>
)}
{rules.length === 0 ? (
<div className="empty-state">No alert rules yet.</div>
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th>Scope</th>
<th>Field</th>
<th>Condition</th>
<th>Severity</th>
<th>Active</th>
<th></th>
</tr>
</thead>
<tbody>
{rules.map(r => (
<tr key={r.id}>
<td>{r.asset_id ? r.asset_name : `All ${r.asset_type ? ASSET_TYPE_LABELS[r.asset_type] : ''}`}</td>
<td>{r.field_key.replace(/_/g, ' ')}</td>
<td>{CONDITION_LABELS[r.condition]} {r.threshold}</td>
<td><span className={`badge badge-sev-${r.severity}`}>{r.severity}</span></td>
<td>
<button className="btn btn-sm" onClick={() => toggleRuleActive(r)}>
{r.active ? 'Active' : 'Inactive'}
</button>
</td>
<td>
<button className="btn btn-sm btn-danger" onClick={() => removeRule(r.id)}>
<Trash2 size={12} strokeWidth={1.75} />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)
}

110
frontend/src/types.ts Normal file
View file

@ -0,0 +1,110 @@
export type AssetType = 'boiler' | 'water_softener' | 'calorifier' | 'pump'
export type AlertCondition = 'lt' | 'gt' | 'eq' | 'stale_minutes'
export type AlertSeverity = 'warning' | 'critical'
export type AlertStatus = 'open' | 'acknowledged' | 'resolved'
export type PhotoType = 'asset' | 'serial_plate'
export const ASSET_TYPES: AssetType[] = ['boiler', 'water_softener', 'calorifier', 'pump']
export const ASSET_TYPE_LABELS: Record<AssetType, string> = {
boiler: 'Boiler',
water_softener: 'Water Softener',
calorifier: 'Calorifier',
pump: 'Pump / Pressurisation Set',
}
export const CONDITION_LABELS: Record<AlertCondition, string> = {
lt: 'Less than',
gt: 'Greater than',
eq: 'Equal to',
stale_minutes: 'Stale for (minutes, no update)',
}
export interface PlantAsset {
id: number
name: string
asset_type: AssetType
location: string | null
make_model: string | null
serial_no: string | null
install_date: string | null
notes: string | null
active: boolean
mqtt_topic_prefix: string | null
created_at: string
photo_count?: number
}
export interface TelemetryField {
asset_id: number
field_key: string
value_numeric: string | null
value_text: string | null
updated_at: string
}
export interface AssetStatus extends PlantAsset {
latest: TelemetryField[]
open_alert_count: number
max_severity: AlertSeverity | null
}
export interface AlertRule {
id: number
asset_id: number | null
asset_type: AssetType | null
field_key: string
condition: AlertCondition
threshold: string
severity: AlertSeverity
active: boolean
created_at: string
asset_name?: string | null
}
export interface PlantAlert {
id: number
rule_id: number
asset_id: number
field_key: string
value_at_trigger: string | null
status: AlertStatus
triggered_at: string
acknowledged_at: string | null
acknowledged_by: string | null
resolved_at: string | null
asset_name: string
asset_type: AssetType
condition: AlertCondition
threshold: string
severity: AlertSeverity
}
export interface AssetPhoto {
id: number
asset_id: number
file_name: string
file_path: string
mime_type: string
photo_type: PhotoType
uploaded_by: string
uploaded_at: string
}
export interface AppSetting {
key: string
value: string
updated_at: string
}
export interface User {
user_id: number
name: string
email: string
is_admin: boolean
caps: string[] // bare slugs — verify?app=plant strips the prefix
}
export function can(user: User, cap: string): boolean {
return user.is_admin || user.caps.includes(cap)
}

1
frontend/src/vite-env.d.ts vendored Normal file
View file

@ -0,0 +1 @@
/// <reference types="vite/client" />

19
frontend/tsconfig.json Normal file
View file

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": false,
"noUnusedParameters": false
},
"include": ["src"]
}

7
frontend/vite.config.ts Normal file
View file

@ -0,0 +1,7 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
base: '/plant/',
plugins: [react()],
})