Scaffold plant app - MQTT monitoring for boiler-room equipment
Read-only monitoring/alerting for boilers, water softener, calorifiers and pumps via a generic MQTT-topic-prefix asset model, so new equipment can be onboarded without new ingestion code. Threshold and stale-data alert rules with email + in-app notification. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
commit
503b397dff
38 changed files with 5044 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-plant-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",
|
||||
"mqtt": "^5.10.3",
|
||||
"nodemailer": "^6.9.16",
|
||||
"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 || 'plant'
|
||||
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 all non-settings caps until re-login
|
||||
caps = ['view', 'guest_details', 'rate_details', 'view_all_notes', 'complete_tasks', 'update_status']
|
||||
}
|
||||
|
||||
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}` })
|
||||
}
|
||||
}
|
||||
}
|
||||
145
backend/src/db.js
Normal file
145
backend/src/db.js
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import pg from 'pg'
|
||||
|
||||
const { Pool } = pg
|
||||
export const pool = new Pool({ connectionString: process.env.DATABASE_URL })
|
||||
|
||||
export async function initDb() {
|
||||
await pool.query(`
|
||||
-- Plant-room equipment register — boilers, water softeners, calorifiers,
|
||||
-- pump/pressurisation sets. Read-only monitoring only: no target/setpoint
|
||||
-- columns here and no driver abstraction, unlike hvac's zone_devices.
|
||||
CREATE TABLE IF NOT EXISTS plant_assets (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
asset_type TEXT NOT NULL, -- boiler | water_softener | calorifier | pump
|
||||
location TEXT,
|
||||
make_model TEXT,
|
||||
serial_no TEXT,
|
||||
install_date DATE,
|
||||
notes TEXT,
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
mqtt_topic_prefix TEXT, -- e.g. 'plant/water-softener' — nullable until wired to a device
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS plant_assets_type_idx ON plant_assets (asset_type);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS plant_assets_topic_prefix_idx ON plant_assets (mqtt_topic_prefix) WHERE mqtt_topic_prefix IS NOT NULL;
|
||||
|
||||
-- Raw telemetry history, one row per MQTT message. field_key is whatever
|
||||
-- topic segment(s) follow the asset's mqtt_topic_prefix (see lib/mqtt.js) —
|
||||
-- generic across any asset type, never a fixed column set. Both a numeric
|
||||
-- and text value are kept: numeric fields (salt_level_pct) populate
|
||||
-- value_numeric, boolean/enum fields (regeneration_active, salt_level_status)
|
||||
-- populate value_text (and value_numeric too when the text is exactly
|
||||
-- "true"/"false", so booleans can still be charted).
|
||||
CREATE TABLE IF NOT EXISTS plant_telemetry_raw (
|
||||
id SERIAL PRIMARY KEY,
|
||||
asset_id INT NOT NULL REFERENCES plant_assets(id) ON DELETE CASCADE,
|
||||
field_key TEXT NOT NULL,
|
||||
value_numeric NUMERIC,
|
||||
value_text TEXT,
|
||||
recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS plant_telemetry_raw_asset_field_idx ON plant_telemetry_raw (asset_id, field_key, recorded_at DESC);
|
||||
|
||||
-- Latest known value per asset+field — what the Dashboard and stale-minutes
|
||||
-- alert sweep read from, upserted on every telemetry insert.
|
||||
CREATE TABLE IF NOT EXISTS plant_asset_latest (
|
||||
asset_id INT NOT NULL REFERENCES plant_assets(id) ON DELETE CASCADE,
|
||||
field_key TEXT NOT NULL,
|
||||
value_numeric NUMERIC,
|
||||
value_text TEXT,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
PRIMARY KEY (asset_id, field_key)
|
||||
);
|
||||
|
||||
-- Alert rules — either scoped to one asset (asset_id set) or to every asset
|
||||
-- of a type (asset_type set, asset_id NULL). 'stale_minutes' rules are swept
|
||||
-- periodically by lib/scheduler.js; lt/gt/eq rules are evaluated inline as
|
||||
-- telemetry arrives (lib/mqtt.js -> lib/alert-engine.js).
|
||||
CREATE TABLE IF NOT EXISTS plant_alert_rules (
|
||||
id SERIAL PRIMARY KEY,
|
||||
asset_id INT REFERENCES plant_assets(id) ON DELETE CASCADE,
|
||||
asset_type TEXT,
|
||||
field_key TEXT NOT NULL,
|
||||
condition TEXT NOT NULL, -- lt | gt | eq | stale_minutes
|
||||
threshold NUMERIC NOT NULL,
|
||||
severity TEXT NOT NULL DEFAULT 'warning', -- warning | critical
|
||||
active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CHECK (asset_id IS NOT NULL OR asset_type IS NOT NULL)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS plant_alert_rules_lookup_idx ON plant_alert_rules (field_key, condition) WHERE active = TRUE;
|
||||
|
||||
-- Triggered alerts. Auto-resolved by the same check that raised them once
|
||||
-- the underlying condition clears (see lib/alert-engine.js) — "acknowledge"
|
||||
-- is a separate, purely human action (someone has seen it) from "resolved"
|
||||
-- (the condition itself is no longer breaching).
|
||||
CREATE TABLE IF NOT EXISTS plant_alerts (
|
||||
id SERIAL PRIMARY KEY,
|
||||
rule_id INT NOT NULL REFERENCES plant_alert_rules(id) ON DELETE CASCADE,
|
||||
asset_id INT NOT NULL REFERENCES plant_assets(id) ON DELETE CASCADE,
|
||||
field_key TEXT NOT NULL,
|
||||
value_at_trigger TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'open', -- open | acknowledged | resolved
|
||||
triggered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
acknowledged_at TIMESTAMPTZ,
|
||||
acknowledged_by TEXT,
|
||||
resolved_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS plant_alerts_status_idx ON plant_alerts (status, triggered_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS plant_alerts_open_lookup_idx ON plant_alerts (rule_id, asset_id, field_key) WHERE status = 'open';
|
||||
|
||||
-- Asset photos — same shape as hvac's device_photos (multipart + sharp,
|
||||
-- shared uploads_data volume). photo_type 'asset' (general shot) or
|
||||
-- 'serial_plate' (model/serial plate close-up).
|
||||
CREATE TABLE IF NOT EXISTS asset_photos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
asset_id INT NOT NULL REFERENCES plant_assets(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 'asset', -- asset | serial_plate
|
||||
uploaded_by TEXT,
|
||||
uploaded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS asset_photos_asset_idx ON asset_photos (asset_id);
|
||||
|
||||
-- Generic app settings (cross-app-integration pattern, see conventions doc) —
|
||||
-- plant has no other app to integrate with yet, just an alert-notification
|
||||
-- recipient, but the table/route/page shape is kept standard so a future
|
||||
-- integration is a one-row addition, not a new pattern.
|
||||
CREATE TABLE IF NOT EXISTS app_settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
`)
|
||||
|
||||
await seedDefaultSettings()
|
||||
}
|
||||
|
||||
async function seedDefaultSettings() {
|
||||
const defaults = {
|
||||
alert_notify_email: '',
|
||||
}
|
||||
for (const [key, value] of Object.entries(defaults)) {
|
||||
await pool.query(
|
||||
`INSERT INTO app_settings (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`,
|
||||
[key, value]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSetting(key) {
|
||||
const { rows } = await pool.query('SELECT value FROM app_settings WHERE key = $1', [key])
|
||||
return rows.length ? rows[0].value : null
|
||||
}
|
||||
|
||||
export async function setSetting(key, value) {
|
||||
await pool.query(
|
||||
`INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`,
|
||||
[key, value]
|
||||
)
|
||||
}
|
||||
55
backend/src/index.js
Normal file
55
backend/src/index.js
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
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 { assetRoutes } from './routes/assets.js'
|
||||
import { statusRoutes } from './routes/status.js'
|
||||
import { alertRoutes } from './routes/alerts.js'
|
||||
import { alertRuleRoutes } from './routes/alert-rules.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(assetRoutes, { uploadsDir: UPLOADS_DIR })
|
||||
await app.register(statusRoutes)
|
||||
await app.register(alertRoutes)
|
||||
await app.register(alertRuleRoutes)
|
||||
await app.register(settingsRoutes)
|
||||
|
||||
try {
|
||||
await initDb()
|
||||
|
||||
// MQTT broker (shared infra, LXC 104) may not exist or be reachable 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}`))
|
||||
|
||||
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
|
||||
}
|
||||
108
backend/src/lib/alert-engine.js
Normal file
108
backend/src/lib/alert-engine.js
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
// Shared alert evaluation for both ingestion paths: lib/mqtt.js calls
|
||||
// checkThresholdRules() inline on every message (lt/gt/eq), and lib/scheduler.js
|
||||
// calls checkStaleRules() on its periodic sweep (stale_minutes only). Both
|
||||
// funnel through the same trigger/auto-resolve helpers so an alert is never
|
||||
// raised or cleared differently depending on which path noticed it.
|
||||
import { pool } from '../db.js'
|
||||
import { notifyPlantAlert } from './mailer.js'
|
||||
|
||||
function breaches(condition, threshold, numericValue) {
|
||||
if (numericValue === null || numericValue === undefined) return false
|
||||
const v = Number(numericValue)
|
||||
if (!Number.isFinite(v)) return false
|
||||
const t = Number(threshold)
|
||||
if (condition === 'lt') return v < t
|
||||
if (condition === 'gt') return v > t
|
||||
if (condition === 'eq') return v === t
|
||||
return false
|
||||
}
|
||||
|
||||
async function findRules(fieldKey, conditions, assetId, assetType) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT * FROM plant_alert_rules
|
||||
WHERE active = TRUE AND field_key = $1 AND condition = ANY($2)
|
||||
AND (asset_id = $3 OR (asset_id IS NULL AND asset_type = $4))`,
|
||||
[fieldKey, conditions, assetId, assetType]
|
||||
)
|
||||
return rows
|
||||
}
|
||||
|
||||
async function triggerAlert(rule, assetId, fieldKey, valueAtTrigger) {
|
||||
const { rows: openRows } = await pool.query(
|
||||
`SELECT id FROM plant_alerts WHERE rule_id = $1 AND asset_id = $2 AND field_key = $3 AND status = 'open'`,
|
||||
[rule.id, assetId, fieldKey]
|
||||
)
|
||||
if (openRows.length) return // already open — don't re-notify on every message/sweep tick
|
||||
|
||||
const { rows: inserted } = await pool.query(
|
||||
`INSERT INTO plant_alerts (rule_id, asset_id, field_key, value_at_trigger)
|
||||
VALUES ($1, $2, $3, $4) RETURNING *`,
|
||||
[rule.id, assetId, fieldKey, String(valueAtTrigger)]
|
||||
)
|
||||
const { rows: assetRows } = await pool.query('SELECT * FROM plant_assets WHERE id = $1', [assetId])
|
||||
if (assetRows.length) {
|
||||
notifyPlantAlert(inserted[0], assetRows[0], rule).catch(err =>
|
||||
console.error('[alert-engine] notify failed:', err.message)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async function autoResolveIfOpen(ruleId, assetId, fieldKey) {
|
||||
await pool.query(
|
||||
`UPDATE plant_alerts SET status = 'resolved', resolved_at = NOW()
|
||||
WHERE rule_id = $1 AND asset_id = $2 AND field_key = $3 AND status = 'open'`,
|
||||
[ruleId, assetId, fieldKey]
|
||||
)
|
||||
}
|
||||
|
||||
// Called by lib/mqtt.js on every message with a parsed numeric value (may be
|
||||
// null for pure-text fields, in which case lt/gt/eq rules simply never match).
|
||||
export async function checkThresholdRules(assetId, fieldKey, numericValue) {
|
||||
const { rows: assetRows } = await pool.query('SELECT asset_type FROM plant_assets WHERE id = $1', [assetId])
|
||||
if (!assetRows.length) return
|
||||
const assetType = assetRows[0].asset_type
|
||||
|
||||
const rules = await findRules(fieldKey, ['lt', 'gt', 'eq'], assetId, assetType)
|
||||
for (const rule of rules) {
|
||||
if (breaches(rule.condition, rule.threshold, numericValue)) {
|
||||
await triggerAlert(rule, assetId, fieldKey, numericValue)
|
||||
} else {
|
||||
await autoResolveIfOpen(rule.id, assetId, fieldKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Called by lib/scheduler.js's periodic sweep — every active stale_minutes
|
||||
// rule, against every asset it applies to (its own asset_id, or every active
|
||||
// asset of its asset_type).
|
||||
export async function checkStaleRules() {
|
||||
const { rows: rules } = await pool.query(
|
||||
`SELECT * FROM plant_alert_rules WHERE active = TRUE AND condition = 'stale_minutes'`
|
||||
)
|
||||
if (!rules.length) return
|
||||
|
||||
for (const rule of rules) {
|
||||
const { rows: assets } = await pool.query(
|
||||
`SELECT id FROM plant_assets
|
||||
WHERE active = TRUE
|
||||
AND ($1::int IS NULL OR id = $1)
|
||||
AND ($2::text IS NULL OR asset_type = $2)`,
|
||||
[rule.asset_id, rule.asset_type]
|
||||
)
|
||||
|
||||
for (const asset of assets) {
|
||||
const { rows: latest } = await pool.query(
|
||||
`SELECT updated_at FROM plant_asset_latest WHERE asset_id = $1 AND field_key = $2`,
|
||||
[asset.id, rule.field_key]
|
||||
)
|
||||
const lastUpdate = latest[0]?.updated_at
|
||||
const ageMinutes = lastUpdate ? (Date.now() - new Date(lastUpdate).getTime()) / 60000 : Infinity
|
||||
|
||||
if (ageMinutes >= Number(rule.threshold)) {
|
||||
await triggerAlert(rule, asset.id, rule.field_key, `stale for ${Math.round(ageMinutes)}m`)
|
||||
} else {
|
||||
await autoResolveIfOpen(rule.id, asset.id, rule.field_key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
77
backend/src/lib/mailer.js
Normal file
77
backend/src/lib/mailer.js
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import nodemailer from 'nodemailer'
|
||||
import { getSetting } from '../db.js'
|
||||
|
||||
const SETTINGS_URL = process.env.SETTINGS_URL || ''
|
||||
const SETTINGS_SECRET = process.env.SETTINGS_SECRET || ''
|
||||
|
||||
let _smtpCache = null // { config, expires_at }
|
||||
let _transporter = null
|
||||
|
||||
async function getSmtpConfig() {
|
||||
if (_smtpCache && Date.now() < _smtpCache.expires_at) return _smtpCache.config
|
||||
const res = await fetch(`${SETTINGS_URL}/settings/api/internal/integration/smtp`, {
|
||||
headers: { Authorization: `Bearer ${SETTINGS_SECRET}` },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
if (!res.ok) throw new Error(`Failed to fetch SMTP config from settings: ${res.status}`)
|
||||
const config = await res.json()
|
||||
if (!config.host) throw new Error('SMTP not configured in settings')
|
||||
_smtpCache = { config, expires_at: Date.now() + 5 * 60_000 }
|
||||
_transporter = null
|
||||
return config
|
||||
}
|
||||
|
||||
async function getTransporter() {
|
||||
if (_transporter) return _transporter
|
||||
const config = await getSmtpConfig()
|
||||
const port = parseInt(config.port || '587')
|
||||
_transporter = nodemailer.createTransport({
|
||||
host: config.host,
|
||||
port,
|
||||
secure: port === 465,
|
||||
auth: config.user ? { user: config.user, pass: config.pass } : undefined,
|
||||
})
|
||||
return _transporter
|
||||
}
|
||||
|
||||
const HOTEL_NAME = process.env.VITE_HOTEL_NAME || 'Hotel'
|
||||
|
||||
// Fire-and-forget: email failure must never block telemetry ingestion or the alert write.
|
||||
async function send(to, subject, text) {
|
||||
if (!to) return
|
||||
try {
|
||||
const config = await getSmtpConfig()
|
||||
const transport = await getTransporter()
|
||||
await transport.sendMail({
|
||||
from: config.from || `"${HOTEL_NAME} Plant Room" <noreply@localhost>`,
|
||||
to,
|
||||
subject,
|
||||
text,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`Plant mail to ${to} failed: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const CONDITION_LABEL = { lt: 'below', gt: 'above', eq: 'equal to', stale_minutes: 'stale beyond (minutes)' }
|
||||
|
||||
export async function notifyPlantAlert(alert, asset, rule) {
|
||||
const to = await getSetting('alert_notify_email')
|
||||
if (!to) return
|
||||
|
||||
const lines = [
|
||||
`Asset: ${asset.name} (${asset.asset_type})`,
|
||||
`Location: ${asset.location || 'n/a'}`,
|
||||
`Field: ${rule.field_key}`,
|
||||
`Condition: ${rule.field_key} ${CONDITION_LABEL[rule.condition] || rule.condition} ${rule.threshold}`,
|
||||
`Value: ${alert.value_at_trigger}`,
|
||||
`Severity: ${rule.severity}`,
|
||||
`Triggered: ${new Date(alert.triggered_at).toLocaleString('en-GB')}`,
|
||||
]
|
||||
|
||||
return send(
|
||||
to,
|
||||
`[Plant] ${rule.severity.toUpperCase()}: ${asset.name} — ${rule.field_key}`,
|
||||
lines.join('\n')
|
||||
)
|
||||
}
|
||||
157
backend/src/lib/mqtt.js
Normal file
157
backend/src/lib/mqtt.js
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
// MQTT client for plant-room asset telemetry. Connection/backoff skeleton
|
||||
// follows utilities/backend/src/lib/mqtt.js's shape (own reconnect/backoff,
|
||||
// credentials fetched at runtime from settings). Unlike utilities' single
|
||||
// exact-topic -> meter_id map, this subscribes to a whole prefix per asset
|
||||
// (`<mqtt_topic_prefix>/#`) since one plant asset publishes many fields under
|
||||
// its own topic tree (e.g. the water softener's salt_level_pct,
|
||||
// tank_a_capacity_remaining, regeneration_active, ...). The topic segment(s)
|
||||
// after the prefix become the field_key — generic for any asset type, never
|
||||
// hardcoded per device.
|
||||
import mqtt from 'mqtt'
|
||||
import { pool } from '../db.js'
|
||||
import { checkThresholdRules } from './alert-engine.js'
|
||||
|
||||
const CLIENT_NAME = 'plant-backend'
|
||||
const BROKER_RECONNECT_BACKOFF_MS = [30, 60, 120, 300, 600, 1800].map(s => s * 1000) // 30s -> 30min
|
||||
|
||||
let client = null
|
||||
let connecting = false
|
||||
let reconnectAttempt = 0
|
||||
let prefixMap = [] // [{ prefix, assetId }], longest prefix first so overlapping prefixes resolve to the most specific asset
|
||||
let subscribedTopics = new Set()
|
||||
|
||||
async function getCredentials() {
|
||||
const url = `${process.env.SETTINGS_URL}/settings/api/internal/integration/mqtt`
|
||||
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 }
|
||||
}
|
||||
|
||||
export async function refreshAssetMap() {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, mqtt_topic_prefix FROM plant_assets WHERE mqtt_topic_prefix IS NOT NULL AND active = TRUE`
|
||||
)
|
||||
prefixMap = rows
|
||||
.map(r => ({ prefix: r.mqtt_topic_prefix.replace(/\/+$/, ''), assetId: r.id }))
|
||||
.sort((a, b) => b.prefix.length - a.prefix.length)
|
||||
if (client?.connected) subscribeToKnownTopics()
|
||||
}
|
||||
|
||||
function subscribeToKnownTopics() {
|
||||
const nextTopics = new Set(prefixMap.map(p => `${p.prefix}/#`))
|
||||
const stale = [...subscribedTopics].filter(t => !nextTopics.has(t))
|
||||
const fresh = [...nextTopics].filter(t => !subscribedTopics.has(t))
|
||||
if (stale.length) client.unsubscribe(stale)
|
||||
if (fresh.length) client.subscribe(fresh)
|
||||
subscribedTopics = nextTopics
|
||||
}
|
||||
|
||||
function resolveAsset(topic) {
|
||||
for (const p of prefixMap) {
|
||||
if (topic === p.prefix || topic.startsWith(p.prefix + '/')) return p
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Booleans (e.g. regeneration_active: "true"/"false") get both a text value
|
||||
// and a 0/1 numeric value so they can still be charted or used in lt/gt rules;
|
||||
// enums (e.g. salt_level_status: "ok"/"low") only ever populate value_text.
|
||||
function parseValue(raw) {
|
||||
const text = raw.trim()
|
||||
const lower = text.toLowerCase()
|
||||
if (lower === 'true' || lower === 'false') return { numeric: lower === 'true' ? 1 : 0, text }
|
||||
const num = Number(text)
|
||||
return { numeric: Number.isFinite(num) && text !== '' ? num : null, text }
|
||||
}
|
||||
|
||||
async function handleMessage(topic, message) {
|
||||
const match = resolveAsset(topic)
|
||||
if (!match) return
|
||||
|
||||
const remainder = topic.slice(match.prefix.length).replace(/^\/+/, '')
|
||||
const fieldKey = (remainder ? remainder.replace(/\//g, '_') : topic)
|
||||
const { numeric, text } = parseValue(message.toString())
|
||||
|
||||
try {
|
||||
await pool.query(
|
||||
`INSERT INTO plant_telemetry_raw (asset_id, field_key, value_numeric, value_text) VALUES ($1, $2, $3, $4)`,
|
||||
[match.assetId, fieldKey, numeric, text]
|
||||
)
|
||||
await pool.query(
|
||||
`INSERT INTO plant_asset_latest (asset_id, field_key, value_numeric, value_text, updated_at)
|
||||
VALUES ($1, $2, $3, $4, NOW())
|
||||
ON CONFLICT (asset_id, field_key) DO UPDATE
|
||||
SET value_numeric = EXCLUDED.value_numeric, value_text = EXCLUDED.value_text, updated_at = NOW()`,
|
||||
[match.assetId, fieldKey, numeric, text]
|
||||
)
|
||||
await checkThresholdRules(match.assetId, fieldKey, numeric)
|
||||
} catch (err) {
|
||||
console.error('[mqtt] telemetry insert/alert-check failed:', err.message)
|
||||
}
|
||||
}
|
||||
|
||||
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 refreshAssetMap()
|
||||
|
||||
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')
|
||||
subscribedTopics = new Set()
|
||||
subscribeToKnownTopics()
|
||||
resolve()
|
||||
})
|
||||
|
||||
c.on('message', handleMessage)
|
||||
|
||||
c.on('error', (err) => {
|
||||
console.error('[mqtt] connection error:', err.message)
|
||||
})
|
||||
|
||||
c.on('close', () => {
|
||||
if (client === c) client = null
|
||||
connecting = false
|
||||
scheduleReconnect()
|
||||
})
|
||||
|
||||
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
|
||||
}
|
||||
26
backend/src/lib/scheduler.js
Normal file
26
backend/src/lib/scheduler.js
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Periodic sweep for 'stale_minutes' alert rules only — breach-on-message
|
||||
// (lt/gt/eq) is handled inline as telemetry arrives, in lib/mqtt.js. This
|
||||
// stack has no cron library anywhere (see utilities/backend/src/lib/scheduler.js);
|
||||
// a 1-minute setInterval wall-clock poll is plenty granular for a rule whose
|
||||
// own threshold is expressed in minutes.
|
||||
import { checkStaleRules } from './alert-engine.js'
|
||||
|
||||
const SWEEP_MS = 60 * 1000
|
||||
|
||||
let running = false
|
||||
|
||||
export function startScheduler() {
|
||||
const tick = async () => {
|
||||
if (running) return
|
||||
running = true
|
||||
try {
|
||||
await checkStaleRules()
|
||||
} catch (err) {
|
||||
console.error('[scheduler] stale-rule sweep failed:', err.message)
|
||||
} finally {
|
||||
running = false
|
||||
}
|
||||
}
|
||||
setTimeout(tick, 10_000)
|
||||
setInterval(tick, SWEEP_MS)
|
||||
}
|
||||
93
backend/src/routes/alert-rules.js
Normal file
93
backend/src/routes/alert-rules.js
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
|
||||
const CONDITIONS = ['lt', 'gt', 'eq', 'stale_minutes']
|
||||
const SEVERITIES = ['warning', 'critical']
|
||||
const ASSET_TYPES = ['boiler', 'water_softener', 'calorifier', 'pump']
|
||||
|
||||
export async function alertRuleRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
// All of alert-rules CRUD (including read) is gated on manage_assets — this
|
||||
// is an admin/maintenance-lead configuration surface, not something every
|
||||
// 'view' user needs to see; open alerts themselves are visible via /api/alerts.
|
||||
app.addHook('preHandler', requireCap('manage_assets'))
|
||||
|
||||
app.get('/api/alert-rules', async () => {
|
||||
const { rows } = await pool.query(`
|
||||
SELECT r.*, a.name AS asset_name
|
||||
FROM plant_alert_rules r
|
||||
LEFT JOIN plant_assets a ON a.id = r.asset_id
|
||||
ORDER BY r.created_at DESC
|
||||
`)
|
||||
return rows
|
||||
})
|
||||
|
||||
app.post('/api/alert-rules', async (req, reply) => {
|
||||
const b = req.body || {}
|
||||
if (!b.field_key || !String(b.field_key).trim()) return reply.status(400).send({ error: 'field_key is required' })
|
||||
if (!CONDITIONS.includes(b.condition)) return reply.status(400).send({ error: `condition must be one of: ${CONDITIONS.join(', ')}` })
|
||||
if (b.threshold === undefined || b.threshold === null || isNaN(Number(b.threshold))) {
|
||||
return reply.status(400).send({ error: 'threshold must be a number' })
|
||||
}
|
||||
if (b.severity && !SEVERITIES.includes(b.severity)) return reply.status(400).send({ error: `severity must be one of: ${SEVERITIES.join(', ')}` })
|
||||
if (!b.asset_id && !b.asset_type) return reply.status(400).send({ error: 'Either asset_id or asset_type must be set' })
|
||||
if (b.asset_type && !ASSET_TYPES.includes(b.asset_type)) return reply.status(400).send({ error: `asset_type must be one of: ${ASSET_TYPES.join(', ')}` })
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO plant_alert_rules (asset_id, asset_type, field_key, condition, threshold, severity, active)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7)
|
||||
RETURNING *`,
|
||||
[
|
||||
b.asset_id || null, b.asset_id ? null : b.asset_type, b.field_key.trim(), b.condition,
|
||||
Number(b.threshold), b.severity || 'warning', b.active !== undefined ? b.active : true,
|
||||
]
|
||||
)
|
||||
return reply.status(201).send(rows[0])
|
||||
})
|
||||
|
||||
app.patch('/api/alert-rules/:id', async (req, reply) => {
|
||||
const { rows: existing } = await pool.query('SELECT * FROM plant_alert_rules WHERE id = $1', [req.params.id])
|
||||
if (!existing.length) return reply.status(404).send({ error: 'Rule not found' })
|
||||
const cur = existing[0]
|
||||
const b = req.body || {}
|
||||
|
||||
if (b.condition !== undefined && !CONDITIONS.includes(b.condition)) {
|
||||
return reply.status(400).send({ error: `condition must be one of: ${CONDITIONS.join(', ')}` })
|
||||
}
|
||||
if (b.severity !== undefined && !SEVERITIES.includes(b.severity)) {
|
||||
return reply.status(400).send({ error: `severity must be one of: ${SEVERITIES.join(', ')}` })
|
||||
}
|
||||
if (b.asset_type !== undefined && b.asset_type !== null && !ASSET_TYPES.includes(b.asset_type)) {
|
||||
return reply.status(400).send({ error: `asset_type must be one of: ${ASSET_TYPES.join(', ')}` })
|
||||
}
|
||||
|
||||
const next = {
|
||||
asset_id: b.asset_id !== undefined ? b.asset_id : cur.asset_id,
|
||||
asset_type: b.asset_type !== undefined ? b.asset_type : cur.asset_type,
|
||||
field_key: b.field_key !== undefined ? b.field_key : cur.field_key,
|
||||
condition: b.condition !== undefined ? b.condition : cur.condition,
|
||||
threshold: b.threshold !== undefined ? Number(b.threshold) : cur.threshold,
|
||||
severity: b.severity !== undefined ? b.severity : cur.severity,
|
||||
active: b.active !== undefined ? b.active : cur.active,
|
||||
}
|
||||
if (next.asset_id) next.asset_type = null
|
||||
if (!next.asset_id && !next.asset_type) {
|
||||
return reply.status(400).send({ error: 'Either asset_id or asset_type must be set' })
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE plant_alert_rules SET
|
||||
asset_id = $1, asset_type = $2, field_key = $3, condition = $4, threshold = $5, severity = $6, active = $7
|
||||
WHERE id = $8
|
||||
RETURNING *`,
|
||||
[next.asset_id, next.asset_type, next.field_key, next.condition, next.threshold, next.severity, next.active, req.params.id]
|
||||
)
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
app.delete('/api/alert-rules/:id', async (req, reply) => {
|
||||
const { rows } = await pool.query('DELETE FROM plant_alert_rules WHERE id = $1 RETURNING id', [req.params.id])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Rule not found' })
|
||||
return { ok: true }
|
||||
})
|
||||
}
|
||||
64
backend/src/routes/alerts.js
Normal file
64
backend/src/routes/alerts.js
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
|
||||
const STATUSES = ['open', 'acknowledged', 'resolved']
|
||||
const SEVERITIES = ['warning', 'critical']
|
||||
|
||||
export async function alertRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/alerts?status=open&severity=critical — joined with asset + rule detail
|
||||
app.get('/api/alerts', { preHandler: requireCap('view') }, async (req) => {
|
||||
const { status, severity } = req.query || {}
|
||||
const conditions = []
|
||||
const params = []
|
||||
|
||||
if (status && STATUSES.includes(status)) {
|
||||
params.push(status)
|
||||
conditions.push(`al.status = $${params.length}`)
|
||||
}
|
||||
if (severity && SEVERITIES.includes(severity)) {
|
||||
params.push(severity)
|
||||
conditions.push(`r.severity = $${params.length}`)
|
||||
}
|
||||
const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT al.*, a.name AS asset_name, a.asset_type, r.condition, r.threshold, r.severity
|
||||
FROM plant_alerts al
|
||||
JOIN plant_assets a ON a.id = al.asset_id
|
||||
JOIN plant_alert_rules r ON r.id = al.rule_id
|
||||
${where}
|
||||
ORDER BY al.triggered_at DESC
|
||||
LIMIT 500`,
|
||||
params
|
||||
)
|
||||
return rows
|
||||
})
|
||||
|
||||
// PATCH /api/alerts/:id — { action: 'acknowledge' | 'resolve' }
|
||||
app.patch('/api/alerts/:id', { preHandler: requireCap('acknowledge_alerts') }, async (req, reply) => {
|
||||
const { rows: existing } = await pool.query('SELECT * FROM plant_alerts WHERE id = $1', [req.params.id])
|
||||
if (!existing.length) return reply.status(404).send({ error: 'Alert not found' })
|
||||
|
||||
const { action } = req.body || {}
|
||||
if (!['acknowledge', 'resolve'].includes(action)) {
|
||||
return reply.status(400).send({ error: "action must be 'acknowledge' or 'resolve'" })
|
||||
}
|
||||
|
||||
let rows
|
||||
if (action === 'acknowledge') {
|
||||
;({ rows } = await pool.query(
|
||||
`UPDATE plant_alerts SET status = 'acknowledged', acknowledged_at = NOW(), acknowledged_by = $1
|
||||
WHERE id = $2 RETURNING *`,
|
||||
[req.user.email, req.params.id]
|
||||
))
|
||||
} else {
|
||||
;({ rows } = await pool.query(
|
||||
`UPDATE plant_alerts SET status = 'resolved', resolved_at = NOW() WHERE id = $1 RETURNING *`,
|
||||
[req.params.id]
|
||||
))
|
||||
}
|
||||
return rows[0]
|
||||
})
|
||||
}
|
||||
152
backend/src/routes/assets.js
Normal file
152
backend/src/routes/assets.js
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
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 } from '../db.js'
|
||||
import { refreshAssetMap } from '../lib/mqtt.js'
|
||||
|
||||
const ALLOWED_IMAGES = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
|
||||
const PHOTO_TYPES = ['asset', 'serial_plate']
|
||||
const ASSET_TYPES = ['boiler', 'water_softener', 'calorifier', 'pump']
|
||||
|
||||
const WRITABLE_FIELDS = [
|
||||
'name', 'asset_type', 'location', 'make_model', 'serial_no',
|
||||
'install_date', 'notes', 'active', 'mqtt_topic_prefix',
|
||||
]
|
||||
|
||||
export async function assetRoutes(app, opts) {
|
||||
const UPLOADS_DIR = opts.uploadsDir
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/assets — every asset, with photo count
|
||||
app.get('/api/assets', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows } = await pool.query(`
|
||||
SELECT a.*, (SELECT COUNT(*)::int FROM asset_photos p WHERE p.asset_id = a.id) AS photo_count
|
||||
FROM plant_assets a
|
||||
ORDER BY a.asset_type, a.name
|
||||
`)
|
||||
return rows
|
||||
})
|
||||
|
||||
app.get('/api/assets/:id', { preHandler: requireCap('view') }, async (req, reply) => {
|
||||
const { rows } = await pool.query('SELECT * FROM plant_assets WHERE id = $1', [req.params.id])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Asset not found' })
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
// POST /api/assets — create
|
||||
app.post('/api/assets', { preHandler: requireCap('manage_assets') }, async (req, reply) => {
|
||||
const b = req.body || {}
|
||||
if (!b.name || !String(b.name).trim()) return reply.status(400).send({ error: 'name is required' })
|
||||
if (!ASSET_TYPES.includes(b.asset_type)) {
|
||||
return reply.status(400).send({ error: `asset_type must be one of: ${ASSET_TYPES.join(', ')}` })
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO plant_assets
|
||||
(name, asset_type, location, make_model, serial_no, install_date, notes, active, mqtt_topic_prefix)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
|
||||
RETURNING *`,
|
||||
[
|
||||
b.name.trim(), b.asset_type, b.location || null, b.make_model || null, b.serial_no || null,
|
||||
b.install_date || null, b.notes || null, b.active !== undefined ? b.active : true,
|
||||
b.mqtt_topic_prefix || null,
|
||||
]
|
||||
)
|
||||
await refreshAssetMap().catch(err => app.log.warn(`mqtt asset map refresh failed: ${err.message}`))
|
||||
return reply.status(201).send(rows[0])
|
||||
})
|
||||
|
||||
// PATCH /api/assets/:id — partial update
|
||||
app.patch('/api/assets/:id', { preHandler: requireCap('manage_assets') }, async (req, reply) => {
|
||||
const { rows: existing } = await pool.query('SELECT * FROM plant_assets WHERE id = $1', [req.params.id])
|
||||
if (!existing.length) return reply.status(404).send({ error: 'Asset not found' })
|
||||
const current = existing[0]
|
||||
const b = req.body || {}
|
||||
|
||||
if (b.asset_type !== undefined && !ASSET_TYPES.includes(b.asset_type)) {
|
||||
return reply.status(400).send({ error: `asset_type must be one of: ${ASSET_TYPES.join(', ')}` })
|
||||
}
|
||||
|
||||
const next = { ...current }
|
||||
for (const field of WRITABLE_FIELDS) {
|
||||
if (b[field] !== undefined) next[field] = b[field]
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE plant_assets SET
|
||||
name = $1, asset_type = $2, location = $3, make_model = $4, serial_no = $5,
|
||||
install_date = $6, notes = $7, active = $8, mqtt_topic_prefix = $9
|
||||
WHERE id = $10
|
||||
RETURNING *`,
|
||||
[
|
||||
next.name, next.asset_type, next.location, next.make_model, next.serial_no,
|
||||
next.install_date, next.notes, next.active, next.mqtt_topic_prefix, req.params.id,
|
||||
]
|
||||
)
|
||||
await refreshAssetMap().catch(err => app.log.warn(`mqtt asset map refresh failed: ${err.message}`))
|
||||
return rows[0]
|
||||
})
|
||||
|
||||
// POST /api/assets/:id/photos — multipart: file + photo_type (asset | serial_plate)
|
||||
app.post('/api/assets/:id/photos', { preHandler: requireCap('manage_assets') }, async (req, reply) => {
|
||||
const assetId = parseInt(req.params.id)
|
||||
const { rows } = await pool.query('SELECT id FROM plant_assets WHERE id = $1', [assetId])
|
||||
if (!rows.length) return reply.status(404).send({ error: 'Asset not found' })
|
||||
|
||||
let fileData = null, photoType = 'asset'
|
||||
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
|
||||
// pattern as hvac's device_photos / 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, 'assets', String(assetId))
|
||||
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 = `/assets/${assetId}/${fileData.savedAs}`
|
||||
const { rows: ins } = await pool.query(
|
||||
`INSERT INTO asset_photos (asset_id, file_name, file_path, mime_type, file_size, photo_type, uploaded_by)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
|
||||
[assetId, fileData.originalName, filePath, 'image/jpeg', fileData.size, photoType, req.user.email]
|
||||
)
|
||||
return ins[0]
|
||||
})
|
||||
|
||||
app.get('/api/assets/:id/photos', { preHandler: requireCap('view') }, async (req) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT * FROM asset_photos WHERE asset_id = $1 ORDER BY uploaded_at DESC',
|
||||
[req.params.id]
|
||||
)
|
||||
return rows
|
||||
})
|
||||
|
||||
app.delete('/api/photos/:id', { preHandler: requireCap('manage_assets') }, async (req, reply) => {
|
||||
const { rows } = await pool.query('SELECT * FROM asset_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 asset_photos WHERE id = $1', [req.params.id])
|
||||
return { ok: true }
|
||||
})
|
||||
}
|
||||
42
backend/src/routes/settings.js
Normal file
42
backend/src/routes/settings.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
import { isConnected as mqttConnected } from '../lib/mqtt.js'
|
||||
|
||||
// Standard app_settings pattern (see conventions doc's "Cross-app integration
|
||||
// credentials" section) — plant only has one setting today (who gets alert
|
||||
// emails), but the shape is kept generic so a future integration is a one-row
|
||||
// addition to ALLOWED_KEYS + the seed default in db.js, not a new pattern.
|
||||
const ALLOWED_KEYS = new Set(['alert_notify_email'])
|
||||
|
||||
export async function settingsRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
app.get('/api/settings', { preHandler: requireCap('settings') }, async () => {
|
||||
const { rows } = await pool.query('SELECT key, value, updated_at FROM app_settings ORDER BY key')
|
||||
return { settings: rows }
|
||||
})
|
||||
|
||||
app.put('/api/settings', { preHandler: requireCap('settings') }, async (req, reply) => {
|
||||
const { settings } = req.body || {}
|
||||
if (!Array.isArray(settings)) return reply.status(400).send({ error: 'settings must be an array' })
|
||||
|
||||
for (const { key, value } of settings) {
|
||||
if (!ALLOWED_KEYS.has(key)) continue
|
||||
await pool.query(
|
||||
`INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2, NOW())
|
||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`,
|
||||
[key, value ?? '']
|
||||
)
|
||||
}
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
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 be unreachable, or plant-backend has no credentials in settings.',
|
||||
}
|
||||
})
|
||||
}
|
||||
54
backend/src/routes/status.js
Normal file
54
backend/src/routes/status.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import { requireAuth, requireCap } from '../auth.js'
|
||||
import { pool } from '../db.js'
|
||||
import { isConnected as mqttConnected } from '../lib/mqtt.js'
|
||||
|
||||
const SEVERITY_RANK = { critical: 2, warning: 1 }
|
||||
|
||||
export async function statusRoutes(app) {
|
||||
app.addHook('preHandler', requireAuth)
|
||||
|
||||
// GET /api/status — every active asset, its latest telemetry fields, and a
|
||||
// worst-open-alert severity for the Dashboard's per-card colour + top banner.
|
||||
app.get('/api/status', { preHandler: requireCap('view') }, async () => {
|
||||
const { rows: assets } = await pool.query(`
|
||||
SELECT * FROM plant_assets WHERE active = TRUE ORDER BY asset_type, name
|
||||
`)
|
||||
|
||||
const { rows: latest } = await pool.query(`
|
||||
SELECT asset_id, field_key, value_numeric, value_text, updated_at
|
||||
FROM plant_asset_latest
|
||||
`)
|
||||
const latestByAsset = new Map()
|
||||
for (const l of latest) {
|
||||
if (!latestByAsset.has(l.asset_id)) latestByAsset.set(l.asset_id, [])
|
||||
latestByAsset.get(l.asset_id).push(l)
|
||||
}
|
||||
|
||||
const { rows: openAlerts } = await pool.query(`
|
||||
SELECT al.asset_id, r.severity
|
||||
FROM plant_alerts al
|
||||
JOIN plant_alert_rules r ON r.id = al.rule_id
|
||||
WHERE al.status = 'open'
|
||||
`)
|
||||
const alertSummaryByAsset = new Map()
|
||||
for (const a of openAlerts) {
|
||||
const cur = alertSummaryByAsset.get(a.asset_id) || { count: 0, max_severity: null }
|
||||
cur.count++
|
||||
if (!cur.max_severity || SEVERITY_RANK[a.severity] > SEVERITY_RANK[cur.max_severity]) {
|
||||
cur.max_severity = a.severity
|
||||
}
|
||||
alertSummaryByAsset.set(a.asset_id, cur)
|
||||
}
|
||||
|
||||
return {
|
||||
open_alerts: openAlerts.length,
|
||||
assets: assets.map(a => ({
|
||||
...a,
|
||||
latest: latestByAsset.get(a.id) || [],
|
||||
open_alert_count: alertSummaryByAsset.get(a.id)?.count || 0,
|
||||
max_severity: alertSummaryByAsset.get(a.id)?.max_severity || null,
|
||||
})),
|
||||
mqtt_connected: mqttConnected(),
|
||||
}
|
||||
})
|
||||
}
|
||||
41
docker-compose.yml
Normal file
41
docker-compose.yml
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
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=plant
|
||||
- OFFICE_IP_CHECK=${OFFICE_IP_CHECK:-disabled}
|
||||
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/plant
|
||||
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="#0e7490" />
|
||||
<title>Plant Room</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
40
frontend/nginx.conf
Normal file
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 /plant/api/auth/ {
|
||||
proxy_pass http://10.10.10.101:3001/api/auth/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
|
||||
location /plant/api/ {
|
||||
proxy_pass http://backend:3001/api/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
add_header Cache-Control "no-store";
|
||||
}
|
||||
|
||||
location /plant/health {
|
||||
proxy_pass http://backend:3001/health;
|
||||
}
|
||||
|
||||
location ~* /plant/.*\.(js|css|png|ico|svg|woff2?)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location /plant/ {
|
||||
add_header Cache-Control "no-cache" always;
|
||||
try_files $uri /plant/index.html;
|
||||
}
|
||||
|
||||
location = / {
|
||||
return 301 /plant/;
|
||||
}
|
||||
}
|
||||
1901
frontend/package-lock.json
generated
Normal file
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-plant-frontend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"lucide-react": "^0.468.0",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^6.28.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"typescript": "^5.7.2",
|
||||
"vite": "^6.0.5"
|
||||
}
|
||||
}
|
||||
35
frontend/src/App.tsx
Normal file
35
frontend/src/App.tsx
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
|
||||
import AuthGate, { useAuth } from './components/AuthGate'
|
||||
import Layout from './components/Layout'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import Assets from './pages/Assets'
|
||||
import Alerts from './pages/Alerts'
|
||||
import Settings from './pages/Settings'
|
||||
import { can } from './types'
|
||||
|
||||
function Home() {
|
||||
const { user } = useAuth()
|
||||
if (can(user, 'view')) return <Navigate to="/dashboard" replace />
|
||||
if (can(user, 'manage_assets')) return <Navigate to="/assets" replace />
|
||||
if (can(user, 'settings')) return <Navigate to="/settings" replace />
|
||||
return <div className="page"><p className="muted">You don't have access to any Plant Room pages yet.</p></div>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter basename="/plant">
|
||||
<AuthGate>
|
||||
<Layout>
|
||||
<Routes>
|
||||
<Route path="/" element={<Home />} />
|
||||
<Route path="/dashboard" element={<Dashboard />} />
|
||||
<Route path="/assets" element={<Assets />} />
|
||||
<Route path="/alerts" element={<Alerts />} />
|
||||
<Route path="/settings" element={<Settings />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Layout>
|
||||
</AuthGate>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
112
frontend/src/api.ts
Normal file
112
frontend/src/api.ts
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
import type {
|
||||
PlantAsset, AssetStatus, AssetPhoto, AlertRule, PlantAlert, AppSetting, PhotoType,
|
||||
} from './types'
|
||||
|
||||
const BASE = '/plant/api'
|
||||
|
||||
async function request<T>(path: string, opts: RequestInit = {}): Promise<T> {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json', ...opts.headers },
|
||||
...opts,
|
||||
})
|
||||
if (res.status === 401) {
|
||||
;(window.top ?? window).location.href = '/login'
|
||||
throw new Error('Unauthenticated')
|
||||
}
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: res.statusText }))
|
||||
throw new Error(err.error || `Request failed: ${res.status}`)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// Assets
|
||||
export function fetchAssets(): Promise<PlantAsset[]> {
|
||||
return request('/assets')
|
||||
}
|
||||
export function createAsset(body: Partial<PlantAsset>): Promise<PlantAsset> {
|
||||
return request('/assets', { method: 'POST', body: JSON.stringify(body) })
|
||||
}
|
||||
export function updateAsset(id: number, body: Partial<PlantAsset>): Promise<PlantAsset> {
|
||||
return request(`/assets/${id}`, { method: 'PATCH', body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
// Asset photos — multipart, so no JSON content-type header
|
||||
export async function uploadAssetPhoto(assetId: number, file: File, photoType: PhotoType): Promise<AssetPhoto> {
|
||||
const form = new FormData()
|
||||
form.append('photo_type', photoType)
|
||||
form.append('file', file)
|
||||
const res = await fetch(`${BASE}/assets/${assetId}/photos`, { method: 'POST', credentials: 'include', body: form })
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: res.statusText }))
|
||||
throw new Error(err.error || `Upload failed: ${res.status}`)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
export function fetchAssetPhotos(assetId: number): Promise<AssetPhoto[]> {
|
||||
return request(`/assets/${assetId}/photos`)
|
||||
}
|
||||
export function deleteAssetPhoto(id: number): Promise<{ ok: boolean }> {
|
||||
return request(`/photos/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
export function photoUrl(filePath: string): string {
|
||||
return `${BASE}/uploads${filePath}`
|
||||
}
|
||||
|
||||
// Status (dashboard)
|
||||
export function fetchStatus(): Promise<{ open_alerts: number; mqtt_connected: boolean; assets: AssetStatus[] }> {
|
||||
return request('/status')
|
||||
}
|
||||
|
||||
// Alerts
|
||||
export function fetchAlerts(filters: { status?: string; severity?: string } = {}): Promise<PlantAlert[]> {
|
||||
const params = new URLSearchParams()
|
||||
if (filters.status) params.set('status', filters.status)
|
||||
if (filters.severity) params.set('severity', filters.severity)
|
||||
const qs = params.toString()
|
||||
return request(`/alerts${qs ? `?${qs}` : ''}`)
|
||||
}
|
||||
export function acknowledgeAlert(id: number): Promise<PlantAlert> {
|
||||
return request(`/alerts/${id}`, { method: 'PATCH', body: JSON.stringify({ action: 'acknowledge' }) })
|
||||
}
|
||||
export function resolveAlert(id: number): Promise<PlantAlert> {
|
||||
return request(`/alerts/${id}`, { method: 'PATCH', body: JSON.stringify({ action: 'resolve' }) })
|
||||
}
|
||||
|
||||
// Alert rules — threshold/asset_id/asset_type are write-side numbers/nulls,
|
||||
// distinct enough from AlertRule's read-side (string threshold) shape that a
|
||||
// plain object type is simpler than fighting Partial<AlertRule> here.
|
||||
export interface AlertRuleInput {
|
||||
asset_id?: number | null
|
||||
asset_type?: AlertRule['asset_type']
|
||||
field_key?: string
|
||||
condition?: AlertRule['condition']
|
||||
threshold?: number
|
||||
severity?: AlertRule['severity']
|
||||
active?: boolean
|
||||
}
|
||||
|
||||
export function fetchAlertRules(): Promise<AlertRule[]> {
|
||||
return request('/alert-rules')
|
||||
}
|
||||
export function createAlertRule(body: AlertRuleInput): Promise<AlertRule> {
|
||||
return request('/alert-rules', { method: 'POST', body: JSON.stringify(body) })
|
||||
}
|
||||
export function updateAlertRule(id: number, body: AlertRuleInput): Promise<AlertRule> {
|
||||
return request(`/alert-rules/${id}`, { method: 'PATCH', body: JSON.stringify(body) })
|
||||
}
|
||||
export function deleteAlertRule(id: number): Promise<{ ok: boolean }> {
|
||||
return request(`/alert-rules/${id}`, { method: 'DELETE' })
|
||||
}
|
||||
|
||||
// Settings
|
||||
export function getSettings(): Promise<{ settings: AppSetting[] }> {
|
||||
return request('/settings')
|
||||
}
|
||||
export function saveSettings(settings: { key: string; value: string }[]): Promise<{ ok: boolean }> {
|
||||
return request('/settings', { method: 'PUT', body: JSON.stringify({ settings }) })
|
||||
}
|
||||
export function fetchMqttStatus(): Promise<{ connected: boolean; note: string }> {
|
||||
return request('/settings/mqtt-status')
|
||||
}
|
||||
93
frontend/src/components/AssetPhotoUpload.tsx
Normal file
93
frontend/src/components/AssetPhotoUpload.tsx
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import { useRef, useState } from 'react'
|
||||
import { Camera, Image as ImageIcon, Loader2, X } from 'lucide-react'
|
||||
import type { AssetPhoto, PhotoType } from '../types'
|
||||
import { uploadAssetPhoto, deleteAssetPhoto, photoUrl } from '../api'
|
||||
|
||||
// Camera/library capture split: one input with capture="environment" (opens the
|
||||
// device camera directly on mobile), one plain file input (opens the photo
|
||||
// library/file picker) — same split as hvac's DevicePhotoUpload.
|
||||
export default function AssetPhotoUpload({ assetId, photoType, photos, onChanged, canDelete }: {
|
||||
assetId: number
|
||||
photoType: PhotoType
|
||||
photos: AssetPhoto[]
|
||||
onChanged: () => void
|
||||
canDelete: boolean
|
||||
}) {
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [lightbox, setLightbox] = useState<string | null>(null)
|
||||
const cameraInput = useRef<HTMLInputElement>(null)
|
||||
const libraryInput = useRef<HTMLInputElement>(null)
|
||||
|
||||
const slotPhotos = photos.filter(p => p.photo_type === photoType)
|
||||
|
||||
async function handleFile(file: File | undefined) {
|
||||
if (!file) return
|
||||
setUploading(true); setError('')
|
||||
try {
|
||||
await uploadAssetPhoto(assetId, file, photoType)
|
||||
onChanged()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Upload failed')
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(id: number) {
|
||||
await deleteAssetPhoto(id).catch(() => {})
|
||||
onChanged()
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{ marginBottom: 10 }}>
|
||||
<div className="photo-grid">
|
||||
{slotPhotos.map(p => (
|
||||
<div key={p.id} className="photo-thumb-wrap">
|
||||
<img className="photo-thumb" src={photoUrl(p.file_path)} onClick={() => setLightbox(photoUrl(p.file_path))} />
|
||||
{canDelete && (
|
||||
<button className="photo-del" onClick={() => remove(p.id)} title="Delete photo">
|
||||
<X size={12} strokeWidth={2} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{uploading && (
|
||||
<div className="photo-thumb-wrap">
|
||||
<div className="photo-thumb photo-thumb-uploading">
|
||||
<Loader2 size={20} strokeWidth={1.75} className="spin" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <div className="error-banner">{error}</div>}
|
||||
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<button type="button" className="btn btn-sm" onClick={() => cameraInput.current?.click()}>
|
||||
<Camera size={14} strokeWidth={1.75} /> Take photo
|
||||
</button>
|
||||
<input
|
||||
ref={cameraInput}
|
||||
type="file" accept="image/*" capture="environment" style={{ display: 'none' }}
|
||||
onChange={e => { handleFile(e.target.files?.[0]); e.target.value = '' }}
|
||||
/>
|
||||
<button type="button" className="btn btn-sm" onClick={() => libraryInput.current?.click()}>
|
||||
<ImageIcon size={14} strokeWidth={1.75} /> Choose from library
|
||||
</button>
|
||||
<input
|
||||
ref={libraryInput}
|
||||
type="file" accept="image/*" style={{ display: 'none' }}
|
||||
onChange={e => { handleFile(e.target.files?.[0]); e.target.value = '' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{lightbox && (
|
||||
<div className="lightbox-overlay" onClick={() => setLightbox(null)}>
|
||||
<img className="lightbox-img" src={lightbox} />
|
||||
<button className="lightbox-close" onClick={() => setLightbox(null)}><X size={20} strokeWidth={1.75} /></button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
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=plant', { credentials: 'include' })
|
||||
.then(async r => {
|
||||
if (r.ok) {
|
||||
setUser(await r.json())
|
||||
setState('authed')
|
||||
} else if (isEmbedded()) {
|
||||
window.top!.location.href = `/login?from=${encodeURIComponent('/app/plant')}`
|
||||
} else {
|
||||
setState('login')
|
||||
}
|
||||
})
|
||||
.catch(() => { if (!isEmbedded()) setState('login') })
|
||||
}, [])
|
||||
|
||||
// Inactivity auto-logout — configurable per device (Admin Settings → Device).
|
||||
useEffect(() => {
|
||||
const ms = getInactivityMs()
|
||||
if (state !== 'authed' || !ms) return
|
||||
const timeoutMs: number = ms
|
||||
|
||||
async function forceLogout() {
|
||||
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {})
|
||||
setUser(null)
|
||||
setState('login')
|
||||
}
|
||||
|
||||
function reset() {
|
||||
if (timerRef.current) clearTimeout(timerRef.current)
|
||||
timerRef.current = setTimeout(forceLogout, timeoutMs)
|
||||
}
|
||||
|
||||
const events = ['mousemove', 'keydown', 'click', 'touchstart'] as const
|
||||
events.forEach(e => window.addEventListener(e, reset, { passive: true }))
|
||||
reset()
|
||||
|
||||
return () => {
|
||||
if (timerRef.current) clearTimeout(timerRef.current)
|
||||
events.forEach(e => window.removeEventListener(e, reset))
|
||||
}
|
||||
}, [state])
|
||||
|
||||
async function login(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setLoading(true)
|
||||
setError('')
|
||||
try {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST', credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
})
|
||||
if (!res.ok) { setError('Invalid email or password'); return }
|
||||
const verify = await fetch('/api/auth/verify?app=plant', { credentials: 'include' })
|
||||
if (verify.ok) {
|
||||
setUser(await verify.json())
|
||||
setState('authed')
|
||||
} else {
|
||||
setError("You don't have access to this app.")
|
||||
}
|
||||
} catch {
|
||||
setError('Connection error — please try again')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (state === 'checking') {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
height: '100vh', fontFamily: 'var(--font)', color: 'var(--text-mid)'
|
||||
}}>
|
||||
Loading…
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (state === 'login') {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center',
|
||||
justifyContent: 'center', height: '100dvh', padding: '1.5rem',
|
||||
background: 'var(--navy-dark)',
|
||||
}}>
|
||||
<div style={{
|
||||
background: 'var(--navy)', borderRadius: 'var(--radius)',
|
||||
padding: '2rem', width: '100%', maxWidth: '360px',
|
||||
border: '1px solid var(--surface-2)',
|
||||
}}>
|
||||
<h1 style={{ fontSize: '1.4rem', marginBottom: '1.5rem', color: 'var(--gold)' }}>
|
||||
Plant Room
|
||||
</h1>
|
||||
<form onSubmit={login} style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
|
||||
<input
|
||||
type="email" value={email} onChange={e => setEmail(e.target.value)}
|
||||
placeholder="Email" required autoComplete="email"
|
||||
style={inputStyle}
|
||||
/>
|
||||
<input
|
||||
type="password" value={password} onChange={e => setPassword(e.target.value)}
|
||||
placeholder="Password" required autoComplete="current-password"
|
||||
style={inputStyle}
|
||||
/>
|
||||
{error && <p style={{ color: 'var(--danger)', fontSize: '0.875rem' }}>{error}</p>}
|
||||
<button type="submit" disabled={loading} style={{
|
||||
background: loading ? 'var(--surface-2)' : 'var(--gold)',
|
||||
color: loading ? 'var(--text-muted)' : 'var(--navy-dark)',
|
||||
border: 'none', borderRadius: '6px', padding: '0.625rem',
|
||||
fontSize: '1rem', fontWeight: 600, marginTop: '0.25rem',
|
||||
}}>
|
||||
{loading ? 'Signing in…' : 'Sign in'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Ctx.Provider value={{ user: user! }}>
|
||||
{children}
|
||||
</Ctx.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const inputStyle: React.CSSProperties = {
|
||||
background: 'var(--navy-dark)', border: '1px solid var(--surface-2)',
|
||||
borderRadius: '6px', color: 'var(--text)', padding: '0.625rem 0.75rem',
|
||||
fontSize: '1rem', width: '100%', outline: 'none',
|
||||
}
|
||||
73
frontend/src/components/Layout.tsx
Normal file
73
frontend/src/components/Layout.tsx
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import { NavLink, useLocation } from 'react-router-dom'
|
||||
import { Gauge, LayoutGrid, Wrench, Bell, Settings, Menu, LogOut } from 'lucide-react'
|
||||
import { useAuth } from './AuthGate'
|
||||
import { can } from '../types'
|
||||
|
||||
const ICON_PROPS = { size: 16, strokeWidth: 1.75 }
|
||||
|
||||
const NAV = [
|
||||
{ to: '/dashboard', label: 'Dashboard', icon: LayoutGrid, cap: 'view' },
|
||||
{ to: '/assets', label: 'Assets', icon: Wrench, cap: 'manage_assets' },
|
||||
{ to: '/alerts', label: 'Alerts', icon: Bell, cap: 'view' },
|
||||
{ to: '/settings', label: 'Settings', icon: Settings, cap: 'settings' },
|
||||
]
|
||||
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
const { user } = useAuth()
|
||||
const items = NAV.filter(n => can(user, n.cap))
|
||||
const location = useLocation()
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
|
||||
async function logout() {
|
||||
await fetch('/plant/api/auth/logout', { method: 'POST', credentials: 'include' })
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
useEffect(() => { setMenuOpen(false) }, [location.pathname])
|
||||
|
||||
return (
|
||||
<div className={`app-shell${menuOpen ? ' menu-open' : ''}`}>
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar-logo">
|
||||
<Gauge size={18} strokeWidth={1.75} />
|
||||
Plant Room
|
||||
</div>
|
||||
<nav className="sidebar-nav">
|
||||
{items.map(({ to, label, icon: Icon }) => (
|
||||
<NavLink key={to} to={to} className={({ isActive }) => isActive ? 'active' : ''}>
|
||||
<Icon {...ICON_PROPS} />
|
||||
{label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<div className="sidebar-user" style={{ whiteSpace: 'normal' }}>
|
||||
<div style={{ fontWeight: 600, color: 'var(--text)', fontSize: '12px', marginBottom: '2px' }}>{user.name}</div>
|
||||
<div style={{ fontSize: '11px', marginBottom: '8px' }}>{user.email}</div>
|
||||
<button onClick={logout} style={{
|
||||
display: 'flex', alignItems: 'center', gap: '6px',
|
||||
background: 'none', border: 'none', color: 'inherit',
|
||||
fontSize: '12px', padding: 0, cursor: 'pointer',
|
||||
}}>
|
||||
<LogOut size={13} strokeWidth={1.75} />
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{menuOpen && <div className="menu-backdrop" onClick={() => setMenuOpen(false)} />}
|
||||
|
||||
<header className="top-bar">
|
||||
<button className="top-bar-burger" onClick={() => setMenuOpen(o => !o)}>
|
||||
<Menu size={20} strokeWidth={1.75} />
|
||||
</button>
|
||||
<Gauge size={18} strokeWidth={1.75} color="var(--gold)" />
|
||||
<span className="top-bar-title">Plant Room</span>
|
||||
</header>
|
||||
|
||||
<main className="page-content">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
374
frontend/src/index.css
Normal file
374
frontend/src/index.css
Normal file
|
|
@ -0,0 +1,374 @@
|
|||
/* Stack design system tokens — include verbatim in every app */
|
||||
:root {
|
||||
--navy: #1a1a2e;
|
||||
--navy-dark: #0f0f20;
|
||||
--gold: #c9a84c;
|
||||
--gold-light: #e8c96d;
|
||||
--surface: rgba(255,255,255,0.07);
|
||||
--surface-2: rgba(255,255,255,0.08);
|
||||
--text: rgba(255,255,255,0.88);
|
||||
--text-muted: rgba(255,255,255,0.48);
|
||||
--body-bg: #f4f5f7;
|
||||
--card-bg: #ffffff;
|
||||
--card-border: #e4e8ee;
|
||||
--text-dark: #1e293b;
|
||||
--text-mid: #64748b;
|
||||
--shadow-sm: 0 1px 3px rgba(0,0,0,0.07), 0 1px 2px rgba(0,0,0,0.04);
|
||||
--shadow-md: 0 4px 12px rgba(0,0,0,0.08);
|
||||
--danger: #dc2626;
|
||||
--radius: 10px;
|
||||
--font: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
}
|
||||
body { background: var(--body-bg); color: var(--text-dark); font-family: var(--font); }
|
||||
|
||||
/* App theme + semantic tokens */
|
||||
:root {
|
||||
--app-primary: #0e7490;
|
||||
--app-primary-light: #0891b2;
|
||||
|
||||
--sev-warning: #d97706;
|
||||
--sev-critical: #dc2626;
|
||||
--sev-ok: #16a34a;
|
||||
|
||||
--danger-bg: #fef2f2;
|
||||
--warn-bg: #fffbeb;
|
||||
--ok-bg: #f0fdf4;
|
||||
|
||||
--sidebar-w: 240px;
|
||||
--topbar-h: 56px;
|
||||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
html, body, #root { height: 100%; margin: 0; font-size: 14px; }
|
||||
|
||||
::-webkit-scrollbar { width: 4px; height: 4px; }
|
||||
::-webkit-scrollbar-track { background: transparent; }
|
||||
::-webkit-scrollbar-thumb { background: var(--card-border); border-radius: 2px; }
|
||||
|
||||
/* ── App shell ─────────────────────────────────────────────── */
|
||||
.app-shell { display: flex; height: 100vh; overflow: hidden; }
|
||||
|
||||
.sidebar {
|
||||
width: var(--sidebar-w);
|
||||
background: var(--navy);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.sidebar-logo {
|
||||
padding: 20px 16px 12px;
|
||||
color: var(--gold);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: .05em;
|
||||
text-transform: uppercase;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.sidebar-logo svg { opacity: .8; }
|
||||
.sidebar-nav { flex: 1; padding: 8px 0; }
|
||||
.sidebar-nav a {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 16px;
|
||||
color: var(--text-muted);
|
||||
text-decoration: none;
|
||||
font-size: 13.5px;
|
||||
transition: background .15s, color .15s;
|
||||
}
|
||||
.sidebar-nav a:hover { background: var(--surface); color: var(--text); }
|
||||
.sidebar-nav a.active { background: rgba(201,168,76,.1); color: var(--gold); }
|
||||
.sidebar-user {
|
||||
padding: 12px 16px;
|
||||
border-top: 1px solid var(--surface-2);
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.top-bar {
|
||||
display: none;
|
||||
height: var(--topbar-h);
|
||||
background: var(--navy);
|
||||
color: var(--text);
|
||||
align-items: center;
|
||||
padding: 0 12px;
|
||||
gap: 10px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.top-bar-title { flex: 1; font-size: 15px; font-weight: 600; color: var(--gold); }
|
||||
|
||||
.page-content { flex: 1; overflow-y: auto; display: flex; flex-direction: column; }
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.sidebar {
|
||||
position: fixed;
|
||||
top: 0; left: 0; bottom: 0;
|
||||
z-index: 200;
|
||||
transform: translateX(calc(-1 * var(--sidebar-w)));
|
||||
transition: transform 0.25s ease;
|
||||
}
|
||||
.app-shell.menu-open .sidebar { transform: translateX(0); }
|
||||
.top-bar { display: flex; }
|
||||
.app-shell { flex-direction: column; }
|
||||
.field-row { flex-direction: column; }
|
||||
}
|
||||
|
||||
.menu-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.5);
|
||||
z-index: 199;
|
||||
}
|
||||
|
||||
.top-bar-burger {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* ── Page chrome ───────────────────────────────────────────── */
|
||||
.page { padding: 20px; max-width: 1100px; width: 100%; margin: 0 auto; }
|
||||
.page-header { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
|
||||
.page-header h1 { font-size: 18px; margin: 0; flex: 1; }
|
||||
|
||||
/* ── Buttons ───────────────────────────────────────────────── */
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border: 1px solid var(--card-border);
|
||||
background: var(--card-bg);
|
||||
color: var(--text-dark);
|
||||
border-radius: var(--radius);
|
||||
padding: 7px 14px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
font-family: var(--font);
|
||||
transition: background .12s, border-color .12s;
|
||||
}
|
||||
.btn:hover { border-color: var(--text-mid); }
|
||||
.btn:disabled { opacity: .5; cursor: default; }
|
||||
.btn-primary { background: var(--gold); border-color: var(--gold); color: var(--navy); font-weight: 600; }
|
||||
.btn-primary:hover { background: var(--gold-light); border-color: var(--gold-light); }
|
||||
.btn-danger { background: var(--danger); border-color: var(--danger); color: #fff; }
|
||||
.btn-sm { padding: 4px 10px; font-size: 12px; border-radius: 8px; }
|
||||
|
||||
/* ── Forms ─────────────────────────────────────────────────── */
|
||||
.field { margin-bottom: 12px; }
|
||||
.field label { display: block; font-size: 12px; font-weight: 600; color: var(--text-mid); margin-bottom: 4px; }
|
||||
.field input[type="text"], .field input[type="email"], .field input[type="date"],
|
||||
.field input[type="number"], .field select, .field textarea {
|
||||
width: 100%;
|
||||
border: 1px solid var(--card-border);
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
font-size: 13.5px;
|
||||
font-family: var(--font);
|
||||
color: var(--text-dark);
|
||||
background: var(--card-bg);
|
||||
}
|
||||
.field textarea { min-height: 72px; resize: vertical; }
|
||||
.field-row { display: flex; gap: 12px; }
|
||||
.field-row > .field { flex: 1; }
|
||||
.field-check { display: flex; align-items: center; gap: 8px; font-size: 13.5px; cursor: pointer; }
|
||||
.field-check input { width: 16px; height: 16px; accent-color: var(--gold); }
|
||||
.field-hint { font-size: 11.5px; color: var(--text-mid); margin-top: 3px; }
|
||||
|
||||
/* ── Cards ─────────────────────────────────────────────────── */
|
||||
.card {
|
||||
background: var(--card-bg);
|
||||
border: 1px solid var(--card-border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-sm);
|
||||
padding: 14px 16px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
/* ── Asset grid / cards ────────────────────────────────────── */
|
||||
.asset-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; }
|
||||
.asset-card {
|
||||
border-left: 4px solid var(--sev-ok);
|
||||
}
|
||||
.asset-card.sev-warning { border-left-color: var(--sev-warning); }
|
||||
.asset-card.sev-critical { border-left-color: var(--sev-critical); }
|
||||
.asset-card-title { font-weight: 600; font-size: 14px; margin-bottom: 4px; display: flex; align-items: center; gap: 6px; justify-content: space-between; }
|
||||
.asset-card-meta { font-size: 12px; color: var(--text-mid); margin-bottom: 8px; }
|
||||
.asset-field-list { display: flex; flex-direction: column; gap: 4px; }
|
||||
.asset-field-row { display: flex; justify-content: space-between; gap: 8px; font-size: 12.5px; }
|
||||
.asset-field-key { color: var(--text-mid); }
|
||||
.asset-field-value { font-weight: 600; color: var(--text-dark); }
|
||||
|
||||
/* ── Badges ────────────────────────────────────────────────── */
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
border-radius: 20px;
|
||||
padding: 2px 9px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: #fff;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.badge-sev-warning { background: var(--sev-warning); }
|
||||
.badge-sev-critical { background: var(--sev-critical); }
|
||||
.badge-sev-ok { background: var(--sev-ok); }
|
||||
|
||||
.badge-status-open { background: var(--sev-critical); }
|
||||
.badge-status-acknowledged { background: var(--sev-warning); }
|
||||
.badge-status-resolved { background: var(--sev-ok); }
|
||||
|
||||
.badge-outline {
|
||||
background: transparent;
|
||||
border: 1px solid var(--card-border);
|
||||
color: var(--text-mid);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* ── Modal ─────────────────────────────────────────────────── */
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(15,15,32,.55);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding: 24px 12px;
|
||||
z-index: 100;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.modal {
|
||||
background: var(--card-bg);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow-md);
|
||||
width: 100%;
|
||||
max-width: 680px;
|
||||
padding: 20px;
|
||||
margin: auto 0;
|
||||
}
|
||||
.modal-header { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 14px; }
|
||||
.modal-header h2 { font-size: 16px; margin: 0; flex: 1; }
|
||||
.modal-close {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: var(--text-mid);
|
||||
padding: 2px;
|
||||
display: flex;
|
||||
}
|
||||
.modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 16px; flex-wrap: wrap; }
|
||||
|
||||
/* ── Photos ────────────────────────────────────────────────── */
|
||||
.photo-grid { display: flex; gap: 8px; flex-wrap: wrap; margin: 8px 0; }
|
||||
.photo-thumb {
|
||||
width: 84px;
|
||||
height: 84px;
|
||||
border-radius: 8px;
|
||||
object-fit: cover;
|
||||
border: 1px solid var(--card-border);
|
||||
cursor: pointer;
|
||||
}
|
||||
.photo-thumb-uploading {
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
background: var(--card-border); color: var(--text-mid);
|
||||
}
|
||||
@keyframes spin { to { transform: rotate(360deg); } }
|
||||
.spin { animation: spin .75s linear infinite; }
|
||||
.photo-thumb-wrap { position: relative; }
|
||||
.photo-del {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -6px;
|
||||
background: var(--danger);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
}
|
||||
.lightbox-overlay {
|
||||
position: fixed; inset: 0; z-index: 200;
|
||||
background: rgba(0,0,0,.92);
|
||||
display: flex; align-items: center; justify-content: center;
|
||||
padding: 16px;
|
||||
}
|
||||
.lightbox-img { max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 4px; }
|
||||
.lightbox-close {
|
||||
position: absolute; top: 16px; right: 16px;
|
||||
background: rgba(255,255,255,.15); border: none; border-radius: 50%;
|
||||
width: 38px; height: 38px; display: flex; align-items: center; justify-content: center;
|
||||
cursor: pointer; color: #fff; transition: background .12s;
|
||||
}
|
||||
.lightbox-close:hover { background: rgba(255,255,255,.28); }
|
||||
|
||||
/* ── Tables ────────────────────────────────────────────────── */
|
||||
.table-wrap { overflow-x: auto; background: var(--card-bg); border: 1px solid var(--card-border); border-radius: var(--radius); box-shadow: var(--shadow-sm); }
|
||||
table.data { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
table.data th {
|
||||
text-align: left;
|
||||
padding: 9px 12px;
|
||||
font-size: 11.5px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .04em;
|
||||
color: var(--text-mid);
|
||||
border-bottom: 1px solid var(--card-border);
|
||||
white-space: nowrap;
|
||||
}
|
||||
table.data td { padding: 9px 12px; border-bottom: 1px solid var(--card-border); vertical-align: top; }
|
||||
table.data tr:last-child td { border-bottom: none; }
|
||||
table.data tr.clickable { cursor: pointer; }
|
||||
|
||||
/* ── Misc ──────────────────────────────────────────────────── */
|
||||
.empty-state { text-align: center; color: var(--text-mid); padding: 40px 16px; font-size: 13.5px; }
|
||||
.error-banner {
|
||||
background: var(--danger-bg);
|
||||
border: 1px solid var(--danger);
|
||||
color: var(--danger);
|
||||
border-radius: var(--radius);
|
||||
padding: 10px 14px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.ok-banner {
|
||||
background: var(--ok-bg);
|
||||
border: 1px solid var(--sev-ok);
|
||||
color: var(--sev-ok);
|
||||
border-radius: var(--radius);
|
||||
padding: 10px 14px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.warn-banner {
|
||||
background: var(--warn-bg);
|
||||
border: 1px solid var(--sev-warning);
|
||||
color: var(--sev-warning);
|
||||
border-radius: var(--radius);
|
||||
padding: 10px 14px;
|
||||
margin-bottom: 12px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.section-title { font-size: 13px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em; color: var(--text-mid); margin: 18px 0 8px; }
|
||||
.muted { color: var(--text-mid); }
|
||||
|
||||
/* Sidebar scrollbar */
|
||||
.sidebar::-webkit-scrollbar, .sidebar-nav::-webkit-scrollbar { width: 4px; }
|
||||
.sidebar::-webkit-scrollbar-track, .sidebar-nav::-webkit-scrollbar-track { background: transparent; }
|
||||
.sidebar::-webkit-scrollbar-thumb, .sidebar-nav::-webkit-scrollbar-thumb { background: rgba(201,168,76,0.35); border-radius: 2px; }
|
||||
.sidebar::-webkit-scrollbar-thumb:hover, .sidebar-nav::-webkit-scrollbar-thumb:hover { background: rgba(201,168,76,0.65); }
|
||||
.sidebar, .sidebar-nav { scrollbar-width: thin; scrollbar-color: rgba(201,168,76,0.35) transparent; }
|
||||
10
frontend/src/main.tsx
Normal file
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>
|
||||
)
|
||||
146
frontend/src/pages/Alerts.tsx
Normal file
146
frontend/src/pages/Alerts.tsx
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
import { useEffect, useState, useCallback } from 'react'
|
||||
import { Check, CheckCheck } from 'lucide-react'
|
||||
import { fetchAlerts, acknowledgeAlert, resolveAlert } from '../api'
|
||||
import type { PlantAlert, AlertStatus, AlertSeverity } from '../types'
|
||||
import { CONDITION_LABELS } from '../types'
|
||||
import { useAuth } from '../components/AuthGate'
|
||||
import { can } from '../types'
|
||||
|
||||
const STATUS_OPTIONS: { value: AlertStatus | ''; label: string }[] = [
|
||||
{ value: '', label: 'All statuses' },
|
||||
{ value: 'open', label: 'Open' },
|
||||
{ value: 'acknowledged', label: 'Acknowledged' },
|
||||
{ value: 'resolved', label: 'Resolved' },
|
||||
]
|
||||
const SEVERITY_OPTIONS: { value: AlertSeverity | ''; label: string }[] = [
|
||||
{ value: '', label: 'All severities' },
|
||||
{ value: 'warning', label: 'Warning' },
|
||||
{ value: 'critical', label: 'Critical' },
|
||||
]
|
||||
|
||||
export default function Alerts() {
|
||||
const { user } = useAuth()
|
||||
const canAck = can(user, 'acknowledge_alerts')
|
||||
|
||||
const [alerts, setAlerts] = useState<PlantAlert[]>([])
|
||||
const [status, setStatus] = useState<AlertStatus | ''>('open')
|
||||
const [severity, setSeverity] = useState<AlertSeverity | ''>('')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [busyId, setBusyId] = useState<number | null>(null)
|
||||
|
||||
const load = useCallback(() => {
|
||||
setLoading(true)
|
||||
fetchAlerts({ status: status || undefined, severity: severity || undefined })
|
||||
.then(setAlerts)
|
||||
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load alerts'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [status, severity])
|
||||
|
||||
useEffect(() => { load() }, [load])
|
||||
|
||||
async function ack(id: number) {
|
||||
setBusyId(id); setError('')
|
||||
try {
|
||||
await acknowledgeAlert(id)
|
||||
load()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to acknowledge')
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
async function resolve(id: number) {
|
||||
setBusyId(id); setError('')
|
||||
try {
|
||||
await resolveAlert(id)
|
||||
load()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to resolve')
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div className="page-header">
|
||||
<h1>Alerts</h1>
|
||||
</div>
|
||||
|
||||
{error && <div className="error-banner">{error}</div>}
|
||||
|
||||
<div className="field-row" style={{ marginBottom: 16, maxWidth: 420 }}>
|
||||
<div className="field">
|
||||
<label>Status</label>
|
||||
<select value={status} onChange={e => setStatus(e.target.value as AlertStatus | '')}>
|
||||
{STATUS_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Severity</label>
|
||||
<select value={severity} onChange={e => setSeverity(e.target.value as AlertSeverity | '')}>
|
||||
{SEVERITY_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<p className="muted">Loading…</p>
|
||||
) : alerts.length === 0 ? (
|
||||
<div className="empty-state">No alerts match this filter.</div>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Asset</th>
|
||||
<th>Field</th>
|
||||
<th>Condition</th>
|
||||
<th>Value at trigger</th>
|
||||
<th>Severity</th>
|
||||
<th>Status</th>
|
||||
<th>Triggered</th>
|
||||
{canAck && <th>Actions</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{alerts.map(a => (
|
||||
<tr key={a.id}>
|
||||
<td>{a.asset_name}</td>
|
||||
<td>{a.field_key.replace(/_/g, ' ')}</td>
|
||||
<td>{CONDITION_LABELS[a.condition]} {a.threshold}</td>
|
||||
<td>{a.value_at_trigger ?? '—'}</td>
|
||||
<td><span className={`badge badge-sev-${a.severity}`}>{a.severity}</span></td>
|
||||
<td><span className={`badge badge-status-${a.status}`}>{a.status}</span></td>
|
||||
<td>{new Date(a.triggered_at).toLocaleString('en-GB')}</td>
|
||||
{canAck && (
|
||||
<td>
|
||||
{a.status === 'open' && (
|
||||
<div style={{ display: 'flex', gap: 6 }}>
|
||||
<button className="btn btn-sm" disabled={busyId === a.id} onClick={() => ack(a.id)}>
|
||||
<Check size={12} strokeWidth={1.75} /> Ack
|
||||
</button>
|
||||
<button className="btn btn-sm" disabled={busyId === a.id} onClick={() => resolve(a.id)}>
|
||||
<CheckCheck size={12} strokeWidth={1.75} /> Resolve
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{a.status === 'acknowledged' && (
|
||||
<button className="btn btn-sm" disabled={busyId === a.id} onClick={() => resolve(a.id)}>
|
||||
<CheckCheck size={12} strokeWidth={1.75} /> Resolve
|
||||
</button>
|
||||
)}
|
||||
{a.status === 'resolved' && <span className="muted" style={{ fontSize: 12 }}>—</span>}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
291
frontend/src/pages/Assets.tsx
Normal file
291
frontend/src/pages/Assets.tsx
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
import { Fragment, useEffect, useState } from 'react'
|
||||
import { ChevronDown, ChevronRight, Plus } from 'lucide-react'
|
||||
import { fetchAssets, createAsset, updateAsset, fetchAssetPhotos } from '../api'
|
||||
import type { PlantAsset, AssetPhoto } from '../types'
|
||||
import { ASSET_TYPES, ASSET_TYPE_LABELS } from '../types'
|
||||
import AssetPhotoUpload from '../components/AssetPhotoUpload'
|
||||
import { useAuth } from '../components/AuthGate'
|
||||
import { can } from '../types'
|
||||
|
||||
const BLANK_FORM = {
|
||||
name: '', asset_type: 'boiler' as PlantAsset['asset_type'], location: '', make_model: '',
|
||||
serial_no: '', install_date: '', notes: '', mqtt_topic_prefix: '',
|
||||
}
|
||||
|
||||
export default function Assets() {
|
||||
const { user } = useAuth()
|
||||
const canManage = can(user, 'manage_assets')
|
||||
|
||||
const [assets, setAssets] = useState<PlantAsset[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
const [expanded, setExpanded] = useState<number | null>(null)
|
||||
const [photosByAsset, setPhotosByAsset] = useState<Record<number, AssetPhoto[]>>({})
|
||||
const [editForm, setEditForm] = useState<Record<string, string>>({})
|
||||
|
||||
const [showNew, setShowNew] = useState(false)
|
||||
const [newForm, setNewForm] = useState(BLANK_FORM)
|
||||
const [creating, setCreating] = useState(false)
|
||||
|
||||
function load() {
|
||||
fetchAssets()
|
||||
.then(setAssets)
|
||||
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load'))
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
useEffect(load, [])
|
||||
|
||||
async function toggleExpand(a: PlantAsset) {
|
||||
if (expanded === a.id) { setExpanded(null); return }
|
||||
setExpanded(a.id)
|
||||
setEditForm({
|
||||
name: a.name, asset_type: a.asset_type, location: a.location || '', make_model: a.make_model || '',
|
||||
serial_no: a.serial_no || '', install_date: a.install_date ? a.install_date.slice(0, 10) : '',
|
||||
notes: a.notes || '', mqtt_topic_prefix: a.mqtt_topic_prefix || '', active: String(a.active),
|
||||
})
|
||||
if (!photosByAsset[a.id]) {
|
||||
const photos = await fetchAssetPhotos(a.id).catch(() => [])
|
||||
setPhotosByAsset(prev => ({ ...prev, [a.id]: photos }))
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadPhotos(id: number) {
|
||||
const photos = await fetchAssetPhotos(id).catch(() => [])
|
||||
setPhotosByAsset(prev => ({ ...prev, [id]: photos }))
|
||||
}
|
||||
|
||||
async function saveEdit(id: number) {
|
||||
setError(''); setMsg('')
|
||||
try {
|
||||
await updateAsset(id, {
|
||||
name: editForm.name,
|
||||
asset_type: editForm.asset_type as PlantAsset['asset_type'],
|
||||
location: editForm.location || null,
|
||||
make_model: editForm.make_model || null,
|
||||
serial_no: editForm.serial_no || null,
|
||||
install_date: editForm.install_date || null,
|
||||
notes: editForm.notes || null,
|
||||
mqtt_topic_prefix: editForm.mqtt_topic_prefix || null,
|
||||
active: editForm.active === 'true',
|
||||
})
|
||||
setMsg('Saved')
|
||||
setTimeout(() => setMsg(''), 2000)
|
||||
load()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Save failed')
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreate(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!newForm.name.trim()) return
|
||||
setCreating(true); setError(''); setMsg('')
|
||||
try {
|
||||
await createAsset({
|
||||
name: newForm.name.trim(),
|
||||
asset_type: newForm.asset_type,
|
||||
location: newForm.location || null,
|
||||
make_model: newForm.make_model || null,
|
||||
serial_no: newForm.serial_no || null,
|
||||
install_date: newForm.install_date || null,
|
||||
notes: newForm.notes || null,
|
||||
mqtt_topic_prefix: newForm.mqtt_topic_prefix || null,
|
||||
})
|
||||
setNewForm(BLANK_FORM)
|
||||
setShowNew(false)
|
||||
setMsg('Asset created')
|
||||
load()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Create failed')
|
||||
} finally {
|
||||
setCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <div className="page"><p className="muted">Loading…</p></div>
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div className="page-header">
|
||||
<h1>Assets</h1>
|
||||
{canManage && (
|
||||
<button className="btn btn-primary" onClick={() => setShowNew(s => !s)}>
|
||||
<Plus size={14} strokeWidth={1.75} /> {showNew ? 'Cancel' : 'Add asset'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <div className="error-banner">{error}</div>}
|
||||
{msg && <div className="ok-banner">{msg}</div>}
|
||||
|
||||
{showNew && canManage && (
|
||||
<form onSubmit={handleCreate} className="card" style={{ marginBottom: 16 }}>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label>Name</label>
|
||||
<input type="text" value={newForm.name} onChange={e => setNewForm({ ...newForm, name: e.target.value })} required />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Type</label>
|
||||
<select value={newForm.asset_type} onChange={e => setNewForm({ ...newForm, asset_type: e.target.value as PlantAsset['asset_type'] })}>
|
||||
{ASSET_TYPES.map(t => <option key={t} value={t}>{ASSET_TYPE_LABELS[t]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label>Location</label>
|
||||
<input type="text" value={newForm.location} onChange={e => setNewForm({ ...newForm, location: e.target.value })} placeholder="Plant room, roof, ..." />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>MQTT topic prefix</label>
|
||||
<input type="text" value={newForm.mqtt_topic_prefix} onChange={e => setNewForm({ ...newForm, mqtt_topic_prefix: e.target.value })} placeholder="plant/water-softener" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label>Make / model</label>
|
||||
<input type="text" value={newForm.make_model} onChange={e => setNewForm({ ...newForm, make_model: e.target.value })} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Serial no.</label>
|
||||
<input type="text" value={newForm.serial_no} onChange={e => setNewForm({ ...newForm, serial_no: e.target.value })} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Install date</label>
|
||||
<input type="date" value={newForm.install_date} onChange={e => setNewForm({ ...newForm, install_date: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Notes</label>
|
||||
<textarea value={newForm.notes} onChange={e => setNewForm({ ...newForm, notes: e.target.value })} />
|
||||
</div>
|
||||
<button className="btn btn-primary" type="submit" disabled={creating}>
|
||||
{creating ? 'Creating…' : 'Create asset'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{assets.length === 0 ? (
|
||||
<div className="empty-state">No assets yet — add the first one above.</div>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data">
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>Name</th>
|
||||
<th>Type</th>
|
||||
<th>Location</th>
|
||||
<th>MQTT prefix</th>
|
||||
<th>Active</th>
|
||||
<th>Photos</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{assets.map(a => (
|
||||
<Fragment key={a.id}>
|
||||
<tr className="clickable" onClick={() => toggleExpand(a)}>
|
||||
<td>{expanded === a.id ? <ChevronDown size={14} strokeWidth={1.75} /> : <ChevronRight size={14} strokeWidth={1.75} />}</td>
|
||||
<td>{a.name}</td>
|
||||
<td>{ASSET_TYPE_LABELS[a.asset_type]}</td>
|
||||
<td>{a.location || <span className="muted">—</span>}</td>
|
||||
<td>{a.mqtt_topic_prefix || <span className="muted">not wired</span>}</td>
|
||||
<td><span className={`badge ${a.active ? 'badge-sev-ok' : 'badge-outline'}`}>{a.active ? 'Active' : 'Inactive'}</span></td>
|
||||
<td>{a.photo_count ?? 0}</td>
|
||||
</tr>
|
||||
{expanded === a.id && (
|
||||
<tr>
|
||||
<td colSpan={7}>
|
||||
{canManage ? (
|
||||
<>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label>Name</label>
|
||||
<input type="text" value={editForm.name || ''} onChange={e => setEditForm({ ...editForm, name: e.target.value })} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Type</label>
|
||||
<select value={editForm.asset_type || ''} onChange={e => setEditForm({ ...editForm, asset_type: e.target.value })}>
|
||||
{ASSET_TYPES.map(t => <option key={t} value={t}>{ASSET_TYPE_LABELS[t]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Active</label>
|
||||
<select value={editForm.active || 'true'} onChange={e => setEditForm({ ...editForm, active: e.target.value })}>
|
||||
<option value="true">Active</option>
|
||||
<option value="false">Inactive</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label>Location</label>
|
||||
<input type="text" value={editForm.location || ''} onChange={e => setEditForm({ ...editForm, location: e.target.value })} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>MQTT topic prefix</label>
|
||||
<input type="text" value={editForm.mqtt_topic_prefix || ''} onChange={e => setEditForm({ ...editForm, mqtt_topic_prefix: e.target.value })} placeholder="plant/water-softener" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label>Make / model</label>
|
||||
<input type="text" value={editForm.make_model || ''} onChange={e => setEditForm({ ...editForm, make_model: e.target.value })} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Serial no.</label>
|
||||
<input type="text" value={editForm.serial_no || ''} onChange={e => setEditForm({ ...editForm, serial_no: e.target.value })} />
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Install date</label>
|
||||
<input type="date" value={editForm.install_date || ''} onChange={e => setEditForm({ ...editForm, install_date: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Notes</label>
|
||||
<textarea value={editForm.notes || ''} onChange={e => setEditForm({ ...editForm, notes: e.target.value })} />
|
||||
</div>
|
||||
<button className="btn btn-primary btn-sm" onClick={() => saveEdit(a.id)} style={{ marginBottom: 12 }}>
|
||||
Save changes
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<div className="field-hint" style={{ marginBottom: 8 }}>
|
||||
{a.make_model || 'No make/model set'} · {a.serial_no || 'No serial recorded'}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="field-row">
|
||||
<div style={{ flex: 1 }}>
|
||||
<div className="field-hint" style={{ marginBottom: 4 }}>Asset photo</div>
|
||||
<AssetPhotoUpload
|
||||
assetId={a.id} photoType="asset"
|
||||
photos={photosByAsset[a.id] || []}
|
||||
onChanged={() => reloadPhotos(a.id)}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div className="field-hint" style={{ marginBottom: 4 }}>Serial / model plate photo</div>
|
||||
<AssetPhotoUpload
|
||||
assetId={a.id} photoType="serial_plate"
|
||||
photos={photosByAsset[a.id] || []}
|
||||
onChanged={() => reloadPhotos(a.id)}
|
||||
canDelete={canManage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
118
frontend/src/pages/Dashboard.tsx
Normal file
118
frontend/src/pages/Dashboard.tsx
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import { useEffect, useState, useCallback } from 'react'
|
||||
import { AlertTriangle, WifiOff } from 'lucide-react'
|
||||
import { fetchStatus } from '../api'
|
||||
import type { AssetStatus, AssetType } from '../types'
|
||||
import { ASSET_TYPES, ASSET_TYPE_LABELS } from '../types'
|
||||
|
||||
const POLL_MS = 30000
|
||||
|
||||
function fieldLabel(key: string): string {
|
||||
return key.replace(/_/g, ' ')
|
||||
}
|
||||
|
||||
function fieldValue(f: { value_numeric: string | null; value_text: string | null }): string {
|
||||
if (f.value_text !== null && f.value_text !== '' && isNaN(Number(f.value_text))) return f.value_text
|
||||
if (f.value_numeric !== null) return f.value_numeric
|
||||
return f.value_text ?? '—'
|
||||
}
|
||||
|
||||
function AssetCard({ asset }: { asset: AssetStatus }) {
|
||||
const sevClass = asset.max_severity ? `sev-${asset.max_severity}` : ''
|
||||
return (
|
||||
<div className={`card asset-card ${sevClass}`}>
|
||||
<div className="asset-card-title">
|
||||
<span>{asset.name}</span>
|
||||
{asset.max_severity && (
|
||||
<span className={`badge badge-sev-${asset.max_severity}`}>
|
||||
{asset.open_alert_count} open
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="asset-card-meta">
|
||||
{asset.location || 'No location set'}
|
||||
{asset.mqtt_topic_prefix ? '' : ' · not wired to MQTT yet'}
|
||||
</div>
|
||||
{asset.latest.length === 0 ? (
|
||||
<div className="muted" style={{ fontSize: 12.5 }}>No telemetry received yet.</div>
|
||||
) : (
|
||||
<div className="asset-field-list">
|
||||
{asset.latest.map(f => (
|
||||
<div key={f.field_key} className="asset-field-row">
|
||||
<span className="asset-field-key">{fieldLabel(f.field_key)}</span>
|
||||
<span className="asset-field-value">{fieldValue(f)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Dashboard() {
|
||||
const [assets, setAssets] = useState<AssetStatus[]>([])
|
||||
const [openAlerts, setOpenAlerts] = useState(0)
|
||||
const [mqttConnected, setMqttConnected] = useState(true)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const load = useCallback(() => {
|
||||
fetchStatus()
|
||||
.then(res => {
|
||||
setAssets(res.assets)
|
||||
setOpenAlerts(res.open_alerts)
|
||||
setMqttConnected(res.mqtt_connected)
|
||||
setError('')
|
||||
})
|
||||
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load status'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
const t = setInterval(load, POLL_MS)
|
||||
return () => clearInterval(t)
|
||||
}, [load])
|
||||
|
||||
if (loading) return <div className="page"><p className="muted">Loading…</p></div>
|
||||
|
||||
const byType = (t: AssetType) => assets.filter(a => a.asset_type === t)
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div className="page-header">
|
||||
<h1>Dashboard</h1>
|
||||
</div>
|
||||
|
||||
{error && <div className="error-banner">{error}</div>}
|
||||
{!mqttConnected && (
|
||||
<div className="warn-banner" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<WifiOff size={14} strokeWidth={1.75} />
|
||||
MQTT broker not connected — asset telemetry may be stale.
|
||||
</div>
|
||||
)}
|
||||
{openAlerts > 0 && (
|
||||
<div className="error-banner" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<AlertTriangle size={14} strokeWidth={1.75} />
|
||||
{openAlerts} open alert{openAlerts === 1 ? '' : 's'} — see the Alerts page.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{assets.length === 0 ? (
|
||||
<div className="empty-state">No active assets yet — add one on the Assets page.</div>
|
||||
) : (
|
||||
ASSET_TYPES.map(type => {
|
||||
const group = byType(type)
|
||||
if (group.length === 0) return null
|
||||
return (
|
||||
<div key={type}>
|
||||
<div className="section-title">{ASSET_TYPE_LABELS[type]}</div>
|
||||
<div className="asset-grid">
|
||||
{group.map(a => <AssetCard key={a.id} asset={a} />)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
267
frontend/src/pages/Settings.tsx
Normal file
267
frontend/src/pages/Settings.tsx
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
import { useEffect, useState } from 'react'
|
||||
import { Wifi, WifiOff, Plus, Trash2 } from 'lucide-react'
|
||||
import {
|
||||
getSettings, saveSettings, fetchMqttStatus, fetchAssets,
|
||||
fetchAlertRules, createAlertRule, updateAlertRule, deleteAlertRule,
|
||||
} from '../api'
|
||||
import type { PlantAsset, AlertRule, AlertCondition, AlertSeverity } from '../types'
|
||||
import { ASSET_TYPES, ASSET_TYPE_LABELS, CONDITION_LABELS } from '../types'
|
||||
|
||||
const SETTING_LABELS: Record<string, { label: string; hint: string; placeholder?: string }> = {
|
||||
alert_notify_email: {
|
||||
label: 'Alert notification email',
|
||||
hint: 'Address that receives an email whenever a new alert is triggered. Leave blank to disable alert emails.',
|
||||
placeholder: 'maintenance@example.com',
|
||||
},
|
||||
}
|
||||
|
||||
const CONDITIONS: AlertCondition[] = ['lt', 'gt', 'eq', 'stale_minutes']
|
||||
const SEVERITIES: AlertSeverity[] = ['warning', 'critical']
|
||||
|
||||
const BLANK_RULE = {
|
||||
scope: 'asset_type' as 'asset' | 'asset_type',
|
||||
asset_id: '' as string,
|
||||
asset_type: 'boiler' as PlantAsset['asset_type'],
|
||||
field_key: '',
|
||||
condition: 'lt' as AlertCondition,
|
||||
threshold: '',
|
||||
severity: 'warning' as AlertSeverity,
|
||||
}
|
||||
|
||||
export default function Settings() {
|
||||
const [values, setValues] = useState<Record<string, string>>({})
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [msg, setMsg] = useState('')
|
||||
|
||||
const [mqttConnected, setMqttConnected] = useState<boolean | null>(null)
|
||||
const [mqttNote, setMqttNote] = useState('')
|
||||
|
||||
const [assets, setAssets] = useState<PlantAsset[]>([])
|
||||
const [rules, setRules] = useState<AlertRule[]>([])
|
||||
const [showNewRule, setShowNewRule] = useState(false)
|
||||
const [newRule, setNewRule] = useState(BLANK_RULE)
|
||||
const [creatingRule, setCreatingRule] = useState(false)
|
||||
|
||||
function loadSettings() {
|
||||
getSettings()
|
||||
.then(({ settings }) => {
|
||||
const v: Record<string, string> = {}
|
||||
for (const s of settings) v[s.key] = s.value
|
||||
setValues(v)
|
||||
})
|
||||
.catch(e => setError(e instanceof Error ? e.message : 'Failed to load settings'))
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
|
||||
function loadRules() {
|
||||
fetchAlertRules().then(setRules).catch(() => {})
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadSettings()
|
||||
loadRules()
|
||||
fetchAssets().then(setAssets).catch(() => {})
|
||||
fetchMqttStatus().then(s => { setMqttConnected(s.connected); setMqttNote(s.note) }).catch(() => {})
|
||||
}, [])
|
||||
|
||||
async function handleSaveSettings() {
|
||||
setSaving(true); setError(''); setMsg('')
|
||||
try {
|
||||
await saveSettings(Object.entries(values).map(([key, value]) => ({ key, value })))
|
||||
setMsg('Settings saved'); setTimeout(() => setMsg(''), 2500)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Save failed')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateRule(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
if (!newRule.field_key.trim() || newRule.threshold === '') return
|
||||
setCreatingRule(true); setError(''); setMsg('')
|
||||
try {
|
||||
await createAlertRule({
|
||||
asset_id: newRule.scope === 'asset' && newRule.asset_id ? Number(newRule.asset_id) : null,
|
||||
asset_type: newRule.scope === 'asset_type' ? newRule.asset_type : null,
|
||||
field_key: newRule.field_key.trim(),
|
||||
condition: newRule.condition,
|
||||
threshold: Number(newRule.threshold),
|
||||
severity: newRule.severity,
|
||||
})
|
||||
setNewRule(BLANK_RULE)
|
||||
setShowNewRule(false)
|
||||
loadRules()
|
||||
setMsg('Alert rule created')
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to create rule')
|
||||
} finally {
|
||||
setCreatingRule(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleRuleActive(rule: AlertRule) {
|
||||
try {
|
||||
await updateAlertRule(rule.id, { active: !rule.active })
|
||||
loadRules()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to update rule')
|
||||
}
|
||||
}
|
||||
|
||||
async function removeRule(id: number) {
|
||||
try {
|
||||
await deleteAlertRule(id)
|
||||
loadRules()
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : 'Failed to delete rule')
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) return <div className="page"><p className="muted">Loading…</p></div>
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div className="page-header">
|
||||
<h1>Settings</h1>
|
||||
</div>
|
||||
|
||||
{error && <div className="error-banner">{error}</div>}
|
||||
{msg && <div className="ok-banner">{msg}</div>}
|
||||
|
||||
<div className="section-title">MQTT Broker</div>
|
||||
<div className="card" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{mqttConnected ? <Wifi size={16} strokeWidth={1.75} color="var(--sev-ok)" /> : <WifiOff size={16} strokeWidth={1.75} color="var(--danger)" />}
|
||||
<span>{mqttNote || 'Checking…'}</span>
|
||||
</div>
|
||||
|
||||
<div className="section-title">Notifications</div>
|
||||
{Object.entries(SETTING_LABELS).map(([key, meta]) => (
|
||||
<div className="field" key={key} style={{ maxWidth: 420 }}>
|
||||
<label>{meta.label}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={values[key] ?? ''}
|
||||
placeholder={meta.placeholder}
|
||||
onChange={e => setValues(v => ({ ...v, [key]: e.target.value }))}
|
||||
/>
|
||||
<div className="field-hint">{meta.hint}</div>
|
||||
</div>
|
||||
))}
|
||||
<button className="btn btn-primary" disabled={saving} onClick={handleSaveSettings} style={{ marginBottom: 24 }}>
|
||||
{saving ? 'Saving…' : 'Save Settings'}
|
||||
</button>
|
||||
|
||||
<div className="section-title" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<span>Alert Rules</span>
|
||||
<button className="btn btn-sm" onClick={() => setShowNewRule(s => !s)}>
|
||||
<Plus size={13} strokeWidth={1.75} /> {showNewRule ? 'Cancel' : 'Add rule'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showNewRule && (
|
||||
<form onSubmit={handleCreateRule} className="card" style={{ marginBottom: 16 }}>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label>Applies to</label>
|
||||
<select value={newRule.scope} onChange={e => setNewRule({ ...newRule, scope: e.target.value as 'asset' | 'asset_type' })}>
|
||||
<option value="asset_type">Every asset of a type</option>
|
||||
<option value="asset">A specific asset</option>
|
||||
</select>
|
||||
</div>
|
||||
{newRule.scope === 'asset_type' ? (
|
||||
<div className="field">
|
||||
<label>Asset type</label>
|
||||
<select value={newRule.asset_type} onChange={e => setNewRule({ ...newRule, asset_type: e.target.value as PlantAsset['asset_type'] })}>
|
||||
{ASSET_TYPES.map(t => <option key={t} value={t}>{ASSET_TYPE_LABELS[t]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
) : (
|
||||
<div className="field">
|
||||
<label>Asset</label>
|
||||
<select value={newRule.asset_id} onChange={e => setNewRule({ ...newRule, asset_id: e.target.value })} required>
|
||||
<option value="">Select an asset…</option>
|
||||
{assets.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="field-row">
|
||||
<div className="field">
|
||||
<label>Field key</label>
|
||||
<input
|
||||
type="text" value={newRule.field_key}
|
||||
onChange={e => setNewRule({ ...newRule, field_key: e.target.value })}
|
||||
placeholder="salt_level_pct" required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Condition</label>
|
||||
<select value={newRule.condition} onChange={e => setNewRule({ ...newRule, condition: e.target.value as AlertCondition })}>
|
||||
{CONDITIONS.map(c => <option key={c} value={c}>{CONDITION_LABELS[c]}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Threshold</label>
|
||||
<input
|
||||
type="number" value={newRule.threshold}
|
||||
onChange={e => setNewRule({ ...newRule, threshold: e.target.value })}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="field">
|
||||
<label>Severity</label>
|
||||
<select value={newRule.severity} onChange={e => setNewRule({ ...newRule, severity: e.target.value as AlertSeverity })}>
|
||||
{SEVERITIES.map(s => <option key={s} value={s}>{s}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn btn-primary" type="submit" disabled={creatingRule}>
|
||||
{creatingRule ? 'Creating…' : 'Create rule'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{rules.length === 0 ? (
|
||||
<div className="empty-state">No alert rules yet.</div>
|
||||
) : (
|
||||
<div className="table-wrap">
|
||||
<table className="data">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Scope</th>
|
||||
<th>Field</th>
|
||||
<th>Condition</th>
|
||||
<th>Severity</th>
|
||||
<th>Active</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rules.map(r => (
|
||||
<tr key={r.id}>
|
||||
<td>{r.asset_id ? r.asset_name : `All ${r.asset_type ? ASSET_TYPE_LABELS[r.asset_type] : ''}`}</td>
|
||||
<td>{r.field_key.replace(/_/g, ' ')}</td>
|
||||
<td>{CONDITION_LABELS[r.condition]} {r.threshold}</td>
|
||||
<td><span className={`badge badge-sev-${r.severity}`}>{r.severity}</span></td>
|
||||
<td>
|
||||
<button className="btn btn-sm" onClick={() => toggleRuleActive(r)}>
|
||||
{r.active ? 'Active' : 'Inactive'}
|
||||
</button>
|
||||
</td>
|
||||
<td>
|
||||
<button className="btn btn-sm btn-danger" onClick={() => removeRule(r.id)}>
|
||||
<Trash2 size={12} strokeWidth={1.75} />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
110
frontend/src/types.ts
Normal file
110
frontend/src/types.ts
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
export type AssetType = 'boiler' | 'water_softener' | 'calorifier' | 'pump'
|
||||
export type AlertCondition = 'lt' | 'gt' | 'eq' | 'stale_minutes'
|
||||
export type AlertSeverity = 'warning' | 'critical'
|
||||
export type AlertStatus = 'open' | 'acknowledged' | 'resolved'
|
||||
export type PhotoType = 'asset' | 'serial_plate'
|
||||
|
||||
export const ASSET_TYPES: AssetType[] = ['boiler', 'water_softener', 'calorifier', 'pump']
|
||||
|
||||
export const ASSET_TYPE_LABELS: Record<AssetType, string> = {
|
||||
boiler: 'Boiler',
|
||||
water_softener: 'Water Softener',
|
||||
calorifier: 'Calorifier',
|
||||
pump: 'Pump / Pressurisation Set',
|
||||
}
|
||||
|
||||
export const CONDITION_LABELS: Record<AlertCondition, string> = {
|
||||
lt: 'Less than',
|
||||
gt: 'Greater than',
|
||||
eq: 'Equal to',
|
||||
stale_minutes: 'Stale for (minutes, no update)',
|
||||
}
|
||||
|
||||
export interface PlantAsset {
|
||||
id: number
|
||||
name: string
|
||||
asset_type: AssetType
|
||||
location: string | null
|
||||
make_model: string | null
|
||||
serial_no: string | null
|
||||
install_date: string | null
|
||||
notes: string | null
|
||||
active: boolean
|
||||
mqtt_topic_prefix: string | null
|
||||
created_at: string
|
||||
photo_count?: number
|
||||
}
|
||||
|
||||
export interface TelemetryField {
|
||||
asset_id: number
|
||||
field_key: string
|
||||
value_numeric: string | null
|
||||
value_text: string | null
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface AssetStatus extends PlantAsset {
|
||||
latest: TelemetryField[]
|
||||
open_alert_count: number
|
||||
max_severity: AlertSeverity | null
|
||||
}
|
||||
|
||||
export interface AlertRule {
|
||||
id: number
|
||||
asset_id: number | null
|
||||
asset_type: AssetType | null
|
||||
field_key: string
|
||||
condition: AlertCondition
|
||||
threshold: string
|
||||
severity: AlertSeverity
|
||||
active: boolean
|
||||
created_at: string
|
||||
asset_name?: string | null
|
||||
}
|
||||
|
||||
export interface PlantAlert {
|
||||
id: number
|
||||
rule_id: number
|
||||
asset_id: number
|
||||
field_key: string
|
||||
value_at_trigger: string | null
|
||||
status: AlertStatus
|
||||
triggered_at: string
|
||||
acknowledged_at: string | null
|
||||
acknowledged_by: string | null
|
||||
resolved_at: string | null
|
||||
asset_name: string
|
||||
asset_type: AssetType
|
||||
condition: AlertCondition
|
||||
threshold: string
|
||||
severity: AlertSeverity
|
||||
}
|
||||
|
||||
export interface AssetPhoto {
|
||||
id: number
|
||||
asset_id: number
|
||||
file_name: string
|
||||
file_path: string
|
||||
mime_type: string
|
||||
photo_type: PhotoType
|
||||
uploaded_by: string
|
||||
uploaded_at: string
|
||||
}
|
||||
|
||||
export interface AppSetting {
|
||||
key: string
|
||||
value: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface User {
|
||||
user_id: number
|
||||
name: string
|
||||
email: string
|
||||
is_admin: boolean
|
||||
caps: string[] // bare slugs — verify?app=plant strips the prefix
|
||||
}
|
||||
|
||||
export function can(user: User, cap: string): boolean {
|
||||
return user.is_admin || user.caps.includes(cap)
|
||||
}
|
||||
1
frontend/src/vite-env.d.ts
vendored
Normal file
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: '/plant/',
|
||||
plugins: [react()],
|
||||
})
|
||||
43
seed-app.js
Normal file
43
seed-app.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
#!/usr/bin/env node
|
||||
// Run from plant/ 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 ('plant', 'Plant Room', 'Plant-room equipment monitoring and alerting — boilers, water softener, calorifiers and pumps via MQTT telemetry', '/plant', 'Gauge', '#0e7490', 'Operations', '10.10.10.123', 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
|
||||
`)
|
||||
|
||||
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 the plant-room dashboard and alert list', 1),
|
||||
('manage_assets', 'Manage Assets', 'Create/edit assets, alert rules and asset photos', 2),
|
||||
('acknowledge_alerts', 'Acknowledge Alerts','Acknowledge and resolve triggered alerts', 3),
|
||||
('settings', 'Settings', 'Configure plant app settings', 4)
|
||||
) AS c(slug, name, description, sort_order)
|
||||
WHERE a.slug = 'plant'
|
||||
ON CONFLICT (app_id, slug) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
description = EXCLUDED.description,
|
||||
sort_order = EXCLUDED.sort_order
|
||||
`)
|
||||
|
||||
// No default Staff grants — read-only monitoring is still plant-room-adjacent
|
||||
// operational data, access is admin-assigned per role via the portal (same
|
||||
// convention as hvac/wages/utilities, the other recently-added apps).
|
||||
|
||||
console.log('plant app seeded.')
|
||||
await pool.end()
|
||||
Loading…
Add table
Add a link
Reference in a new issue