From 3203577a9d0c68eb93fad2de749a00465d0fe3a9 Mon Sep 17 00:00:00 2001 From: jhartworks Date: Thu, 19 Nov 2026 13:51:04 +0100 Subject: [PATCH] feat: enhance sidebar functionality and styling - Updated sidebar component to support dynamic width based on collapsed state. - Improved sidebar icon rendering and added user account management features. - Introduced new trend chart settings component for better user interaction. - Added utility functions for engineering units and trend chart settings. - Implemented color assignment logic for trend series to enhance visual representation. - Enhanced CSS styles for better responsiveness and usability across different screen sizes. - Introduced new configuration for Vite server to allow shared directory access. - Added .dockerignore file to optimize Docker build context. --- .dockerignore | 28 + .env.example | 5 +- .gitignore | 1 - README.md | 34 +- api/Dockerfile | 7 +- api/src/db.js | 25 +- api/src/index.js | 104 +++- api/src/lib/isp.js | 112 ++-- api/src/lib/store.js | 45 +- collector/Dockerfile | 5 +- collector/src/index.js | 40 +- docker-compose.yml | 16 +- runner/Dockerfile | 7 +- runner/src/index.js | 12 +- shared/engineering-units.mjs | 49 ++ shared/trend-chart-settings.mjs | 51 ++ shared/trend-preferences.mjs | 24 + shared/trend-time.mjs | 6 + web/Dockerfile | 9 +- web/src/App.jsx | 691 +++++++++++----------- web/src/api.js | 2 + web/src/components/Sidebar.jsx | 83 +++ web/src/components/TrendChart.jsx | 352 +++++------ web/src/components/TrendChartSettings.jsx | 116 ++++ web/src/components/trend-colors.mjs | 69 +++ web/src/components/trend-scales.mjs | 73 +++ web/src/styles.css | 294 +++++++-- web/vite.config.js | 6 + 28 files changed, 1508 insertions(+), 758 deletions(-) create mode 100644 .dockerignore create mode 100644 shared/engineering-units.mjs create mode 100644 shared/trend-chart-settings.mjs create mode 100644 shared/trend-preferences.mjs create mode 100644 shared/trend-time.mjs create mode 100644 web/src/components/Sidebar.jsx create mode 100644 web/src/components/TrendChartSettings.jsx create mode 100644 web/src/components/trend-colors.mjs create mode 100644 web/src/components/trend-scales.mjs diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b802caf --- /dev/null +++ b/.dockerignore @@ -0,0 +1,28 @@ +** +!api/ +!api/package*.json +!api/src/ +!api/src/** +!collector/ +!collector/package*.json +!collector/src/ +!collector/src/** +!runner/ +!runner/package*.json +!runner/src/ +!runner/src/** +!web/ +!web/package*.json +!web/index.html +!web/vite.config.js +!web/public/ +!web/public/** +!web/src/ +!web/src/** +!shared/ +!shared/*.mjs +**/node_modules +**/dist +**/.env +**/.env.* +**/.git diff --git a/.env.example b/.env.example index 64c9c2f..f9b0b10 100644 --- a/.env.example +++ b/.env.example @@ -9,5 +9,6 @@ MARIADB_ROOT_PASSWORD=SE3112 MARIADB_PASSWORD=3112 DB_PASSWORD_FALLBACK=root REDIS_PASSWORD=replace-with-a-long-random-redis-password -CORS_ORIGIN=http://localhost:5173 -VITE_API_PORT=18080 \ No newline at end of file +CORS_ORIGIN=http://localhost:81 +LEGACY_TREND_TIME_ZONE=Europe/Berlin +VITE_API_PORT=18080 diff --git a/.gitignore b/.gitignore index 426bb6d..ba71ae4 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,4 @@ dist npm-debug.log* .scratch/runtime data/ -web/src .env diff --git a/README.md b/README.md index be03e0b..30289f2 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ SeLTD/ ```text Browser │ - │ http://localhost:5173 + │ http://localhost:81 ▼ React/Vite Frontend (web) │ @@ -115,7 +115,7 @@ Wichtig: Die API laeuft im Container intern auf Port `8080`, wird aber nach auss | Service | Container | Interner Port | Host-Port | Zweck | | --- | --- | ---: | ---: | --- | -| Web | `seltd-web` | 5173 | 5173 | React/Vite-Oberflaeche | +| Web | `seltd-web` | 5173 | 81 | React/Vite-Oberflaeche | | API | `seltd-api` | 8080 | 18080 | REST-API | | Collector | `seltd-collector` | 18110 | 18110 | Quellen, Datenpunkte, Scans, Polling | | MariaDB | `seltd-mariadb` | 3306 | 3306 | Trend- und Benutzerdaten | @@ -168,30 +168,9 @@ docker ps -a ### 3. Aufrufen Nun stehen dir mehrere Tools zur Verfügung: -<<<<<<< HEAD - -Frontend | `http://localhost:5173` +| Frontend | `http://localhost:81` | --> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends. -API Healthcheck | `http://localhost:18080/api/health` ---> hier kannst du schauen ob die API läuft - -Collector Healthcheck | `http://localhost:18110/health` ---> hier kannst du schauen ob der Collector läuft, was nur wichtig ist, wenn du Datenpunkte per OPC,KNX, Modbus oder Bacnet angebunden hast. - -Dockhand | `http://localhost:3000` ---> Dockhand ist Container verwaltungstool, dass es dir ermöglicht, auch grafisch den Zustand deiner Container und deines Stacks zu sehen. - Der Vorteil hier, im Gegensatz zur normalen Docker Desktopoberfläche: Du kannst es auf jedem beliebigen anderen Rechner, der auf dein Netzwerk zugriff hat, öffnen. - -cAdvisor | `http://localhost:9090` ---> Cadvisor stellt alle Containerdaten für Monitoring und Analyticprogramme bereit. - So kann bei einer größeren Anlage, das Dockersystem mitr Prometheus oder ähnlichem überwacht werden. - Cadvisor stellt di Daten per html bereit, kannst du dir gern anschauen, ist aber ziemlich unübersichtlich. -======= -| Frontend | `http://localhost:5173` | ---> Das ist die normale Weboberfläche zum anschauen, editieren und anpassen von Trends. ->>>>>>> c06fe1fd4df46b203002412d6d8d0362c979166c - | API Healthcheck | `http://localhost:18080/api/health` | --> hier kannst du schauen ob die API läuft @@ -230,6 +209,7 @@ Die wichtigsten Variablen liegen in `.env`. | `MARIADB_ROOT_PASSWORD` | `SE3112` | MariaDB-Root-Passwort | | `DB_PASSWORD_FALLBACK` | `root` | Fallback fuer alte Entwicklungsvolumes | | `CORS_ORIGIN` | `*` | Erlaubter Browser-Ursprung fuer API-Aufrufe | +| `LEGACY_TREND_TIME_ZONE` | `Europe/Berlin` | Zeitzone der gespeicherten Controllerzeit in Bestandstabellen mit `Wert1` usw. Fuer bereits in UTC gespeicherte Bestandsdaten `+00:00` setzen. | | `VITE_API_PORT` | `18080` | API-Port, den das Frontend im Browser nutzt | | `POLL_TICK_MS` | `1000` | Collector-Tick fuer Polling-Pruefung | @@ -538,10 +518,10 @@ docker ps curl http://localhost:18080/api/health ``` -Wenn Frontend lokal auf `localhost:5173` laeuft: +Wenn das Frontend lokal auf `localhost:81` laeuft: ```env -CORS_ORIGIN=* +CORS_ORIGIN=http://localhost:81 ``` Danach API neu starten: @@ -693,4 +673,4 @@ npm --prefix symcon-collector run check npm --prefix bacnet-collector run check npm --prefix runner run check npm --prefix web run check -``` \ No newline at end of file +``` diff --git a/api/Dockerfile b/api/Dockerfile index 9b90684..b8ade08 100644 --- a/api/Dockerfile +++ b/api/Dockerfile @@ -1,11 +1,12 @@ FROM node:22-alpine -WORKDIR /app +WORKDIR /app/api -COPY package*.json ./ +COPY api/package*.json ./ RUN npm ci -COPY src ./src +COPY api/src ./src +COPY shared /app/shared EXPOSE 8080 diff --git a/api/src/db.js b/api/src/db.js index 8a3e06a..a579def 100644 --- a/api/src/db.js +++ b/api/src/db.js @@ -1,8 +1,9 @@ import mysql from "mysql2/promise"; import { config } from "./config.js"; +import { setUtcSession } from "../../shared/trend-time.mjs"; function createPool(password) { - return mysql.createPool({ + const pool = mysql.createPool({ host: config.dbHost, port: config.dbPort, user: config.dbUser, @@ -13,7 +14,10 @@ function createPool(password) { namedPlaceholders: true, multipleStatements: true, charset: "utf8mb4", + timezone: "Z", }); + pool.on("connection", setUtcSession); + return pool; } const candidatePasswords = [...new Set([config.dbPassword, config.dbPasswordFallback].filter(Boolean))]; @@ -32,9 +36,19 @@ function delay(milliseconds) { return new Promise((resolve) => setTimeout(resolve, milliseconds)); } -async function queryWithCredentials(sql, values) { +async function execute(pool, sql, values, isolated) { + if (!isolated) return pool.query(sql, values); + const connection = await pool.getConnection(); try { - return await activePool.query(sql, values); + return await connection.query(sql); + } finally { + connection.destroy(); + } +} + +async function queryWithCredentials(sql, values, isolated) { + try { + return await execute(activePool, sql, values, isolated); } catch (error) { if (!isAccessDenied(error) || candidatePasswords.length < 2) { throw error; @@ -44,7 +58,7 @@ async function queryWithCredentials(sql, values) { if (password === activePassword) continue; const fallbackPool = createPool(password); try { - const result = await fallbackPool.query(sql, values); + const result = await execute(fallbackPool, sql, values, isolated); const previousPool = activePool; activePool = fallbackPool; activePassword = password; @@ -74,4 +88,5 @@ async function query(sql, values) { throw lastError; } -export const pool = { query }; \ No newline at end of file +export const pool = { query }; +export const importSql = (sql) => queryWithCredentials(sql, undefined, true); diff --git a/api/src/index.js b/api/src/index.js index 3956aa3..b8b9215 100644 --- a/api/src/index.js +++ b/api/src/index.js @@ -3,7 +3,10 @@ import cors from "cors"; import express from "express"; import { authenticateToken, authenticateTokenOptional, createToken, requireRoles } from "./auth.js"; import { config } from "./config.js"; -import { pool } from "./db.js"; +import { importSql, pool } from "./db.js"; +import { AUTO_UNIT } from "../../shared/engineering-units.mjs"; +import { normalizeTrendChartSettings } from "../../shared/trend-chart-settings.mjs"; +import { DEFAULT_TREND_PRESET, TREND_PRESETS } from "../../shared/trend-preferences.mjs"; import { createTrendTable, ensureIspMetadata, @@ -11,12 +14,14 @@ import { fetchLatestValues, fetchTrendSeries, getAvailableIsps, + migrateLegacyUserLevels, normalizeEngineeringUnit, normalizeRange, resolveTrendTablePointCount, sanitizeIspName, sanitizePointIndex, updateIspMetadata, + verifyLegacyTrendTimeZone, } from "./lib/isp.js"; import { deleteSelection, @@ -292,17 +297,19 @@ async function listRunnerQueue() { } }); } +async function resolveAccessibleSelection(selectionId, user) { + const selection = await getSelection(redis, selectionId); + if (!canUseSelection(selection, user)) { + throw new Error("Selection not found or not accessible."); + } + return selection; +} + async function resolveSelectionPoints(body, user) { if (body.selectionId) { - const selection = await getSelection(redis, body.selectionId); - - if (!canUseSelection(selection, user)) { - throw new Error("Selection not found or not accessible."); - } - + const selection = await resolveAccessibleSelection(body.selectionId, user); return assertPoints(selection.points || []); } - return assertPoints(body.points || []); } @@ -536,15 +543,21 @@ app.put( points.forEach((point) => { const pointIndex = sanitizePointIndex(point.pointIndex); const key = String(pointIndex); + const existing = metadata.points[key] || {}; + const alias = String(point.alias || "").trim() || existing.alias || `Wert${pointIndex}`; + const kind = point.kind === "digital" ? "digital" : "analog"; + const unit = point.unit ?? existing.unit; + const unitAuto = unit === AUTO_UNIT || !unit || (point.unit == null && existing.unitAuto === true); metadata.points[key] = { - ...metadata.points[key], - alias: String(point.alias || metadata.points[key].alias).trim() || metadata.points[key].alias, - unit: normalizeEngineeringUnit(point.unit || metadata.points[key].unit), - factor: Number.isFinite(Number(point.factor)) ? Number(point.factor) : metadata.points[key].factor, - kind: point.kind === "digital" ? "digital" : "analog", - min: Number.isFinite(Number(point.min)) ? Number(point.min) : metadata.points[key].min, - max: Number.isFinite(Number(point.max)) ? Number(point.max) : metadata.points[key].max, - color: typeof point.color === "string" ? point.color : metadata.points[key].color, + ...existing, + alias, + unit: normalizeEngineeringUnit(unitAuto ? AUTO_UNIT : unit, kind, alias), + unitAuto, + factor: Number.isFinite(Number(point.factor)) ? Number(point.factor) : (existing.factor ?? 1), + kind, + min: Number.isFinite(Number(point.min)) ? Number(point.min) : (existing.min ?? 0), + max: Number.isFinite(Number(point.max)) ? Number(point.max) : (existing.max ?? 100), + color: typeof point.color === "string" ? point.color : existing.color, }; }); } @@ -574,7 +587,7 @@ app.post("/api/units", authenticateToken, requirePermission("edit_aliases"), wra })); app.patch("/api/units/:symbol", authenticateToken, requirePermission("edit_aliases"), wrap(async (req, res) => { - const existingSymbol = decodeURIComponent(req.params.symbol || "").trim(); + const existingSymbol = String(req.params.symbol || "").trim(); if (!existingSymbol) { return res.status(400).json({ error: "Einheit fehlt." }); } @@ -632,7 +645,8 @@ app.post( throw new Error("SQL-Inhalt ist leer."); } - await pool.query(sql); + await importSql(sql); + await migrateLegacyUserLevels(pool); const isps = await getAvailableIsps(pool, config.dbName); res.json({ ok: true, importedTables: isps.length, filename: req.body.filename || null }); }) @@ -757,6 +771,7 @@ app.post("/api/selections", authenticateToken, requirePermission("view_trends"), description: String(req.body.description || "").trim(), shared: Boolean(req.body.shared), points, + chartSettings: normalizeTrendChartSettings(req.body.chartSettings, points), }); res.status(201).json({ selection }); @@ -779,9 +794,12 @@ app.put("/api/selections/:selectionId", authenticateToken, requirePermission("vi { ...existing, name: String(req.body.name || existing.name).trim(), - description: String(req.body.description || existing.description || "").trim(), + description: String(req.body.description ?? existing.description ?? "").trim(), shared: typeof req.body.shared === "boolean" ? req.body.shared : existing.shared, points, + chartSettings: normalizeTrendChartSettings( + req.body.chartSettings === undefined ? existing.chartSettings : req.body.chartSettings, points + ), }, existing.id ); @@ -804,9 +822,37 @@ app.delete("/api/selections/:selectionId", authenticateToken, requirePermission( res.status(204).send(); })); +async function getTrendDefaults() { + const stored = await redis.get("settings:trend:default-preset"); + return { defaultPresetDays: TREND_PRESETS.some(({ value }) => value === stored) ? stored : DEFAULT_TREND_PRESET }; +} + +async function getTrendDisplayOptions(user) { + const [preferences, defaults] = await Promise.all([getPreferences(redis, user?.sub), getTrendDefaults()]); + return { ...defaults, maxSeries: preferences.maxTrendSeries }; +} + +async function fetchDisplayTrend(points, range, { maxSeries, defaultPresetDays }) { + const trend = await fetchTrendSeries(pool, redis, points.slice(0, maxSeries), normalizeRange(range, defaultPresetDays)); + return { ...trend, requestedSeriesCount: points.length, maxSeries }; +} + +app.get("/api/settings/trend", wrap(async (_req, res) => { + res.json(await getTrendDefaults()); +})); + +app.put("/api/settings/trend", authenticateToken, requireRoles("admin"), wrap(async (req, res) => { + const defaultPresetDays = String(req.body?.defaultPresetDays ?? ""); + if (!TREND_PRESETS.some(({ value }) => value === defaultPresetDays)) { + return res.status(400).json({ error: "Bitte einen gültigen Standardzeitraum auswählen." }); + } + await redis.set("settings:trend:default-preset", defaultPresetDays); + res.json({ defaultPresetDays }); +})); + app.post("/api/trends/query", authenticateTokenOptional, wrap(async (req, res) => { const points = await resolveSelectionPoints(req.body, resolveViewerUser(req)); - const trendData = await fetchTrendSeries(pool, redis, points, normalizeRange(req.body.range)); + const trendData = await fetchDisplayTrend(points, req.body.range, await getTrendDisplayOptions(req.user)); res.json(trendData); })); @@ -830,13 +876,20 @@ app.post("/api/dashboard/data", authenticateTokenOptional, wrap(async (req, res) const widgets = Array.isArray(req.body.widgets) ? req.body.widgets : []; const results = []; const viewer = resolveViewerUser(req); + const trendOptions = widgets.some((widget) => widget.type === "chart") ? await getTrendDisplayOptions(req.user) : null; for (const widget of widgets) { - const points = widget.selectionId ? await resolveSelectionPoints({ selectionId: widget.selectionId }, viewer) : assertPoints(widget.points || []); + const selection = widget.selectionId ? await resolveAccessibleSelection(widget.selectionId, viewer) : null; + const points = assertPoints(selection ? selection.points : (widget.points || [])); if (widget.type === "chart") { - const trendData = await fetchTrendSeries(pool, redis, points, normalizeRange(widget.range)); - results.push({ id: widget.id, type: widget.type, ...trendData }); + const trendData = await fetchDisplayTrend(points, widget.range, trendOptions); + results.push({ + id: widget.id, + type: widget.type, + ...trendData, + ...(selection ? { chartSettings: normalizeTrendChartSettings(selection.chartSettings, points) } : {}), + }); } else { const values = await fetchLatestValues(pool, redis, points); results.push({ id: widget.id, type: widget.type, values }); @@ -870,7 +923,8 @@ app.put("/api/integrations", authenticateToken, requirePermission("manage_integr })); app.get("/api/runner/jobs", authenticateToken, requirePermission("manage_runner"), wrap(async (_req, res) => { - res.json({ jobs: await listRunnerJobs(), queue: await listRunnerQueue() }); + const [jobs, queue, integration] = await Promise.all([listRunnerJobs(), listRunnerQueue(), redis.get("integration:api")]); + res.json({ jobs, queue, mailConfigured: Boolean(JSON.parse(integration || "{}").mailApiKey) }); })); app.post("/api/runner/jobs", authenticateToken, requirePermission("manage_runner"), wrap(async (req, res) => { @@ -922,6 +976,8 @@ app.use((error, _req, res, _next) => { await ensureUtf8Database(); await ensureUserSchema(); +await verifyLegacyTrendTimeZone(pool); +await migrateLegacyUserLevels(pool); await ensureRolesSchema(); await ensureAdminUser(); diff --git a/api/src/lib/isp.js b/api/src/lib/isp.js index 88cc632..e55c9c4 100644 --- a/api/src/lib/isp.js +++ b/api/src/lib/isp.js @@ -1,4 +1,7 @@ -const META_PREFIX = "meta:isp:"; +import { AUTO_UNIT, DEFAULT_ANALOG_UNIT, resolveEngineeringUnit } from "../../../shared/engineering-units.mjs"; +import { LEGACY_DATUM_UTC, LEGACY_TREND_TIME_ZONE } from "../../../shared/trend-time.mjs"; + +const META_PREFIX = "meta:isp:"; export const LEGACY_POINT_LIMIT = 200; export const LOCAL_POINT_LIMIT = 2000; @@ -106,40 +109,18 @@ function parseHslColor(value) { }; } -function createRandomPointColor(seed) { - const hue = Math.round((seed * 47 + 17 + Math.random() * 28) % 360); - const saturation = 72 + (seed % 4) * 4; - const lightness = 45 + (seed % 3) * 4; - return hslToHex(hue, saturation, lightness); -} - -export function normalizeEngineeringUnit(value, kind = "analog") { - const normalizedKind = kind === "digital" ? "digital" : "analog"; - const raw = String(value ?? "").trim(); - if (!raw) { - return normalizedKind === "digital" ? "bool" : "\u00B0C"; - } - - if (normalizedKind === "digital" && /^(?:bool|boolean)$/i.test(raw)) { - return "bool"; - } - - if (/^\?C$/i.test(raw) || /^\u00B0\s*C$/i.test(raw) || (/[^\x00-\x7F]/.test(raw) && /C/i.test(raw))) { - return normalizedKind === "digital" ? "bool" : "\u00B0C"; - } - - return raw; -} +export const normalizeEngineeringUnit = resolveEngineeringUnit; function createDefaultPoint(index) { return { alias: `Wert${index}`, - unit: "\u00B0C", + unit: DEFAULT_ANALOG_UNIT, + unitAuto: true, factor: 1, kind: "analog", min: 0, max: 100, - color: createRandomPointColor(index), + color: "#000000", }; } @@ -174,7 +155,7 @@ export async function createLegacyWideTrendTable(pool, tableName) { CREATE TABLE IF NOT EXISTS \`${safeTable}\` ( \`id\` INT(11) NOT NULL AUTO_INCREMENT, \`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - \`userlevel\` INT(1) NOT NULL, + \`userlevel\` INT(1) NULL DEFAULT NULL, ${buildValueColumns()}, PRIMARY KEY (\`id\`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; @@ -205,6 +186,40 @@ export async function createTrendTable(pool, tableName) { return safeTable; } +export async function migrateLegacyUserLevels(pool) { + const [columns] = await pool.query(` + SELECT c.TABLE_NAME AS tableName, c.COLUMN_TYPE AS columnType, + c.COLUMN_DEFAULT AS defaultValue, c.COLUMN_COMMENT AS comment + FROM information_schema.COLUMNS c + JOIN information_schema.TABLES t + ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME + WHERE c.TABLE_SCHEMA = DATABASE() + AND c.TABLE_NAME REGEXP '^(isp[a-z0-9_]*|trend_[a-z0-9_]+)$' + AND t.TABLE_TYPE = 'BASE TABLE' + AND c.COLUMN_NAME = 'userlevel' AND c.IS_NULLABLE = 'NO' + AND EXISTS ( + SELECT 1 FROM information_schema.COLUMNS v + WHERE v.TABLE_SCHEMA = c.TABLE_SCHEMA AND v.TABLE_NAME = c.TABLE_NAME + AND v.COLUMN_NAME REGEXP '^Wert[0-9]+$' + ) + `); + for (const { tableName, columnType, defaultValue, comment } of columns) { + const table = sanitizeIspName(tableName); + if (!/^(?:tinyint|smallint|mediumint|int|bigint)(?:\(\d+\))?(?: unsigned)?(?: zerofill)?$/i.test(columnType)) { + throw new Error(`Unexpected userlevel column type in ${table}.`); + } + const defaultSql = /^-?\d+$/.test(String(defaultValue)) ? String(defaultValue) : "NULL"; + await pool.query(`ALTER TABLE \`${table}\` MODIFY COLUMN \`userlevel\` ${columnType} NULL DEFAULT ${defaultSql} COMMENT ?`, [comment]); + } +} + +export async function verifyLegacyTrendTimeZone(pool) { + const [[row]] = await pool.query("SELECT CONVERT_TZ('2026-01-01 12:00:00', ?, '+00:00') AS converted", [LEGACY_TREND_TIME_ZONE]); + if (!row.converted) { + throw new Error(`MariaDB cannot resolve LEGACY_TREND_TIME_ZONE=${LEGACY_TREND_TIME_ZONE}. Check its time zone tables.`); + } +} + async function loadSourcePointSeeds(pool, tableName) { const safeTable = sanitizeIspName(tableName); @@ -275,7 +290,10 @@ async function describeTrendTable(pool, dbName, tableName) { const widePointCount = columnNames.filter((name) => /^Wert\d+$/i.test(name)).length; if (widePointCount > 0) { - const [rows] = await pool.query(`SELECT COUNT(*) AS rowCount, MAX(datum) AS latestTimestamp FROM \`${safeTable}\``); + const [rows] = await pool.query( + `SELECT COUNT(*) AS rowCount, CONVERT_TZ(MAX(datum), ?, '+00:00') AS latestTimestamp FROM \`${safeTable}\``, + [LEGACY_TREND_TIME_ZONE] + ); return { tableName: safeTable, storage: "wide", @@ -393,7 +411,8 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO parsed.points[pointKey] = { ...defaultPoint, alias: initialAlias, - unit: normalizeEngineeringUnit(sourceSeed?.unit || defaultPoint.unit, sourceSeed?.kind || defaultPoint.kind), + unit: normalizeEngineeringUnit(sourceSeed?.unit, sourceSeed?.kind || defaultPoint.kind, initialAlias), + unitAuto: !sourceSeed?.unit, kind: sourceSeed?.kind || defaultPoint.kind, }; changed = true; @@ -412,18 +431,16 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO point.kind = sourceSeed.kind; changed = true; } - const normalizedUnit = normalizeEngineeringUnit(point.unit, point.kind || sourceSeed?.kind || defaultPoint.kind); + const kind = point.kind || sourceSeed?.kind || defaultPoint.kind; + const normalizedUnit = normalizeEngineeringUnit( + point.unitAuto === true ? AUTO_UNIT : (point.unit || sourceSeed?.unit), + kind, + point.alias + ); if (normalizedUnit !== point.unit) { point.unit = normalizedUnit; changed = true; } - if ((!point.unit || point.unit === normalizeEngineeringUnit(defaultPoint.unit, defaultPoint.kind)) && sourceSeed?.unit) { - const seededUnit = normalizeEngineeringUnit(sourceSeed.unit, sourceSeed.kind || point.kind || defaultPoint.kind); - if (point.unit !== seededUnit) { - point.unit = seededUnit; - changed = true; - } - } if (!point.kind) { point.kind = sourceSeed?.kind || defaultPoint.kind; changed = true; @@ -468,7 +485,8 @@ export async function ensureIspMetadata(pool, redis, isp, pointCount = LEGACY_PO metadata.points[pointKey] = { ...metadata.points[pointKey], alias: sourceSeed.alias || sourceSeed.name || metadata.points[pointKey].alias, - unit: normalizeEngineeringUnit(sourceSeed.unit || metadata.points[pointKey].unit, sourceSeed.kind || metadata.points[pointKey].kind), + unit: normalizeEngineeringUnit(sourceSeed.unit, sourceSeed.kind, sourceSeed.alias || sourceSeed.name), + unitAuto: !sourceSeed.unit, kind: sourceSeed.kind || metadata.points[pointKey].kind, }; }); @@ -581,8 +599,11 @@ export async function fetchTrendSeries(pool, redis, points, range) { const limit = range.maxRows || 4000; const [rows] = await pool.query( - `SELECT datum, ${columns} FROM \`${isp}\` WHERE datum BETWEEN ? AND ? ORDER BY datum DESC LIMIT ?`, - [range.from, range.to, limit] + `SELECT ${LEGACY_DATUM_UTC} AS datum, ${columns} FROM \`${isp}\` + WHERE datum BETWEEN DATE_SUB(?, INTERVAL 1 DAY) AND DATE_ADD(?, INTERVAL 1 DAY) + AND ${LEGACY_DATUM_UTC} BETWEEN ? AND ? + ORDER BY \`${isp}\`.datum DESC LIMIT ?`, + [LEGACY_TREND_TIME_ZONE, range.from, range.to, LEGACY_TREND_TIME_ZONE, range.from, range.to, limit] ); rows.reverse().forEach((row) => { @@ -673,7 +694,10 @@ export async function fetchLatestValues(pool, redis, points) { .map((descriptor) => `\`Wert${descriptor.pointIndex}\``) .join(", "); - const [rows] = await pool.query(`SELECT datum, ${columns} FROM \`${isp}\` ORDER BY datum DESC LIMIT 1`); + const [rows] = await pool.query( + `SELECT ${LEGACY_DATUM_UTC} AS datum, ${columns} FROM \`${isp}\` ORDER BY \`${isp}\`.datum DESC LIMIT 1`, + [LEGACY_TREND_TIME_ZONE] + ); const row = rows[0]; pointDescriptors.forEach((descriptor) => { @@ -690,8 +714,8 @@ export async function fetchLatestValues(pool, redis, points) { return values; } -export function normalizeRange(input = {}) { - const presetDays = Number(input.presetDays || 1); +export function normalizeRange(input = {}, defaultPresetDays = 1) { + const presetDays = Number(input.presetDays || defaultPresetDays); const maxRows = Number(input.maxRows || 4000); const now = new Date(); const to = input.to ? new Date(input.to) : now; diff --git a/api/src/lib/store.js b/api/src/lib/store.js index 54a6524..440c825 100644 --- a/api/src/lib/store.js +++ b/api/src/lib/store.js @@ -1,4 +1,7 @@ const SELECTION_SET_KEY = "selection:ids"; +import { DEFAULT_UNITS as DEFAULT_UNIT_DEFINITIONS, normalizeUnitSymbol as canonicalUnitSymbol } from "../../../shared/engineering-units.mjs"; +import { DEFAULT_MAX_TREND_SERIES, normalizeMaxTrendSeries } from "../../../shared/trend-preferences.mjs"; + const SELECTION_SEQ_KEY = "selection:seq"; const ROLE_SET_KEY = "role:names"; const UNIT_SET_KEY = "unit:symbols"; @@ -24,33 +27,12 @@ export const DEFAULT_ROLE_DEFINITIONS = [ }, ]; -export const DEFAULT_UNIT_DEFINITIONS = [ - { symbol: "\u00B0C", label: "Grad Celsius", isSystem: true }, - { symbol: "%", label: "Prozent", isSystem: true }, - { symbol: "K", label: "Kelvin", isSystem: true }, - { symbol: "V", label: "Volt", isSystem: true }, - { symbol: "A", label: "Ampere", isSystem: true }, - { symbol: "Pa", label: "Pascal", isSystem: true }, - { symbol: "bool", label: "Digital / Bool", isSystem: true }, -]; - function safeParse(jsonValue) { return jsonValue ? JSON.parse(jsonValue) : null; } function normalizeUnitSymbol(value, fallback = "") { - const raw = String(value ?? "").trim(); - const collapsed = raw.replace(/\s+/g, ""); - - if (!collapsed) { - return fallback; - } - - if (/^\?C$/i.test(collapsed) || /^Â?\u00B0C$/i.test(collapsed)) { - return "\u00B0C"; - } - - return raw; + return canonicalUnitSymbol(value) || fallback; } function unitStorageKey(symbol) { @@ -179,11 +161,14 @@ export async function listUnits(redis) { const symbols = await redis.smembers(UNIT_SET_KEY); const items = await Promise.all(symbols.map((symbol) => redis.get(unitStorageKey(symbol)))); - return items - .map((item) => safeParse(item)) - .filter(Boolean) - .map((unit) => normalizeUnitRecord(unit)) - .sort((left, right) => left.symbol.localeCompare(right.symbol, "de-DE")); + const units = new Map(); + for (const item of items) { + const record = safeParse(item); + if (!record) continue; + const unit = normalizeUnitRecord(record); + if (!units.has(unit.symbol) || record.symbol === unit.symbol) units.set(unit.symbol, unit); + } + return [...units.values()].sort((left, right) => left.symbol.localeCompare(right.symbol, "de-DE")); } export async function saveUnit(redis, unit, previousSymbol = "") { @@ -264,11 +249,14 @@ export async function saveDashboard(redis, userId, dashboard) { } export async function getPreferences(redis, userId) { - return safeParse(await redis.get(`preferences:${userId}`)) || { + const stored = userId == null ? null : safeParse(await redis.get(`preferences:${userId}`)); + return { theme: "system", csvDelimiter: ";", sidebarPinned: true, trendLineWidth: 1.8, + ...stored, + maxTrendSeries: normalizeMaxTrendSeries(stored?.maxTrendSeries, DEFAULT_MAX_TREND_SERIES), }; } @@ -281,6 +269,7 @@ export async function savePreferences(redis, userId, preferences) { csvDelimiter: preferences.csvDelimiter || current.csvDelimiter || ";", sidebarPinned: typeof preferences.sidebarPinned === "boolean" ? preferences.sidebarPinned : current.sidebarPinned, trendLineWidth: Number.isFinite(Number(preferences.trendLineWidth)) ? Number(preferences.trendLineWidth) : Number(current.trendLineWidth || 1.8), + maxTrendSeries: normalizeMaxTrendSeries(preferences.maxTrendSeries, current.maxTrendSeries), updatedAt: new Date().toISOString(), }; await redis.set(`preferences:${userId}`, JSON.stringify(payload)); diff --git a/collector/Dockerfile b/collector/Dockerfile index 9a868eb..d6d869a 100644 --- a/collector/Dockerfile +++ b/collector/Dockerfile @@ -2,10 +2,11 @@ FROM node:22-alpine WORKDIR /app -COPY package*.json ./ +COPY collector/package*.json ./ RUN npm ci -COPY src ./src +COPY collector/src ./src +COPY shared /shared RUN mkdir -p /app/data EXPOSE 18110 diff --git a/collector/src/index.js b/collector/src/index.js index c02e343..8d6b9bb 100644 --- a/collector/src/index.js +++ b/collector/src/index.js @@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url"; import { Buffer } from "node:buffer"; import net from "node:net"; import mysql from "mysql2/promise"; +import { resolveEngineeringUnit } from "../../shared/engineering-units.mjs"; const __dirname = dirname(fileURLToPath(import.meta.url)); const dataDir = join(__dirname, "..", "data"); @@ -192,27 +193,8 @@ function normalizeText(value) { return repairText(String(value === undefined || value === null ? "" : value).trim()); } -function normalizeUnit(value) { - const raw = normalizeText(value); - const collapsed = raw.replace(/\s+/g, ""); - if (!collapsed) { - return "°C"; - } - - if (/^(?:\?C|\u00B0C)$/i.test(collapsed)) { - return "°C"; - } - - return raw; -} - -function normalizePointUnit(value, kind = "analog") { - const normalizedKind = normalizePointKind(kind); - const raw = normalizeText(value); - if (!raw) { - return normalizedKind === "digital" ? "bool" : "°C"; - } - return normalizeUnit(raw); +function normalizePointUnit(value, kind, name) { + return resolveEngineeringUnit(normalizeText(value), normalizePointKind(kind), name); } function normalizePointIndex(value, fallback) { @@ -308,7 +290,7 @@ function parseModbusCsv(payload) { pointIndex, name: normalizeText(get("name", `Register ${index + 1}`)) || `Register ${index + 1}`, alias: normalizeText(get("alias", get("name", `Register ${index + 1}`))) || normalizeText(get("name", `Register ${index + 1}`)) || `Register ${index + 1}`, - unit: normalizePointUnit(get("unit"), get("kind", get("type", "analog"))), + unit: normalizePointUnit(get("unit"), get("kind", get("type", "analog")), get("alias", get("name"))), dataType: get("datatype", "holding-register"), kind: normalizePointKind(get("kind", get("type", "analog"))), enabled: payload.enabled === true, @@ -361,7 +343,7 @@ function parseKnxXml(payload) { pointIndex: index + 1, name, alias: name, - unit: normalizePointUnit("", dpt.startsWith("1.") ? "digital" : "analog"), + unit: normalizePointUnit("", dpt.startsWith("1.") ? "digital" : "analog", name), dataType: dpt || "group-address", kind: dpt.startsWith("1.") ? "digital" : "analog", enabled: payload.enabled === true, @@ -401,7 +383,7 @@ function createManualDatapoint(store, payload) { pointIndex, name, alias, - unit: normalizePointUnit(payload.unit, payload.kind), + unit: normalizePointUnit(payload.unit, payload.kind, alias), kind: normalizePointKind(payload.kind), enabled: payload.enabled !== false, alarmEnabled: payload.alarmEnabled === true, @@ -438,7 +420,7 @@ function createScanDatapoint(source, payload, index) { pointIndex, name: normalizeText(payload.name || alias) || alias, alias, - unit: normalizePointUnit(payload.unit, payload.kind), + unit: normalizePointUnit(payload.unit, payload.kind, alias), kind: normalizePointKind(payload.kind), enabled: payload.enabled === true, alarmEnabled: payload.alarmEnabled === true, @@ -936,7 +918,7 @@ function mapIpsymconVariable(source, variable, categoryId, index) { nodeId: String(variableId), dataType: variableType ? `ipsymcon-${variableType}` : "ipsymcon-variable", kind, - unit: normalizePointUnit(variable?.unit, kind), + unit: normalizePointUnit(variable?.unit, kind, name), currentValue: variable?.value ?? null, quality: normalizeText(variable?.quality || "unknown"), path: normalizeText(variable?.actual_path || ""), @@ -1744,7 +1726,7 @@ async function ensureTrendTable(tableName) { CREATE TABLE IF NOT EXISTS \`${table}\` ( \`id\` INT(11) NOT NULL AUTO_INCREMENT, \`datum\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - \`userlevel\` INT(1) NOT NULL, + \`userlevel\` INT(1) NULL DEFAULT NULL, ${buildValueColumns()}, PRIMARY KEY (\`id\`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci @@ -1898,7 +1880,7 @@ async function syncDatapointRegistryEntries(datapoints) { normalizeText(datapoint.alias || datapoint.name || `Wert${datapoint.pointIndex}`), normalizeText(datapoint.name || datapoint.alias || `Wert${datapoint.pointIndex}`), String(datapoint.protocol || "unknown"), - normalizeUnit(datapoint.unit || ""), + normalizePointUnit(datapoint.unit, datapoint.kind, datapoint.alias || datapoint.name), String(datapoint.kind || "analog"), datapoint.enabled === true ? 1 : 0, datapoint.alarmEnabled === true ? 1 : 0, @@ -2359,7 +2341,7 @@ const server = createServer(async (req, res) => { address: typeof body.address === "string" ? normalizeText(body.address) : store.datapoints[index].address, nodeId: typeof body.nodeId === "string" ? normalizeText(body.nodeId) : store.datapoints[index].nodeId, dataType: typeof body.dataType === "string" && body.dataType.trim() ? normalizeText(body.dataType) : store.datapoints[index].dataType, - unit: body.unit ? normalizePointUnit(body.unit, body.kind || store.datapoints[index].kind) : store.datapoints[index].unit, + unit: body.unit != null ? normalizePointUnit(body.unit, body.kind || store.datapoints[index].kind, body.alias || body.name || store.datapoints[index].alias) : store.datapoints[index].unit, kind: body.kind ? normalizePointKind(body.kind) : store.datapoints[index].kind, scale: Number.isFinite(Number(body.scale)) ? Number(body.scale) : store.datapoints[index].scale, }; diff --git a/docker-compose.yml b/docker-compose.yml index 57ce38d..a363535 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -38,7 +38,8 @@ services: api: build: - context: ./api + context: . + dockerfile: api/Dockerfile container_name: seltd-api restart: unless-stopped environment: @@ -49,6 +50,7 @@ services: DB_USER: root DB_PASSWORD: ${MARIADB_ROOT_PASSWORD:-SE3112} DB_PASSWORD_FALLBACK: ${DB_PASSWORD_FALLBACK:-root} + LEGACY_TREND_TIME_ZONE: ${LEGACY_TREND_TIME_ZONE:-Europe/Berlin} REDIS_URL: redis://:${REDIS_PASSWORD:?Set REDIS_PASSWORD in .env}@redis:6379/0 JWT_SECRET: ${JWT_SECRET:-change-me} ADMIN_USERNAME: ${ADMIN_USERNAME:-admin} @@ -71,13 +73,14 @@ services: web: build: - context: ./web + context: . + dockerfile: web/Dockerfile container_name: seltd-web restart: unless-stopped environment: VITE_API_PORT: ${VITE_API_PORT:-18080} ports: - - "5173:5173" + - "81:5173" depends_on: api: condition: service_healthy @@ -89,7 +92,8 @@ services: collector: build: - context: ./collector + context: . + dockerfile: collector/Dockerfile container_name: seltd-collector restart: unless-stopped environment: @@ -160,7 +164,8 @@ services: runner: build: - context: ./runner + context: . + dockerfile: runner/Dockerfile container_name: seltd-runner restart: unless-stopped environment: @@ -173,6 +178,7 @@ services: EXPORT_DIR: /exports RUNNER_TICK_MS: ${RUNNER_TICK_MS:-1000} RUNNER_TIMEZONE: ${RUNNER_TIMEZONE:-Europe/Berlin} + LEGACY_TREND_TIME_ZONE: ${LEGACY_TREND_TIME_ZONE:-Europe/Berlin} volumes: - runner_exports:/exports depends_on: diff --git a/runner/Dockerfile b/runner/Dockerfile index 2ae2592..e1437ea 100644 --- a/runner/Dockerfile +++ b/runner/Dockerfile @@ -1,7 +1,8 @@ FROM node:22-alpine -WORKDIR /app -COPY package*.json ./ +WORKDIR /app/runner +COPY runner/package*.json ./ RUN npm install -COPY src ./src +COPY runner/src ./src +COPY shared /app/shared RUN mkdir -p /exports CMD ["npm", "start"] diff --git a/runner/src/index.js b/runner/src/index.js index aa31a45..529fc46 100644 --- a/runner/src/index.js +++ b/runner/src/index.js @@ -5,6 +5,8 @@ import https from "node:https"; import path from "node:path"; import Redis from "ioredis"; import mysql from "mysql2/promise"; +import { LEGACY_DATUM_UTC, LEGACY_TREND_TIME_ZONE, setUtcSession } from "../../shared/trend-time.mjs"; +import { normalizeUnitSymbol } from "../../shared/engineering-units.mjs"; const redis = new Redis(process.env.REDIS_URL || "redis://redis:6379", { maxRetriesPerRequest: 2 }); const db = mysql.createPool({ @@ -14,9 +16,11 @@ const db = mysql.createPool({ user: process.env.DB_USER || "root", password: process.env.DB_PASSWORD || "SE3112", charset: "utf8mb4", + timezone: "Z", waitForConnections: true, connectionLimit: 3, }); +db.on("connection", setUtcSession); const exportDir = process.env.EXPORT_DIR || "/exports"; const tickMs = Math.max(500, Number(process.env.RUNNER_TICK_MS || 1000)); const timeZone = process.env.RUNNER_TIMEZONE || "Europe/Berlin"; @@ -87,7 +91,7 @@ async function getPointMeta(isp, pointIndex) { const point = Array.isArray(points) ? points.find((item) => Number(item.pointIndex) === Number(pointIndex)) : points[String(pointIndex)] || points[Number(pointIndex)]; - return { alias: point?.alias || `Wert${pointIndex}`, unit: point?.unit || "" }; + return { alias: point?.alias || `Wert${pointIndex}`, unit: normalizeUnitSymbol(point?.unit) }; } async function exportSelection(job, selection) { @@ -113,8 +117,10 @@ async function exportSelection(job, selection) { } else { const column = `Wert${pointIndex}`; const [data] = await db.query( - `SELECT datum, \`${column}\` AS value FROM \`${table}\` WHERE datum >= ? ORDER BY datum ASC`, - [since], + `SELECT ${LEGACY_DATUM_UTC} AS datum, \`${column}\` AS value FROM \`${table}\` + WHERE datum >= DATE_SUB(?, INTERVAL 1 DAY) AND ${LEGACY_DATUM_UTC} >= ? + ORDER BY \`${table}\`.datum ASC`, + [LEGACY_TREND_TIME_ZONE, since, LEGACY_TREND_TIME_ZONE, since], ); for (const item of data) { const value = formatExportValue(item.value); diff --git a/shared/engineering-units.mjs b/shared/engineering-units.mjs new file mode 100644 index 0000000..d07d5b8 --- /dev/null +++ b/shared/engineering-units.mjs @@ -0,0 +1,49 @@ +export const AUTO_UNIT = "__auto__"; +export const DEFAULT_ANALOG_UNIT = "\u00B0C"; +export const DIGITAL_UNIT = "Digital"; + +export const DEFAULT_UNITS = [ + [DEFAULT_ANALOG_UNIT, "Grad Celsius"], + ["%", "Prozent"], + ["K", "Kelvin"], + ["V", "Volt"], + ["A", "Ampere"], + ["Pa", "Pascal"], + [DIGITAL_UNIT, "Digital"], + ["ppm", "Parts per million"], + ["%RH", "Relative Feuchte"], + ["COV", "COV"], + ["mBar", "Millibar"], + ["Bar", "Bar"], + ["kW", "Kilowatt"], + ["kWh", "Kilowattstunden"], + ["Liter", "Liter"], + ["m\u00B3", "Kubikmeter"], +].map(([symbol, label]) => ({ symbol, label, isSystem: true })); + +export function normalizeUnitSymbol(value) { + const symbol = String(value ?? "").trim(); + if (/^(?:bool|boolean|digital)$/i.test(symbol)) return DIGITAL_UNIT; + if (/^(?:\?C|\u00C2*\u00B0\s*C)$/i.test(symbol)) return DEFAULT_ANALOG_UNIT; + if (/^%\s*rh$/i.test(symbol)) return "%RH"; + if (/^m(?:\^?3|\u00B3)$/i.test(symbol)) return "m\u00B3"; + return DEFAULT_UNITS.find((unit) => unit.symbol.toLowerCase() === symbol.toLowerCase())?.symbol ?? symbol; +} + +export function detectEngineeringUnit(name, kind) { + if (kind === "digital") return DIGITAL_UNIT; + const label = String(name ?? "").toLowerCase(); + if (/co[2\u2082]/.test(label)) return "ppm"; + if (/feucht|humidity/.test(label)) return "%RH"; + if (/energie|energy|kwh/.test(label)) return "kWh"; + if (/leistung|power/.test(label)) return "kW"; + if (/druck|pressure/.test(label)) return /m\s*bar|millibar/.test(label) ? "mBar" : "Pa"; + if (/temp|f(?:\u00FC|ue)hler/.test(label)) return DEFAULT_ANALOG_UNIT; + return ""; +} + +export function resolveEngineeringUnit(value, kind, name) { + const unit = normalizeUnitSymbol(value); + if (unit && unit !== AUTO_UNIT) return unit; + return detectEngineeringUnit(name, kind) || DEFAULT_ANALOG_UNIT; +} diff --git a/shared/trend-chart-settings.mjs b/shared/trend-chart-settings.mjs new file mode 100644 index 0000000..083d3e1 --- /dev/null +++ b/shared/trend-chart-settings.mjs @@ -0,0 +1,51 @@ +export const CHART_DIVISIONS = [3, 4, 6, 8, 10]; + +export const DEFAULT_CHART_SETTINGS = { + divisions: 6, + grid: "both", + gridStyle: "dashed", + shadedBands: false, + opacity: 100, + highContrast: false, + axes: {}, + assignments: {}, +}; + +function entries(value) { + return value && typeof value === "object" && !Array.isArray(value) ? Object.entries(value) : []; +} + +function numericBound(value) { + if (typeof value === "number" && Number.isFinite(value)) return value; + if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) return Number(value); + return ""; +} + +export function normalizeTrendChartSettings(input, points) { + const settings = input || {}; + const pointKeys = points && new Set(points.map((point) => `${point.isp}:${point.pointIndex}`)); + const axes = Object.fromEntries(entries(settings.axes) + .filter(([id, axis]) => axis && typeof axis === "object" && ( + (id.startsWith("unit:") && id.length <= 261) + || (id.startsWith("point:") && (!pointKeys || pointKeys.has(id.slice(6)))) + )) + .map(([id, axis]) => [id, { + ...(axis.side === "left" || axis.side === "right" ? { side: axis.side } : {}), + mode: axis.mode === "manual" ? "manual" : "auto", + min: numericBound(axis.min), + max: numericBound(axis.max), + }])); + const assignments = Object.fromEntries(entries(settings.assignments) + .filter(([key, value]) => value === "own" && (!pointKeys || pointKeys.has(key)))); + + return { + divisions: CHART_DIVISIONS.includes(settings.divisions) ? settings.divisions : DEFAULT_CHART_SETTINGS.divisions, + grid: ["both", "horizontal", "vertical", "none"].includes(settings.grid) ? settings.grid : DEFAULT_CHART_SETTINGS.grid, + gridStyle: settings.gridStyle === "solid" ? "solid" : DEFAULT_CHART_SETTINGS.gridStyle, + shadedBands: settings.shadedBands === true, + opacity: Number.isFinite(settings.opacity) ? Math.max(20, Math.min(100, settings.opacity)) : DEFAULT_CHART_SETTINGS.opacity, + highContrast: settings.highContrast === true, + axes, + assignments, + }; +} diff --git a/shared/trend-preferences.mjs b/shared/trend-preferences.mjs new file mode 100644 index 0000000..aa42366 --- /dev/null +++ b/shared/trend-preferences.mjs @@ -0,0 +1,24 @@ +export const DEFAULT_TREND_PRESET = "1"; +export const DEFAULT_MAX_TREND_SERIES = 10; +export const MAX_TREND_SERIES = 100; + +export const TREND_PRESETS = [ + { value: "0.0034722222", label: "5 min" }, + { value: "0.0069444444", label: "10 min" }, + { value: "0.0208333333", label: "30 min" }, + { value: "0.0416666667", label: "1 h" }, + { value: "0.0833333333", label: "2 h" }, + { value: "0.25", label: "6 h" }, + { value: "0.5", label: "12 h" }, + { value: "1", label: "24 h" }, + { value: "2", label: "2 Tage" }, + { value: "3", label: "3 Tage" }, + { value: "7", label: "7 Tage" }, + { value: "14", label: "14 Tage" }, + { value: "30", label: "30 Tage" }, +]; + +export function normalizeMaxTrendSeries(value, fallback = DEFAULT_MAX_TREND_SERIES) { + const count = Number(value); + return Number.isInteger(count) && count >= 1 && count <= MAX_TREND_SERIES ? count : fallback; +} diff --git a/shared/trend-time.mjs b/shared/trend-time.mjs new file mode 100644 index 0000000..bb47283 --- /dev/null +++ b/shared/trend-time.mjs @@ -0,0 +1,6 @@ +export const LEGACY_TREND_TIME_ZONE = process.env.LEGACY_TREND_TIME_ZONE || "Europe/Berlin"; +export const LEGACY_DATUM_UTC = "CONVERT_TZ(datum, ?, '+00:00')"; + +export function setUtcSession(connection) { + connection.query("SET time_zone = '+00:00'"); +} diff --git a/web/Dockerfile b/web/Dockerfile index 2e02921..930f1fe 100644 --- a/web/Dockerfile +++ b/web/Dockerfile @@ -1,11 +1,14 @@ FROM node:22-alpine -WORKDIR /app +WORKDIR /app/web -COPY package*.json ./ +COPY web/package*.json ./ RUN npm ci -COPY . . +COPY web/index.html web/vite.config.js ./ +COPY web/src ./src +COPY web/public ./public +COPY shared /app/shared EXPOSE 5173 diff --git a/web/src/App.jsx b/web/src/App.jsx index a1beb06..8818afb 100644 --- a/web/src/App.jsx +++ b/web/src/App.jsx @@ -1,16 +1,36 @@ -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { api } from "./api.js"; import Gauge from "./components/Gauge.jsx"; import TrendChart from "./components/TrendChart.jsx"; +import Sidebar, { SmallFootnote } from "./components/Sidebar.jsx"; +import { AUTO_UNIT, DEFAULT_UNITS as DEFAULT_UNIT_OPTIONS, DIGITAL_UNIT, normalizeUnitSymbol, resolveEngineeringUnit } from "../../shared/engineering-units.mjs"; +import { DEFAULT_CHART_SETTINGS, normalizeTrendChartSettings } from "../../shared/trend-chart-settings.mjs"; +import { + DEFAULT_MAX_TREND_SERIES, + DEFAULT_TREND_PRESET, + MAX_TREND_SERIES, + TREND_PRESETS as TREND_PRESET_OPTIONS, + normalizeMaxTrendSeries, +} from "../../shared/trend-preferences.mjs"; const views = [ - { id: "dashboard", label: "Dashboard", short: "D" }, - { id: "trends", label: "Trend", short: "T" }, - { id: "admin", label: "Admin", short: "A" }, - { id: "settings", label: "Einstellungen", short: "E" }, + { id: "dashboard", label: "Dashboard" }, + { id: "trends", label: "Trend" }, + { id: "admin", label: "Admin" }, + { id: "settings", label: "Einstellungen" }, ]; +const CHART_DRAFT_KEY = "seltd:trend-chart"; + +function loadChartDraft() { + try { + return normalizeTrendChartSettings(JSON.parse(localStorage.getItem(CHART_DRAFT_KEY))); + } catch { + return DEFAULT_CHART_SETTINGS; + } +} + const adminSections = [ { id: "aliases", label: "Aliase" }, { id: "units", label: "Einheiten" }, @@ -23,22 +43,6 @@ const adminSections = [ { id: "debug", label: "Debug" }, ]; -const TREND_PRESET_OPTIONS = [ - { value: "0.0034722222", label: "5 min" }, - { value: "0.0069444444", label: "10 min" }, - { value: "0.0208333333", label: "30 min" }, - { value: "0.0416666667", label: "1 h" }, - { value: "0.0833333333", label: "2 h" }, - { value: "0.25", label: "6 h" }, - { value: "0.5", label: "12 h" }, - { value: "1", label: "24 h" }, - { value: "2", label: "2 Tage" }, - { value: "3", label: "3 Tage" }, - { value: "7", label: "7 Tage" }, - { value: "14", label: "14 Tage" }, - { value: "30", label: "30 Tage" }, -]; - const SCALE_PRESET_OPTIONS = ["1", "0.1", "0.01", "0.001", "10", "100", "1000"]; const MODBUS_DATA_TYPE_OPTIONS = [ @@ -59,7 +63,7 @@ const MODBUS_DATA_TYPE_OPTIONS = [ ]; const emptyTrendRange = { - presetDays: "1", + presetDays: "", from: "", to: "", maxRows: 20000, @@ -76,7 +80,7 @@ const defaultWidgetDraft = { type: "chart", source: "manual", selectionId: "", - rangePresetDays: 1, + rangePresetDays: "", min: 0, max: 100, }; @@ -94,29 +98,6 @@ const PERMISSION_OPTIONS = [ { id: "manage_runner", label: "CSV-Runner verwalten" }, ]; -const pointColors = [ - "#d62839", - "#2563eb", - "#ef4444", - "#1d4ed8", - "#f97316", - "#0f766e", - "#b91c1c", - "#1e40af", - "#dc2626", - "#0891b2", -]; - -const DEFAULT_UNIT_OPTIONS = [ - { symbol: "°C", label: "Grad Celsius", isSystem: true }, - { symbol: "%", label: "Prozent", isSystem: true }, - { symbol: "K", label: "Kelvin", isSystem: true }, - { symbol: "V", label: "Volt", isSystem: true }, - { symbol: "A", label: "Ampere", isSystem: true }, - { symbol: "Pa", label: "Pascal", isSystem: true }, - { symbol: "bool", label: "Digital / Bool", isSystem: true }, -]; -const UNIT_PRESETS = DEFAULT_UNIT_OPTIONS.map((unit) => unit.symbol); const CUSTOM_UNIT_VALUE = "__custom__"; const PROTOCOL_DEFAULT_PORTS = { "modbus-tcp": "502", @@ -178,8 +159,10 @@ function getDefaultPointDataType(protocol) { return "holding-register"; } -function getDefaultUnitForKind(kind) { - return kind === "digital" ? "bool" : "°C"; +function unitForChangedKind(unit, kind) { + if (unit === AUTO_UNIT) return unit; + if (kind === "digital") return DIGITAL_UNIT; + return normalizeUnitSymbol(unit) === DIGITAL_UNIT ? AUTO_UNIT : unit; } function getPointDataTypeOptions(protocol) { @@ -256,7 +239,7 @@ function normalizeDisplayUnit(value) { if (!collapsed || /^\?C$/i.test(collapsed) || /^Â?°C$/i.test(collapsed) || (/[ÃÂ�]/.test(nextValue) && /(?:°|\?|C)/i.test(nextValue))) { return "°C"; } - return nextValue; + return normalizeUnitSymbol(nextValue); } function formatCollectorValue(value) { @@ -393,7 +376,7 @@ function buildAliasCsv(aliasEditor) { const rows = getOrderedPointEntries(aliasEditor).map((point) => [ point.pointIndex, point.alias, - point.unit, + resolveEngineeringUnit(point.unitAuto ? AUTO_UNIT : point.unit, point.kind, point.alias), point.factor, point.kind, point.min, @@ -416,29 +399,6 @@ function matchesSearch(filterText, values) { return values.some((value) => normalizeDisplayText(value).toLowerCase().includes(search)); } -function hashString(value) { - return String(value) - .split("") - .reduce((sum, char) => sum + char.charCodeAt(0), 0); -} - -function resolvePointColor(point, metadataCache) { - const color = metadataCache[point.isp]?.points?.[String(point.pointIndex)]?.color; - if (color) { - return color; - } - - const key = `${point.isp}:${point.pointIndex}`; - return pointColors[hashString(key) % pointColors.length]; -} - -function resolveLatestColor(value) { - if (value.color) { - return value.color; - } - return pointColors[hashString(value.key) % pointColors.length]; -} - function getUserDisplayName(currentUser) { if (!currentUser) { return ""; @@ -453,20 +413,16 @@ function getUserDisplayName(currentUser) { return name.toLowerCase() === username.toLowerCase() ? name : `${name} · @${username}`; } -function SmallFootnote() { - return
by J.H. | SE Inno GmbH
; -} - -function UnitField({ units, value, onChange }) { +function UnitField({ units, value, onChange, alias, kind }) { const options = units?.length ? units : DEFAULT_UNIT_OPTIONS; const normalizedOptions = options.map((unit) => ({ ...unit, symbol: normalizeDisplayUnit(unit.symbol), label: normalizeDisplayText(unit.label || unit.symbol, normalizeDisplayUnit(unit.symbol)), })); - const normalizedValue = normalizeDisplayUnit(value || "\u00B0C"); + const normalizedValue = value ? normalizeDisplayUnit(value) : ""; const hasPresetMatch = normalizedOptions.some((unit) => unit.symbol === normalizedValue); - const selectedValue = hasPresetMatch ? normalizedValue : CUSTOM_UNIT_VALUE; + const selectedValue = value === AUTO_UNIT || hasPresetMatch ? normalizedValue : CUSTOM_UNIT_VALUE; return (
@@ -475,13 +431,14 @@ function UnitField({ units, value, onChange }) { onChange={(event) => { const nextValue = event.target.value; if (nextValue === CUSTOM_UNIT_VALUE) { - onChange(hasPresetMatch ? "" : normalizedValue); + onChange(selectedValue === CUSTOM_UNIT_VALUE ? normalizedValue : ""); return; } onChange(nextValue); }} > - {normalizedOptions.map((unit) => )} + + {normalizedOptions.map((unit) => )} {selectedValue === CUSTOM_UNIT_VALUE ? ( @@ -520,12 +477,14 @@ function ScaleField({ value, onChange }) { function ColorField({ value, onChange }) { const normalizedValue = hslToHexString(value || ""); - const pickerValue = /^#(?:[0-9a-fA-F]{3}){1,2}$/.test(normalizedValue || "") ? normalizedValue : "#d62839"; + const pickerValue = /^#[0-9a-f]{6}$/i.test(normalizedValue) ? normalizedValue + : /^#[0-9a-f]{3}$/i.test(normalizedValue) ? "#" + [...normalizedValue.slice(1)].map((digit) => digit.repeat(2)).join("") + : "#000000"; return (
- onChange(event.target.value)} /> - onChange(event.target.value)} /> + onChange(event.target.value)} /> + onChange(event.target.value)} />
); } @@ -538,19 +497,6 @@ function TrashIcon() { ); } -function PinIcon({ pinned }) { - return pinned ? ( - - ) : ( - - ); -} - function IconButton({ title, onClick, children, danger = false }) { return (
onFilterTextChange(event.target.value)} />
- {filteredPoints.map((point) => ( - - ))} + {filteredPoints.length === 0 ? {selectedOnly && selectedPoints.length === 0 ? "Noch keine Auswahl." : "Keine passenden Datenpunkte."} : null} + {filteredPoints.map((point) => { + const key = `${point.isp}:${point.pointIndex}`; + const selected = selectedKeys.has(key); + const alias = normalizeDisplayText(point.alias, `Wert ${point.pointIndex}`); + return ( + + ); + })}
); @@ -695,6 +643,7 @@ export default function App() { const [busy, setBusy] = useState(false); const [sessionReady, setSessionReady] = useState(false); const [preferencesReady, setPreferencesReady] = useState(false); + const preferenceWrite = useRef(Promise.resolve()); const [isps, setIsps] = useState([]); const [selectedIsp, setSelectedIsp] = useState(""); const [metadataCache, setMetadataCache] = useState({}); @@ -702,10 +651,17 @@ export default function App() { const [workingPoints, setWorkingPoints] = useState([]); const [trendRange, setTrendRange] = useState(emptyTrendRange); const [trendResult, setTrendResult] = useState(null); - const [latestValues, setLatestValues] = useState([]); + const [trendLoading, setTrendLoading] = useState(false); + const trendRequest = useRef(0); + const [defaultTrendPreset, setDefaultTrendPreset] = useState(DEFAULT_TREND_PRESET); + const [trendPresetDraft, setTrendPresetDraft] = useState(DEFAULT_TREND_PRESET); + const [maxTrendSeries, setMaxTrendSeries] = useState(DEFAULT_MAX_TREND_SERIES); const [selections, setSelections] = useState([]); const [selectedSelectionId, setSelectedSelectionId] = useState(""); const [selectionDraft, setSelectionDraft] = useState(defaultSelectionDraft); + const [chartSettings, setChartSettings] = useState(loadChartDraft); + const [savingSelection, setSavingSelection] = useState(false); + const selectionContext = useRef(0); const [dashboard, setDashboard] = useState({ widgets: [] }); const [dashboardData, setDashboardData] = useState({}); const [widgetDraft, setWidgetDraft] = useState(defaultWidgetDraft); @@ -718,7 +674,6 @@ export default function App() { const [csvDelimiter, setCsvDelimiter] = useState(";"); const [sidebarPinned, setSidebarPinned] = useState(true); const [trendLineWidth, setTrendLineWidth] = useState("1.8"); - const [sidebarHover, setSidebarHover] = useState(false); const [trendFocus, setTrendFocus] = useState(false); const [adminIsp, setAdminIsp] = useState(""); const [aliasEditor, setAliasEditor] = useState(null); @@ -735,7 +690,7 @@ export default function App() { const [isCreatingSource, setIsCreatingSource] = useState(false); const [sourceDraft, setSourceDraft] = useState(defaultSourceDraft); const [sourceModalOpen, setSourceModalOpen] = useState(false); - const emptyManualDatapointDraft = (protocol = defaultSourceDraft.protocol, kind = "analog") => ({ alias: "", address: "", pointIndex: "", unit: getDefaultUnitForKind(kind), dataType: getDefaultPointDataType(protocol), kind, scale: "1", writeMode: "", condition: "" }); + const emptyManualDatapointDraft = (protocol = defaultSourceDraft.protocol, kind = "analog") => ({ alias: "", address: "", pointIndex: "", unit: AUTO_UNIT, dataType: getDefaultPointDataType(protocol), kind, scale: "1", writeMode: "", condition: "" }); const [collectorPointFilter, setCollectorPointFilter] = useState(""); const [alarmPointFilter, setAlarmPointFilter] = useState(""); const [manualDatapointDraft, setManualDatapointDraft] = useState(emptyManualDatapointDraft()); @@ -743,6 +698,7 @@ export default function App() { const [debugSnapshot, setDebugSnapshot] = useState(null); const [integrationSettings, setIntegrationSettings] = useState({ mailUrl: "https://mailapi.se-inno.de", whatsappUrl: "https://whatsappapi.se-inno.de", voipUrl: "https://voipapi.se-inno.de", mailApiKey: "", whatsappApiKey: "", voipApiKey: "" }); const [integrationStatus, setIntegrationStatus] = useState({ mailConfigured: false, whatsappConfigured: false, voipConfigured: false }); + const [runnerMailConfigured, setRunnerMailConfigured] = useState(false); const [runnerJobs, setRunnerJobs] = useState([]); const [runnerQueue, setRunnerQueue] = useState([]); const [runnerDraft, setRunnerDraft] = useState({ name: "", selectionId: "", enabled: true, time: "06:00", rangeHours: "24", delimiter: ";", mailEnabled: false, mailTo: "", mailSubject: "Trenddaten", mailMessage: "Automatischer Export aus SE Local Trenddata." }); @@ -762,10 +718,17 @@ export default function App() { const canManageRunner = isAuthenticated && hasPermission(user, "manage_runner"); const canAccessAdmin = canEditAliases || canManageSources || canManageAlarms || canManageUsers || canManageRoles || canManageIntegrations || canManageRunner || canViewDebug; const firstAdminSection = canEditAliases ? "aliases" : canManageSources ? "sources" : canManageAlarms ? "alarms" : canManageUsers ? "users" : canManageRoles ? "roles" : canManageIntegrations ? "integrations" : canManageRunner ? "runner" : canViewDebug ? "debug" : "aliases"; - const sidebarCollapsed = !sidebarPinned && !sidebarHover; + const sidebarCollapsed = !sidebarPinned; + const selectedSelection = selections.find((selection) => selection.id === selectedSelectionId); + const canEditSelectedSelection = Boolean(selectedSelection && ( + selectedSelection.ownerId === user?.id || user?.role === "admin" + )); const currentView = views.find((view) => view.id === activeView) || views[0]; const selectionListClassName = selections.length <= 2 ? "selection-list compact" : "selection-list"; const trendMaxRows = Number(trendRange.maxRows) || 0; + const activeTrendPreset = trendRange.presetDays || defaultTrendPreset; + const trendPeriodLabel = trendRange.from && trendRange.to ? "Eigener Zeitraum" + : TREND_PRESET_OPTIONS.find((option) => option.value === activeTrendPreset)?.label; const showTrendLimitWarning = trendMaxRows > 20000; const roleOptions = roles.length ? roles : [ { name: "viewer", label: "Viewer" }, @@ -918,6 +881,17 @@ export default function App() { resetFlash(); }, [activeView, adminSection]); + useEffect(() => { + let ignore = false; + api.getTrendDefaults().then(({ defaultPresetDays }) => { + if (!ignore) { + setDefaultTrendPreset(defaultPresetDays); + setTrendPresetDraft(defaultPresetDays); + } + }).catch(() => undefined); + return () => { ignore = true; }; + }, []); + useEffect(() => { let ignore = false; @@ -938,6 +912,7 @@ export default function App() { setUser(null); setIsps(ispResult.isps || []); setSelections([]); + setMaxTrendSeries(DEFAULT_MAX_TREND_SERIES); setDashboard(dashboardResult); setActiveView((current) => current === "admin" ? "dashboard" : current); setPreferencesReady(false); @@ -961,6 +936,7 @@ export default function App() { setCsvDelimiter(pref.csvDelimiter || ";"); setSidebarPinned(typeof pref.sidebarPinned === "boolean" ? pref.sidebarPinned : true); setTrendLineWidth(String(pref.trendLineWidth || 1.8)); + setMaxTrendSeries(normalizeMaxTrendSeries(pref.maxTrendSeries)); setIsps(ispResult.isps || []); setSelections(selectionResult.selections); setDashboard(dashboardResult); @@ -1036,13 +1012,17 @@ export default function App() { return; } - api.savePreferences(token, { + const preferences = { theme: themeMode, csvDelimiter, sidebarPinned, trendLineWidth: Number(trendLineWidth), - }).catch(() => undefined); - }, [csvDelimiter, preferencesReady, sidebarPinned, themeMode, token, trendLineWidth]); + maxTrendSeries, + }; + preferenceWrite.current = preferenceWrite.current + .then(() => api.savePreferences(token, preferences)) + .catch(() => undefined); + }, [csvDelimiter, maxTrendSeries, preferencesReady, sidebarPinned, themeMode, token, trendLineWidth]); useEffect(() => { if (!selectedIsp || metadataCache[selectedIsp]) { @@ -1096,10 +1076,17 @@ export default function App() { return; } - api.loadDashboardData(token || undefined, { widgets: dashboard.widgets }) - .then((result) => setDashboardData(Object.fromEntries(result.widgets.map((widget) => [widget.id, widget])))) - .catch((error) => setBootError(error.message)); - }, [dashboard, token]); + let canceled = false; + preferenceWrite.current + .then(() => !canceled && api.loadDashboardData(token || undefined, { widgets: dashboard.widgets })) + .then((result) => { + if (!canceled) setDashboardData(Object.fromEntries(result.widgets.map((widget) => [widget.id, widget]))); + }) + .catch((error) => { + if (!canceled) setBootError(error.message); + }); + return () => { canceled = true; }; + }, [dashboard, maxTrendSeries, selections, token]); useEffect(() => { if (!token || !canManageUsers) { @@ -1155,13 +1142,22 @@ export default function App() { if (!token || !canManageRunner) { setRunnerJobs([]); setRunnerQueue([]); + setRunnerMailConfigured(false); return; } + if (activeView !== "admin" || adminSection !== "runner") return; + let ignore = false; api.getRunnerJobs(token) - .then((result) => { setRunnerJobs(result.jobs || []); setRunnerQueue(result.queue || []); }) - .catch((error) => setBootError(error.message)); - }, [canManageRunner, token]); + .then((result) => { + if (ignore) return; + setRunnerJobs(result.jobs || []); + setRunnerQueue(result.queue || []); + setRunnerMailConfigured(result.mailConfigured === true); + }) + .catch((error) => { if (!ignore) setBootError(error.message); }); + return () => { ignore = true; }; + }, [activeView, adminSection, canManageRunner, token]); useEffect(() => { const refreshIsps = () => { @@ -1225,7 +1221,7 @@ export default function App() { setManualDatapointDraft((current) => ({ ...current, dataType: getDefaultPointDataType(currentSource.protocol || "modbus-tcp"), - unit: current.unit || getDefaultUnitForKind(current.kind || "analog"), + unit: current.unit ?? AUTO_UNIT, })); }, [currentSource]); @@ -1280,6 +1276,15 @@ export default function App() { } }, [selectedSelectionId, selections]); + useEffect(() => { + if (selectedSelectionId) return; + try { + localStorage.setItem(CHART_DRAFT_KEY, JSON.stringify(chartSettings)); + } catch { + // Browser storage is optional for unsaved selections. + } + }, [chartSettings, selectedSelectionId]); + useEffect(() => { if (!token || !canViewDebug || adminSection !== "debug") { return; @@ -1307,6 +1312,9 @@ export default function App() { }; const handleLogout = () => { + selectionContext.current += 1; + trendRequest.current += 1; + setTrendLoading(false); setToken(""); setUser(null); setIsps([]); @@ -1315,9 +1323,11 @@ export default function App() { setDashboardData({}); setMetadataCache({}); setTrendResult(null); - setLatestValues([]); setWorkingPoints([]); + setSelectedSelectionId(""); setSelectionDraft(defaultSelectionDraft); + setChartSettings(loadChartDraft()); + setTrendFocus(false); setActiveView("dashboard"); setAdminSection("aliases"); localStorage.removeItem("seltd-token"); @@ -1336,17 +1346,30 @@ export default function App() { setWorkingPoints((current) => current.filter((point) => !(point.isp === target.isp && point.pointIndex === target.pointIndex))); }; + const toggleWorkingPoint = (point) => { + if (workingPoints.some((entry) => entry.isp === point.isp && entry.pointIndex === point.pointIndex)) { + removePoint(point); + } else { + addPoint(point.pointIndex, point.isp); + } + }; + const startNewSelection = () => { + selectionContext.current += 1; + trendRequest.current += 1; + setTrendLoading(false); setSelectedSelectionId(""); setWorkingPoints([]); setSelectionDraft(defaultSelectionDraft); + setChartSettings(loadChartDraft()); setTrendResult(null); - setLatestValues([]); + setTrendRange((current) => ({ ...current, presetDays: "", from: "", to: "" })); setTrendFocus(false); setPointFilter(""); }; const loadSelection = (selection) => { + selectionContext.current += 1; setSelectedSelectionId(selection.id); setWorkingPoints(selection.points); setSelectionDraft({ @@ -1354,8 +1377,11 @@ export default function App() { description: selection.description || "", shared: Boolean(selection.shared), }); + setChartSettings(normalizeTrendChartSettings(selection.chartSettings, selection.points)); + setTrendResult(null); setTrendFocus(false); setActiveView("trends"); + void runTrendQuery(selection.points); }; const deleteSelection = async (selectionId) => { @@ -1364,70 +1390,85 @@ export default function App() { } resetFlash(); + const context = selectionContext.current; try { await api.deleteSelection(token, selectionId); - const refreshed = await api.getSelections(token); - setSelections(refreshed.selections); + setSelections((current) => current.filter((selection) => selection.id !== selectionId)); + if (selectionId === selectedSelectionId && context === selectionContext.current) startNewSelection(); } catch (error) { setBootError(error.message); } }; - const runTrendQuery = async () => { - if (workingPoints.length === 0) { + const runTrendQuery = async (points = workingPoints) => { + if (points.length === 0) { setBootError("Bitte zuerst Datenpunkte auswählen."); return; } - setBusy(true); + const requestId = ++trendRequest.current; + setTrendLoading(true); resetFlash(); try { const range = trendRange.from && trendRange.to - ? { from: trendRange.from, to: trendRange.to, maxRows: Number(trendRange.maxRows) } - : { presetDays: Number(trendRange.presetDays), maxRows: Number(trendRange.maxRows) }; - const [trend, latest] = await Promise.all([ - api.queryTrends(token, { points: workingPoints, range }), - api.latestValues(token, { points: workingPoints }), - ]); + ? { from: new Date(trendRange.from).toISOString(), to: new Date(trendRange.to).toISOString(), maxRows: Number(trendRange.maxRows) } + : { presetDays: Number(activeTrendPreset), maxRows: Number(trendRange.maxRows) }; + await preferenceWrite.current; + if (requestId !== trendRequest.current) return; + const trend = await api.queryTrends(token, { points, range }); + if (requestId !== trendRequest.current) return; setTrendResult(trend); - setLatestValues(latest.values); } catch (error) { - setBootError(error.message); + if (requestId === trendRequest.current) setBootError(error.message); } finally { - setBusy(false); + if (requestId === trendRequest.current) setTrendLoading(false); } }; const saveCurrentSelection = async () => { + if (savingSelection) return; if (workingPoints.length === 0) { setBootError("Eine Auswahl braucht mindestens einen Datenpunkt."); return; } resetFlash(); + setSavingSelection(true); + const context = selectionContext.current; try { - await api.createSelection(token, { + const payload = { ...selectionDraft, points: workingPoints, - }); - const refreshed = await api.getSelections(token); - setSelections(refreshed.selections); - const savedSelection = refreshed.selections.find((selection) => selection.name === (selectionDraft.name || "Neue Auswahl")) || refreshed.selections[0]; - if (savedSelection) { - setSelectedSelectionId(savedSelection.id); + chartSettings, + }; + const { selection } = canEditSelectedSelection + ? await api.updateSelection(token, selectedSelection.id, payload) + : await api.createSelection(token, payload); + setSelections((current) => [selection, ...current.filter((item) => item.id !== selection.id)]); + if (context === selectionContext.current) { + setSelectedSelectionId(selection.id); + setSuccessMessage("Auswahl samt Diagrammeinstellungen gespeichert."); } - setSuccessMessage("Auswahl gespeichert."); } catch (error) { - setBootError(error.message); + if (context === selectionContext.current) setBootError(error.message); + } finally { + setSavingSelection(false); } }; + const trendChartSettingsProps = { + settings: chartSettings, + onSettingsChange: (change) => setChartSettings((current) => ({ ...current, ...change })), + onSaveSettings: canEditSelectedSelection ? saveCurrentSelection : undefined, + savingSettings: savingSelection, + }; + const addWidget = () => { const widget = { id: createWidgetId(), title: widgetDraft.title || `Widget ${dashboard.widgets.length + 1}`, type: widgetDraft.type, - range: { presetDays: Number(widgetDraft.rangePresetDays || 1) }, + range: { presetDays: Number(widgetDraft.rangePresetDays || defaultTrendPreset) }, min: Number(widgetDraft.min), max: Number(widgetDraft.max), }; @@ -1510,7 +1551,7 @@ export default function App() { points: getOrderedPointEntries(aliasEditor).map((point) => ({ pointIndex: Number(point.pointIndex), alias: point.alias, - unit: point.unit, + unit: point.unitAuto ? AUTO_UNIT : point.unit, factor: point.factor, kind: point.kind, min: point.min, @@ -1833,7 +1874,7 @@ export default function App() { alias: datapoint.alias || datapoint.name || "", address: datapoint.address || datapoint.nodeId || "", pointIndex: String(datapoint.pointIndex || ""), - unit: normalizeDisplayUnit(datapoint.unit || "°C"), + unit: datapoint.unit ? normalizeDisplayUnit(datapoint.unit) : AUTO_UNIT, dataType: datapoint.dataType || getDefaultPointDataType(sourceDraft.protocol), kind: datapoint.kind || "analog", scale: String(datapoint.scale ?? "1"), @@ -1858,7 +1899,7 @@ export default function App() { name: manualDatapointDraft.alias, address: manualDatapointDraft.address, pointIndex: manualDatapointDraft.pointIndex, - unit: manualDatapointDraft.unit || "\u00B0C", + unit: manualDatapointDraft.unit || AUTO_UNIT, dataType: manualDatapointDraft.dataType, nodeId: sourceDraft.protocol === "opc-ua" ? manualDatapointDraft.address : "", kind: manualDatapointDraft.kind, @@ -2094,6 +2135,19 @@ export default function App() { const applyIntegrationResult = (result) => { setIntegrationSettings({ mailApiKey: "", whatsappApiKey: "", voipApiKey: "", ...(result.settings || {}) }); setIntegrationStatus({ mailConfigured: Boolean(result.mailConfigured), whatsappConfigured: Boolean(result.whatsappConfigured), voipConfigured: Boolean(result.voipConfigured) }); + setRunnerMailConfigured(result.mailConfigured === true); + }; + + const saveDefaultTrendPreset = async () => { + resetFlash(); + try { + const { defaultPresetDays } = await api.saveTrendDefaults(token, { defaultPresetDays: trendPresetDraft }); + setDefaultTrendPreset(defaultPresetDays); + setTrendPresetDraft(defaultPresetDays); + setSuccessMessage("Standardzeitraum gespeichert."); + } catch (error) { + setBootError(error.message); + } }; const saveIntegrationSettings = async () => { @@ -2150,6 +2204,7 @@ export default function App() { } const payload = { ...runnerDraft, + mailEnabled: runnerMailConfigured ? runnerDraft.mailEnabled : undefined, rangeHours: Number(runnerDraft.rangeHours) || 24, }; if (runnerDraft.id) { @@ -2160,6 +2215,7 @@ export default function App() { const refreshed = await api.getRunnerJobs(token); setRunnerJobs(refreshed.jobs || []); setRunnerQueue(refreshed.queue || []); + setRunnerMailConfigured(refreshed.mailConfigured === true); resetRunnerDraft(); setSuccessMessage("Runner-Job gespeichert."); } catch (error) { @@ -2246,76 +2302,24 @@ export default function App() { } return ( -
- - -
+
Ansicht
@@ -2366,7 +2370,7 @@ export default function App() { @@ -2432,7 +2436,7 @@ export default function App() {
- +
); } @@ -2458,7 +2462,7 @@ export default function App() { timestamp={value.timestamp} /> ) : ( -
+
{normalizeDisplayText(value.displayName)} {normalizeDisplayText(value.alias)} @@ -2491,36 +2495,22 @@ export default function App() { allowExports allowFocusMode lineWidth={Number(trendLineWidth)} + {...trendChartSettingsProps} /> ) : (

Trendansicht

-

Nach dem Laden erscheinen hier Graph, Exporte und Vollbildansicht.

+

{trendLoading ? "Trend wird geladen ..." : "Nach dem Laden erscheinen hier Graph, Exporte und Vollbildansicht."}

)} - {latestValues.length ? ( -
- {latestValues.map((value) => ( -
-
- {normalizeDisplayText(value.displayName)} - {normalizeDisplayText(value.alias)} - {formatTimestampLabel(value.timestamp)} -
-
{value.value !== null ? formatValue(value.value) : normalizeDisplayText(value.raw, "--")}{normalizeDisplayUnit(value.unit)}
-
- ))} -
- ) : null}
-
+

Datenpunktauswahl

-

Im Dropdown erscheinen nur Tabellen, die bereits Daten enthalten.

- +
-

Aktuelle Punkte

-

Mehrere ISPs können gemeinsam angezeigt werden.

+

Aktuelle Auswahl

+

{workingPoints.length} Datenpunkte

-
- {workingPoints.map((point) => { - const meta = metadataCache[point.isp]?.points?.[String(point.pointIndex)]; - const color = resolvePointColor(point, metadataCache); - return ( - - ); - })} -
- -
+
+ Zeitraum und Darstellung {trendPeriodLabel} · {trendLineWidth} px +
@@ -2590,12 +2571,14 @@ export default function App() { Ende setTrendRange((current) => ({ ...current, to: event.target.value }))} /> -
+
+ {showTrendLimitWarning ?

{"Mehr als 20000 Datensätze sind möglich, können aber zu längeren Ladezeiten führen."}

: null} + - {showTrendLimitWarning ?

{"Mehr als 20000 Datensätze sind möglich, können aber zu längeren Ladezeiten führen."}

: null} + {workingPoints.length > maxTrendSeries ? Im Diagramm erscheinen die ersten {maxTrendSeries} Datenpunkte. : null}
- +
{isAuthenticated ? ( @@ -2621,23 +2604,26 @@ export default function App() { -
- - -
- - - - +
+ Auswahl bearbeiten und speichern +
+ + + +
+ +
) : null}
@@ -2654,6 +2640,7 @@ export default function App() { allowExports allowFocusMode lineWidth={Number(trendLineWidth)} + {...trendChartSettingsProps} /> ) : (
@@ -2758,9 +2745,13 @@ export default function App() {
Wert {point.pointIndex}
updateAliasPoint(String(point.pointIndex), { alias: event.target.value })} /> - updateAliasPoint(String(point.pointIndex), { unit: nextValue })} /> + updateAliasPoint(String(point.pointIndex), { unit, unitAuto: unit === AUTO_UNIT, kind: unit === DIGITAL_UNIT ? "digital" : point.kind })} /> updateAliasPoint(String(point.pointIndex), { factor: nextValue })} /> - { + const kind = event.target.value; + const unit = unitForChangedKind(point.unitAuto ? AUTO_UNIT : point.unit, kind); + updateAliasPoint(String(point.pointIndex), { kind, unit, unitAuto: unit === AUTO_UNIT }); + }}> @@ -2800,20 +2791,19 @@ export default function App() {
-
- {availableUnits.map((unit) => ( -
-
- {unit.symbol} - {unit.label} - {unit.isSystem ? "Systemeinheit" : "Benutzerdefiniert"} -
-
- -
-
- ))} -
+ + + + {availableUnits.map((unit) => ( + + + + + + + ))} + +
SymbolBezeichnungTypAktion
{unit.symbol}{unit.label}{unit.isSystem ? "Systemeinheit" : "Benutzerdefiniert"}
) : null} @@ -2945,7 +2935,7 @@ export default function App() { - - - - +
+ + + + +
+ {!runnerMailConfigured ? Sobald unter Admin → API ein Mail-API-Key gespeichert ist, kannst du den CSV-Mailversand aktivieren. : null}
{runnerDraft.id ? : null} @@ -3729,8 +3723,31 @@ export default function App() { + + {user?.role === "admin" ? ( + <> + +
+ +
+ + ) : null}
diff --git a/web/src/api.js b/web/src/api.js index d31f048..312e064 100644 --- a/web/src/api.js +++ b/web/src/api.js @@ -80,6 +80,8 @@ export const api = { loadDashboardData: (token, body) => apiRequest("/dashboard/data", { method: "POST", token, body }), getPreferences: (token) => apiRequest("/preferences", { token }), savePreferences: (token, body) => apiRequest("/preferences", { method: "PUT", token, body }), + getTrendDefaults: () => apiRequest("/settings/trend"), + saveTrendDefaults: (token, body) => apiRequest("/settings/trend", { method: "PUT", token, body }), getIntegrations: (token) => apiRequest("/integrations", { token }), saveIntegrations: (token, body) => apiRequest("/integrations", { method: "PUT", token, body }), getRunnerJobs: (token) => apiRequest("/runner/jobs", { token }), diff --git a/web/src/components/Sidebar.jsx b/web/src/components/Sidebar.jsx new file mode 100644 index 0000000..3c5e125 --- /dev/null +++ b/web/src/components/Sidebar.jsx @@ -0,0 +1,83 @@ +const icons = { + dashboard: "M3 3h7v7H3z M14 3h7v7h-7z M3 14h7v7H3z M14 14h7v7h-7z", + trends: "M3 4v16h18 M6 15l5-5 4 3 6-7", + admin: "M12 22s7-3 7-10V5l-7-3-7 3v7c0 7 7 10 7 10Z M9 12l2 2 4-4", + settings: "M4 6h6m4 0h6 M4 12h10m4 0h2 M4 18h2m4 0h10 M10 4v4m4 2v4m-8 2v4", + expand: "M3 5h18v14H3z M9 5v14 M13 9l3 3-3 3", + collapse: "M3 5h18v14H3z M9 5v14 M16 9l-3 3 3 3", + login: "M14 4h6v16h-6 M4 12h12 M12 8l4 4-4 4", + logout: "M10 4H4v16h6 M8 12h12 M16 8l4 4-4 4", +}; + +function SidebarIcon({ name }) { + return ( + + ); +} + +export function SmallFootnote() { + return
by J.H. | SE Inno GmbH
; +} + +export default function Sidebar({ collapsed, onToggle, views, activeView, onNavigate, user, userLabel, onLogout }) { + const toggleLabel = collapsed ? "Seitenleiste ausklappen" : "Seitenleiste einklappen"; + const accountLabel = user ? "Abmelden" : "Anmelden"; + + return ( + + ); +} diff --git a/web/src/components/TrendChart.jsx b/web/src/components/TrendChart.jsx index 81e50d4..d423475 100644 --- a/web/src/components/TrendChart.jsx +++ b/web/src/components/TrendChart.jsx @@ -1,16 +1,20 @@ -import { useEffect, useMemo, useRef, useState } from "react"; +import { useMemo, useRef, useState } from "react"; import { jsPDF } from "jspdf"; import * as XLSX from "xlsx"; import { CartesianGrid, + Customized, Line, LineChart, - ReferenceArea, ResponsiveContainer, Tooltip, XAxis, YAxis, } from "recharts"; +import TrendChartSettings from "./TrendChartSettings.jsx"; +import { getTimeZoom, getTrendAxes, getTrendAxisScale, seriesAxisId } from "./trend-scales.mjs"; +import { DEFAULT_CHART_SETTINGS } from "../../../shared/trend-chart-settings.mjs"; +import { assignTrendColors } from "./trend-colors.mjs"; function downloadBlob(filename, blob) { const url = URL.createObjectURL(blob); @@ -25,43 +29,68 @@ function quoteCell(value) { return `"${String(value ?? "").replaceAll('"', '""')}"`; } -function buildRandomColor(index) { - const hue = Math.round((Math.random() * 360 + index * 41) % 360); - const saturation = 72 + (index % 3) * 4; - const lightness = 46 + (index % 4) * 3; - return `hsl(${hue} ${saturation}% ${lightness}%)`; -} - -function getAnalogDomain(rows, visibleSeries) { - const values = []; - rows.forEach((row) => { - visibleSeries.filter((item) => item.kind !== "digital").forEach((item) => { - const value = row[item.key]; - if (Number.isFinite(value)) { - values.push(value); - } - }); - }); - - if (!values.length) { - return [0, 1]; - } - - const min = Math.min(...values); - const max = Math.max(...values); - if (min === max) { - return [min - 1, max + 1]; - } - - const padding = (max - min) * 0.08; - return [min - padding, max + padding]; -} - function formatTrendNumber(value) { const numeric = Number(value); return Number.isFinite(numeric) ? numeric.toFixed(2) : "--"; } +function TimeZoomOverlay({ offset, onZoom }) { + const activeDrag = useRef(null); + const [drag, setDrag] = useState(null); + if (!offset?.width || !offset.height) return null; + + function position(event) { + const bounds = event.currentTarget.getBoundingClientRect(); + return Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width)); + } + + function cancel() { + activeDrag.current = null; + setDrag(null); + } + + return ( + + {drag ? ( + + ) : null} + { + if (!event.isPrimary || event.button !== 0) return; + const start = position(event); + event.currentTarget.setPointerCapture(event.pointerId); + activeDrag.current = { start, end: start, pointerId: event.pointerId }; + setDrag(activeDrag.current); + }} + onPointerMove={(event) => { + if (activeDrag.current?.pointerId !== event.pointerId) return; + setDrag({ ...activeDrag.current, end: position(event) }); + }} + onPointerUp={(event) => { + if (activeDrag.current?.pointerId !== event.pointerId) return; + const { start } = activeDrag.current; + const end = position(event); + if (Math.abs(end - start) * offset.width >= 8) onZoom(start, end); + cancel(); + }} + onPointerCancel={cancel} + onLostPointerCapture={cancel} + /> + + ); +} + export default function TrendChart({ result, title = "Trendansicht", @@ -73,153 +102,47 @@ export default function TrendChart({ allowFocusMode = true, compact = false, lineWidth = 1.8, + settings = DEFAULT_CHART_SETTINGS, + onSettingsChange, + onSaveSettings, + savingSettings, }) { - const wrapperRef = useRef(null); const chartHostRef = useRef(null); - const dragBoxRef = useRef(null); - const domainRef = useRef({ x: [0, 1], y: [0, 1] }); const [selectedKeys, setSelectedKeys] = useState([]); - const [dragBox, setDragBox] = useState(null); const [zoomDomain, setZoomDomain] = useState(null); const [exportFormat, setExportFormat] = useState("csv"); const [transparentBackground, setTransparentBackground] = useState(false); - const series = useMemo(() => { - const fallbackColors = []; - return (result?.series || []).map((item, index) => ({ + const series = useMemo(() => assignTrendColors(result?.series || []) + .map((item) => ({ ...item, - color: item.color || (fallbackColors[index] ||= buildRandomColor(index)), name: `${item.displayName} · ${item.alias}${item.unit ? ` (${item.unit})` : ""}`, - })); - }, [result]); + })), [result]); - const rows = useMemo(() => (result?.rows || []).map((row) => ({ - ...row, - timestampMs: new Date(row.timestamp).getTime(), - })), [result]); + const rows = useMemo(() => (result?.rows || []) + .map((row) => ({ ...row, timestampMs: new Date(row.timestamp).getTime() })) + .filter((row) => Number.isFinite(row.timestampMs)) + .sort((left, right) => left.timestampMs - right.timestampMs), [result]); - const visibleSeries = selectedKeys.length ? series.filter((item) => selectedKeys.includes(item.key)) : series; - const analogSeries = visibleSeries.filter((item) => item.kind !== "digital"); - const digitalSeries = visibleSeries.filter((item) => item.kind === "digital"); - - const baseXDomain = useMemo(() => { - if (!rows.length) { - return [0, 1]; - } - return [rows[0].timestampMs, rows[rows.length - 1].timestampMs]; - }, [rows]); - - const baseYDomain = useMemo(() => { - if (analogSeries.length === 0 && digitalSeries.length > 0) { - return [0, 2]; - } - return getAnalogDomain(rows, visibleSeries); - }, [analogSeries.length, digitalSeries.length, rows, visibleSeries]); - - const xDomain = zoomDomain?.x || baseXDomain; - const yDomain = zoomDomain?.y || baseYDomain; - const hasFocusSelection = selectedKeys.length > 0 && selectedKeys.length < series.length; + const baseXDomain = rows.length > 1 + ? [rows[0].timestampMs, rows.at(-1).timestampMs] + : [(rows[0]?.timestampMs ?? 0) - 1000, (rows[0]?.timestampMs ?? 0) + 1000]; + const activeZoom = zoomDomain && zoomDomain.result === result ? zoomDomain.domain : null; + const xDomain = activeZoom || baseXDomain; + const axes = useMemo(() => getTrendAxes(series, settings.assignments).map((axis) => ({ + ...axis, + scale: getTrendAxisScale(axis, settings.axes[axis.id], rows, activeZoom, settings.divisions), + })), [series, settings.assignments, settings.axes, settings.divisions, rows, activeZoom]); + const axisIndex = new Map(axes.map((axis, index) => [axis.id, index])); + const activeKeys = new Set(series.filter((entry) => selectedKeys.includes(entry.key)).map((entry) => entry.key)); + const hasFocusSelection = activeKeys.size > 0 && activeKeys.size < series.length; + const seriesLimited = result?.requestedSeriesCount > result?.maxSeries; const normalizedLineWidth = Number.isFinite(Number(lineWidth)) ? Number(lineWidth) : 1.8; - useEffect(() => { - domainRef.current = { x: xDomain, y: yDomain }; - }, [xDomain, yDomain]); - - const mapDragToDomain = (clientX, clientY) => { - const rect = chartHostRef.current?.getBoundingClientRect() || wrapperRef.current?.getBoundingClientRect(); - if (!rect) { - return null; - } - - const activeDomain = domainRef.current; - const xRatio = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)); - const yRatio = Math.max(0, Math.min(1, (clientY - rect.top) / rect.height)); - const xValue = activeDomain.x[0] + (activeDomain.x[1] - activeDomain.x[0]) * xRatio; - const yValue = activeDomain.y[1] - (activeDomain.y[1] - activeDomain.y[0]) * yRatio; - - return { - xValue, - yValue, - xPixel: clientX - rect.left, - yPixel: clientY - rect.top, - }; - }; - - const handleMouseDown = (event) => { - if (event.button !== 0) { - return; - } - event.preventDefault(); - const mapped = mapDragToDomain(event.clientX, event.clientY); - if (!mapped) { - return; - } - const nextDragBox = { start: mapped, end: mapped }; - dragBoxRef.current = nextDragBox; - setDragBox(nextDragBox); - }; - - const updateDragBox = (clientX, clientY) => { - const mapped = mapDragToDomain(clientX, clientY); - if (!mapped) { - return; - } - setDragBox((current) => { - if (!current) { - return current; - } - const nextDragBox = { ...current, end: mapped }; - dragBoxRef.current = nextDragBox; - return nextDragBox; - }); - }; - - const finalizeDragBox = (box) => { - if (!box) { - return; - } - - const deltaX = Math.abs(box.end.xPixel - box.start.xPixel); - const deltaY = Math.abs(box.end.yPixel - box.start.yPixel); - if (deltaX < 12 && deltaY < 12) { - dragBoxRef.current = null; - setDragBox(null); - return; - } - - const currentDomain = domainRef.current; - setZoomDomain({ - x: deltaX < 12 ? currentDomain.x : [Math.min(box.start.xValue, box.end.xValue), Math.max(box.start.xValue, box.end.xValue)], - y: deltaY < 12 ? currentDomain.y : [Math.min(box.start.yValue, box.end.yValue), Math.max(box.start.yValue, box.end.yValue)], - }); - dragBoxRef.current = null; - setDragBox(null); - }; - - useEffect(() => { - if (!dragBox) { - return undefined; - } - - const handleWindowMouseMove = (event) => { - updateDragBox(event.clientX, event.clientY); - }; - - const handleWindowMouseUp = () => { - finalizeDragBox(dragBoxRef.current); - }; - - window.addEventListener("mousemove", handleWindowMouseMove); - window.addEventListener("mouseup", handleWindowMouseUp); - return () => { - window.removeEventListener("mousemove", handleWindowMouseMove); - window.removeEventListener("mouseup", handleWindowMouseUp); - }; - }, [dragBox, xDomain, yDomain]); - - const resetZoom = () => { - setZoomDomain(null); - }; + function zoomTime(start, end) { + const domain = getTimeZoom(xDomain, start, end); + if (domain) setZoomDomain({ result, domain }); + } const clearFocus = () => { setSelectedKeys([]); @@ -365,6 +288,7 @@ export default function TrendChart({

{title}

Keine Daten im gewählten Zeitraum.

+ {seriesLimited ? Diagrammlimit: {result.maxSeries} von {result.requestedSeriesCount} Datenpunkten. : null}
); } @@ -374,7 +298,8 @@ export default function TrendChart({

{title}

-

Ziehen mit gedrückter Maustaste zoomt Zeit und Wertebereich gemeinsam.

+ {rows.length > 1 && !compact ?

Zum Zeitzoom einen Bereich im Diagramm aufziehen.

: null} + {seriesLimited ?

Diagrammlimit: {result.maxSeries} von {result.requestedSeriesCount} Datenpunkten.

: null}
{allowExports ? ( @@ -403,41 +328,68 @@ export default function TrendChart({ ) : null} - {zoomDomain ? : null} + {onSettingsChange ? ( + + ) : null} + {!compact && rows.length > 1 ? : null} + {activeZoom ? : null} {allowFocusMode ? : null}
-
-
+
+
- + new Date(value).toLocaleString("de-DE", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })} minTickGap={28} - stroke="var(--muted)" + stroke="var(--trend-axis)" /> - {analogSeries.length ? : null} - {digitalSeries.length ? ( + {axes.map((axis, index) => ( - ) : null} + ))} new Date(value).toLocaleString("de-DE")} formatter={(value, name) => [formatTrendNumber(value), name]} @@ -448,35 +400,25 @@ export default function TrendChart({ fontSize: 12, }} /> - {dragBox ? ( - - ) : null} {series.map((entry) => { - const isolated = selectedKeys.length > 0 && !selectedKeys.includes(entry.key); + const isolated = hasFocusSelection && !activeKeys.has(entry.key); return ( ); })} + {rows.length > 1 ? : null}
@@ -485,8 +427,8 @@ export default function TrendChart({
{series.map((entry) => { - const dimmed = selectedKeys.length > 0 && !selectedKeys.includes(entry.key); - const active = selectedKeys.includes(entry.key); + const dimmed = hasFocusSelection && !activeKeys.has(entry.key); + const active = activeKeys.has(entry.key); return ( +
+ ) : null} +
+ Datenreihen zuordnen + {series.map((entry) => ( + + ))} +
+
+ + ); +} diff --git a/web/src/components/trend-colors.mjs b/web/src/components/trend-colors.mjs new file mode 100644 index 0000000..58d9518 --- /dev/null +++ b/web/src/components/trend-colors.mjs @@ -0,0 +1,69 @@ +const PALETTE = [ + "#0072b2", "#d55e00", "#009e73", "#a03a83", "#b77a00", "#665aca", + "#e03b53", "#167b93", "#3e7b0d", "#87543f", "#d14caa", "#4d6090", +]; + +function hexRgb(color) { + const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color); + const hex = short ? short.slice(1).map((digit) => digit.repeat(2)).join("") : color.slice(1); + if (color.startsWith("#") && /^[0-9a-f]{6}$/i.test(hex)) { + return hex.match(/../g).map((pair) => parseInt(pair, 16)); + } + return null; +} + +function distance(left, right) { + const [red, green, blue] = left.map((channel, index) => channel - right[index]); + const redMean = (left[0] + right[0]) / 512; + return (2 + redMean) * red ** 2 + 4 * green ** 2 + (3 - redMean) * blue ** 2; +} + +function hslColor(hue, saturation, lightness) { + const amplitude = saturation * Math.min(lightness, 1 - lightness); + return "#" + [0, 8, 4].map((offset) => { + const angle = (offset + hue / 30) % 12; + const channel = lightness - amplitude * Math.max(-1, Math.min(angle - 3, 9 - angle, 1)); + return Math.round(255 * channel).toString(16).padStart(2, "0"); + }).join(""); +} + +function isAutomaticColor(color) { + return !color || /^(?:black|#0{3}|#0{6}|rgb\(\s*0(?:\s*,\s*|\s+)0(?:\s*,\s*|\s+)0\s*\))$/i.test(color); +} + +export function assignTrendColors(series) { + const automatic = series.filter((entry) => isAutomaticColor(entry.color?.trim())); + if (!automatic.length) return series; + + const seed = series.reduce((hash, { key }) => { + for (const char of key) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) >>> 0; + return hash; + }, 0); + const offset = seed % PALETTE.length; + const palette = PALETTE.slice(offset).concat(PALETTE.slice(0, offset)); + if (series.length > palette.length) { + for (const lightness of [0.39, 0.49, 0.58]) { + for (let hue = seed % 10; hue < 360; hue += 6) palette.push(hslColor(hue, 0.72, lightness)); + } + } + + const manual = series.filter((entry) => !isAutomaticColor(entry.color?.trim())); + const used = manual.map((entry) => hexRgb(entry.color.trim())).filter(Boolean); + const candidates = [...new Set(palette)].map((color) => ({ + color, + rgb: hexRgb(color), + contrast: Infinity, + })); + function compareTo(rgb) { + for (const candidate of candidates) candidate.contrast = Math.min(candidate.contrast, distance(candidate.rgb, rgb)); + } + used.forEach(compareTo); + const colors = new Map(); + for (const entry of automatic) { + const best = candidates.reduce((index, candidate, current) => candidate.contrast > candidates[index].contrast ? current : index, 0); + const [chosen] = candidates.splice(best, 1); + colors.set(entry.key, chosen.color); + compareTo(chosen.rgb); + } + return series.map((entry) => colors.has(entry.key) ? { ...entry, color: colors.get(entry.key) } : entry); +} diff --git a/web/src/components/trend-scales.mjs b/web/src/components/trend-scales.mjs new file mode 100644 index 0000000..bc2aeda --- /dev/null +++ b/web/src/components/trend-scales.mjs @@ -0,0 +1,73 @@ +import { DIGITAL_UNIT, normalizeUnitSymbol } from "../../../shared/engineering-units.mjs"; + +export function unitAxisId(series) { + return `unit:${series.kind === "digital" ? DIGITAL_UNIT : normalizeUnitSymbol(series.unit)}`; +} + +export function seriesAxisId(series, assignments) { + return assignments[series.key] === "own" ? `point:${series.key}` : unitAxisId(series); +} + +export function getTrendAxes(series, assignments) { + const groups = new Map(); + for (const entry of series) { + const id = seriesAxisId(entry, assignments); + if (!groups.has(id)) { + const digital = entry.kind === "digital"; + const unit = digital ? DIGITAL_UNIT : normalizeUnitSymbol(entry.unit); + groups.set(id, { + id, + unit, + digital, + name: id.startsWith("point:") ? `${entry.alias} (${unit || "ohne Einheit"})` : unit || "Ohne Einheit", + side: groups.size % 2 === 0 ? "left" : "right", + series: [], + }); + } + groups.get(id).series.push(entry); + } + return [...groups.values()]; +} + +function findExtent(rows, series, window) { + let min = Infinity; + let max = -Infinity; + for (const row of rows) { + if (window && (row.timestampMs < window[0] || row.timestampMs > window[1])) continue; + for (const entry of series) { + const value = row[entry.key]; + if (!Number.isFinite(value)) continue; + if (value < min) min = value; + if (value > max) max = value; + } + } + return [min, max]; +} + +export function getTrendAxisScale(axis, settings, rows, window, divisions) { + if (axis.digital) return { domain: [0, 2], ticks: [0, 1] }; + + let [min, max] = findExtent(rows, axis.series, window); + if (min === Infinity && window) [min, max] = findExtent(rows, axis.series); + if (min === Infinity) [min, max] = [0, 1]; + const padding = min === max ? Math.abs(min) * 0.05 || 1 : (max - min) * 0.08; + const validManual = settings?.min !== "" && settings?.max !== "" + && Number.isFinite(Number(settings?.min)) && Number.isFinite(Number(settings?.max)) + && Number(settings.min) < Number(settings.max); + const domain = settings?.mode === "manual" && validManual + ? [Number(settings.min), Number(settings.max)] + : [min - padding, max + padding]; + + return { + domain, + ticks: Array.from({ length: divisions + 1 }, (_, index) => domain[0] + (domain[1] - domain[0]) * index / divisions), + invalid: settings?.mode === "manual" && !validManual, + }; +} + +export function getTimeZoom(domain, start, end) { + const span = domain[1] - domain[0]; + const min = Math.round(domain[0] + span * Math.min(start, end)); + const max = Math.round(domain[0] + span * Math.max(start, end)); + return max > min && (min > domain[0] || max < domain[1]) ? [min, max] : null; +} diff --git a/web/src/styles.css b/web/src/styles.css index 467cdcf..daa6e0c 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -223,13 +223,14 @@ span { } .app-shell { + --sidebar-width: 188px; display: grid; - grid-template-columns: 188px 1fr; + grid-template-columns: var(--sidebar-width) minmax(0, 1fr); min-height: 100vh; } -.app-shell.trend-focus { - grid-template-columns: 72px 1fr; +.app-shell.sidebar-collapsed { + --sidebar-width: 64px; } .sidebar { @@ -238,13 +239,12 @@ span { height: 100vh; padding: 0.65rem 0.55rem 0.7rem; display: grid; - grid-template-rows: auto 1fr auto; + grid-template-rows: auto 1fr; gap: 0.75rem; - width: 188px; - overflow: hidden; + min-width: 0; + overflow: auto; background: var(--sidebar-bg); border-right: 1px solid var(--sidebar-border); - transition: width 160ms ease, padding 160ms ease; } .sidebar::before { @@ -256,23 +256,19 @@ span { } .sidebar.collapsed { - width: 64px; - padding-inline: 0.35rem; + padding-inline: 0.55rem; } -.sidebar.collapsed .sidebar-top { +.sidebar.collapsed .sidebar-top, +.sidebar.collapsed .nav-list, +.sidebar.collapsed .sidebar-footer { justify-items: center; + align-items: center; } .sidebar.collapsed .sidebar-brand-row { - width: 100%; - padding-left: 0; - padding-right: 0; - justify-content: center; -} - -.sidebar.collapsed .logo-lockup { - justify-content: center; + flex-direction: column; + padding-inline: 0; } .sidebar.collapsed .logo-lockup img { @@ -281,16 +277,21 @@ span { } .sidebar.collapsed .nav-list { - width: 100%; + align-self: stretch; gap: 0.45rem; } -.sidebar.collapsed .nav-button { - width: 100%; +.sidebar.collapsed .nav-button, +.sidebar.collapsed .sidebar-account, +.sidebar.collapsed .sidebar-toggle { + width: 38px; + min-width: 38px; + height: 38px; min-height: 38px; justify-content: center; + justify-self: center; padding: 0; - font-size: 12px; + border-radius: 10px; } .sidebar-top { @@ -331,6 +332,10 @@ span { border-bottom: 1px solid var(--border); } +.sidebar-toggle { + flex-shrink: 0; +} + .nav-list, .button-row, .widget-stack, @@ -355,9 +360,16 @@ span { padding: 0.38rem 0.58rem; border-radius: 12px; justify-content: flex-start; + gap: 0.42rem; font-size: 12px; } +.sidebar svg { + width: 18px; + height: 18px; + flex-shrink: 0; +} + .user-card { padding-top: 0.1rem; } @@ -382,19 +394,15 @@ span { border-top: 1px solid var(--border); } -.sidebar-logout { - justify-self: start; - border-radius: 999px; - padding-inline: 0.7rem; -} - -.sidebar-login { +.sidebar-account { justify-self: start; border-radius: 999px; padding-inline: 0.7rem; + gap: 0.42rem; } .content { + min-width: 0; padding: 0.55rem 0.65rem 0.7rem; display: grid; gap: 0.55rem; @@ -603,14 +611,23 @@ span { } .chart-wrapper { + --trend-axis: var(--muted); + --trend-grid: var(--grid); + --trend-band: color-mix(in srgb, var(--text) 5%, transparent); width: 100%; min-height: 320px; user-select: none; - cursor: crosshair; - touch-action: none; + overflow-x: auto; + touch-action: pan-y; } -.chart-wrapper.dragging { +.chart-wrapper.high-contrast { + --trend-axis: var(--text); + --trend-grid: color-mix(in srgb, var(--text) 42%, transparent); + --trend-band: color-mix(in srgb, var(--text) 10%, transparent); +} + +.trend-zoom-target { cursor: crosshair; } @@ -620,12 +637,75 @@ span { .chart-toolbar { align-items: flex-start; + position: relative; } .chart-actions { align-items: center; } +.trend-settings > summary { + cursor: pointer; + list-style: none; +} + +.trend-settings > summary::-webkit-details-marker { + display: none; +} + +.trend-settings-popover { + position: absolute; + z-index: 12; + top: 100%; + right: 0; + width: min(100%, 420px); + max-height: min(64vh, 540px); + overflow: auto; + overscroll-behavior: contain; + background: var(--surface-strong); + border: 1px solid var(--border-strong); + border-radius: 12px; + box-shadow: 0 12px 28px #0003; + padding: 0.8rem; +} + +.trend-settings-fields, +.trend-series-setting { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.5rem; +} + +.trend-settings-save { + justify-content: flex-end; + margin-top: 0.65rem; +} + +.trend-settings-fields > small, +.trend-opacity-field { + grid-column: 1 / -1; +} + +.trend-settings-group { + margin: 0.65rem 0 0; + padding: 0.55rem; + min-width: 0; + border: 1px solid var(--border-strong); + border-radius: 8px; +} + +.trend-axis-settings + .trend-axis-settings, +.trend-series-setting + .trend-series-setting { + margin-top: 0.55rem; + padding-top: 0.55rem; + border-top: 1px solid var(--border); +} + +.trend-series-setting { + align-items: center; + overflow-wrap: anywhere; +} + .chart-check { display: inline-flex; align-items: center; @@ -693,12 +773,123 @@ span { display: grid; gap: 0.65rem; align-content: start; + min-width: 0; } -.trend-side { +.trend-point-panel, +.trend-point-library { + grid-template-rows: auto auto minmax(0, 1fr); + min-height: 0; min-width: 0; } +.trend-point-library .point-list { + align-content: start; + grid-auto-rows: max-content; + max-height: min(36dvh, 24rem); + min-height: 0; + overscroll-behavior: contain; +} + +.point-item[aria-pressed="true"], +.trend-point-library [aria-pressed="true"] { + border-color: var(--border-strong); + background: color-mix(in srgb, var(--brand-2) 8%, var(--surface-strong)); +} + +.trend-options { + border: 1px solid var(--border); + border-radius: 10px; + padding: 0.44rem 0.55rem; +} + +.trend-options summary { + cursor: pointer; +} + +.trend-options summary small { + float: right; + color: var(--muted); +} + +.trend-options[open] summary { + margin-bottom: 0.44rem; +} + +.trend-selection-save > .primary-button { + margin-top: 0.44rem; +} + +@media (min-width: 981px) and (min-height: 560px) { + .content.trend-content { + display: flex; + flex-direction: column; + height: 100dvh; + } + + .trend-content .trend-layout { + flex: 1; + min-height: 0; + grid-template-rows: minmax(0, 1fr); + } + + .trend-content .trend-side { + align-self: stretch; + align-content: stretch; + min-height: 0; + grid-template-rows: minmax(0, 1fr) auto; + } + + .trend-content .trend-point-library .point-list { + max-height: none; + } +} + +.unit-table { + width: 100%; + border-collapse: collapse; + text-align: left; +} + +.unit-table th, +.unit-table td { + padding: 0.38rem 0.52rem; + border-bottom: 1px solid var(--border); + overflow-wrap: anywhere; +} + +.unit-table thead th, +.unit-table small { + color: var(--muted); +} + +.unit-table tbody tr:nth-child(even) { + background: color-mix(in srgb, var(--border) 36%, transparent); +} + +.unit-table :is(th, td):last-child { + text-align: right; + width: 1%; + overflow-wrap: normal; + white-space: nowrap; +} + +.runner-mail-fields { + margin: 0; + padding: 0.5rem 0; + border: 0; + border-top: 1px solid var(--border); + min-width: 0; +} + +.runner-mail-fields:disabled { + opacity: 0.55; +} + +.runner-mail-fields:disabled input { + cursor: not-allowed; +} + .stat-card, .gauge-card, .user-row { @@ -956,9 +1147,8 @@ span { } @media (max-width: 980px) { - .app-shell, - .app-shell.trend-focus { - grid-template-columns: 1fr; + .app-shell { + grid-template-columns: minmax(0, 1fr); } .sidebar, @@ -968,6 +1158,36 @@ span { height: auto; } + .sidebar.collapsed { + grid-template-columns: minmax(0, 1fr) auto; + grid-template-rows: auto; + column-gap: 0.4rem; + padding-block: 0.4rem; + } + + .sidebar.collapsed .sidebar-top, + .sidebar.collapsed .sidebar-brand-row, + .sidebar.collapsed .nav-list { + display: flex; + flex-direction: row; + align-items: center; + gap: 0.3rem; + } + + .sidebar.collapsed .sidebar-top { + flex-wrap: wrap; + } + + .sidebar.collapsed .sidebar-brand-row, + .sidebar.collapsed .sidebar-footer { + padding: 0; + border: 0; + } + + .sidebar.collapsed .sidebar-footer { + align-self: center; + } + .grid.two, .form-grid, .alias-row, @@ -1576,4 +1796,4 @@ span { font-size: 0.65rem; font-weight: 700; line-height: 1.2; -} \ No newline at end of file +} diff --git a/web/vite.config.js b/web/vite.config.js index dd83cd4..b9c3a6d 100644 --- a/web/vite.config.js +++ b/web/vite.config.js @@ -1,7 +1,13 @@ +import { fileURLToPath } from "node:url"; import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], + server: { + fs: { + allow: [fileURLToPath(new URL(".", import.meta.url)), fileURLToPath(new URL("../shared", import.meta.url))], + }, + }, });