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.
This commit is contained in:
1 parent
2f5f86452f
commit
3203577a9d
28 files changed
+1508
-758
No files matched your search
+20
-5
@@ -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 };
|
||||
export const pool = { query };
|
||||
export const importSql = (sql) => queryWithCredentials(sql, undefined, true);
|
||||
+80
-24
@@ -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();
|
||||
|
||||
|
||||
+68
-44
@@ -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;
|
||||
|
||||
+17
-28
@@ -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));
|
||||
|
||||
Reference in new issue
Block a user