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:
commit
276c04f8c6
42 changed files with 5461 additions and 0 deletions
5
.gitignore
vendored
Normal file
5
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
uploads/
|
||||
*.log
|
||||
8
backend/Dockerfile
Normal file
8
backend/Dockerfile
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
FROM node:22-alpine
|
||||
WORKDIR /app
|
||||
COPY package.json .
|
||||
RUN npm install --omit=dev
|
||||
COPY src ./src
|
||||
RUN mkdir -p /app/uploads
|
||||
EXPOSE 3001
|
||||
CMD ["node", "src/index.js"]
|
||||
21
backend/package.json
Normal file
21
backend/package.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"name": "hnf-hvac-backend",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node src/index.js",
|
||||
"dev": "node --watch src/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^9.4.0",
|
||||
"@fastify/cors": "^9.0.1",
|
||||
"@fastify/multipart": "^8.3.0",
|
||||
"@fastify/static": "^7.0.4",
|
||||
"fastify": "^4.28.1",
|
||||
"jose": "^5.9.6",
|
||||
"luxon": "^3.5.0",
|
||||
"mqtt": "^5.10.3",
|
||||
"pg": "^8.13.1",
|
||||
"sharp": "^0.33.0"
|
||||
}
|
||||
}
|
||||
57
backend/src/auth.js
Normal file
57
backend/src/auth.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { jwtVerify } from 'jose'
|
||||
import { isOnsite } from './ip-check.js'
|
||||
|
||||
const APP_SLUG = process.env.APP_SLUG || 'hvac'
|
||||
const secret = new TextEncoder().encode(process.env.CENTRAL_AUTH_SECRET || '')
|
||||
|
||||
export async function requireAuth(request, reply) {
|
||||
const token = request.cookies?.hnf_session
|
||||
if (!token) return reply.status(401).send({ error: 'Not authenticated' })
|
||||
|
||||
let payload
|
||||
try {
|
||||
const { payload: p } = await jwtVerify(token, secret)
|
||||
payload = p
|
||||
} catch {
|
||||
return reply.status(401).send({ error: 'Invalid session' })
|
||||
}
|
||||
|
||||
if (!payload.apps?.includes(APP_SLUG)) {
|
||||
return reply.status(403).send({ error: 'No permission for this app' })
|
||||
}
|
||||
|
||||
if (!payload.offsite_allowed) {
|
||||
const clientIP = request.headers['x-real-ip'] || request.ip
|
||||
if (!(await isOnsite(clientIP))) {
|
||||
return reply.status(403).send({ error: 'Access restricted to site network' })
|
||||
}
|
||||
}
|
||||
|
||||
const prefix = `${APP_SLUG}:`
|
||||
let caps
|
||||
if (Array.isArray(payload.caps)) {
|
||||
caps = payload.caps.filter(c => c.startsWith(prefix)).map(c => c.slice(prefix.length))
|
||||
} else {
|
||||
// Legacy token — grant view-only until re-login
|
||||
caps = ['view']
|
||||
}
|
||||
|
||||
request.user = {
|
||||
email: payload.sub,
|
||||
name: payload.name,
|
||||
is_admin: payload.is_admin ?? false,
|
||||
caps,
|
||||
}
|
||||
}
|
||||
|
||||
export function hasCap(request, cap) {
|
||||
return request.user?.is_admin === true || request.user?.caps?.includes(cap) === true
|
||||
}
|
||||
|
||||
export function requireCap(cap) {
|
||||
return async (request, reply) => {
|
||||
if (!hasCap(request, cap)) {
|
||||
return reply.status(403).send({ error: `Missing capability: ${cap}` })
|
||||
}
|
||||
}
|
||||
}
|
||||
148
backend/src/db.js
Normal file
148
backend/src/db.js
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
import pg from 'pg'
|
||||
|
||||
const { Pool } = pg
|
||||
export const pool = new Pool({ connectionString: process.env.DATABASE_URL })
|
||||
|
||||
export async function initDb() {
|
||||
await pool.query(`
|
||||
-- Generic key/value config store (hk-planner/maintenance pattern) — holds
|
||||
-- excluded_site_ids, poll_interval_minutes, maintenance integration URL/key, etc.
|
||||
CREATE TABLE IF NOT EXISTS config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value JSONB NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Zones: rooms (synced from NewBook) and public areas (manual, Phase 3 control).
|
||||
-- Single table for the whole device lifetime — Phase 2/3 aircon-specific columns
|
||||
-- (cool setpoint, fan mode) land here later as nullable ADD COLUMNs, not a new table.
|
||||
CREATE TABLE IF NOT EXISTS zones (
|
||||
id SERIAL PRIMARY KEY,
|
||||
zone_type TEXT NOT NULL DEFAULT 'room', -- room | public_area
|
||||
source TEXT NOT NULL DEFAULT 'manual', -- newbook | manual
|
||||
newbook_site_id TEXT UNIQUE,
|
||||
name TEXT NOT NULL,
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE, -- soft-deactivate on NewBook sync, never hard delete
|
||||
occupied_temp NUMERIC(4,1) NOT NULL DEFAULT 22.0,
|
||||
vacant_temp NUMERIC(4,1) NOT NULL DEFAULT 16.0,
|
||||
heating_offset_min INT NOT NULL DEFAULT 120, -- minutes before arrival to start heating
|
||||
cooling_offset_min INT NOT NULL DEFAULT -30, -- minutes after departure to stop (negative = before checkout)
|
||||
auto_mode BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
sync_valves BOOLEAN NOT NULL DEFAULT TRUE, -- sync guest setpoint changes across valves in the same zone
|
||||
exclude_bathroom BOOLEAN NOT NULL DEFAULT TRUE, -- bathroom valve excluded from guest-adjustment sync
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Device mapping — one row per physical device, assigned to a zone by staff via
|
||||
-- the Devices onboarding flow (never auto-mapped from device naming conventions).
|
||||
CREATE TABLE IF NOT EXISTS zone_devices (
|
||||
id SERIAL PRIMARY KEY,
|
||||
zone_id INT REFERENCES zones(id) ON DELETE SET NULL,
|
||||
device_type TEXT NOT NULL, -- shelly_trv | mhi_modbus | midea | daikin | home_assistant
|
||||
external_ref TEXT NOT NULL, -- MAC / Modbus address / LAN device ID / HA entity_id
|
||||
discovered_name TEXT, -- raw name/label from the device — display-only, never parsed
|
||||
location TEXT, -- bedroom / bathroom / living / free text, set by staff
|
||||
maintenance_asset_id INT, -- set once "Create asset in Maintenance" succeeds (Phase 1: stub, always NULL)
|
||||
last_seen TIMESTAMPTZ,
|
||||
battery_pct INT,
|
||||
health_state TEXT NOT NULL DEFAULT 'healthy', -- healthy | degraded | poor | unresponsive | calibration_error
|
||||
wifi_rssi INT,
|
||||
current_target_temp NUMERIC(4,1),
|
||||
target_origin TEXT, -- automation | guest | pending | unknown (Shelly source field)
|
||||
device_ip TEXT, -- for the HTTP wake-up fallback
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS zone_devices_zone_idx ON zone_devices (zone_id);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS zone_devices_type_ref_idx ON zone_devices (device_type, external_ref);
|
||||
|
||||
-- Two photo slots per device (device photo + serial/model plate) — same pattern
|
||||
-- as maintenance's task_photos: multipart + sharp, uploads_data volume.
|
||||
CREATE TABLE IF NOT EXISTS device_photos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
device_id INT NOT NULL REFERENCES zone_devices(id) ON DELETE CASCADE,
|
||||
file_name TEXT NOT NULL,
|
||||
file_path TEXT NOT NULL,
|
||||
mime_type TEXT,
|
||||
file_size INT,
|
||||
photo_type TEXT NOT NULL DEFAULT 'device', -- device | serial_plate
|
||||
uploaded_by TEXT,
|
||||
uploaded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS device_photos_device_idx ON device_photos (device_id);
|
||||
|
||||
-- Minimal, TTL'd booking cache — room-planner style (no full booking mirror).
|
||||
-- Kept per-zone so a NewBook fetch failure can fall back to the last successful
|
||||
-- read instead of treating "fetch failed" as "no booking" (fail-safe requirement).
|
||||
CREATE TABLE IF NOT EXISTS booking_cache (
|
||||
zone_id INT PRIMARY KEY REFERENCES zones(id) ON DELETE CASCADE,
|
||||
booking_data JSONB,
|
||||
fetched_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Persisted current room state — survives backend restarts, and lets the
|
||||
-- scheduler apply setpoints only at state *transitions* (never poll-and-reassert
|
||||
-- during 'occupied', which would stomp guest button/WS adjustments).
|
||||
CREATE TABLE IF NOT EXISTS zone_state (
|
||||
zone_id INT PRIMARY KEY REFERENCES zones(id) ON DELETE CASCADE,
|
||||
room_state TEXT NOT NULL DEFAULT 'vacant', -- vacant | booked | heating_up | occupied | cooling_down
|
||||
last_booking_status TEXT,
|
||||
last_transition_at TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Rolling log of state transitions, manual overrides, sync runs and errors.
|
||||
CREATE TABLE IF NOT EXISTS activity_log (
|
||||
id SERIAL PRIMARY KEY,
|
||||
zone_id INT REFERENCES zones(id) ON DELETE CASCADE,
|
||||
event_type TEXT NOT NULL, -- transition | override | sync | device_command | error
|
||||
from_state TEXT,
|
||||
to_state TEXT,
|
||||
note TEXT,
|
||||
source TEXT NOT NULL DEFAULT 'scheduler', -- scheduler | manual | sync
|
||||
user_email TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS activity_log_zone_idx ON activity_log (zone_id, created_at DESC);
|
||||
`)
|
||||
|
||||
await seedDefaults()
|
||||
}
|
||||
|
||||
async function seedDefaults() {
|
||||
const defaults = {
|
||||
excluded_site_ids: [],
|
||||
poll_interval_minutes: 10, // matches the old integration's DEFAULT_SCAN_INTERVAL
|
||||
default_arrival_time: '15:00:00',
|
||||
default_departure_time: '10:00:00',
|
||||
maintenance_url: '',
|
||||
maintenance_api_key: '',
|
||||
}
|
||||
for (const [key, value] of Object.entries(defaults)) {
|
||||
await pool.query(
|
||||
`INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`,
|
||||
[key, JSON.stringify(value)]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getConfig(key, fallback = null) {
|
||||
const { rows } = await pool.query('SELECT value FROM config WHERE key = $1', [key])
|
||||
return rows.length ? rows[0].value : fallback
|
||||
}
|
||||
|
||||
export async function setConfig(key, value) {
|
||||
await pool.query(
|
||||
`INSERT INTO config (key, value, updated_at) VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`,
|
||||
[key, JSON.stringify(value)]
|
||||
)
|
||||
}
|
||||
|
||||
export async function logActivity(zoneId, eventType, { fromState, toState, note, source = 'scheduler', userEmail } = {}) {
|
||||
await pool.query(
|
||||
`INSERT INTO activity_log (zone_id, event_type, from_state, to_state, note, source, user_email)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
|
||||
[zoneId, eventType, fromState || null, toState || null, note || null, source, userEmail || null]
|
||||
)
|
||||
}
|
||||
57
backend/src/index.js
Normal file
57
backend/src/index.js
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import Fastify from 'fastify'
|
||||
import cookie from '@fastify/cookie'
|
||||
import cors from '@fastify/cors'
|
||||
import multipart from '@fastify/multipart'
|
||||
import staticFiles from '@fastify/static'
|
||||
import { fileURLToPath } from 'url'
|
||||
import { dirname, join } from 'path'
|
||||
import { initDb } from './db.js'
|
||||
import { connect as connectMqtt } from './lib/mqtt.js'
|
||||
import { startScheduler } from './lib/scheduler.js'
|
||||
import { zoneRoutes } from './routes/zones.js'
|
||||
import { deviceRoutes } from './routes/devices.js'
|
||||
import { statusRoutes } from './routes/status.js'
|
||||
import { overrideRoutes } from './routes/override.js'
|
||||
import { configRoutes } from './routes/config.js'
|
||||
import { settingsRoutes } from './routes/settings.js'
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url))
|
||||
const UPLOADS_DIR = join(__dirname, '..', 'uploads')
|
||||
|
||||
const app = Fastify({ logger: true, trustProxy: true })
|
||||
const startedAt = Date.now()
|
||||
|
||||
await app.register(cookie)
|
||||
await app.register(cors, {
|
||||
origin: process.env.CORS_ORIGIN || false,
|
||||
credentials: true,
|
||||
})
|
||||
await app.register(multipart, { limits: { fileSize: 10 * 1024 * 1024 } })
|
||||
await app.register(staticFiles, {
|
||||
root: UPLOADS_DIR,
|
||||
prefix: '/api/uploads/',
|
||||
decorateReply: false,
|
||||
})
|
||||
|
||||
app.get('/health', async () => ({ status: 'healthy', version: process.env.BUILD_VERSION || String(startedAt) }))
|
||||
|
||||
await app.register(zoneRoutes)
|
||||
await app.register(deviceRoutes, { uploadsDir: UPLOADS_DIR })
|
||||
await app.register(statusRoutes)
|
||||
await app.register(overrideRoutes)
|
||||
await app.register(configRoutes)
|
||||
await app.register(settingsRoutes)
|
||||
|
||||
try {
|
||||
await initDb()
|
||||
|
||||
// MQTT broker (shared infra, LXC 104) may not exist yet — connect() handles that
|
||||
// gracefully with its own backoff and never blocks startup.
|
||||
connectMqtt().catch(err => app.log.warn(`MQTT connect failed at startup: ${err.message}`))
|
||||
|
||||
await startScheduler()
|
||||
await app.listen({ port: 3001, host: '0.0.0.0' })
|
||||
} catch (err) {
|
||||
app.log.error(err)
|
||||
process.exit(1)
|
||||
}
|
||||
80
backend/src/ip-check.js
Normal file
80
backend/src/ip-check.js
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
import dns from 'dns/promises'
|
||||
|
||||
const raw = (process.env.OFFICE_IP_CHECK || 'disabled').trim()
|
||||
const matchers = raw.split(',').map(s => s.trim()).filter(Boolean)
|
||||
|
||||
const TTL = 5 * 60 * 1000
|
||||
const cache = new Map()
|
||||
|
||||
const PUBLIC_IP_URLS = [
|
||||
'https://api.ipify.org',
|
||||
'https://ifconfig.co/ip',
|
||||
'https://icanhazip.com',
|
||||
]
|
||||
|
||||
function normalizeIP(ip) {
|
||||
return ip?.startsWith('::ffff:') ? ip.slice(7) : ip
|
||||
}
|
||||
|
||||
function isIPv4(s) {
|
||||
return /^\d{1,3}(\.\d{1,3}){3}$/.test(s)
|
||||
}
|
||||
|
||||
function ipInCidr(ip, cidr) {
|
||||
const [range, bits] = cidr.split('/')
|
||||
if (!isIPv4(ip) || !isIPv4(range)) return false
|
||||
const mask = ~(2 ** (32 - parseInt(bits)) - 1) >>> 0
|
||||
const toInt = s => s.split('.').reduce((a, o) => (a << 8) + parseInt(o), 0) >>> 0
|
||||
return (toInt(ip) & mask) === (toInt(range) & mask)
|
||||
}
|
||||
|
||||
async function fetchPublicIP() {
|
||||
for (const url of PUBLIC_IP_URLS) {
|
||||
try {
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), 4000)
|
||||
const res = await fetch(url, { signal: ctrl.signal })
|
||||
clearTimeout(timer)
|
||||
if (!res.ok) continue
|
||||
const ip = (await res.text()).trim()
|
||||
if (isIPv4(ip)) return ip
|
||||
} catch {
|
||||
// try next
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
async function resolveDynamic(key, resolver) {
|
||||
const hit = cache.get(key)
|
||||
if (hit && Date.now() < hit.expiry) return hit.ip
|
||||
const ip = await resolver()
|
||||
if (ip) {
|
||||
cache.set(key, { ip, expiry: Date.now() + TTL })
|
||||
return ip
|
||||
}
|
||||
return hit ? hit.ip : null
|
||||
}
|
||||
|
||||
export async function isOnsite(requestIP) {
|
||||
if (matchers.length === 0 || matchers.includes('disabled')) return true
|
||||
const ip = normalizeIP(requestIP)
|
||||
if (!ip) return false
|
||||
|
||||
for (const m of matchers) {
|
||||
if (m === 'auto') {
|
||||
const pub = await resolveDynamic('auto', fetchPublicIP)
|
||||
if (pub && ip === pub) return true
|
||||
} else if (m.includes('/')) {
|
||||
if (ipInCidr(ip, m)) return true
|
||||
} else if (/[a-zA-Z]/.test(m)) {
|
||||
const resolved = await resolveDynamic(m, async () => {
|
||||
try { return (await dns.resolve4(m))[0] } catch { return null }
|
||||
})
|
||||
if (resolved && ip === resolved) return true
|
||||
} else {
|
||||
if (ip === m) return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
100
backend/src/lib/drivers/homeassistant.js
Normal file
100
backend/src/lib/drivers/homeassistant.js
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// Optional escape-hatch driver — same discover()/getStatus()/setTarget() interface
|
||||
// as every other driver, backed by Home Assistant's REST API instead of a direct
|
||||
// protocol. Per the plan: HA is not required by hvac and nothing else depends on
|
||||
// it existing. Credentials (base_url + long-lived access token) are meant to be
|
||||
// configured once, centrally, as a new integration type in the shared `settings`
|
||||
// service (same tier as NewBook/SMTP) — that settings endpoint does not exist yet,
|
||||
// so this driver no-ops (returns empty / not-configured) until it does. No
|
||||
// hardcoded credentials, no fake integration.
|
||||
const DEVICE_TYPE = 'home_assistant'
|
||||
|
||||
async function getCredentials() {
|
||||
try {
|
||||
const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/home_assistant`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${process.env.SETTINGS_SECRET}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!res.ok) return null
|
||||
const s = await res.json()
|
||||
if (!s.base_url || !s.access_token) return null
|
||||
return { baseUrl: s.base_url.replace(/\/$/, ''), token: s.access_token }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// GET /api/states filtered to climate.* entities.
|
||||
export async function discover() {
|
||||
const creds = await getCredentials()
|
||||
if (!creds) {
|
||||
return { ok: false, error: 'Home Assistant integration not configured in settings', devices: [] }
|
||||
}
|
||||
try {
|
||||
const res = await fetch(`${creds.baseUrl}/api/states`, {
|
||||
headers: { Authorization: `Bearer ${creds.token}` },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
if (!res.ok) throw new Error(`HA API ${res.status}`)
|
||||
const states = await res.json()
|
||||
const devices = states
|
||||
.filter(s => s.entity_id?.startsWith('climate.'))
|
||||
.map(s => ({
|
||||
external_ref: s.entity_id,
|
||||
discovered_name: s.attributes?.friendly_name || s.entity_id,
|
||||
model: 'home_assistant',
|
||||
}))
|
||||
return { ok: true, devices }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err.message, devices: [] }
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStatus(externalRef) {
|
||||
const creds = await getCredentials()
|
||||
if (!creds) return null
|
||||
try {
|
||||
const res = await fetch(`${creds.baseUrl}/api/states/${encodeURIComponent(externalRef)}`, {
|
||||
headers: { Authorization: `Bearer ${creds.token}` },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
if (!res.ok) return null
|
||||
const state = await res.json()
|
||||
return {
|
||||
external_ref: externalRef,
|
||||
current_target_temp: state.attributes?.temperature ?? null,
|
||||
health_state: 'healthy',
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function setTarget(externalRef, { mode, tempC }) {
|
||||
const creds = await getCredentials()
|
||||
if (!creds) return false
|
||||
try {
|
||||
if (tempC != null) {
|
||||
await fetch(`${creds.baseUrl}/api/services/climate/set_temperature`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${creds.token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ entity_id: externalRef, temperature: tempC }),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
}
|
||||
if (mode) {
|
||||
await fetch(`${creds.baseUrl}/api/services/climate/set_hvac_mode`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${creds.token}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ entity_id: externalRef, hvac_mode: mode }),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
}
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('[homeassistant driver] setTarget failed:', err.message)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export { DEVICE_TYPE }
|
||||
44
backend/src/lib/drivers/trv.js
Normal file
44
backend/src/lib/drivers/trv.js
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// Driver interface implementation for Shelly Gen1 TRVs, backed by lib/mqtt.js.
|
||||
// Every driver in the stack exposes the same shape: discover() / getStatus(externalRef) /
|
||||
// setTarget(externalRef, { mode, tempC }) — the scheduler and the Devices onboarding
|
||||
// flow only ever talk to this interface, never to MQTT directly.
|
||||
import { pool } from '../../db.js'
|
||||
import { getDiscoveredDevices, setTargetWithRetry, isConnected } from '../mqtt.js'
|
||||
|
||||
export const DEVICE_TYPE = 'shelly_trv'
|
||||
|
||||
// Returns raw devices seen on the MQTT broker (from shellies/announce +
|
||||
// shellies/+/settings), regardless of whether they're already mapped to a zone.
|
||||
// Never auto-maps by parsing the device name — that's a staff action in the UI.
|
||||
export async function discover() {
|
||||
if (!isConnected()) {
|
||||
return { ok: false, error: 'MQTT broker not connected', devices: [] }
|
||||
}
|
||||
const devices = getDiscoveredDevices().map(d => ({
|
||||
external_ref: d.deviceId,
|
||||
discovered_name: d.name,
|
||||
model: d.model,
|
||||
mac: d.mac,
|
||||
ip: d.ip,
|
||||
}))
|
||||
return { ok: true, devices }
|
||||
}
|
||||
|
||||
export async function getStatus(externalRef) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT external_ref, current_target_temp, target_origin, health_state, battery_pct, wifi_rssi, last_seen
|
||||
FROM zone_devices WHERE device_type = $1 AND external_ref = $2`,
|
||||
[DEVICE_TYPE, externalRef]
|
||||
)
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
// mode is accepted for interface parity with other drivers (Modbus/Midea/Daikin
|
||||
// have real heat/cool/off modes) — Shelly TRVs are heat-only, so it's ignored here.
|
||||
export async function setTarget(externalRef, { tempC }) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT device_ip FROM zone_devices WHERE device_type = $1 AND external_ref = $2`,
|
||||
[DEVICE_TYPE, externalRef]
|
||||
)
|
||||
return setTargetWithRetry({ external_ref: externalRef, device_ip: rows[0]?.device_ip || null }, tempC)
|
||||
}
|
||||
21
backend/src/lib/maintenance-client.js
Normal file
21
backend/src/lib/maintenance-client.js
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
// STUB — "Create asset in Maintenance" is explicitly out of scope for this build.
|
||||
//
|
||||
// Per the hvac plan doc (§ "Create a maintenance asset from a device"), the real
|
||||
// integration needs a joint change in `maintenance` first: its own self-service
|
||||
// Settings → API Keys page (copied from forecasting's ApiKeysPage pattern) plus a
|
||||
// new X-API-Key-authenticated `POST /api/public/assets` endpoint. Neither exists
|
||||
// in `maintenance` yet — it currently has no API-key auth at all. Building a real
|
||||
// client against an endpoint that doesn't exist would just be a fake integration,
|
||||
// so this module intentionally does nothing beyond returning a clear "not
|
||||
// implemented" result. Wire this up for real once the maintenance-side work lands
|
||||
// (tracked as its own small piece of work, not bundled into hvac's deploy).
|
||||
export async function createMaintenanceAsset(_device, _zone) {
|
||||
return {
|
||||
ok: false,
|
||||
notImplemented: true,
|
||||
error: 'Maintenance asset creation is not yet available — maintenance needs its own ' +
|
||||
'Settings → API Keys page and a public asset-creation endpoint first (see hvac plan, ' +
|
||||
'"Create a maintenance asset from a device"). Configure maintenance_url / maintenance_api_key ' +
|
||||
'in hvac Settings once that lands.',
|
||||
}
|
||||
}
|
||||
335
backend/src/lib/mqtt.js
Normal file
335
backend/src/lib/mqtt.js
Normal file
|
|
@ -0,0 +1,335 @@
|
|||
// Mosquitto client wrapper for Shelly Gen1 TRVs.
|
||||
//
|
||||
// Ported from the retired homeassistant-newbook-heating-component's trv_monitor.py /
|
||||
// shelly_detector.py — same topic convention, same retry/backoff/stagger/wake-up
|
||||
// reliability logic, same guest-vs-automation source detection. The broker itself
|
||||
// is shared infra (its own LXC, not part of this app) and doesn't exist yet at the
|
||||
// time this file is written, so every public function here degrades cleanly when
|
||||
// the broker is unreachable rather than crashing the backend.
|
||||
//
|
||||
// Credentials are fetched at runtime from the settings service, not baked into
|
||||
// docker-compose — same self-service pattern as newbook.js's getCredentials().
|
||||
// NOTE: the settings endpoint below (`/settings/api/internal/integration/mqtt`)
|
||||
// does not exist yet — this client is written against the shape described in the
|
||||
// hvac plan doc so it "just works" once settings adds it. Until then every
|
||||
// connection attempt fails fast and retries in the background; nothing here blocks
|
||||
// backend startup.
|
||||
import mqtt from 'mqtt'
|
||||
import { pool } from '../db.js'
|
||||
|
||||
const CLIENT_NAME = 'hvac-backend'
|
||||
|
||||
// Same reliability tuning as the old trv_monitor.py: 30s -> 30min backoff, staggered
|
||||
// per-valve commands ~10s apart, HTTP wake-up before declaring a TRV unresponsive.
|
||||
const RETRY_DELAYS_MS = [30, 60, 120, 300, 300, 600, 600, 900, 900, 1800].map(s => s * 1000)
|
||||
const STAGGER_MS = 10 * 1000
|
||||
const BROKER_RECONNECT_BACKOFF_MS = [30, 60, 120, 300, 600, 1800].map(s => s * 1000) // 30s -> 30min
|
||||
|
||||
const GUEST_SOURCES = ['button', 'WS']
|
||||
const AUTOMATION_SOURCES = ['mqtt', 'http']
|
||||
|
||||
let client = null
|
||||
let connecting = false
|
||||
let reconnectAttempt = 0
|
||||
|
||||
// device_id (Shelly's own id, e.g. "shellytrv-84FD270DD7CC") -> { mac, model, ip, name, lastAnnounceAt }
|
||||
const discovered = new Map()
|
||||
|
||||
async function getCredentials() {
|
||||
const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/mqtt?client=${CLIENT_NAME}`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${process.env.SETTINGS_SECRET}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!res.ok) throw new Error(`Settings service returned ${res.status} fetching MQTT credentials`)
|
||||
const s = await res.json()
|
||||
if (!s.host || !s.username || !s.password) throw new Error('MQTT broker credentials not configured in settings')
|
||||
return { host: s.host, port: s.port || 1883, username: s.username, password: s.password }
|
||||
}
|
||||
|
||||
// Parse a Shelly Gen1 announce/settings payload. Gen2+ devices (which carry a
|
||||
// "gen" field) are explicitly unsupported — same guard as the retired
|
||||
// shelly_detector.py, since Gen2 uses RPC-over-MQTT, not these flat topics.
|
||||
function isGen1(payload) {
|
||||
return !('gen' in payload)
|
||||
}
|
||||
|
||||
function recordDiscovery(deviceId, { mac, model, ip, name }) {
|
||||
const existing = discovered.get(deviceId) || {}
|
||||
discovered.set(deviceId, {
|
||||
deviceId,
|
||||
mac: mac || existing.mac || '',
|
||||
model: model || existing.model || '',
|
||||
ip: ip || existing.ip || '',
|
||||
name: name || existing.name || deviceId,
|
||||
lastAnnounceAt: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
async function handleAnnounce(payload) {
|
||||
if (!isGen1(payload)) return
|
||||
if (!payload.id || !payload.model) return
|
||||
if (payload.model !== 'SHTRV-01') return // TRVs only in Phase 1
|
||||
recordDiscovery(payload.id, { mac: payload.mac, model: payload.model, ip: payload.ip })
|
||||
}
|
||||
|
||||
async function handleSettings(deviceId, payload) {
|
||||
const deviceInfo = payload.device || {}
|
||||
if (!deviceInfo.type || !deviceInfo.mac) return
|
||||
if ('gen' in payload) return
|
||||
if (deviceInfo.type !== 'SHTRV-01') return
|
||||
recordDiscovery(deviceId, {
|
||||
mac: deviceInfo.mac,
|
||||
model: deviceInfo.type,
|
||||
ip: payload.wifi_sta?.ip || '',
|
||||
name: payload.name || deviceId,
|
||||
})
|
||||
}
|
||||
|
||||
// shellies/room-{room_id}-{location}-trv/thermostat/0/target_t -> { temp, source }
|
||||
// source: button|WS = guest-initiated (never resync from these); mqtt|http = our own
|
||||
// automation's command (safe to resync other valves in the room).
|
||||
async function handleStatus(externalRef, payload) {
|
||||
const targetTemp = payload.temp
|
||||
const source = payload.source
|
||||
const isGuest = GUEST_SOURCES.includes(source)
|
||||
const origin = isGuest ? 'guest' : (AUTOMATION_SOURCES.includes(source) ? 'automation' : 'unknown')
|
||||
|
||||
try {
|
||||
await pool.query(
|
||||
`UPDATE zone_devices
|
||||
SET last_seen = NOW(), current_target_temp = $2, target_origin = $3, updated_at = NOW()
|
||||
WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef, targetTemp ?? null, origin]
|
||||
)
|
||||
} catch (err) {
|
||||
// DB not reachable / table not ready yet — don't crash the MQTT client over it
|
||||
console.error('[mqtt] failed to record status update:', err.message)
|
||||
}
|
||||
|
||||
if (isGuest && targetTemp != null) {
|
||||
await syncGuestAdjustmentToRoom(externalRef, targetTemp).catch(err => {
|
||||
console.error('[mqtt] guest valve sync failed:', err.message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Debounce so we don't loop: our own resync command comes back as source='mqtt'
|
||||
// (automation), which already wouldn't re-trigger this function — but keep a
|
||||
// time-based guard too, matching the old trv_monitor.py's SYNC_DEBOUNCE_SECONDS.
|
||||
const SYNC_DEBOUNCE_MS = 30 * 1000
|
||||
const lastGuestSyncAt = new Map() // external_ref -> timestamp ms
|
||||
|
||||
// Guest-initiated Temperature Respect + valve sync: when a guest adjusts one TRV
|
||||
// (source=button|WS), sync the new setpoint to the room's other valves — unless
|
||||
// the zone has sync_valves disabled, or the source/target valve is the bathroom
|
||||
// and exclude_bathroom is enabled. Never touches valves in other zones.
|
||||
async function syncGuestAdjustmentToRoom(externalRef, tempC) {
|
||||
const last = lastGuestSyncAt.get(externalRef)
|
||||
if (last && Date.now() - last < SYNC_DEBOUNCE_MS) return
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT zd.zone_id, zd.location, z.sync_valves, z.exclude_bathroom
|
||||
FROM zone_devices zd JOIN zones z ON z.id = zd.zone_id
|
||||
WHERE zd.device_type = 'shelly_trv' AND zd.external_ref = $1`,
|
||||
[externalRef]
|
||||
)
|
||||
const row = rows[0]
|
||||
if (!row || !row.zone_id || !row.sync_valves) return
|
||||
|
||||
const sourceIsBathroom = (row.location || '').toLowerCase().includes('bathroom')
|
||||
if (row.exclude_bathroom && sourceIsBathroom) return // bathroom adjustments don't propagate
|
||||
|
||||
const { rows: siblings } = await pool.query(
|
||||
`SELECT external_ref, device_ip, location FROM zone_devices
|
||||
WHERE device_type = 'shelly_trv' AND zone_id = $1 AND external_ref != $2`,
|
||||
[row.zone_id, externalRef]
|
||||
)
|
||||
const targets = siblings.filter(s => !(row.exclude_bathroom && (s.location || '').toLowerCase().includes('bathroom')))
|
||||
if (!targets.length) return
|
||||
|
||||
lastGuestSyncAt.set(externalRef, Date.now())
|
||||
console.log(`[mqtt] guest adjusted ${externalRef} to ${tempC}°C — syncing ${targets.length} other valve(s) in zone ${row.zone_id}`)
|
||||
await batchSetZoneTemperature(targets.map(t => ({ external_ref: t.external_ref, device_ip: t.device_ip })), tempC)
|
||||
}
|
||||
|
||||
function topicMatchesStatus(topic) {
|
||||
return /^shellies\/(.+)\/thermostat\/0\/target_t$/.exec(topic)
|
||||
}
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (connecting) return
|
||||
const delay = BROKER_RECONNECT_BACKOFF_MS[Math.min(reconnectAttempt, BROKER_RECONNECT_BACKOFF_MS.length - 1)]
|
||||
reconnectAttempt++
|
||||
console.warn(`[mqtt] broker unreachable — retrying in ${delay / 1000}s`)
|
||||
setTimeout(() => { connect().catch(() => {}) }, delay)
|
||||
}
|
||||
|
||||
export async function connect() {
|
||||
if (connecting || client?.connected) return
|
||||
connecting = true
|
||||
try {
|
||||
const creds = await getCredentials()
|
||||
await new Promise((resolve, reject) => {
|
||||
const c = mqtt.connect(`mqtt://${creds.host}:${creds.port}`, {
|
||||
username: creds.username,
|
||||
password: creds.password,
|
||||
clientId: `${CLIENT_NAME}-${Math.random().toString(16).slice(2, 8)}`,
|
||||
connectTimeout: 10000,
|
||||
reconnectPeriod: 0, // we own reconnect/backoff ourselves
|
||||
})
|
||||
|
||||
c.on('connect', () => {
|
||||
client = c
|
||||
reconnectAttempt = 0
|
||||
connecting = false
|
||||
console.log('[mqtt] connected to broker')
|
||||
c.subscribe(['shellies/announce', 'shellies/+/settings', 'shellies/+/thermostat/0/target_t'])
|
||||
resolve()
|
||||
})
|
||||
|
||||
c.on('message', (topic, message) => {
|
||||
let payload
|
||||
try { payload = JSON.parse(message.toString()) } catch { return }
|
||||
|
||||
if (topic === 'shellies/announce') {
|
||||
handleAnnounce(payload).catch(() => {})
|
||||
return
|
||||
}
|
||||
const settingsMatch = /^shellies\/(.+)\/settings$/.exec(topic)
|
||||
if (settingsMatch) {
|
||||
handleSettings(settingsMatch[1], payload).catch(() => {})
|
||||
return
|
||||
}
|
||||
const statusMatch = topicMatchesStatus(topic)
|
||||
if (statusMatch) {
|
||||
handleStatus(statusMatch[1], payload).catch(() => {})
|
||||
}
|
||||
})
|
||||
|
||||
c.on('error', (err) => {
|
||||
console.error('[mqtt] connection error:', err.message)
|
||||
})
|
||||
|
||||
c.on('close', () => {
|
||||
if (client === c) client = null
|
||||
connecting = false
|
||||
scheduleReconnect()
|
||||
})
|
||||
|
||||
// mqtt.js's own connect() already retried internally on the initial attempt;
|
||||
// if it never even reaches 'connect' fire our own backoff.
|
||||
setTimeout(() => {
|
||||
if (!client) { c.end(true); connecting = false; reject(new Error('MQTT connect timed out')) }
|
||||
}, 12000)
|
||||
})
|
||||
} catch (err) {
|
||||
connecting = false
|
||||
console.error('[mqtt] could not connect (broker/credentials unavailable):', err.message)
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
export function isConnected() {
|
||||
return !!client?.connected
|
||||
}
|
||||
|
||||
export function getDiscoveredDevices() {
|
||||
return Array.from(discovered.values())
|
||||
}
|
||||
|
||||
// Publish a setpoint command to a single TRV. Does NOT wait for acknowledgment —
|
||||
// use setTargetWithRetry() for the full reliability pipeline.
|
||||
function publishTarget(externalRef, tempC) {
|
||||
if (!client?.connected) throw new Error('MQTT broker not connected')
|
||||
const topic = `shellies/${externalRef}/thermostat/0/command/target_t`
|
||||
client.publish(topic, String(tempC))
|
||||
}
|
||||
|
||||
async function waitForAck(externalRef, tempC, timeoutMs) {
|
||||
const start = Date.now()
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT current_target_temp, updated_at FROM zone_devices
|
||||
WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef]
|
||||
)
|
||||
const row = rows[0]
|
||||
if (row?.current_target_temp != null && Math.abs(Number(row.current_target_temp) - tempC) < 0.1
|
||||
&& new Date(row.updated_at).getTime() >= start) {
|
||||
return true
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 5000))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HTTP GET wake-up fallback — Shelly devices in deep sleep sometimes respond to a
|
||||
// plain HTTP GET even when not responding over MQTT. Best-effort only.
|
||||
async function tryHttpWakeUp(deviceIp) {
|
||||
if (!deviceIp) return false
|
||||
try {
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), 10000)
|
||||
const res = await fetch(`http://${deviceIp}/status`, { signal: ctrl.signal })
|
||||
clearTimeout(timer)
|
||||
return res.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Set a single TRV's target temperature with exponential-backoff retry (30s -> 30min)
|
||||
// and an HTTP wake-up attempt before finally marking the device unresponsive.
|
||||
export async function setTargetWithRetry(device, tempC) {
|
||||
const { external_ref: externalRef, device_ip: deviceIp } = device
|
||||
|
||||
for (let attempt = 0; attempt < RETRY_DELAYS_MS.length; attempt++) {
|
||||
try {
|
||||
publishTarget(externalRef, tempC)
|
||||
} catch (err) {
|
||||
console.error(`[mqtt] publish failed for ${externalRef}:`, err.message)
|
||||
}
|
||||
|
||||
const acked = await waitForAck(externalRef, tempC, RETRY_DELAYS_MS[attempt])
|
||||
if (acked) {
|
||||
await pool.query(
|
||||
`UPDATE zone_devices SET health_state = 'healthy' WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef]
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
const healthState = attempt >= 5 ? 'poor' : attempt >= 3 ? 'degraded' : 'healthy'
|
||||
await pool.query(
|
||||
`UPDATE zone_devices SET health_state = $2 WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef, healthState]
|
||||
).catch(() => {})
|
||||
}
|
||||
|
||||
// All MQTT retries exhausted — try HTTP wake-up before giving up
|
||||
const wokeUp = await tryHttpWakeUp(deviceIp)
|
||||
if (wokeUp) {
|
||||
try { publishTarget(externalRef, tempC) } catch { /* ignore */ }
|
||||
const acked = await waitForAck(externalRef, tempC, 30000)
|
||||
if (acked) return true
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`UPDATE zone_devices SET health_state = 'unresponsive' WHERE device_type = 'shelly_trv' AND external_ref = $1`,
|
||||
[externalRef]
|
||||
).catch(() => {})
|
||||
console.error(`[mqtt] ${externalRef} failed to acknowledge target ${tempC}°C after ${RETRY_DELAYS_MS.length} attempts${wokeUp ? ' + HTTP wake-up' : ''}`)
|
||||
return false
|
||||
}
|
||||
|
||||
// Set temperature for multiple TRVs in a zone, staggered ~10s apart so several
|
||||
// battery-powered valves don't all wake their WiFi radio at once.
|
||||
export async function batchSetZoneTemperature(devices, tempC) {
|
||||
const results = {}
|
||||
for (let i = 0; i < devices.length; i++) {
|
||||
if (i > 0) await new Promise(r => setTimeout(r, STAGGER_MS))
|
||||
results[devices[i].external_ref] = await setTargetWithRetry(devices[i], tempC)
|
||||
}
|
||||
return results
|
||||
}
|
||||
80
backend/src/lib/newbook.js
Normal file
80
backend/src/lib/newbook.js
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// Adapted (near-verbatim) from room-planner/backend/src/lib/newbook.js.
|
||||
// Credentials come from the shared settings service, never a docker-compose env var.
|
||||
const API_BASE = 'https://api.newbook.cloud/rest/'
|
||||
|
||||
async function getCredentials() {
|
||||
const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/newbook`
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${process.env.SETTINGS_SECRET}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!res.ok) throw new Error(`Settings service returned ${res.status} fetching NewBook credentials`)
|
||||
const s = await res.json()
|
||||
return {
|
||||
username: s.username || '',
|
||||
password: s.password || '',
|
||||
apiKey: s.api_key || '',
|
||||
region: s.region || 'eu',
|
||||
}
|
||||
}
|
||||
|
||||
async function callApi(endpoint, data = {}) {
|
||||
const creds = await getCredentials()
|
||||
if (!creds.username || !creds.password || !creds.apiKey) {
|
||||
throw new Error('NewBook API credentials not configured')
|
||||
}
|
||||
|
||||
// Single-hotel scope — matches room-planner's convention, no multi-property support.
|
||||
const locationId = process.env.NEWBOOK_LOCATION_ID
|
||||
const body = { ...data, region: creds.region, api_key: creds.apiKey }
|
||||
if (locationId) body.location_id = locationId
|
||||
|
||||
const auth = Buffer.from(`${creds.username}:${creds.password}`).toString('base64')
|
||||
const ctrl = new AbortController()
|
||||
const timer = setTimeout(() => ctrl.abort(), 30000)
|
||||
|
||||
try {
|
||||
const res = await fetch(API_BASE + endpoint, {
|
||||
method: 'POST',
|
||||
signal: ctrl.signal,
|
||||
headers: { 'Content-Type': 'application/json', 'Authorization': `Basic ${auth}` },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
clearTimeout(timer)
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '')
|
||||
throw new Error(`NewBook API ${res.status}: ${text.slice(0, 200)}`)
|
||||
}
|
||||
return await res.json()
|
||||
} catch (err) {
|
||||
clearTimeout(timer)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch all sites (rooms) — used by the zones sync + include/exclude checklist.
|
||||
export async function fetchSites() {
|
||||
const res = await callApi('sites_list', {})
|
||||
return res?.data ?? []
|
||||
}
|
||||
|
||||
// Fetch bookings whose stay overlaps the date window (list_type 'staying' includes
|
||||
// a booking arriving on period_to). This is what the scheduler polls to build the
|
||||
// room state machine — see lib/scheduler.js.
|
||||
export async function fetchBookings(fromDate, toDate) {
|
||||
const res = await callApi('bookings_list', {
|
||||
period_from: `${fromDate} 00:00:00`,
|
||||
period_to: `${toDate} 23:59:59`,
|
||||
list_type: 'staying',
|
||||
})
|
||||
return res?.data ?? []
|
||||
}
|
||||
|
||||
export async function testConnection() {
|
||||
try {
|
||||
const sites = await fetchSites()
|
||||
return { ok: true, message: `Connected. Found ${sites.length} site(s).` }
|
||||
} catch (err) {
|
||||
return { ok: false, error: err.message }
|
||||
}
|
||||
}
|
||||
238
backend/src/lib/scheduler.js
Normal file
238
backend/src/lib/scheduler.js
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
// Room state machine + should_heat decision, ported from the retired
|
||||
// homeassistant-newbook-heating-component's booking_processor.py / heating_controller.py
|
||||
// (see /docs/HEATING_LOGIC.md in that archive for the worked examples this was tested
|
||||
// against: walk-in immediate heat, advance-booking pre-heat, multi-day stay, departed
|
||||
// cooling). All time math runs in Europe/London via luxon so the BST/GMT transition
|
||||
// doesn't silently break "minutes before a wall-clock time" arithmetic.
|
||||
import { DateTime } from 'luxon'
|
||||
import { pool, getConfig, logActivity } from '../db.js'
|
||||
import { fetchBookings } from './newbook.js'
|
||||
import { batchSetZoneTemperature } from './mqtt.js'
|
||||
|
||||
const TZ = 'Europe/London'
|
||||
const ACTIVE_BOOKING_STATUSES = ['confirmed', 'unconfirmed', 'arrived']
|
||||
const HEAT_STATES = ['heating_up', 'occupied']
|
||||
const COOL_STATES = ['vacant', 'cooling_down', 'booked']
|
||||
|
||||
let timerHandle = null
|
||||
let running = false
|
||||
|
||||
function parseNbDateTime(str) {
|
||||
if (!str) return null
|
||||
const dt = DateTime.fromFormat(str, 'yyyy-MM-dd HH:mm:ss', { zone: TZ })
|
||||
if (dt.isValid) return dt
|
||||
const dateOnly = DateTime.fromFormat(str, 'yyyy-MM-dd', { zone: TZ })
|
||||
return dateOnly.isValid ? dateOnly : null
|
||||
}
|
||||
|
||||
function parseHHMMSS(str, fallback) {
|
||||
if (!str) return fallback
|
||||
const parts = str.split(':').map(Number)
|
||||
if (parts.some(Number.isNaN)) return fallback
|
||||
return { hour: parts[0], minute: parts[1] || 0 }
|
||||
}
|
||||
|
||||
// calculate_heating_schedule() — heating_start = arrival - heating_offset_minutes,
|
||||
// cooling_start = departure + cooling_offset_minutes (cooling_offset can be negative
|
||||
// to stop heating BEFORE checkout). Arrival uses the EARLIER of actual vs default
|
||||
// arrival time; departure uses the LATER of actual vs default departure time.
|
||||
export function calculateHeatingSchedule(zone, booking, defaults) {
|
||||
if (!booking) return null
|
||||
const arrivalRaw = parseNbDateTime(booking.booking_arrival)
|
||||
const departureRaw = parseNbDateTime(booking.booking_departure)
|
||||
if (!arrivalRaw || !departureRaw) return null
|
||||
|
||||
const defaultArrival = parseHHMMSS(defaults.default_arrival_time, { hour: 15, minute: 0 })
|
||||
const defaultDeparture = parseHHMMSS(defaults.default_departure_time, { hour: 10, minute: 0 })
|
||||
|
||||
const actualArrivalMins = arrivalRaw.hour * 60 + arrivalRaw.minute
|
||||
const defaultArrivalMins = defaultArrival.hour * 60 + defaultArrival.minute
|
||||
const earliestArrivalMins = Math.min(actualArrivalMins, defaultArrivalMins)
|
||||
const arrival = arrivalRaw.startOf('day').plus({ minutes: earliestArrivalMins })
|
||||
|
||||
const actualDepartureMins = departureRaw.hour * 60 + departureRaw.minute
|
||||
const defaultDepartureMins = defaultDeparture.hour * 60 + defaultDeparture.minute
|
||||
const latestDepartureMins = Math.max(actualDepartureMins, defaultDepartureMins)
|
||||
const departure = departureRaw.startOf('day').plus({ minutes: latestDepartureMins })
|
||||
|
||||
const heatingStart = arrival.plus({ minutes: -zone.heating_offset_min })
|
||||
const coolingStart = departure.plus({ minutes: zone.cooling_offset_min })
|
||||
|
||||
return { heatingStart, coolingStart, arrival, departure }
|
||||
}
|
||||
|
||||
// determine_room_state() — priority order: 1) explicit booking status (arrived/departed
|
||||
// override everything), 2) time-based state from the schedule, 3) vacant if no booking.
|
||||
export function determineRoomState(booking, schedule, now) {
|
||||
if (!booking) return 'vacant'
|
||||
const status = (booking.booking_status || '').toLowerCase()
|
||||
|
||||
if (status === 'departed') return 'cooling_down'
|
||||
if (status === 'arrived') return 'occupied'
|
||||
|
||||
if (!schedule) return 'booked'
|
||||
const { heatingStart, coolingStart, arrival } = schedule
|
||||
if (!heatingStart || !coolingStart) return 'booked'
|
||||
|
||||
// A booking arriving on a future date shouldn't show as "booked" today.
|
||||
if (arrival.toISODate() > now.toISODate()) return 'vacant'
|
||||
|
||||
// heating_up covers both pre-arrival preheat AND "past arrival but not checked
|
||||
// in yet" — keep heating until the PMS actually marks the guest arrived.
|
||||
if (now >= heatingStart && now < coolingStart) return 'heating_up'
|
||||
if (now >= coolingStart) return 'cooling_down'
|
||||
if (now < heatingStart) return 'booked'
|
||||
return 'vacant' // shouldn't happen
|
||||
}
|
||||
|
||||
// should_heat() — auto mode AND an active booking status AND the room state in
|
||||
// [heating_up, occupied]. All three must hold.
|
||||
export function shouldHeat(booking, roomState, autoMode) {
|
||||
if (!autoMode) return false
|
||||
if (!booking) return false
|
||||
const status = (booking.booking_status || '').toLowerCase()
|
||||
if (!ACTIVE_BOOKING_STATUSES.includes(status)) return false
|
||||
return HEAT_STATES.includes(roomState)
|
||||
}
|
||||
|
||||
async function getZoneDevices(zoneId) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, external_ref, device_ip, device_type FROM zone_devices WHERE zone_id = $1`,
|
||||
[zoneId]
|
||||
)
|
||||
return rows
|
||||
}
|
||||
|
||||
async function applyTarget(zone, tempC) {
|
||||
const devices = await getZoneDevices(zone.id)
|
||||
const trvs = devices.filter(d => d.device_type === 'shelly_trv')
|
||||
if (!trvs.length) return { ok: false, reason: 'no_devices' }
|
||||
const results = await batchSetZoneTemperature(trvs, tempC)
|
||||
const successful = Object.values(results).filter(Boolean).length
|
||||
return { ok: successful > 0, successful, total: trvs.length }
|
||||
}
|
||||
|
||||
// Apply heating logic ONLY at state transitions — never poll-and-reassert during
|
||||
// 'occupied', which would stomp a guest's button/WS adjustment made mid-stay.
|
||||
async function applyStateTransition(zone, oldState, newState) {
|
||||
const target = HEAT_STATES.includes(newState) ? Number(zone.occupied_temp) : Number(zone.vacant_temp)
|
||||
const result = await applyTarget(zone, target)
|
||||
await logActivity(zone.id, 'transition', {
|
||||
fromState: oldState,
|
||||
toState: newState,
|
||||
note: result.ok
|
||||
? `Set ${target}°C (${result.successful}/${result.total} devices)`
|
||||
: `Failed to set ${target}°C (${result.reason || `${result.successful || 0}/${result.total || 0} devices`})`,
|
||||
source: 'scheduler',
|
||||
})
|
||||
}
|
||||
|
||||
async function getZoneState(zoneId) {
|
||||
const { rows } = await pool.query('SELECT * FROM zone_state WHERE zone_id = $1', [zoneId])
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
async function saveZoneState(zoneId, roomState, bookingStatus) {
|
||||
await pool.query(
|
||||
`INSERT INTO zone_state (zone_id, room_state, last_booking_status, last_transition_at, updated_at)
|
||||
VALUES ($1, $2, $3, NOW(), NOW())
|
||||
ON CONFLICT (zone_id) DO UPDATE SET
|
||||
room_state = EXCLUDED.room_state,
|
||||
last_booking_status = EXCLUDED.last_booking_status,
|
||||
last_transition_at = CASE WHEN zone_state.room_state != EXCLUDED.room_state THEN NOW() ELSE zone_state.last_transition_at END,
|
||||
updated_at = NOW()`,
|
||||
[zoneId, roomState, bookingStatus]
|
||||
)
|
||||
}
|
||||
|
||||
// One poll cycle: fetch bookings once, walk every active room zone, apply heating
|
||||
// logic only where the room's state has actually changed since the last cycle.
|
||||
export async function pollOnce() {
|
||||
const defaults = {
|
||||
default_arrival_time: await getConfig('default_arrival_time', '15:00:00'),
|
||||
default_departure_time: await getConfig('default_departure_time', '10:00:00'),
|
||||
}
|
||||
|
||||
const now = DateTime.now().setZone(TZ)
|
||||
const today = now.toISODate()
|
||||
|
||||
const { rows: zones } = await pool.query(
|
||||
`SELECT * FROM zones WHERE active = TRUE AND zone_type = 'room' AND newbook_site_id IS NOT NULL`
|
||||
)
|
||||
if (!zones.length) return
|
||||
|
||||
// Fail-safe: if NewBook is unreachable, keep every zone's last-known-good state —
|
||||
// "fetch failed" must never be treated the same as "no booking" (that would turn
|
||||
// off heating in an occupied room on a transient API blip).
|
||||
let bookings
|
||||
try {
|
||||
bookings = await fetchBookings(today, today)
|
||||
} catch (err) {
|
||||
console.error('[scheduler] NewBook fetch failed — keeping last-known-good state:', err.message)
|
||||
await logActivity(null, 'error', { note: `NewBook poll failed: ${err.message}`, source: 'scheduler' })
|
||||
return
|
||||
}
|
||||
|
||||
const bookingsBySite = new Map()
|
||||
for (const b of bookings) {
|
||||
const siteId = String(b.site_id ?? b.room_id ?? '')
|
||||
if (!siteId) continue
|
||||
// If multiple bookings overlap today for a site, prefer the one that's
|
||||
// actually arrived, then the one arriving soonest.
|
||||
const existing = bookingsBySite.get(siteId)
|
||||
if (!existing) { bookingsBySite.set(siteId, b); continue }
|
||||
const existingStatus = (existing.booking_status || '').toLowerCase()
|
||||
const candidateStatus = (b.booking_status || '').toLowerCase()
|
||||
if (candidateStatus === 'arrived' && existingStatus !== 'arrived') bookingsBySite.set(siteId, b)
|
||||
}
|
||||
|
||||
for (const zone of zones) {
|
||||
try {
|
||||
const booking = bookingsBySite.get(String(zone.newbook_site_id)) || null
|
||||
|
||||
// Cache the booking on every successful fetch so a future failed fetch has
|
||||
// something to fall back to (booking_cache is per-zone, TTL is implicit —
|
||||
// the fail-safe path above never even reaches this loop on a failed fetch).
|
||||
await pool.query(
|
||||
`INSERT INTO booking_cache (zone_id, booking_data, fetched_at) VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (zone_id) DO UPDATE SET booking_data = EXCLUDED.booking_data, fetched_at = NOW()`,
|
||||
[zone.id, booking ? JSON.stringify(booking) : null]
|
||||
)
|
||||
|
||||
const schedule = booking ? calculateHeatingSchedule(zone, booking, defaults) : null
|
||||
const newState = determineRoomState(booking, schedule, now)
|
||||
const prev = await getZoneState(zone.id)
|
||||
const oldState = prev?.room_state || 'vacant'
|
||||
|
||||
await saveZoneState(zone.id, newState, booking?.booking_status || null)
|
||||
|
||||
if (!zone.auto_mode) continue // manual override in effect — don't touch setpoints
|
||||
if (newState === oldState) continue // no transition — never poll-and-reassert
|
||||
|
||||
await applyStateTransition(zone, oldState, newState)
|
||||
} catch (err) {
|
||||
console.error(`[scheduler] zone ${zone.id} update failed:`, err.message)
|
||||
await logActivity(zone.id, 'error', { note: err.message, source: 'scheduler' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function startScheduler() {
|
||||
const minutes = Number(await getConfig('poll_interval_minutes', 10)) || 10
|
||||
const intervalMs = Math.max(1, minutes) * 60 * 1000
|
||||
|
||||
const tick = async () => {
|
||||
if (running) return
|
||||
running = true
|
||||
try { await pollOnce() } catch (err) { console.error('[scheduler] poll failed:', err.message) }
|
||||
running = false
|
||||
}
|
||||
|
||||
await tick()
|
||||
timerHandle = setInterval(tick, intervalMs)
|
||||
}
|
||||
|
||||
export function stopScheduler() {
|
||||
if (timerHandle) clearInterval(timerHandle)
|
||||
timerHandle = null
|
||||
}
|
||||
27
backend/src/routes/config.js
Normal file
27
backend/src/routes/config.js
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
|
||||
// Generic key/value config store (hk-planner/maintenance pattern). Zone-specific
|
||||
// settings (excluded_site_ids, etc.) go through their own routes in zones.js so
|
||||
// each has proper validation — this is the catch-all for simple scalar settings
|
||||
// like poll_interval_minutes, default_arrival_time, maintenance_url/api_key.
|
||||
export async function configRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
app.get('/api/config', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows } = await pool.query('SELECT key, value FROM config ORDER BY key')
|
||||
return Object.fromEntries(rows.map(r => [r.key, r.value]))
|
||||
})
|
||||
|
||||
app.put('/api/config/:key', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
const { key } = req.params
|
||||
const { value } = req.body || {}
|
||||
if (value === undefined) return reply.status(400).send({ error: 'value required' })
|
||||
await pool.query(
|
||||
`INSERT INTO config (key, value, updated_at) VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`,
|
||||
[key, JSON.stringify(value)]
|
||||
)
|
||||
return { ok: true }
|
||||
})
|
||||
}
|
||||
160
backend/src/routes/devices.js
Normal file
160
backend/src/routes/devices.js
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
import { mkdir, unlink, writeFile } from 'fs/promises'
|
||||
import { randomUUID } from 'crypto'
|
||||
import { join } from 'path'
|
||||
import sharp from 'sharp'
|
||||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool, logActivity } from '../db.js'
|
||||
import * as trvDriver from '../lib/drivers/trv.js'
|
||||
import * as haDriver from '../lib/drivers/homeassistant.js'
|
||||
import { createMaintenanceAsset } from '../lib/maintenance-client.js'
|
||||
|
||||
const ALLOWED_IMAGES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
|
||||
const PHOTO_TYPES = ['device', 'serial_plate']
|
||||
|
||||
// device_type -> driver implementing discover()/getStatus()/setTarget(). Phase 2/3
|
||||
// types (mhi_modbus, midea, daikin) are enum values only — no driver yet.
|
||||
const DRIVERS = {
|
||||
shelly_trv: trvDriver,
|
||||
home_assistant: haDriver,
|
||||
}
|
||||
const NOT_YET_IMPLEMENTED = ['mhi_modbus', 'midea', 'daikin']
|
||||
|
||||
export async function deviceRoutes(app, opts) {
|
||||
const UPLOADS_DIR = opts.uploadsDir
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/devices — every mapped + unassigned device, with zone name and photo count
|
||||
app.get('/api/devices', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows } = await pool.query(`
|
||||
SELECT zd.*, z.name AS zone_name,
|
||||
(SELECT COUNT(*)::int FROM device_photos p WHERE p.device_id = zd.id) AS photo_count
|
||||
FROM zone_devices zd
|
||||
LEFT JOIN zones z ON z.id = zd.zone_id
|
||||
ORDER BY zd.zone_id NULLS FIRST, zd.device_type, zd.discovered_name
|
||||
`)
|
||||
return rows
|
||||
})
|
||||
|
||||
// POST /api/devices/discover — { device_type } -> runs that driver's discover(),
|
||||
// and inserts any newly-seen device as an unassigned row (never auto-linked to a zone).
|
||||
app.post('/api/devices/discover', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const { device_type } = req.body || {}
|
||||
if (!device_type) return reply.status(400).send({ error: 'device_type required' })
|
||||
|
||||
if (NOT_YET_IMPLEMENTED.includes(device_type)) {
|
||||
return reply.status(200).send({
|
||||
ok: true, devices: [],
|
||||
note: `${device_type} discovery isn't implemented yet — Phase 1 only covers Shelly TRVs. ` +
|
||||
`This device type exists as a column enum value ready for its Phase 2/3 driver.`,
|
||||
})
|
||||
}
|
||||
|
||||
const driver = DRIVERS[device_type]
|
||||
if (!driver) return reply.status(400).send({ error: `Unknown device_type: ${device_type}` })
|
||||
|
||||
const result = await driver.discover()
|
||||
if (!result.ok) return reply.status(200).send(result) // e.g. broker/HA not reachable — not a hard error
|
||||
|
||||
let discoveredCount = 0
|
||||
for (const d of result.devices) {
|
||||
const res = await pool.query(
|
||||
`INSERT INTO zone_devices (device_type, external_ref, discovered_name)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (device_type, external_ref) DO UPDATE SET discovered_name = EXCLUDED.discovered_name, last_seen = NOW()
|
||||
RETURNING (xmax = 0) AS inserted`,
|
||||
[device_type, d.external_ref, d.discovered_name || d.external_ref]
|
||||
)
|
||||
if (res.rows[0].inserted) discoveredCount++
|
||||
}
|
||||
|
||||
return { ok: true, found: result.devices.length, new: discoveredCount }
|
||||
})
|
||||
|
||||
// PATCH /api/devices/:id — zone/location assignment (a living mapping, not a one-time wizard)
|
||||
app.patch('/api/devices/:id', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const { rows: existing } = await pool.query('SELECT * FROM zone_devices WHERE id = $1', [req.params.id])
|
||||
if (!existing.length) return reply.status(404).send({ error: 'Device not found' })
|
||||
const d = existing[0]
|
||||
const { zone_id, location } = req.body || {}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE zone_devices SET zone_id = $1, location = $2, updated_at = NOW() WHERE id = $3 RETURNING *`,
|
||||
[zone_id !== undefined ? zone_id : d.zone_id, location !== undefined ? location : d.location, req.params.id]
|
||||
)
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
// POST /api/devices/:id/photos — multipart: file + photo_type (device | serial_plate)
|
||||
app.post('/api/devices/:id/photos', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const deviceId = parseInt(req.params.id)
|
||||
const { rows } = await pool.query('SELECT id FROM zone_devices WHERE id = $1', [deviceId])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Device not found' })
|
||||
|
||||
let fileData = null, photoType = 'device'
|
||||
for await (const part of req.parts()) {
|
||||
if (part.type === 'file') {
|
||||
if (!ALLOWED_IMAGES.includes(part.mimetype)) {
|
||||
return reply.status(400).send({ error: 'Only JPEG, PNG and WebP images are allowed' })
|
||||
}
|
||||
const chunks = []
|
||||
for await (const chunk of part.file) chunks.push(chunk)
|
||||
const raw = Buffer.concat(chunks)
|
||||
|
||||
// Auto-rotate (phone EXIF), resize to 1800px max, re-encode as JPEG — same as maintenance's task_photos.
|
||||
const processed = await sharp(raw)
|
||||
.rotate()
|
||||
.resize(1800, 1800, { fit: 'inside', withoutEnlargement: true })
|
||||
.jpeg({ quality: 82, progressive: true })
|
||||
.toBuffer()
|
||||
|
||||
const filename = randomUUID() + '.jpg'
|
||||
const dir = join(UPLOADS_DIR, 'devices', String(deviceId))
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeFile(join(dir, filename), processed)
|
||||
fileData = { originalName: part.filename, savedAs: filename, size: processed.length }
|
||||
} else {
|
||||
const val = await part.value
|
||||
if (part.fieldname === 'photo_type' && PHOTO_TYPES.includes(String(val))) photoType = String(val)
|
||||
}
|
||||
}
|
||||
if (!fileData?.savedAs) return reply.status(400).send({ error: 'No file uploaded' })
|
||||
|
||||
const filePath = `/devices/${deviceId}/${fileData.savedAs}`
|
||||
const { rows: ins } = await pool.query(
|
||||
`INSERT INTO device_photos (device_id, file_name, file_path, mime_type, file_size, photo_type, uploaded_by)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
|
||||
[deviceId, fileData.originalName, filePath, 'image/jpeg', fileData.size, photoType, req.user.email]
|
||||
)
|
||||
return ins[0]
|
||||
})
|
||||
|
||||
app.get('/api/devices/:id/photos', { preHandler: requireCap('view') }, async (req) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT * FROM device_photos WHERE device_id = $1 ORDER BY uploaded_at DESC',
|
||||
[req.params.id]
|
||||
)
|
||||
return rows
|
||||
})
|
||||
|
||||
app.delete('/api/photos/:id', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const { rows } = await pool.query('SELECT * FROM device_photos WHERE id = $1', [req.params.id])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Not found' })
|
||||
await unlink(join(UPLOADS_DIR, rows[0].file_path)).catch(() => {})
|
||||
await pool.query('DELETE FROM device_photos WHERE id = $1', [req.params.id])
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
// POST /api/devices/:id/create-maintenance-asset — explicit stub. Real integration
|
||||
// needs maintenance's own Settings -> API Keys page + POST /api/public/assets first
|
||||
// (see lib/maintenance-client.js). Returns a clear "not implemented" response rather
|
||||
// than faking a cross-app call.
|
||||
app.post('/api/devices/:id/create-maintenance-asset', { preHandler: requireCap('manage_devices') }, async (req, reply) => {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT zd.*, z.name AS zone_name FROM zone_devices zd LEFT JOIN zones z ON z.id = zd.zone_id WHERE zd.id = $1`,
|
||||
[req.params.id]
|
||||
)
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Device not found' })
|
||||
const result = await createMaintenanceAsset(rows[0], { name: rows[0].zone_name })
|
||||
return reply.status(501).send(result)
|
||||
})
|
||||
}
|
||||
41
backend/src/routes/override.js
Normal file
41
backend/src/routes/override.js
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool, logActivity } from '../db.js'
|
||||
import { batchSetZoneTemperature } from '../lib/mqtt.js'
|
||||
|
||||
// Manual force-temperature — the equivalent of the old integration's
|
||||
// newbook.force_room_temperature service. Disables auto mode for the zone so the
|
||||
// scheduler leaves it alone until staff switch auto mode back on (zones.js PATCH).
|
||||
export async function overrideRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
app.post('/api/zones/:id/override', { preHandler: requireCap('control') }, async (req, reply) => {
|
||||
const { temp_c } = req.body || {}
|
||||
const tempC = Number(temp_c)
|
||||
if (!Number.isFinite(tempC)) return reply.status(400).send({ error: 'temp_c must be a number' })
|
||||
|
||||
const { rows } = await pool.query('SELECT * FROM zones WHERE id = $1', [req.params.id])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Zone not found' })
|
||||
const zone = rows[0]
|
||||
|
||||
await pool.query('UPDATE zones SET auto_mode = FALSE WHERE id = $1', [zone.id])
|
||||
|
||||
const { rows: devices } = await pool.query(
|
||||
`SELECT external_ref, device_ip FROM zone_devices WHERE zone_id = $1 AND device_type = 'shelly_trv'`,
|
||||
[zone.id]
|
||||
)
|
||||
if (!devices.length) {
|
||||
return reply.status(200).send({ ok: false, error: 'No TRVs mapped to this zone', auto_mode: false })
|
||||
}
|
||||
|
||||
const results = await batchSetZoneTemperature(devices, tempC)
|
||||
const successful = Object.values(results).filter(Boolean).length
|
||||
|
||||
await logActivity(zone.id, 'override', {
|
||||
note: `Manual override to ${tempC}°C (${successful}/${devices.length} devices, auto mode disabled)`,
|
||||
source: 'manual',
|
||||
userEmail: req.user.email,
|
||||
})
|
||||
|
||||
return { ok: successful > 0, successful, total: devices.length, auto_mode: false }
|
||||
})
|
||||
}
|
||||
25
backend/src/routes/settings.js
Normal file
25
backend/src/routes/settings.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { testConnection } from '../lib/newbook.js'
|
||||
import { isConnected as mqttConnected } from '../lib/mqtt.js'
|
||||
|
||||
// Settings-page-backing endpoints that don't fit the generic config.js key/value
|
||||
// store: connection tests and the MQTT broker's live status. The Home Assistant
|
||||
// integration itself is configured centrally in the shared `settings` app, not
|
||||
// here — this just reports whether it's reachable (via the driver's own no-op
|
||||
// behaviour when unconfigured).
|
||||
export async function settingsRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
app.post('/api/settings/newbook-test', { preHandler: requireCap('settings') }, async () => {
|
||||
return testConnection()
|
||||
})
|
||||
|
||||
app.get('/api/settings/mqtt-status', { preHandler: requireCap('settings') }, async () => {
|
||||
return {
|
||||
connected: mqttConnected(),
|
||||
note: mqttConnected()
|
||||
? 'Connected to the shared MQTT broker.'
|
||||
: 'Not connected — the shared MQTT broker (LXC 104) may not be provisioned yet, or hvac-backend has no credentials in settings.',
|
||||
}
|
||||
})
|
||||
}
|
||||
59
backend/src/routes/status.js
Normal file
59
backend/src/routes/status.js
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
import { isConnected as mqttConnected } from '../lib/mqtt.js'
|
||||
|
||||
export async function statusRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/status — live status per zone: room state, target temp, device health/battery
|
||||
app.get('/api/status', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows: zones } = await pool.query(`
|
||||
SELECT z.*, zs.room_state, zs.last_transition_at, zs.last_booking_status
|
||||
FROM zones z
|
||||
LEFT JOIN zone_state zs ON zs.zone_id = z.id
|
||||
WHERE z.active = TRUE
|
||||
ORDER BY z.zone_type, z.name
|
||||
`)
|
||||
|
||||
const { rows: devices } = await pool.query(`
|
||||
SELECT id, zone_id, device_type, external_ref, discovered_name, location,
|
||||
health_state, battery_pct, wifi_rssi, current_target_temp, target_origin, last_seen
|
||||
FROM zone_devices WHERE zone_id IS NOT NULL
|
||||
`)
|
||||
const devicesByZone = new Map()
|
||||
for (const d of devices) {
|
||||
if (!devicesByZone.has(d.zone_id)) devicesByZone.set(d.zone_id, [])
|
||||
devicesByZone.get(d.zone_id).push(d)
|
||||
}
|
||||
|
||||
return {
|
||||
mqtt_connected: mqttConnected(),
|
||||
zones: zones.map(z => ({
|
||||
...z,
|
||||
room_state: z.room_state || 'vacant',
|
||||
target_temp: ['heating_up', 'occupied'].includes(z.room_state) ? z.occupied_temp : z.vacant_temp,
|
||||
devices: devicesByZone.get(z.id) || [],
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
// GET /api/status/activity — recent activity log, optionally filtered by zone
|
||||
app.get('/api/status/activity', { preHandler: requireCap('view') }, async (req) => {
|
||||
const { zone_id, limit } = req.query || {}
|
||||
const lim = Math.min(parseInt(limit) || 100, 500)
|
||||
if (zone_id) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT al.*, z.name AS zone_name FROM activity_log al LEFT JOIN zones z ON z.id = al.zone_id
|
||||
WHERE al.zone_id = $1 ORDER BY al.created_at DESC LIMIT $2`,
|
||||
[zone_id, lim]
|
||||
)
|
||||
return rows
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`SELECT al.*, z.name AS zone_name FROM activity_log al LEFT JOIN zones z ON z.id = al.zone_id
|
||||
ORDER BY al.created_at DESC LIMIT $1`,
|
||||
[lim]
|
||||
)
|
||||
return rows
|
||||
})
|
||||
}
|
||||
145
backend/src/routes/zones.js
Normal file
145
backend/src/routes/zones.js
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool, getConfig, setConfig, logActivity } from '../db.js'
|
||||
import { fetchSites, testConnection } from '../lib/newbook.js'
|
||||
|
||||
export async function zoneRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/zones — all zones with device counts
|
||||
app.get('/api/zones', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows } = await pool.query(`
|
||||
SELECT z.*, COUNT(zd.id)::int AS device_count
|
||||
FROM zones z
|
||||
LEFT JOIN zone_devices zd ON zd.zone_id = z.id
|
||||
GROUP BY z.id
|
||||
ORDER BY z.zone_type, z.name
|
||||
`)
|
||||
return rows
|
||||
})
|
||||
|
||||
// PATCH /api/zones/:id — per-zone config: temps, offsets, auto_mode, sync_valves, exclude_bathroom
|
||||
app.patch('/api/zones/:id', { preHandler: requireCap('schedule_edit') }, async (req, reply) => {
|
||||
const { rows: existing } = await pool.query('SELECT * FROM zones WHERE id = $1', [req.params.id])
|
||||
if (!existing.length) return reply.status(404).send({ error: 'Zone not found' })
|
||||
const z = existing[0]
|
||||
const {
|
||||
name, occupied_temp, vacant_temp, heating_offset_min, cooling_offset_min,
|
||||
auto_mode, sync_valves, exclude_bathroom,
|
||||
} = req.body || {}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE zones SET
|
||||
name = $1, occupied_temp = $2, vacant_temp = $3, heating_offset_min = $4,
|
||||
cooling_offset_min = $5, auto_mode = $6, sync_valves = $7, exclude_bathroom = $8
|
||||
WHERE id = $9 RETURNING *`,
|
||||
[
|
||||
name ?? z.name,
|
||||
occupied_temp ?? z.occupied_temp,
|
||||
vacant_temp ?? z.vacant_temp,
|
||||
heating_offset_min ?? z.heating_offset_min,
|
||||
cooling_offset_min ?? z.cooling_offset_min,
|
||||
auto_mode ?? z.auto_mode,
|
||||
sync_valves ?? z.sync_valves,
|
||||
exclude_bathroom ?? z.exclude_bathroom,
|
||||
req.params.id,
|
||||
]
|
||||
)
|
||||
if (auto_mode !== undefined && auto_mode !== z.auto_mode) {
|
||||
await logActivity(z.id, 'override', {
|
||||
note: auto_mode ? 'Auto mode re-enabled' : 'Auto mode disabled',
|
||||
source: 'manual',
|
||||
userEmail: req.user.email,
|
||||
})
|
||||
}
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
// POST /api/zones — manual zone creation (public areas, or any non-NewBook device group)
|
||||
app.post('/api/zones', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
const { name, zone_type, occupied_temp, vacant_temp } = req.body || {}
|
||||
if (!name) return reply.status(400).send({ error: 'name required' })
|
||||
if (!['room', 'public_area'].includes(zone_type)) {
|
||||
return reply.status(400).send({ error: "zone_type must be 'room' or 'public_area'" })
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO zones (name, zone_type, source, newbook_site_id, occupied_temp, vacant_temp)
|
||||
VALUES ($1, $2, 'manual', NULL, $3, $4) RETURNING *`,
|
||||
[name, zone_type, occupied_temp || 22.0, vacant_temp || 16.0]
|
||||
)
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
// ── NewBook include/exclude checklist (hk-planner's CategorySettings.tsx pattern) ──
|
||||
|
||||
// GET /api/zones/newbook-sites — live sites list + excluded flag, for the checklist UI
|
||||
app.get('/api/zones/newbook-sites', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
let sites
|
||||
try {
|
||||
sites = await fetchSites()
|
||||
} catch (err) {
|
||||
return reply.status(502).send({ error: `NewBook error: ${err.message}` })
|
||||
}
|
||||
const excluded = (await getConfig('excluded_site_ids', [])) || []
|
||||
return {
|
||||
sites: sites.map(s => ({
|
||||
site_id: String(s.site_id),
|
||||
site_name: s.site_name,
|
||||
category_name: s.category_name || null,
|
||||
excluded: excluded.includes(String(s.site_id)),
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
// PUT /api/zones/newbook-sites — save the excluded_site_ids list
|
||||
app.put('/api/zones/newbook-sites', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
const { excluded_site_ids } = req.body || {}
|
||||
if (!Array.isArray(excluded_site_ids)) return reply.status(400).send({ error: 'excluded_site_ids must be an array' })
|
||||
await setConfig('excluded_site_ids', excluded_site_ids.map(String))
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
app.post('/api/zones/newbook-test', { preHandler: requireCap('settings') }, async () => {
|
||||
return testConnection()
|
||||
})
|
||||
|
||||
// POST /api/zones/sync-newbook — upsert a zone per non-excluded site (maintenance's
|
||||
// locations.js sync-newbook pattern): ON CONFLICT (newbook_site_id) DO UPDATE, and
|
||||
// soft-deactivate (never delete) any previously-synced zone whose site disappeared.
|
||||
app.post('/api/zones/sync-newbook', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
let sites
|
||||
try {
|
||||
sites = await fetchSites()
|
||||
} catch (err) {
|
||||
return reply.status(502).send({ error: `NewBook error: ${err.message}` })
|
||||
}
|
||||
|
||||
const excluded = new Set((await getConfig('excluded_site_ids', [])) || [])
|
||||
const included = sites.filter(s => !excluded.has(String(s.site_id)))
|
||||
|
||||
let created = 0, updated = 0
|
||||
for (const site of included) {
|
||||
const siteId = String(site.site_id)
|
||||
const name = site.site_name || `Room ${siteId}`
|
||||
const res = await pool.query(
|
||||
`INSERT INTO zones (name, zone_type, source, newbook_site_id)
|
||||
VALUES ($1, 'room', 'newbook', $2)
|
||||
ON CONFLICT (newbook_site_id) DO UPDATE SET name = EXCLUDED.name, active = TRUE
|
||||
RETURNING (xmax = 0) AS inserted`,
|
||||
[name, siteId]
|
||||
)
|
||||
res.rows[0].inserted ? created++ : updated++
|
||||
}
|
||||
|
||||
// Zones synced from NewBook whose site is now excluded/gone are deactivated,
|
||||
// never deleted — preserves schedule config + activity history.
|
||||
const includedIds = included.map(s => String(s.site_id))
|
||||
await pool.query(
|
||||
`UPDATE zones SET active = FALSE
|
||||
WHERE source = 'newbook' AND newbook_site_id IS NOT NULL AND NOT (newbook_site_id = ANY($1))`,
|
||||
[includedIds.length ? includedIds : ['']]
|
||||
)
|
||||
|
||||
await logActivity(null, 'sync', { note: `NewBook sync: ${created} created, ${updated} updated`, source: 'sync', userEmail: req.user.email })
|
||||
return { ok: true, created, updated, total: included.length }
|
||||
})
|
||||
}
|
||||
42
docker-compose.yml
Normal file
42
docker-compose.yml
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
services:
|
||||
backend:
|
||||
build: ./backend
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
environment:
|
||||
- DATABASE_URL=${DATABASE_URL}
|
||||
- CENTRAL_AUTH_SECRET=${CENTRAL_AUTH_SECRET}
|
||||
- SETTINGS_URL=${SETTINGS_URL}
|
||||
- SETTINGS_SECRET=${SETTINGS_SECRET}
|
||||
- APP_SLUG=hvac
|
||||
- OFFICE_IP_CHECK=${OFFICE_IP_CHECK:-disabled}
|
||||
- NEWBOOK_LOCATION_ID=${NEWBOOK_LOCATION_ID:-}
|
||||
volumes:
|
||||
- uploads_data:/app/uploads
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:3001/health || exit 1"]
|
||||
interval: 10s
|
||||
retries: 5
|
||||
start_period: 20s
|
||||
restart: unless-stopped
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
args:
|
||||
VITE_HOTEL_NAME: ${VITE_HOTEL_NAME}
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-3080}:80"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
default:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
uploads_data:
|
||||
13
frontend/Dockerfile
Normal file
13
frontend/Dockerfile
Normal 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
16
frontend/index.html
Normal 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
40
frontend/nginx.conf
Normal 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
1901
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
24
frontend/package.json
Normal file
24
frontend/package.json
Normal 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
33
frontend/src/App.tsx
Normal 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
108
frontend/src/api.ts
Normal 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')
|
||||
}
|
||||
166
frontend/src/components/AuthGate.tsx
Normal file
166
frontend/src/components/AuthGate.tsx
Normal 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',
|
||||
}
|
||||
93
frontend/src/components/DevicePhotoUpload.tsx
Normal file
93
frontend/src/components/DevicePhotoUpload.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
72
frontend/src/components/Layout.tsx
Normal file
72
frontend/src/components/Layout.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
27
frontend/src/components/ZoneCard.tsx
Normal file
27
frontend/src/components/ZoneCard.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
180
frontend/src/components/ZoneDetailModal.tsx
Normal file
180
frontend/src/components/ZoneDetailModal.tsx
Normal 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
394
frontend/src/index.css
Normal 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
10
frontend/src/main.tsx
Normal 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>
|
||||
)
|
||||
80
frontend/src/pages/Dashboard.tsx
Normal file
80
frontend/src/pages/Dashboard.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
193
frontend/src/pages/Devices.tsx
Normal file
193
frontend/src/pages/Devices.tsx
Normal 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 & 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>
|
||||
)
|
||||
}
|
||||
213
frontend/src/pages/Settings.tsx
Normal file
213
frontend/src/pages/Settings.tsx
Normal 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
128
frontend/src/types.ts
Normal 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
1
frontend/src/vite-env.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/// <reference types="vite/client" />
|
||||
19
frontend/tsconfig.json
Normal file
19
frontend/tsconfig.json
Normal 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
7
frontend/vite.config.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
export default defineConfig({
|
||||
base: '/hvac/',
|
||||
plugins: [react()],
|
||||
})
|
||||
50
seed-app.js
Normal file
50
seed-app.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
#!/usr/bin/env node
|
||||
// Run from hvac/ dir: DATABASE_URL=... node seed-app.js
|
||||
import pg from 'pg'
|
||||
|
||||
const { Pool } = pg
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL })
|
||||
|
||||
await pool.query(`
|
||||
INSERT INTO apps (slug, name, description, base_path, icon, theme_color, category, internal_host, internal_port)
|
||||
VALUES ('hvac', 'HVAC', 'Room heating control — NewBook-driven TRV scheduling, aircon and boiler (phased)', '/hvac', 'Thermometer', '#c1440e', 'Operations', '10.10.10.128', 3080)
|
||||
ON CONFLICT (slug) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
description = EXCLUDED.description,
|
||||
base_path = EXCLUDED.base_path,
|
||||
icon = EXCLUDED.icon,
|
||||
theme_color = EXCLUDED.theme_color,
|
||||
category = EXCLUDED.category,
|
||||
internal_host = EXCLUDED.internal_host,
|
||||
internal_port = EXCLUDED.internal_port
|
||||
`)
|
||||
|
||||
// Seed capabilities. public_area_control / boiler_view / boiler_control are
|
||||
// Phase 3/4 capabilities seeded now (per the plan) so role assignment doesn't
|
||||
// need a second migration later — no routes are gated on them yet.
|
||||
await pool.query(`
|
||||
INSERT INTO app_capabilities (app_id, slug, name, description, sort_order)
|
||||
SELECT a.id, c.slug, c.name, c.description, c.sort_order
|
||||
FROM apps a, (VALUES
|
||||
('view', 'View', 'View zone dashboard, device status and activity', 1),
|
||||
('control', 'Manual Override', 'Force a zone''s temperature and disable auto mode', 2),
|
||||
('schedule_edit', 'Edit Schedules', 'Adjust per-zone temps, offsets and auto mode', 3),
|
||||
('manage_devices', 'Manage Devices', 'Discover, map, photograph devices; sync zones from NewBook',4),
|
||||
('public_area_control', 'Public Area Control', 'Central control of public-area zones (Phase 3)', 5),
|
||||
('boiler_view', 'Boiler — View', 'View boiler controller status (Phase 4)', 6),
|
||||
('boiler_control', 'Boiler — Control', 'Adjust boiler weather-compensation / pump disable (Phase 4)',7),
|
||||
('settings', 'Settings', 'Configure hvac app settings', 8)
|
||||
) AS c(slug, name, description, sort_order)
|
||||
WHERE a.slug = 'hvac'
|
||||
ON CONFLICT (app_id, slug) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
description = EXCLUDED.description,
|
||||
sort_order = EXCLUDED.sort_order
|
||||
`)
|
||||
|
||||
// No default Staff grants — this app drives physical room heating, so access is
|
||||
// admin-assigned per role via the portal (same convention as wages/utilities,
|
||||
// the two most recently-added apps).
|
||||
|
||||
console.log('hvac app seeded.')
|
||||
await pool.end()
|
||||
Loading…
Add table
Add a link
Reference in a new issue