Scaffold Phase 1 hvac app — NewBook-driven room TRV heating scheduler

Ports the state machine, retry/backoff, and guest-override detection from
the retired homeassistant-newbook-heating-component, without depending on
Home Assistant. Backend (Fastify/pg) + frontend (React/Vite/TS) following
standard stack conventions; LXC 128 (127 was already taken by utilities).

MHI/Midea/Daikin/boiler drivers and the shared MQTT broker (LXC 104) are
later phases/infra, not included here.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
jtricerolph 2026-07-26 18:00:42 +00:00
commit 276c04f8c6
42 changed files with 5461 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/hvac
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="#c1440e" />
<title>HVAC</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 /hvac/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 /hvac/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 /hvac/health {
proxy_pass http://backend:3001/health;
}
location ~* /hvac/.*\.(js|css|png|ico|svg|woff2?)$ {
expires 1y;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
location /hvac/ {
add_header Cache-Control "no-cache" always;
try_files $uri /hvac/index.html;
}
location = / {
return 301 /hvac/;
}
}

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-hvac-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"
}
}

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

@ -0,0 +1,33 @@
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 Devices from './pages/Devices'
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_devices')) return <Navigate to="/devices" replace />
if (can(user, 'settings')) return <Navigate to="/settings" replace />
return <div className="page"><p className="muted">You don't have access to any HVAC pages yet.</p></div>
}
export default function App() {
return (
<BrowserRouter basename="/hvac">
<AuthGate>
<Layout>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/devices" element={<Devices />} />
<Route path="/settings" element={<Settings />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</Layout>
</AuthGate>
</BrowserRouter>
)
}

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

@ -0,0 +1,108 @@
import type {
Zone, ZoneStatus, Device, DevicePhoto, ActivityEntry, NewbookSite, AppConfig,
} from './types'
const BASE = '/hvac/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()
}
// Zones
export function fetchZones(): Promise<Zone[]> {
return request('/zones')
}
export function updateZone(id: number, body: Record<string, unknown>): Promise<Zone> {
return request(`/zones/${id}`, { method: 'PATCH', body: JSON.stringify(body) })
}
export function createZone(body: { name: string; zone_type: 'room' | 'public_area'; occupied_temp?: number; vacant_temp?: number }): Promise<Zone> {
return request('/zones', { method: 'POST', body: JSON.stringify(body) })
}
export function fetchNewbookSites(): Promise<{ sites: NewbookSite[] }> {
return request('/zones/newbook-sites')
}
export function saveExcludedSites(excludedSiteIds: string[]): Promise<{ ok: boolean }> {
return request('/zones/newbook-sites', { method: 'PUT', body: JSON.stringify({ excluded_site_ids: excludedSiteIds }) })
}
export function testNewbookConnection(): Promise<{ ok: boolean; message?: string; error?: string }> {
return request('/zones/newbook-test', { method: 'POST', body: JSON.stringify({}) })
}
export function syncZonesFromNewbook(): Promise<{ ok: boolean; created: number; updated: number; total: number }> {
return request('/zones/sync-newbook', { method: 'POST', body: JSON.stringify({}) })
}
// Status / activity
export function fetchStatus(): Promise<{ mqtt_connected: boolean; zones: ZoneStatus[] }> {
return request('/status')
}
export function fetchActivity(zoneId?: number, limit = 100): Promise<ActivityEntry[]> {
const params = new URLSearchParams()
if (zoneId) params.set('zone_id', String(zoneId))
params.set('limit', String(limit))
return request(`/status/activity?${params.toString()}`)
}
// Override
export function overrideZone(id: number, tempC: number): Promise<{ ok: boolean; successful: number; total: number; auto_mode: boolean; error?: string }> {
return request(`/zones/${id}/override`, { method: 'POST', body: JSON.stringify({ temp_c: tempC }) })
}
// Devices
export function fetchDevices(): Promise<Device[]> {
return request('/devices')
}
export function discoverDevices(deviceType: string): Promise<{ ok: boolean; devices?: unknown[]; found?: number; new?: number; note?: string; error?: string }> {
return request('/devices/discover', { method: 'POST', body: JSON.stringify({ device_type: deviceType }) })
}
export function updateDevice(id: number, body: { zone_id?: number | null; location?: string }): Promise<Device> {
return request(`/devices/${id}`, { method: 'PATCH', body: JSON.stringify(body) })
}
export function createMaintenanceAsset(id: number): Promise<{ ok: boolean; notImplemented?: boolean; error?: string }> {
return request(`/devices/${id}/create-maintenance-asset`, { method: 'POST', body: JSON.stringify({}) })
}
// Device photos — multipart, so no JSON content-type header
export async function uploadDevicePhoto(deviceId: number, file: File, photoType: 'device' | 'serial_plate'): Promise<DevicePhoto> {
const form = new FormData()
form.append('photo_type', photoType)
form.append('file', file)
const res = await fetch(`${BASE}/devices/${deviceId}/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 fetchDevicePhotos(deviceId: number): Promise<DevicePhoto[]> {
return request(`/devices/${deviceId}/photos`)
}
export function deleteDevicePhoto(id: number): Promise<{ ok: boolean }> {
return request(`/photos/${id}`, { method: 'DELETE' })
}
export function photoUrl(filePath: string): string {
return `${BASE}/uploads${filePath}`
}
// Config / settings
export function fetchConfig(): Promise<AppConfig> {
return request('/config')
}
export function updateConfig(key: string, value: unknown): Promise<{ ok: boolean }> {
return request(`/config/${key}`, { method: 'PUT', body: JSON.stringify({ value }) })
}
export function fetchMqttStatus(): Promise<{ connected: boolean; note: string }> {
return request('/settings/mqtt-status')
}

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=hvac', { 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/hvac')}`
} 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=hvac', { 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)' }}>
HVAC
</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,93 @@
import { useRef, useState } from 'react'
import { Camera, Image as ImageIcon, Loader2, X } from 'lucide-react'
import type { DevicePhoto, PhotoType } from '../types'
import { uploadDevicePhoto, deleteDevicePhoto, 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 used elsewhere in the stack for mobile uploads.
export default function DevicePhotoUpload({ deviceId, photoType, photos, onChanged, canDelete }: {
deviceId: number
photoType: PhotoType
photos: DevicePhoto[]
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 uploadDevicePhoto(deviceId, file, photoType)
onChanged()
} catch (e) {
setError(e instanceof Error ? e.message : 'Upload failed')
} finally {
setUploading(false)
}
}
async function remove(id: number) {
await deleteDevicePhoto(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,72 @@
import { useState, useEffect } from 'react'
import { NavLink, useLocation } from 'react-router-dom'
import { Thermometer, LayoutGrid, Cpu, 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: '/devices', label: 'Devices', icon: Cpu, cap: 'manage_devices' },
{ 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('/hvac/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">
<Thermometer size={18} strokeWidth={1.75} />
HVAC
</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>
<Thermometer size={18} strokeWidth={1.75} color="var(--gold)" />
<span className="top-bar-title">HVAC</span>
</header>
<main className="page-content">
{children}
</main>
</div>
)
}

View file

@ -0,0 +1,27 @@
import { Thermometer, BatteryLow } from 'lucide-react'
import type { ZoneStatus } from '../types'
import { ROOM_STATE_LABELS } from '../types'
export default function ZoneCard({ zone, onClick }: { zone: ZoneStatus; onClick: () => void }) {
const unhealthy = zone.devices.filter(d => d.health_state !== 'healthy').length
const lowBattery = zone.devices.some(d => d.battery_pct != null && d.battery_pct < 30)
return (
<div className={`card zone-card st-${zone.room_state}`} onClick={onClick}>
<div className="zone-card-title">
<span>{zone.name}</span>
{!zone.auto_mode && <span className="badge badge-outline">Manual</span>}
</div>
<div className={`badge badge-st-${zone.room_state}`}>{ROOM_STATE_LABELS[zone.room_state]}</div>
<div className="zone-card-temp">
<Thermometer size={16} strokeWidth={1.75} style={{ verticalAlign: '-2px', marginRight: 4 }} />
{Number(zone.target_temp).toFixed(1)}°C
</div>
<div className="zone-card-meta">
<span>{zone.device_count ?? zone.devices.length} device{(zone.device_count ?? zone.devices.length) === 1 ? '' : 's'}</span>
{unhealthy > 0 && <span style={{ color: 'var(--health-degraded)' }}>{unhealthy} needs attention</span>}
{lowBattery && <BatteryLow size={13} strokeWidth={1.75} color="var(--health-degraded)" />}
</div>
</div>
)
}

View file

@ -0,0 +1,180 @@
import { useEffect, useState } from 'react'
import { X, Thermometer, History } from 'lucide-react'
import type { ZoneStatus, ActivityEntry } from '../types'
import { ROOM_STATE_LABELS, can } from '../types'
import { useAuth } from './AuthGate'
import { updateZone, overrideZone, fetchActivity } from '../api'
export default function ZoneDetailModal({ zone, onClose, onSaved }: {
zone: ZoneStatus
onClose: () => void
onSaved: () => void
}) {
const { user } = useAuth()
const canEdit = can(user, 'schedule_edit')
const canControl = can(user, 'control')
const [occupiedTemp, setOccupiedTemp] = useState(zone.occupied_temp)
const [vacantTemp, setVacantTemp] = useState(zone.vacant_temp)
const [heatingOffset, setHeatingOffset] = useState(zone.heating_offset_min)
const [coolingOffset, setCoolingOffset] = useState(zone.cooling_offset_min)
const [autoMode, setAutoMode] = useState(zone.auto_mode)
const [syncValves, setSyncValves] = useState(zone.sync_valves)
const [excludeBathroom, setExcludeBathroom] = useState(zone.exclude_bathroom)
const [overrideTemp, setOverrideTemp] = useState(zone.occupied_temp)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [msg, setMsg] = useState('')
const [activity, setActivity] = useState<ActivityEntry[]>([])
useEffect(() => {
fetchActivity(zone.id, 20).then(setActivity).catch(() => {})
}, [zone.id])
async function save() {
setSaving(true); setError(''); setMsg('')
try {
await updateZone(zone.id, {
occupied_temp: Number(occupiedTemp),
vacant_temp: Number(vacantTemp),
heating_offset_min: heatingOffset,
cooling_offset_min: coolingOffset,
auto_mode: autoMode,
sync_valves: syncValves,
exclude_bathroom: excludeBathroom,
})
setMsg('Saved')
onSaved()
} catch (e) {
setError(e instanceof Error ? e.message : 'Save failed')
} finally {
setSaving(false)
}
}
async function forceTemp() {
setSaving(true); setError(''); setMsg('')
try {
const res = await overrideZone(zone.id, Number(overrideTemp))
if (res.ok) {
setMsg(`Set to ${overrideTemp}°C (${res.successful}/${res.total} devices) — auto mode disabled`)
setAutoMode(false)
onSaved()
} else {
setError(res.error || 'Override failed')
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Override failed')
} finally {
setSaving(false)
}
}
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal" onClick={e => e.stopPropagation()}>
<div className="modal-header">
<h2>{zone.name}</h2>
<button className="modal-close" onClick={onClose}><X size={18} strokeWidth={1.75} /></button>
</div>
<div className={`badge badge-st-${zone.room_state}`} style={{ marginBottom: 10 }}>
{ROOM_STATE_LABELS[zone.room_state]}
</div>
{error && <div className="error-banner">{error}</div>}
{msg && <div className="ok-banner">{msg}</div>}
<div className="section-title">Devices</div>
{zone.devices.length === 0 && <p className="muted">No devices mapped to this zone yet assign some on the Devices page.</p>}
{zone.devices.map(d => (
<div key={d.id} className="card" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div>
<div style={{ fontWeight: 600, fontSize: 13 }}>{d.location || d.discovered_name || d.external_ref}</div>
<div className="muted" style={{ fontSize: 12 }}>
{d.current_target_temp != null ? `${Number(d.current_target_temp).toFixed(1)}°C` : '—'}
{d.battery_pct != null && ` · ${d.battery_pct}% battery`}
</div>
</div>
<span className={`badge badge-health-${d.health_state}`}>{d.health_state.replace('_', ' ')}</span>
</div>
))}
{canControl && (
<>
<div className="section-title">Manual Override</div>
<div className="field-row">
<div className="field" style={{ flex: 'none', width: 120 }}>
<input type="number" step="0.5" value={overrideTemp} onChange={e => setOverrideTemp(e.target.value)} />
</div>
<button className="btn" disabled={saving} onClick={forceTemp}>
<Thermometer size={14} strokeWidth={1.75} /> Force temperature
</button>
</div>
<p className="field-hint">Disables auto mode for this zone until re-enabled below.</p>
</>
)}
{canEdit && (
<>
<div className="section-title">Schedule</div>
<div className="field-row">
<div className="field">
<label>Occupied temp (°C)</label>
<input type="number" step="0.5" value={occupiedTemp} onChange={e => setOccupiedTemp(e.target.value)} />
</div>
<div className="field">
<label>Vacant temp (°C)</label>
<input type="number" step="0.5" value={vacantTemp} onChange={e => setVacantTemp(e.target.value)} />
</div>
</div>
<div className="field-row">
<div className="field">
<label>Heating offset (mins before arrival)</label>
<input type="number" value={heatingOffset} onChange={e => setHeatingOffset(parseInt(e.target.value) || 0)} />
</div>
<div className="field">
<label>Cooling offset (mins after departure)</label>
<input type="number" value={coolingOffset} onChange={e => setCoolingOffset(parseInt(e.target.value) || 0)} />
</div>
</div>
<label className="field-check">
<input type="checkbox" checked={autoMode} onChange={e => setAutoMode(e.target.checked)} />
Auto mode (NewBook-driven scheduling)
</label>
<label className="field-check">
<input type="checkbox" checked={syncValves} onChange={e => setSyncValves(e.target.checked)} />
Sync guest adjustments across valves in this zone
</label>
<label className="field-check">
<input type="checkbox" checked={excludeBathroom} onChange={e => setExcludeBathroom(e.target.checked)} />
Exclude bathroom valve from sync
</label>
<div className="modal-actions">
<button className="btn btn-primary" disabled={saving} onClick={save}>
{saving ? 'Saving…' : 'Save'}
</button>
</div>
</>
)}
{activity.length > 0 && (
<>
<div className="section-title"><History size={12} strokeWidth={1.75} style={{ verticalAlign: '-1px', marginRight: 4 }} />Recent activity</div>
<div className="timeline">
{activity.map(a => (
<div key={a.id} className="timeline-item">
<div className="timeline-body">
{a.note}
<div className="timeline-meta">{new Date(a.created_at).toLocaleString()} · {a.source}</div>
</div>
</div>
))}
</div>
</>
)}
</div>
</div>
)
}

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

@ -0,0 +1,394 @@
/* 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: #c1440e;
--app-primary-light: #e0692f;
/* Room state colours — vacant/booked = cool greys/blues, heating_up/occupied = warm */
--st-vacant: #64748b;
--st-booked: #2563eb;
--st-heating-up: #d97706;
--st-occupied: #dc2626;
--st-cooling-down: #0891b2;
--health-healthy: #16a34a;
--health-degraded: #d97706;
--health-poor: #ea580c;
--health-unresponsive: #dc2626;
--health-calibration: #7c3aed;
--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;
}
/* ── Zone grid / cards ─────────────────────────────────────── */
.zone-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; }
.zone-card {
cursor: pointer;
transition: box-shadow .12s, transform .12s;
border-left: 4px solid var(--st-vacant);
}
.zone-card:hover { box-shadow: var(--shadow-md); transform: translateY(-1px); }
.zone-card.st-vacant { border-left-color: var(--st-vacant); }
.zone-card.st-booked { border-left-color: var(--st-booked); }
.zone-card.st-heating_up { border-left-color: var(--st-heating-up); }
.zone-card.st-occupied { border-left-color: var(--st-occupied); }
.zone-card.st-cooling_down { border-left-color: var(--st-cooling-down); }
.zone-card-title { font-weight: 600; font-size: 14px; margin-bottom: 4px; display: flex; align-items: center; gap: 6px; justify-content: space-between; }
.zone-card-temp { font-size: 22px; font-weight: 700; margin: 6px 0 2px; }
.zone-card-meta { font-size: 12px; color: var(--text-mid); display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
/* ── 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-st-vacant { background: var(--st-vacant); }
.badge-st-booked { background: var(--st-booked); }
.badge-st-heating_up { background: var(--st-heating-up); }
.badge-st-occupied { background: var(--st-occupied); }
.badge-st-cooling_down { background: var(--st-cooling-down); }
.badge-health-healthy { background: var(--health-healthy); }
.badge-health-degraded { background: var(--health-degraded); }
.badge-health-poor { background: var(--health-poor); }
.badge-health-unresponsive { background: var(--health-unresponsive); }
.badge-health-calibration_error { background: var(--health-calibration); }
.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; }
/* ── Timeline / activity log ──────────────────────────────── */
.timeline { margin: 8px 0; }
.timeline-item {
display: flex;
gap: 10px;
padding: 8px 0;
border-bottom: 1px solid var(--card-border);
font-size: 13px;
}
.timeline-item:last-child { border-bottom: none; }
.timeline-icon { color: var(--text-mid); flex-shrink: 0; margin-top: 1px; }
.timeline-body { flex: 1; min-width: 0; }
.timeline-meta { font-size: 11.5px; color: var(--text-mid); margin-top: 2px; }
/* ── 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; }
/* ── 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(--health-healthy);
color: var(--health-healthy);
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,80 @@
import { useEffect, useState, useCallback } from 'react'
import { WifiOff } from 'lucide-react'
import { fetchStatus } from '../api'
import type { ZoneStatus } from '../types'
import ZoneCard from '../components/ZoneCard'
import ZoneDetailModal from '../components/ZoneDetailModal'
const POLL_MS = 30000
export default function Dashboard() {
const [zones, setZones] = useState<ZoneStatus[]>([])
const [mqttConnected, setMqttConnected] = useState(true)
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [selected, setSelected] = useState<ZoneStatus | null>(null)
const load = useCallback(() => {
fetchStatus()
.then(res => {
setZones(res.zones)
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])
const rooms = zones.filter(z => z.zone_type === 'room')
const publicAreas = zones.filter(z => z.zone_type === 'public_area')
if (loading) return <div className="page"><p className="muted">Loading</p></div>
return (
<div className="page">
<div className="page-header">
<h1>Dashboard</h1>
</div>
{error && <div className="error-banner">{error}</div>}
{!mqttConnected && (
<div className="error-banner" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<WifiOff size={14} strokeWidth={1.75} />
MQTT broker not connected device status may be stale and setpoint changes won't reach TRVs.
</div>
)}
<div className="section-title">Rooms</div>
{rooms.length === 0 ? (
<div className="empty-state">No room zones yet sync from NewBook on the Settings page.</div>
) : (
<div className="zone-grid">
{rooms.map(z => <ZoneCard key={z.id} zone={z} onClick={() => setSelected(z)} />)}
</div>
)}
{publicAreas.length > 0 && (
<>
<div className="section-title">Public Areas</div>
<div className="zone-grid">
{publicAreas.map(z => <ZoneCard key={z.id} zone={z} onClick={() => setSelected(z)} />)}
</div>
</>
)}
{selected && (
<ZoneDetailModal
zone={selected}
onClose={() => setSelected(null)}
onSaved={() => { load(); setSelected(null) }}
/>
)}
</div>
)
}

View file

@ -0,0 +1,193 @@
import { Fragment, useEffect, useState } from 'react'
import { RadioTower, ChevronDown, ChevronRight, Wrench } from 'lucide-react'
import {
fetchDevices, discoverDevices, updateDevice, fetchZones, fetchDevicePhotos, createMaintenanceAsset,
} from '../api'
import type { Device, Zone, DevicePhoto, DeviceType } from '../types'
import { DEVICE_TYPE_LABELS, IMPLEMENTED_DEVICE_TYPES } from '../types'
import DevicePhotoUpload from '../components/DevicePhotoUpload'
import { useAuth } from '../components/AuthGate'
import { can } from '../types'
const ALL_DEVICE_TYPES: DeviceType[] = ['shelly_trv', 'mhi_modbus', 'midea', 'daikin', 'home_assistant']
export default function Devices() {
const { user } = useAuth()
const canManage = can(user, 'manage_devices')
const [devices, setDevices] = useState<Device[]>([])
const [zones, setZones] = useState<Zone[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [msg, setMsg] = useState('')
const [discovering, setDiscovering] = useState<DeviceType | null>(null)
const [expanded, setExpanded] = useState<number | null>(null)
const [photosByDevice, setPhotosByDevice] = useState<Record<number, DevicePhoto[]>>({})
function load() {
Promise.all([fetchDevices(), fetchZones()])
.then(([d, z]) => { setDevices(d); setZones(z) })
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load'))
.finally(() => setLoading(false))
}
useEffect(load, [])
async function runDiscover(deviceType: DeviceType) {
setDiscovering(deviceType); setError(''); setMsg('')
try {
const res = await discoverDevices(deviceType)
if (res.note) setMsg(res.note)
else if (res.ok) setMsg(`Found ${res.found ?? 0} device(s), ${res.new ?? 0} new`)
else setMsg(res.error || 'Discovery returned no result')
load()
} catch (e) {
setError(e instanceof Error ? e.message : 'Discovery failed')
} finally {
setDiscovering(null)
}
}
async function assign(id: number, zoneId: number | null, location: string) {
try {
await updateDevice(id, { zone_id: zoneId, location })
load()
} catch (e) {
setError(e instanceof Error ? e.message : 'Save failed')
}
}
async function toggleExpand(id: number) {
if (expanded === id) { setExpanded(null); return }
setExpanded(id)
if (!photosByDevice[id]) {
const photos = await fetchDevicePhotos(id).catch(() => [])
setPhotosByDevice(prev => ({ ...prev, [id]: photos }))
}
}
async function reloadPhotos(id: number) {
const photos = await fetchDevicePhotos(id).catch(() => [])
setPhotosByDevice(prev => ({ ...prev, [id]: photos }))
}
async function createAsset(id: number) {
const res = await createMaintenanceAsset(id).catch(e => ({ ok: false, error: e.message }))
setMsg(res.error || (res.ok ? 'Asset created' : 'Not available yet'))
}
if (loading) return <div className="page"><p className="muted">Loading</p></div>
return (
<div className="page">
<div className="page-header">
<h1>Devices</h1>
</div>
{error && <div className="error-banner">{error}</div>}
{msg && <div className="ok-banner">{msg}</div>}
{canManage && (
<>
<div className="section-title">Discover</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
{ALL_DEVICE_TYPES.map(dt => (
<button
key={dt}
className="btn"
disabled={discovering !== null}
onClick={() => runDiscover(dt)}
title={IMPLEMENTED_DEVICE_TYPES.includes(dt) ? '' : 'Not yet implemented — Phase 2/3'}
>
<RadioTower size={14} strokeWidth={1.75} />
{discovering === dt ? 'Scanning…' : `Discover ${DEVICE_TYPE_LABELS[dt]}`}
</button>
))}
</div>
</>
)}
<div className="section-title">Mapped &amp; Discovered Devices</div>
{devices.length === 0 ? (
<div className="empty-state">No devices discovered yet run a discover scan above.</div>
) : (
<div className="table-wrap">
<table className="data">
<thead>
<tr>
<th></th>
<th>Device</th>
<th>Type</th>
<th>Zone</th>
<th>Location</th>
<th>Health</th>
<th>Photos</th>
</tr>
</thead>
<tbody>
{devices.map(d => (
<Fragment key={d.id}>
<tr className="clickable" onClick={() => toggleExpand(d.id)}>
<td>{expanded === d.id ? <ChevronDown size={14} strokeWidth={1.75} /> : <ChevronRight size={14} strokeWidth={1.75} />}</td>
<td>{d.discovered_name || d.external_ref}<div className="muted" style={{ fontSize: 11 }}>{d.external_ref}</div></td>
<td>{DEVICE_TYPE_LABELS[d.device_type]}</td>
<td onClick={e => e.stopPropagation()}>
<select
disabled={!canManage}
value={d.zone_id ?? ''}
onChange={e => assign(d.id, e.target.value ? Number(e.target.value) : null, d.location || '')}
>
<option value="">Unassigned</option>
{zones.map(z => <option key={z.id} value={z.id}>{z.name}</option>)}
</select>
</td>
<td onClick={e => e.stopPropagation()}>
<input
type="text" defaultValue={d.location || ''} placeholder="bedroom / bathroom…"
disabled={!canManage}
onBlur={e => assign(d.id, d.zone_id, e.target.value)}
style={{ width: 120, border: '1px solid var(--card-border)', borderRadius: 6, padding: '4px 6px', fontSize: 12.5 }}
/>
</td>
<td><span className={`badge badge-health-${d.health_state}`}>{d.health_state.replace('_', ' ')}</span></td>
<td>{d.photo_count}</td>
</tr>
{expanded === d.id && (
<tr>
<td colSpan={7}>
<div className="field-row">
<div style={{ flex: 1 }}>
<div className="field-hint" style={{ marginBottom: 4 }}>Device photo</div>
<DevicePhotoUpload
deviceId={d.id} photoType="device"
photos={photosByDevice[d.id] || []}
onChanged={() => reloadPhotos(d.id)}
canDelete={canManage}
/>
</div>
<div style={{ flex: 1 }}>
<div className="field-hint" style={{ marginBottom: 4 }}>Serial / model plate photo</div>
<DevicePhotoUpload
deviceId={d.id} photoType="serial_plate"
photos={photosByDevice[d.id] || []}
onChanged={() => reloadPhotos(d.id)}
canDelete={canManage}
/>
</div>
</div>
{canManage && d.zone_id && (
<button className="btn btn-sm" onClick={() => createAsset(d.id)}>
<Wrench size={13} strokeWidth={1.75} /> Create asset in Maintenance
</button>
)}
</td>
</tr>
)}
</Fragment>
))}
</tbody>
</table>
</div>
)}
</div>
)
}

View file

@ -0,0 +1,213 @@
import { useEffect, useState } from 'react'
import { Wifi, WifiOff } from 'lucide-react'
import {
fetchNewbookSites, saveExcludedSites, testNewbookConnection, syncZonesFromNewbook,
fetchConfig, updateConfig, fetchMqttStatus, createZone,
} from '../api'
import type { NewbookSite, AppConfig } from '../types'
export default function Settings() {
const [sites, setSites] = useState<NewbookSite[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState('')
const [msg, setMsg] = useState('')
const [testing, setTesting] = useState(false)
const [syncing, setSyncing] = useState(false)
const [config, setConfig] = useState<AppConfig | null>(null)
const [pollMinutes, setPollMinutes] = useState(10)
const [defaultArrival, setDefaultArrival] = useState('15:00:00')
const [defaultDeparture, setDefaultDeparture] = useState('10:00:00')
const [maintUrl, setMaintUrl] = useState('')
const [maintKey, setMaintKey] = useState('')
const [configSaving, setConfigSaving] = useState(false)
const [mqttConnected, setMqttConnected] = useState<boolean | null>(null)
const [mqttNote, setMqttNote] = useState('')
const [publicAreaName, setPublicAreaName] = useState('')
const [creatingZone, setCreatingZone] = useState(false)
function loadSites() {
fetchNewbookSites()
.then(res => setSites(res.sites))
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load NewBook sites'))
.finally(() => setLoading(false))
}
useEffect(() => {
loadSites()
fetchConfig().then(cfg => {
setConfig(cfg)
setPollMinutes(cfg.poll_interval_minutes ?? 10)
setDefaultArrival(cfg.default_arrival_time ?? '15:00:00')
setDefaultDeparture(cfg.default_departure_time ?? '10:00:00')
setMaintUrl(cfg.maintenance_url ?? '')
setMaintKey(cfg.maintenance_api_key ?? '')
}).catch(() => {})
fetchMqttStatus().then(s => { setMqttConnected(s.connected); setMqttNote(s.note) }).catch(() => {})
}, [])
function toggleExcluded(siteId: string) {
setSites(sites.map(s => s.site_id === siteId ? { ...s, excluded: !s.excluded } : s))
}
async function saveSites() {
setError(''); setMsg('')
try {
await saveExcludedSites(sites.filter(s => s.excluded).map(s => s.site_id))
setMsg('Saved'); setTimeout(() => setMsg(''), 2500)
} catch (e) {
setError(e instanceof Error ? e.message : 'Save failed')
}
}
async function handleTest() {
setTesting(true); setError(''); setMsg('')
try {
const res = await testNewbookConnection()
setMsg(res.ok ? `Connection OK: ${res.message || ''}` : `Failed: ${res.error || 'unknown'}`)
} catch (e) {
setError(e instanceof Error ? e.message : 'Test failed')
} finally {
setTesting(false)
}
}
async function handleSync() {
setSyncing(true); setError(''); setMsg('')
try {
const res = await syncZonesFromNewbook()
setMsg(`Synced: ${res.created} created, ${res.updated} updated (${res.total} active sites)`)
} catch (e) {
setError(e instanceof Error ? e.message : 'Sync failed')
} finally {
setSyncing(false)
}
}
async function saveGeneralConfig() {
setConfigSaving(true); setError(''); setMsg('')
try {
await Promise.all([
updateConfig('poll_interval_minutes', pollMinutes),
updateConfig('default_arrival_time', defaultArrival),
updateConfig('default_departure_time', defaultDeparture),
updateConfig('maintenance_url', maintUrl),
updateConfig('maintenance_api_key', maintKey),
])
setMsg('Settings saved'); setTimeout(() => setMsg(''), 2500)
} catch (e) {
setError(e instanceof Error ? e.message : 'Save failed')
} finally {
setConfigSaving(false)
}
}
async function handleCreatePublicArea(e: React.FormEvent) {
e.preventDefault()
if (!publicAreaName.trim()) return
setCreatingZone(true); setError(''); setMsg('')
try {
await createZone({ name: publicAreaName.trim(), zone_type: 'public_area' })
setPublicAreaName('')
setMsg('Public area zone created — assign devices to it on the Devices page.')
} catch (e) {
setError(e instanceof Error ? e.message : 'Create failed')
} finally {
setCreatingZone(false)
}
}
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(--health-healthy)" /> : <WifiOff size={16} strokeWidth={1.75} color="var(--danger)" />}
<span>{mqttNote || 'Checking…'}</span>
</div>
<div className="section-title">NewBook Rooms</div>
<p className="field-hint" style={{ marginBottom: 10 }}>
Untick rooms that shouldn't get NewBook-driven heating scheduling (e.g. owner-occupied or out-of-service rooms).
</p>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
{sites.map(s => (
<label key={s.site_id} className="field-check" style={{
padding: '8px 12px', border: '1px solid var(--card-border)', borderRadius: 8,
background: s.excluded ? 'var(--body-bg)' : 'var(--card-bg)',
}}>
<input type="checkbox" checked={!s.excluded} onChange={() => toggleExcluded(s.site_id)} />
<span style={{ flex: 1, textDecoration: s.excluded ? 'line-through' : 'none', color: s.excluded ? 'var(--text-mid)' : 'var(--text-dark)' }}>
{s.site_name}
</span>
{s.category_name && <span className="muted" style={{ fontSize: 12 }}>{s.category_name}</span>}
</label>
))}
{sites.length === 0 && <p className="muted">No sites returned check NewBook connection.</p>}
</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 24 }}>
<button className="btn btn-primary" onClick={saveSites}>Save Visibility</button>
<button className="btn" disabled={testing} onClick={handleTest}>{testing ? 'Testing…' : 'Test NewBook Connection'}</button>
<button className="btn" disabled={syncing} onClick={handleSync}>{syncing ? 'Syncing…' : 'Sync Zones from NewBook'}</button>
</div>
<div className="section-title">Add a Public Area</div>
<form onSubmit={handleCreatePublicArea} style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
<input
type="text" placeholder="e.g. Lobby, Restaurant, Bar"
value={publicAreaName} onChange={e => setPublicAreaName(e.target.value)}
style={{ flex: 1, border: '1px solid var(--card-border)', borderRadius: 8, padding: '8px 10px' }}
/>
<button className="btn btn-primary" disabled={creatingZone} type="submit">Add zone</button>
</form>
<div className="section-title">Scheduling</div>
<div className="field-row">
<div className="field">
<label>Poll interval (minutes)</label>
<input type="number" min={1} value={pollMinutes} onChange={e => setPollMinutes(parseInt(e.target.value) || 10)} />
</div>
<div className="field">
<label>Default arrival time</label>
<input type="text" value={defaultArrival} onChange={e => setDefaultArrival(e.target.value)} placeholder="15:00:00" />
</div>
<div className="field">
<label>Default departure time</label>
<input type="text" value={defaultDeparture} onChange={e => setDefaultDeparture(e.target.value)} placeholder="10:00:00" />
</div>
</div>
<div className="section-title">Maintenance Integration</div>
<p className="field-hint" style={{ marginBottom: 10 }}>
Not yet available maintenance needs its own Settings API Keys page first.
Once that lands, generate a key there and paste it here to enable "Create asset in Maintenance" on the Devices page.
</p>
<div className="field-row">
<div className="field">
<label>Maintenance URL</label>
<input type="text" value={maintUrl} onChange={e => setMaintUrl(e.target.value)} placeholder="https://hotel.example.com/maintenance" />
</div>
<div className="field">
<label>Maintenance API key</label>
<input type="text" value={maintKey} onChange={e => setMaintKey(e.target.value)} placeholder="paste key" />
</div>
</div>
<div style={{ marginBottom: 24 }}>
<button className="btn btn-primary" disabled={configSaving} onClick={saveGeneralConfig}>
{configSaving ? 'Saving…' : 'Save Settings'}
</button>
</div>
</div>
)
}

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

@ -0,0 +1,128 @@
export type ZoneType = 'room' | 'public_area'
export type ZoneSource = 'newbook' | 'manual'
export type RoomState = 'vacant' | 'booked' | 'heating_up' | 'occupied' | 'cooling_down'
export type DeviceType = 'shelly_trv' | 'mhi_modbus' | 'midea' | 'daikin' | 'home_assistant'
export type HealthState = 'healthy' | 'degraded' | 'poor' | 'unresponsive' | 'calibration_error'
export type PhotoType = 'device' | 'serial_plate'
export const ROOM_STATE_LABELS: Record<RoomState, string> = {
vacant: 'Vacant',
booked: 'Booked',
heating_up: 'Heating Up',
occupied: 'Occupied',
cooling_down: 'Cooling Down',
}
export const DEVICE_TYPE_LABELS: Record<DeviceType, string> = {
shelly_trv: 'Shelly TRV',
mhi_modbus: 'MHI Aircon (Modbus)',
midea: 'Midea Split',
daikin: 'Daikin Split',
home_assistant: 'Home Assistant',
}
// Device types with an implemented Phase 1 driver — everything else in
// DeviceType is an enum value only, ready for its Phase 2/3 driver.
export const IMPLEMENTED_DEVICE_TYPES: DeviceType[] = ['shelly_trv', 'home_assistant']
export interface Zone {
id: number
zone_type: ZoneType
source: ZoneSource
newbook_site_id: string | null
name: string
active: boolean
occupied_temp: string
vacant_temp: string
heating_offset_min: number
cooling_offset_min: number
auto_mode: boolean
sync_valves: boolean
exclude_bathroom: boolean
created_at: string
device_count?: number
}
export interface ZoneStatus extends Zone {
room_state: RoomState
target_temp: string
last_transition_at: string | null
last_booking_status: string | null
devices: DeviceSummary[]
}
export interface DeviceSummary {
id: number
zone_id: number | null
device_type: DeviceType
external_ref: string
discovered_name: string | null
location: string | null
health_state: HealthState
battery_pct: number | null
wifi_rssi: number | null
current_target_temp: string | null
target_origin: string | null
last_seen: string | null
}
export interface Device extends DeviceSummary {
zone_name: string | null
maintenance_asset_id: number | null
device_ip: string | null
photo_count: number
created_at: string
updated_at: string
}
export interface DevicePhoto {
id: number
device_id: number
file_name: string
file_path: string
mime_type: string
photo_type: PhotoType
uploaded_by: string
uploaded_at: string
}
export interface ActivityEntry {
id: number
zone_id: number | null
zone_name: string | null
event_type: string
from_state: string | null
to_state: string | null
note: string | null
source: string
user_email: string | null
created_at: string
}
export interface NewbookSite {
site_id: string
site_name: string
category_name: string | null
excluded: boolean
}
export interface AppConfig {
poll_interval_minutes: number
default_arrival_time: string
default_departure_time: string
maintenance_url: string
maintenance_api_key: string
excluded_site_ids?: string[]
}
export interface User {
user_id: number
name: string
email: string
is_admin: boolean
caps: string[] // bare slugs — verify?app=hvac 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: '/hvac/',
plugins: [react()],
})