From 0385648085114a8b57e71e6bea6f6b563152c1f2 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:49:55 +0100 Subject: [PATCH 01/27] feat(i18n): add the view_monitoring texts Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 6 ++++++ dashboard/internal/webui/catalogs/en.json | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 992f1813..e348b31c 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3127,6 +3127,10 @@ "error.login_failed": "Anmeldung konnte nicht gespeichert werden", "error.logs_forbidden": "Für die Dienstprotokolle fehlt die Berechtigung", "error.method_not_allowed": "Diese Anfragemethode wird nicht unterstützt", + "error.monitoring_ack_forbidden": "Quittieren braucht das Recht Einrichten", + "error.monitoring_ack_invalid": "Die Kennung der Meldung ist ungültig.", + "error.monitoring_ack_unknown": "Diese Meldung gibt es nicht mehr.", + "error.monitoring_save_failed": "Die Quittung konnte nicht gespeichert werden.", "error.mqtt_config_forbidden": "Für diese MQTT-Aktion fehlt die Berechtigung", "error.mqtt_config_forbidden.credentials": "Für MQTT-Zugangsdaten fehlt die Berechtigung", "error.mqtt_config_forbidden.reconnect": "Für den Reconnect fehlt die Berechtigung", @@ -5053,6 +5057,8 @@ "users.role.view_history.label": "Verläufe", "users.role.view_logs.desc": "Die Protokolle der Dienste lesen.", "users.role.view_logs.label": "Dienstprotokolle lesen", + "users.role.view_monitoring.desc": "Meldungen zu Energie, Messketten und Lernfunktionen und alle Lernwerte ansehen.", + "users.role.view_monitoring.label": "Monitoring ansehen", "users.role.view_overview.desc": "Die Übersicht sehen.", "users.role.view_overview.label": "Übersicht", "users.role.view_stats.desc": "Die Statistik sehen.", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 556c895b..d5d1c2e4 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3127,6 +3127,10 @@ "error.login_failed": "The sign-in could not be saved", "error.logs_forbidden": "You do not have permission to view the service logs", "error.method_not_allowed": "This request method is not supported", + "error.monitoring_ack_forbidden": "Acknowledging needs the setup right", + "error.monitoring_ack_invalid": "The notice ID is not valid.", + "error.monitoring_ack_unknown": "This notice no longer exists.", + "error.monitoring_save_failed": "The acknowledgement could not be saved.", "error.mqtt_config_forbidden": "You do not have permission for this MQTT action", "error.mqtt_config_forbidden.credentials": "You do not have permission for MQTT credentials", "error.mqtt_config_forbidden.reconnect": "You do not have permission to reconnect", @@ -5053,6 +5057,8 @@ "users.role.view_history.label": "History", "users.role.view_logs.desc": "Read the logs of the services.", "users.role.view_logs.label": "Read service logs", + "users.role.view_monitoring.desc": "See notices about energy, measurement chains and learning, and all learned values.", + "users.role.view_monitoring.label": "View monitoring", "users.role.view_overview.desc": "See the overview.", "users.role.view_overview.label": "Overview", "users.role.view_stats.desc": "See the statistics.", From 44c40f9ab9a97286332aee1fc01336f7338f9b4b Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:51:45 +0100 Subject: [PATCH 02/27] feat(auth): add the view_monitoring right Version 9 of users.json grants view_monitoring to every account, guest preset and HA preset that has view_energy or view_automations (migrateV8), and the defaults for guests and HA users include it. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/auth/auth.go | 21 +++- dashboard/internal/auth/auth_test.go | 2 +- dashboard/internal/auth/migrate.go | 18 ++- dashboard/internal/auth/migrate_test.go | 103 +++++++++++++++--- dashboard/internal/auth/roles.go | 2 + dashboard/internal/auth/roles_test.go | 2 +- dashboard/internal/webui/templates/users.html | 2 +- docs/dashboard/settings-users.md | 2 +- 8 files changed, 127 insertions(+), 25 deletions(-) diff --git a/dashboard/internal/auth/auth.go b/dashboard/internal/auth/auth.go index 058c9b24..32e0cc43 100644 --- a/dashboard/internal/auth/auth.go +++ b/dashboard/internal/auth/auth.go @@ -306,11 +306,12 @@ func (m *Manager) loadLocked() (bool, error) { // Version 4 ergaenzt die Geraete-Rechte (migrateV3), Version 5 ersetzt // unveraenderte Vorgaben (migrateV4Locked), Version 6 gibt Admins die // Backup-Rechte (migrateV5), Version 7 ergaenzt view_efficiency - // (migrateV6). Jede Umschreibung laeuft - // einmal beim Uebergang und nie wieder. + // (migrateV6). Version 9 ergaenzt view_monitoring (migrateV8). Jede + // Umschreibung laeuft einmal beim Uebergang und nie wieder. upgradeV2 := file.Version < 3 upgradeV3 := file.Version < 4 upgradeV6 := file.Version < 7 + upgradeV8 := file.Version < 9 guestRoles := file.GuestRoles if upgradeV2 { guestRoles = migrateV2(guestRoles, true) @@ -321,6 +322,9 @@ func (m *Manager) loadLocked() (bool, error) { if upgradeV6 { guestRoles = migrateV6(guestRoles) } + if upgradeV8 { + guestRoles = migrateV8(guestRoles) + } m.guestRoles = Normalize(guestAllowedOnly(guestRoles)) m.guestRolesReviewed = file.GuestRolesReviewed for name, user := range m.users { @@ -334,6 +338,9 @@ func (m *Manager) loadLocked() (bool, error) { if upgradeV6 { roles = migrateV6(roles) } + if upgradeV8 { + roles = migrateV8(roles) + } user.Roles = Normalize(roles) m.users[name] = user } @@ -357,6 +364,16 @@ func (m *Manager) loadLocked() (bool, error) { m.haRoles.User = migrateV6(m.haRoles.User) } } + if upgradeV8 { + for id, account := range m.haAccounts { + account.Roles = migrateV8(account.Roles) + m.haAccounts[id] = account + } + if m.haRoles != nil { + m.haRoles.Admin = migrateV8(m.haRoles.Admin) + m.haRoles.User = migrateV8(m.haRoles.User) + } + } } if file.Version < usersFileVersion { // Jede Umschreibung schreibt die Datei auf die neue Version. diff --git a/dashboard/internal/auth/auth_test.go b/dashboard/internal/auth/auth_test.go index 082caf50..0c22533a 100644 --- a/dashboard/internal/auth/auth_test.go +++ b/dashboard/internal/auth/auth_test.go @@ -212,7 +212,7 @@ func TestNewGuestsOnlyView(t *testing.T) { if err != nil { t.Fatal(err) } - want := []string{RoleViewDeviceMap, RoleViewDevices, RoleViewEfficiency, RoleViewEnergy, RoleViewHistory, RoleViewOverview, RoleViewStats} + want := []string{RoleViewDeviceMap, RoleViewDevices, RoleViewEfficiency, RoleViewEnergy, RoleViewHistory, RoleViewMonitoring, RoleViewOverview, RoleViewStats} if !reflect.DeepEqual(session.User.Roles, want) { t.Fatalf("new guest roles %v, want %v", session.User.Roles, want) } diff --git a/dashboard/internal/auth/migrate.go b/dashboard/internal/auth/migrate.go index 47bce278..909a0309 100644 --- a/dashboard/internal/auth/migrate.go +++ b/dashboard/internal/auth/migrate.go @@ -7,7 +7,7 @@ import ( // usersFileVersion ist die Version, die users.json heute schreibt. Eine // Datei mit hoeherer Version wird nicht angefasst, siehe Spec Abschnitt 2. -const usersFileVersion = 8 +const usersFileVersion = 9 // ErrUnsupportedUsersVersion meldet eine users.json aus einer neueren Version // des Dashboards. Der Start bricht ab, die Datei bleibt unveraendert. @@ -114,6 +114,18 @@ func migrateV6(roles []string) []string { return out } +// migrateV8 bringt die Rollen einer Datei der Version 8 nach Version 9: wer +// view_energy oder view_automations hat, bekommt view_monitoring. Ein Eintrag, +// der schon da ist, wird nicht doppelt angehaengt. Die Eingabe sind rohe +// Rollen, die Aufrufer normalisieren selbst. +func migrateV8(roles []string) []string { + out := append([]string(nil), roles...) + if (containsRole(roles, RoleViewEnergy) || containsRole(roles, RoleViewAutomations)) && !containsRole(roles, RoleViewMonitoring) { + out = append(out, RoleViewMonitoring) + } + return out +} + // withoutRole liefert eine Kopie ohne den Schluessel. func withoutRole(roles []string, role string) []string { out := make([]string, 0, len(roles)) @@ -136,7 +148,7 @@ func legacyDefaultGuestRoles() []string { // keine Bearbeitung. Normalisiert, wie die Vorgabe nach einem Neustart aus // users.json kommt, damit Migration und Neuinstallation gleich vergleichen. func defaultGuestRoles() []string { - return Normalize([]string{RoleViewDevices, RoleViewDeviceMap, RoleViewEnergy, RoleViewHistory, RoleViewOverview, RoleViewStats, RoleViewEfficiency}) + return Normalize([]string{RoleViewDevices, RoleViewDeviceMap, RoleViewEnergy, RoleViewHistory, RoleViewOverview, RoleViewStats, RoleViewEfficiency, RoleViewMonitoring}) } // defaultHAUserRoles ist die Vorgabe fuer HA-Konten ohne HA-Admin: Ansehen und @@ -144,7 +156,7 @@ func defaultGuestRoles() []string { func defaultHAUserRoles() []string { return Normalize([]string{ RoleViewOverview, RoleViewDevices, RoleViewDeviceAnalysis, RoleViewHistory, RoleViewStats, RoleViewEfficiency, - RoleViewEnergy, RoleViewDeviceMap, RoleViewConfig, RoleViewAutomations, RoleViewDiagnostics, + RoleViewEnergy, RoleViewDeviceMap, RoleViewConfig, RoleViewAutomations, RoleViewDiagnostics, RoleViewMonitoring, RoleOperateDevices, RoleOperateAutomations, RoleEditLayout, RoleEditDeviceAppearance, RoleEditDeviceMapView, RoleEditSettings, RoleCheckUpdates, }) diff --git a/dashboard/internal/auth/migrate_test.go b/dashboard/internal/auth/migrate_test.go index 0edf3a50..a4dbc946 100644 --- a/dashboard/internal/auth/migrate_test.go +++ b/dashboard/internal/auth/migrate_test.go @@ -89,7 +89,7 @@ func TestMigrationKeepsBehaviorOfFieldFile(t *testing.T) { t.Errorf("guest roles %v, want the new view-only default", guest.Roles) } file := readUsersFile(t, path) - if file.Version != 8 || !reflect.DeepEqual(file.GuestRoles, guest.Roles) { + if file.Version != 9 || !reflect.DeepEqual(file.GuestRoles, guest.Roles) { t.Fatalf("file not migrated: version %d guest_roles %v", file.Version, file.GuestRoles) } if !manager.MigrationNotice() { @@ -146,7 +146,7 @@ func TestBootstrapOnlyWithoutNonGuestUser(t *testing.T) { t.Fatal("bootstrap admin must not get http_login") } file := readUsersFile(t, path) - if file.Version != 8 || !reflect.DeepEqual(file.GuestRoles, defaultGuestRoles()) { + if file.Version != 9 || !reflect.DeepEqual(file.GuestRoles, defaultGuestRoles()) { t.Fatalf("bootstrap file version %d guest_roles %v", file.Version, file.GuestRoles) } if manager.MigrationNotice() { @@ -174,7 +174,7 @@ func TestStartNoLongerBackfillsRoles(t *testing.T) { t.Fatalf("admin roles changed on start: %v", manager.users["admin"].Roles) } // Die Version 2 wird nur auf Version 3 gehoben, die Rollen bleiben gleich. - if file := readUsersFile(t, path); file.Version != 8 || !reflect.DeepEqual(file.GuestRoles, []string{"view_overview"}) { + if file := readUsersFile(t, path); file.Version != 9 || !reflect.DeepEqual(file.GuestRoles, []string{"view_overview"}) { t.Fatalf("version 2 file after start: version %d guest_roles %v", file.Version, file.GuestRoles) } } @@ -294,8 +294,8 @@ func TestMigrationFromVersion2KeepsEveryRight(t *testing.T) { } file := readUsersFile(t, path) - if file.Version != 8 { - t.Fatalf("file version %d, want 8", file.Version) + if file.Version != 9 { + t.Fatalf("file version %d, want 9", file.Version) } if manager.MigrationNotice() || !file.GuestRolesReviewed { t.Fatal("version 2 review state must be kept, no new guest notice") @@ -331,8 +331,8 @@ func TestMigrationFromVersion1GivesSetupPermissions(t *testing.T) { if !reflect.DeepEqual(manager.GuestRoles(), defaultGuestRoles()) { t.Fatalf("default guest roles: %v", manager.GuestRoles()) } - if file := readUsersFile(t, path); file.Version != 8 { - t.Fatalf("file version %d, want 8", file.Version) + if file := readUsersFile(t, path); file.Version != 9 { + t.Fatalf("file version %d, want 9", file.Version) } } @@ -381,8 +381,8 @@ func TestMigrationFromVersion3GivesDeviceRights(t *testing.T) { } file := readUsersFile(t, path) - if file.Version != 8 { - t.Fatalf("file version %d, want 8", file.Version) + if file.Version != 9 { + t.Fatalf("file version %d, want 9", file.Version) } if manager.MigrationNotice() { t.Fatal("version 3 migration must not raise the guest notice") @@ -454,8 +454,8 @@ func TestMigrationFromVersion4ReplacesUntouchedPresets(t *testing.T) { if !manager.MigrationNotice() { t.Error("replacing the guest preset must raise the notice") } - if file := readUsersFile(t, path); file.Version != 8 { - t.Fatalf("file version %d, want 8", file.Version) + if file := readUsersFile(t, path); file.Version != 9 { + t.Fatalf("file version %d, want 9", file.Version) } before, _ := os.ReadFile(path) mustManager(t, path, "admin", "") @@ -578,8 +578,8 @@ func TestMigrateV6GrantsEfficiencyToStatsViewers(t *testing.T) { if len(accounts) != 1 || !containsRole(accounts[0].Roles, RoleViewEfficiency) { t.Errorf("ha account roles: %v", accounts) } - if file := readUsersFile(t, path); file.Version != 8 { - t.Fatalf("file version %d, want 8", file.Version) + if file := readUsersFile(t, path); file.Version != 9 { + t.Fatalf("file version %d, want 9", file.Version) } } @@ -602,8 +602,8 @@ func TestAdminPresetsGetBackupRolesHAPresetsDoNot(t *testing.T) { t.Errorf("guest got %s", key) } } - if file := readUsersFile(t, path); file.Version != 8 { - t.Fatalf("file version %d, want 8", file.Version) + if file := readUsersFile(t, path); file.Version != 9 { + t.Fatalf("file version %d, want 9", file.Version) } } @@ -626,7 +626,7 @@ func TestMigrateV5KeepsReviewedGuestRolesEqualToLegacy(t *testing.T) { if manager.MigrationNotice() { t.Error("a reviewed guest list must not raise the notice again") } - if file := readUsersFile(t, path); !file.GuestRolesReviewed || file.Version != 8 { + if file := readUsersFile(t, path); !file.GuestRolesReviewed || file.Version != 9 { t.Fatalf("file after start: reviewed %v version %d", file.GuestRolesReviewed, file.Version) } } @@ -697,3 +697,74 @@ func TestUsersFileVersion8IsNotMigratedAgain(t *testing.T) { t.Fatal("start of a version 8 file changed users.json") } } + +func TestMigrateV8GrantsMonitoringToEnergyAndAutomationViewers(t *testing.T) { + cases := []struct { + in []string + want bool + }{ + {[]string{RoleViewEnergy}, true}, + {[]string{RoleViewAutomations}, true}, + {[]string{RoleViewDevices}, false}, + {[]string{RoleViewEnergy, RoleViewMonitoring}, true}, + } + for _, c := range cases { + got := migrateV8(c.in) + if containsRole(got, RoleViewMonitoring) != c.want { + t.Errorf("migrateV8(%v) = %v, want view_monitoring %v", c.in, got, c.want) + } + n := 0 + for _, r := range got { + if r == RoleViewMonitoring { + n++ + } + } + if n > 1 { + t.Errorf("migrateV8(%v) adds view_monitoring twice: %v", c.in, got) + } + } +} + +func TestLoadVersion8AddsMonitoringOnce(t *testing.T) { + path := filepath.Join(t.TempDir(), "users.json") + // Version 8: Admin und Gastvorgabe mit view_energy, HA-Vorgabe User mit view_automations. + writeJSON(t, path, map[string]any{ + "version": 8, + "guest_roles": []string{RoleViewEnergy}, + "guest_roles_reviewed": true, + "users": []map[string]any{ + {"username": "admin", "password_hash": mustHash(t, "secret-pass"), "roles": []string{RoleViewEnergy, RoleUserManagement}}, + }, + "ha_roles": map[string]any{ + "admin": []string{RoleViewEnergy}, + "user": []string{RoleViewAutomations}, + }, + }) + manager := mustManager(t, path, "admin", "") + + if !containsRole(manager.users["admin"].Roles, RoleViewMonitoring) { + t.Errorf("admin with view_energy lacks view_monitoring: %v", manager.users["admin"].Roles) + } + if !containsRole(manager.GuestRoles(), RoleViewMonitoring) { + t.Errorf("guest preset with view_energy lacks view_monitoring: %v", manager.GuestRoles()) + } + admin9, user9, set := manager.HARoles() + if !set || !containsRole(admin9, RoleViewMonitoring) || !containsRole(user9, RoleViewMonitoring) { + t.Errorf("ha presets admin %v user %v", admin9, user9) + } + if file := readUsersFile(t, path); file.Version != 9 { + t.Fatalf("file version %d, want 9", file.Version) + } + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + mustManager(t, path, "admin", "") + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(before, after) { + t.Fatal("second load of a version 8 migration changed users.json") + } +} diff --git a/dashboard/internal/auth/roles.go b/dashboard/internal/auth/roles.go index 68b1225c..5203bdf6 100644 --- a/dashboard/internal/auth/roles.go +++ b/dashboard/internal/auth/roles.go @@ -25,6 +25,7 @@ const ( RoleViewConfig = "view_config" RoleViewAutomations = "view_automations" RoleViewDiagnostics = "view_diagnostics" + RoleViewMonitoring = "view_monitoring" ) // Bedienen, Gestalten, Einrichten, Updates und System. @@ -77,6 +78,7 @@ var roleCatalog = []RoleInfo{ {Key: RoleViewConfig, Category: CategoryView, GuestAllowed: true, HAAllowed: true}, {Key: RoleViewAutomations, Category: CategoryView, GuestAllowed: true, HAAllowed: true}, {Key: RoleViewDiagnostics, Category: CategoryView, GuestAllowed: true, HAAllowed: true}, + {Key: RoleViewMonitoring, Category: CategoryView, GuestAllowed: true, HAAllowed: true}, {Key: RoleOperateDevices, Category: CategoryOperate, Requires: RoleViewDevices, GuestAllowed: true, HAAllowed: true}, {Key: RoleOperateAutomations, Category: CategoryOperate, Requires: RoleViewAutomations, GuestAllowed: true, HAAllowed: true}, {Key: "edit_layout", Category: CategoryDesign, Requires: RoleViewOverview, GuestAllowed: true, HAAllowed: true}, diff --git a/dashboard/internal/auth/roles_test.go b/dashboard/internal/auth/roles_test.go index 92c47e39..23724e49 100644 --- a/dashboard/internal/auth/roles_test.go +++ b/dashboard/internal/auth/roles_test.go @@ -8,7 +8,7 @@ import ( func TestRolesCatalogMatchesSpec(t *testing.T) { keys := AllRoles() - if len(keys) != 38 || keys[0] != RoleViewOverview || keys[len(keys)-1] != RoleHTTPLogin { + if len(keys) != 39 || keys[0] != RoleViewOverview || keys[len(keys)-1] != RoleHTTPLogin { t.Fatalf("catalog order: %v", keys) } for _, key := range []string{RoleMQTTConfig, RoleUpdateSettings, RoleViewLogs, RoleSystemActions, RoleTailscale, RoleNetwork, RoleUserManagement} { diff --git a/dashboard/internal/webui/templates/users.html b/dashboard/internal/webui/templates/users.html index 81564e63..24e063dd 100644 --- a/dashboard/internal/webui/templates/users.html +++ b/dashboard/internal/webui/templates/users.html @@ -1,6 +1,6 @@ {{define "users"}} {{/* i18n-keys: users.category.view, users.category.view.desc, users.category.operate, users.category.operate.desc, users.category.design, users.category.design.desc, users.category.setup, users.category.setup.desc, users.category.updates, users.category.updates.desc, users.category.system, users.category.system.desc */}} -{{/* i18n-keys: users.role.view_overview.label, users.role.view_overview.desc, users.role.view_devices.label, users.role.view_devices.desc, users.role.view_history.label, users.role.view_history.desc, users.role.view_stats.label, users.role.view_stats.desc, users.role.view_efficiency.label, users.role.view_efficiency.desc, users.role.view_energy.label, users.role.view_energy.desc, users.role.view_device_map.label, users.role.view_device_map.desc, users.role.view_config.label, users.role.view_config.desc */}} +{{/* i18n-keys: users.role.view_overview.label, users.role.view_overview.desc, users.role.view_devices.label, users.role.view_devices.desc, users.role.view_history.label, users.role.view_history.desc, users.role.view_stats.label, users.role.view_stats.desc, users.role.view_efficiency.label, users.role.view_efficiency.desc, users.role.view_energy.label, users.role.view_energy.desc, users.role.view_device_map.label, users.role.view_device_map.desc, users.role.view_config.label, users.role.view_config.desc, users.role.view_monitoring.label, users.role.view_monitoring.desc */}} {{/* i18n-keys: users.role.view_automations.label, users.role.view_automations.desc, users.role.view_diagnostics.label, users.role.view_diagnostics.desc, users.role.operate_devices.label, users.role.operate_devices.desc, users.role.operate_automations.label, users.role.operate_automations.desc, users.role.edit_layout.label, users.role.edit_layout.desc, users.role.edit_device_map_view.label, users.role.edit_device_map_view.desc, users.role.edit_settings.label, users.role.edit_settings.desc, users.role.view_device_analysis.label, users.role.edit_device_appearance.label */}} {{/* i18n-keys: users.preset.ha_admin, users.preset.ha_admin.desc, users.preset.ha_user, users.preset.ha_user.desc, users.ha.tag.paired, users.ha.tag.waiting, users.ha.tag.unpaired */}} {{/* i18n-keys: users.role.automations.label, users.role.automations.desc, users.role.edit_energy.label, users.role.edit_energy.desc, users.role.edit_device_map.label, users.role.edit_device_map.desc, users.role.edit_config.label, users.role.edit_config.desc, users.role.delete_device_discovery.label, users.role.delete_device_discovery.desc, users.role.mqtt_config.label, users.role.mqtt_config.desc, users.role.edit_setup.label, users.role.edit_setup.desc, users.role.setup_tiny_tuya.label, users.role.setup_tiny_tuya.desc */}} diff --git a/docs/dashboard/settings-users.md b/docs/dashboard/settings-users.md index 6d5e358d..e555d61c 100644 --- a/docs/dashboard/settings-users.md +++ b/docs/dashboard/settings-users.md @@ -53,7 +53,7 @@ the whole group on or off. | Category | What it allows | |---|---| -| View | which pages are visible: Overview, Devices, Device analysis, History, Statistics, Energy, Efficiency, Device map, Configuration, Automations, Diagnostics | +| View | which pages are visible: Overview, Devices, Device analysis, History, Statistics, Energy, Efficiency, Device map, Configuration, Automations, Diagnostics, Monitoring | | Operate | switch devices and set values, turn rules and scenarios on and off | | Design | arrange the overview, style devices (icon and favourites), default view of the device map, change the appearance | | Setup | edit automations, energy assignment, edit device map, edit device configuration, ignore and remove devices from discovery, MQTT connection, set up the dashboard, set up TinyTuya, set up Tailscale, set up the network | From e85d98c298542c670df70647b32ed9a25a7d45c1 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:53:10 +0100 Subject: [PATCH 03/27] feat(monitoring): collect notices from energy, chains and learning Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/monitoring/notice.go | 226 +++++++++++++++++++ dashboard/internal/monitoring/notice_test.go | 96 ++++++++ 2 files changed, 322 insertions(+) create mode 100644 dashboard/internal/monitoring/notice.go create mode 100644 dashboard/internal/monitoring/notice_test.go diff --git a/dashboard/internal/monitoring/notice.go b/dashboard/internal/monitoring/notice.go new file mode 100644 index 00000000..9908c252 --- /dev/null +++ b/dashboard/internal/monitoring/notice.go @@ -0,0 +1,226 @@ +package monitoring + +import ( + "fmt" + "sort" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" + "github.com/Developer-Simon/energy-node-dashboard/internal/energy" + "github.com/Developer-Simon/energy-node-dashboard/internal/settings" +) + +// Step ist ein empfohlener Schritt. Code ist der Katalogschlüssel +// monitoring.step., Target das Sprungziel (leer: nur Text). +type Step struct { + Code string `json:"code"` + Target string `json:"target,omitempty"` + IDs []string `json:"ids,omitempty"` + Chain string `json:"chain,omitempty"` +} + +// Ack ist eine Quittung: Zeitpunkt in Unix-Sekunden und Nutzername. +type Ack struct { + At int64 `json:"at"` + User string `json:"user"` +} + +// Notice ist eine Meldung. Since ist der früheste bekannte Beginn aus der +// Quelle (Kettenbefund), sonst null. FirstSeen und Ack setzt der Store. +type Notice struct { + ID string `json:"id"` + Source string `json:"source"` // energy, chain, learn + Severity string `json:"severity"` // warn, info + Code string `json:"code"` + Params map[string]any `json:"params,omitempty"` + Evidence *autolearn.Evidence `json:"evidence,omitempty"` + Steps []Step `json:"steps"` + FirstSeen int64 `json:"first_seen"` + Ack *Ack `json:"ack"` + Since time.Time `json:"-"` +} + +// Input sind die Quellen einer Sammlung. +type Input struct { + Snapshot energy.Snapshot + Config settings.EnergyConfig + Findings []autolearn.Finding +} + +// Collect baut die Meldungen in fester Reihenfolge: energy, chain, learn. +func Collect(in Input) []Notice { + out := []Notice{} + out = append(out, energyNotices(in)...) + out = append(out, chainNotices(in.Snapshot)...) + out = append(out, learnNotices(in.Findings)...) + return out +} + +func hasLoadRole(assignments map[string]energy.Assignment) bool { + for _, a := range assignments { + if a.Role == energy.RoleLoad { + return true + } + } + return false +} + +func energyNotices(in Input) []Notice { + snap := in.Snapshot + var out []Notice + + if in.Config.Interpretation.LoadMode == energy.LoadModeMeasured && !hasLoadRole(in.Config.Assignments) { + out = append(out, Notice{ + ID: "energy:measured_no_meter", + Source: "energy", + Severity: "warn", + Code: "measured_no_meter", + Steps: []Step{ + {Code: "set_load_role", Target: "energy"}, + {Code: "load_mode_auto", Target: "energy"}, + }, + }) + } + + if snap.BatterySoCWithoutCapacity > 0 { + out = append(out, Notice{ + ID: "energy:soc_capacity", + Source: "energy", + Severity: "warn", + Code: "soc_capacity", + Params: map[string]any{"count": snap.BatterySoCWithoutCapacity}, + Steps: []Step{ + {Code: "enter_capacity", Target: "energy"}, + }, + }) + } + + if snap.UnassignedCount > 0 { + names := []string{} + ids := []string{} + for _, e := range snap.Unassigned { + ids = append(ids, e.EntityID) + if len(names) < 4 { + name := e.Name + if name == "" { + name = e.EntityID + } + names = append(names, fmt.Sprintf("%s: %.0f %s", name, e.Value, e.Unit)) + } + } + out = append(out, Notice{ + ID: "energy:unassigned", + Source: "energy", + Severity: "info", + Code: "unassigned", + Params: map[string]any{ + "count": snap.UnassignedCount, + "names": names, + "more": snap.UnassignedCount - len(names), + }, + Steps: []Step{ + {Code: "assign_roles", Target: "energy.focus", IDs: ids}, + {Code: "hide_values", Target: "energy"}, + }, + }) + } + + if len(in.Config.RoleNeeded) > 0 { + ids := append([]string{}, in.Config.RoleNeeded...) + sort.Strings(ids) + out = append(out, Notice{ + ID: "energy:role_needed", + Source: "energy", + Severity: "info", + Code: "role_needed", + Params: map[string]any{"ids": ids}, + Steps: []Step{ + {Code: "set_role", Target: "energy.focus", IDs: ids}, + {Code: "role_keep", Target: "action.role_keep", IDs: ids}, + }, + }) + } + + return out +} + +func chainNotices(snap energy.Snapshot) []Notice { + var out []Notice + for _, chain := range snap.Chains { + for _, f := range chain.Findings { + steps := []Step{{Code: "chain_open", Target: "energy.chain", Chain: f.ChainID}} + if f.Suggestion != nil { + steps = append(steps, Step{Code: "chain_suggestion", Target: "energy.chain", Chain: f.ChainID}) + } + steps = append(steps, + Step{Code: "efficiency_open", Target: "efficiency"}, + Step{Code: "devicemap_check", Target: "devicemap"}, + ) + out = append(out, Notice{ + ID: fmt.Sprintf("chain:%s:%s", f.ChainID, f.Kind), + Source: "chain", + Severity: "warn", + Code: "chain", + Params: map[string]any{ + "kind": f.Kind, + "chain": f.ChainLabel, + "from": f.From, + "to": f.To, + "since": f.Since.Format(time.RFC3339), + }, + Steps: steps, + Since: f.Since, + }) + } + } + return out +} + +func learnSeverity(s string) string { + switch s { + case "warn", "bad": + return "warn" + case "info": + return "info" + default: + return "info" + } +} + +func learnNotices(findings []autolearn.Finding) []Notice { + var out []Notice + for _, f := range findings { + if len(f.RuleIDs) != 0 || len(f.Apply) != 0 { + continue + } + params := make(map[string]any, len(f.Summary.Params)+1) + for k, v := range f.Summary.Params { + params[k] = v + } + params["kind"] = f.Kind + + var steps []Step + if f.Kind == "shade" { + steps = append(steps, + Step{Code: "shade_look"}, + Step{Code: "shade_accept"}, + ) + } + steps = append(steps, Step{Code: "learned_open", Target: "learned"}) + + n := Notice{ + ID: "learn:" + f.ID, + Source: "learn", + Severity: learnSeverity(f.Severity), + Code: f.Summary.Code, + Params: params, + Steps: steps, + } + if f.Evidence.Shape != "" { + ev := f.Evidence + n.Evidence = &ev + } + out = append(out, n) + } + return out +} diff --git a/dashboard/internal/monitoring/notice_test.go b/dashboard/internal/monitoring/notice_test.go new file mode 100644 index 00000000..5a033637 --- /dev/null +++ b/dashboard/internal/monitoring/notice_test.go @@ -0,0 +1,96 @@ +package monitoring + +import ( + "reflect" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" + "github.com/Developer-Simon/energy-node-dashboard/internal/energy" + "github.com/Developer-Simon/energy-node-dashboard/internal/settings" +) + +func TestCollectEnergyNotices(t *testing.T) { + in := Input{ + Snapshot: energy.Snapshot{ + UnassignedCount: 6, + Unassigned: []energy.UnassignedEntity{ + {EntityID: "a", Name: "Limit", Value: 800.4, Unit: "W"}, + {EntityID: "b", Name: "Total", Value: 878, Unit: "W"}, + }, + BatterySoCWithoutCapacity: 1, + }, + Config: settings.EnergyConfig{ + Interpretation: energy.Interpretation{LoadMode: energy.LoadModeMeasured}, + RoleNeeded: []string{"z", "x"}, + }, + } + got := Collect(in) + ids := []string{} + for _, n := range got { + ids = append(ids, n.ID) + } + want := []string{"energy:measured_no_meter", "energy:soc_capacity", "energy:unassigned", "energy:role_needed"} + if !reflect.DeepEqual(ids, want) { + t.Fatalf("ids = %v, want %v", ids, want) + } + u := got[2] + if u.Params["count"] != 6 || u.Params["more"] != 4 { + t.Errorf("unassigned params = %v", u.Params) + } + if names := u.Params["names"].([]string); names[0] != "Limit: 800 W" { + t.Errorf("names = %v", names) + } + if u.Steps[0].Target != "energy.focus" || !reflect.DeepEqual(u.Steps[0].IDs, []string{"a", "b"}) { + t.Errorf("assign step = %+v", u.Steps[0]) + } + if rn := got[3]; !reflect.DeepEqual(rn.Params["ids"], []string{"x", "z"}) || rn.Steps[1].Target != "action.role_keep" { + t.Errorf("role_needed = %+v", rn) + } +} + +func TestCollectMeasuredWithLoadRoleIsQuiet(t *testing.T) { + in := Input{Config: settings.EnergyConfig{ + Interpretation: energy.Interpretation{LoadMode: energy.LoadModeMeasured}, + Assignments: map[string]energy.Assignment{"haus": {Role: energy.RoleLoad}}, + }} + if got := Collect(in); len(got) != 0 { + t.Fatalf("got %v, want no notice", got) + } +} + +func TestCollectChainFindings(t *testing.T) { + since := time.Date(2026, 11, 18, 10, 0, 0, 0, time.UTC) + in := Input{Snapshot: energy.Snapshot{Chains: []energy.ChainState{{ + ID: "balkon", Label: "Balkon", + Findings: []energy.ChainFinding{{Kind: "drift", ChainID: "balkon", ChainLabel: "Balkon", Since: since, From: "Plug", To: "Umrichter"}}, + }}}} + got := Collect(in) + if len(got) != 1 || got[0].ID != "chain:balkon:drift" || !got[0].Since.Equal(since) { + t.Fatalf("got %+v", got) + } + if got[0].Steps[0].Target != "energy.chain" || got[0].Steps[0].Chain != "balkon" { + t.Errorf("first step = %+v", got[0].Steps[0]) + } +} + +func TestCollectLearnOnlyRulelessWithoutApply(t *testing.T) { + in := Input{Findings: []autolearn.Finding{ + {ID: "shade:225:15", Kind: "shade", Group: "check", Severity: "info", + Summary: autolearn.Text{Code: "check.shade", Params: map[string]any{"from": "14:35"}}, + Evidence: autolearn.Evidence{Shape: "curve"}}, + {ID: "duplicate:a:b", Kind: "duplicate", RuleIDs: []string{"a", "b"}}, + {ID: "baseload:2026-11-01", Kind: "baseload", Apply: []autolearn.Fix{{}}}, + }} + got := Collect(in) + if len(got) != 1 || got[0].ID != "learn:shade:225:15" || got[0].Code != "check.shade" || got[0].Evidence == nil { + t.Fatalf("got %+v", got) + } + codes := []string{} + for _, s := range got[0].Steps { + codes = append(codes, s.Code) + } + if !reflect.DeepEqual(codes, []string{"shade_look", "shade_accept", "learned_open"}) { + t.Errorf("steps = %v", codes) + } +} From f231be943bee690ec5dca59fb85ce68b01bd9ce4 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:54:07 +0100 Subject: [PATCH 04/27] feat(monitoring): keep first seen and acknowledgements per notice Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/backup/catalog.go | 1 + dashboard/internal/monitoring/store.go | 171 ++++++++++++++++++++ dashboard/internal/monitoring/store_test.go | 72 +++++++++ 3 files changed, 244 insertions(+) create mode 100644 dashboard/internal/monitoring/store.go create mode 100644 dashboard/internal/monitoring/store_test.go diff --git a/dashboard/internal/backup/catalog.go b/dashboard/internal/backup/catalog.go index 5794bf91..ed4f2399 100644 --- a/dashboard/internal/backup/catalog.go +++ b/dashboard/internal/backup/catalog.go @@ -104,6 +104,7 @@ var catalog = []Entry{ {RootData, "autolearn/pvmodel.json", ClassRuntime, AreaHistory}, {RootData, "autolearn/pvweather.json", ClassRuntime, AreaHistory}, {RootData, "autolearn/cycles.json", ClassRuntime, AreaHistory}, + {RootData, "autolearn/monitoring.json", ClassRuntime, AreaHistory}, {RootData, "autolearn/*", ClassRuntime, AreaHistory}, {RootData, "autolearn/days/*", ClassRuntime, AreaHistory}, // Lernstand ueber Neustarte: erster Start und ob schon etwas gelernt wurde. diff --git a/dashboard/internal/monitoring/store.go b/dashboard/internal/monitoring/store.go new file mode 100644 index 00000000..446dd447 --- /dev/null +++ b/dashboard/internal/monitoring/store.go @@ -0,0 +1,171 @@ +package monitoring + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "time" +) + +// absentGrace ist die Zeit, die eine fehlende ID im Speicher bleibt. +const absentGrace = time.Hour + +// ErrUnknown meldet eine ID, die gerade keine Meldung ist. +var ErrUnknown = errors.New("monitoring: unknown notice") + +// entry ist der gespeicherte Zustand einer ID. +type entry struct { + FirstSeen int64 `json:"first_seen"` + LastSeen int64 `json:"last_seen"` + Ack *Ack `json:"ack,omitempty"` +} + +// storeFile ist das Dateiformat des Speichers. +type storeFile struct { + Version int `json:"version"` + Entries map[string]*entry `json:"entries"` +} + +// Store merkt je Meldung das Erstsehen und die Quittung. Er ist sicher für +// parallelen Zugriff. +type Store struct { + mu sync.Mutex + path string + entries map[string]*entry + present map[string]bool // IDs aus dem letzten Apply + saved []byte // zuletzt geschriebener oder geladener Inhalt + logf func(string, ...any) +} + +// OpenStore lädt den Speicher aus path. Fehlt die Datei oder ist sie kaputt, +// startet der Speicher leer. Ein leerer Pfad hält den Speicher nur im Speicher. +func OpenStore(path string, logf func(string, ...any)) *Store { + if logf == nil { + logf = func(string, ...any) {} + } + s := &Store{ + path: path, + entries: map[string]*entry{}, + present: map[string]bool{}, + logf: logf, + } + if path == "" { + return s + } + data, err := os.ReadFile(path) + if err != nil { + if !os.IsNotExist(err) { + logf("monitoring: store not read: %v", err) + } + return s + } + var f storeFile + if err := json.Unmarshal(data, &f); err != nil { + logf("monitoring: store broken, starting empty: %v", err) + return s + } + if f.Entries != nil { + s.entries = f.Entries + } + s.saved = data + return s +} + +// Apply setzt FirstSeen und Ack in notices (an Ort und Stelle), merkt neue +// IDs, frischt LastSeen auf und entfernt IDs, die länger als absentGrace fehlen. +func (s *Store) Apply(notices []Notice, now time.Time) { + s.mu.Lock() + defer s.mu.Unlock() + nowUnix := now.Unix() + s.present = map[string]bool{} + for i := range notices { + n := ¬ices[i] + s.present[n.ID] = true + e, ok := s.entries[n.ID] + if !ok { + e = &entry{FirstSeen: nowUnix} + s.entries[n.ID] = e + } + if !n.Since.IsZero() && n.Since.Before(now) { + if since := n.Since.Unix(); since < e.FirstSeen { + e.FirstSeen = since + } + } + e.LastSeen = nowUnix + n.FirstSeen = e.FirstSeen + n.Ack = nil + if e.Ack != nil { + ack := *e.Ack + n.Ack = &ack + } + } + for id, e := range s.entries { + if s.present[id] { + continue + } + if now.Sub(time.Unix(e.LastSeen, 0)) > absentGrace { + delete(s.entries, id) + } + } +} + +// SetAck quittiert (ack true) oder nimmt zurück. Nur für IDs, die beim +// letzten Apply da waren, sonst ErrUnknown. +func (s *Store) SetAck(id string, ack bool, user string, now time.Time) error { + s.mu.Lock() + defer s.mu.Unlock() + if !s.present[id] { + return ErrUnknown + } + e, ok := s.entries[id] + if !ok { + return ErrUnknown + } + if ack { + e.Ack = &Ack{At: now.Unix(), User: user} + } else { + e.Ack = nil + } + return nil +} + +// Save schreibt atomar (Temp-Datei, Rename), nur bei Änderung. +func (s *Store) Save() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.path == "" { + return nil + } + if len(s.entries) == 0 && s.saved == nil { + return nil + } + data, err := json.MarshalIndent(storeFile{Version: 1, Entries: s.entries}, "", " ") + if err != nil { + return fmt.Errorf("monitoring: store could not be encoded: %w", err) + } + if bytes.Equal(data, s.saved) { + return nil + } + tmp, err := os.CreateTemp(filepath.Dir(s.path), ".monitoring-*.tmp") + if err != nil { + return fmt.Errorf("monitoring: save store: %w", err) + } + tmpName := tmp.Name() + _, err = tmp.Write(data) + if cerr := tmp.Close(); err == nil { + err = cerr + } + if err == nil { + err = os.Rename(tmpName, s.path) + } + if err != nil { + _ = os.Remove(tmpName) + return fmt.Errorf("monitoring: save store: %w", err) + } + s.saved = data + return nil +} diff --git a/dashboard/internal/monitoring/store_test.go b/dashboard/internal/monitoring/store_test.go new file mode 100644 index 00000000..d5214291 --- /dev/null +++ b/dashboard/internal/monitoring/store_test.go @@ -0,0 +1,72 @@ +package monitoring + +import ( + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +func TestStoreFirstSeenAckAndGrace(t *testing.T) { + path := filepath.Join(t.TempDir(), "monitoring.json") + s := OpenStore(path, t.Logf) + t0 := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC) + n := []Notice{{ID: "energy:unassigned"}} + s.Apply(n, t0) + if n[0].FirstSeen != t0.Unix() || n[0].Ack != nil { + t.Fatalf("first apply = %+v", n[0]) + } + if err := s.SetAck("energy:unassigned", true, "admin", t0.Add(time.Minute)); err != nil { + t.Fatal(err) + } + // 59 Minuten weg, dann wieder da: Quittung und Erstsehen bleiben. + s.Apply(nil, t0.Add(59*time.Minute)) + n = []Notice{{ID: "energy:unassigned"}} + s.Apply(n, t0.Add(60*time.Minute)) + if n[0].FirstSeen != t0.Unix() || n[0].Ack == nil || n[0].Ack.User != "admin" { + t.Fatalf("after short absence = %+v", n[0]) + } + // Über eine Stunde weg: vergessen, kommt neu. + s.Apply(nil, t0.Add(3*time.Hour)) + n = []Notice{{ID: "energy:unassigned"}} + s.Apply(n, t0.Add(3*time.Hour+time.Minute)) + if n[0].Ack != nil || n[0].FirstSeen != t0.Add(3*time.Hour+time.Minute).Unix() { + t.Fatalf("after long absence = %+v", n[0]) + } +} + +func TestStoreSinceWinsWhenEarlier(t *testing.T) { + s := OpenStore("", t.Logf) + since := time.Date(2026, 11, 18, 0, 0, 0, 0, time.UTC) + n := []Notice{{ID: "chain:a:drift", Since: since}} + s.Apply(n, time.Date(2026, 11, 22, 0, 0, 0, 0, time.UTC)) + if n[0].FirstSeen != since.Unix() { + t.Fatalf("first_seen = %d, want %d", n[0].FirstSeen, since.Unix()) + } +} + +func TestStoreUnknownAckAndPersistence(t *testing.T) { + path := filepath.Join(t.TempDir(), "monitoring.json") + s := OpenStore(path, t.Logf) + now := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC) + if err := s.SetAck("nope", true, "admin", now); !errors.Is(err, ErrUnknown) { + t.Fatalf("err = %v, want ErrUnknown", err) + } + if err := s.Save(); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("empty store wrote a file: %v", err) + } + s.Apply([]Notice{{ID: "x"}}, now) + _ = s.SetAck("x", true, "admin", now) + if err := s.Save(); err != nil { + t.Fatal(err) + } + n := []Notice{{ID: "x"}} + OpenStore(path, t.Logf).Apply(n, now.Add(time.Minute)) + if n[0].Ack == nil || n[0].FirstSeen != now.Unix() { + t.Fatalf("reloaded = %+v", n[0]) + } +} From 2739eaefbce280c7a021903976ad128c63262c95 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:58:27 +0100 Subject: [PATCH 05/27] feat(i18n): add the monitoring unavailable error text Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 1 + dashboard/internal/webui/catalogs/en.json | 1 + 2 files changed, 2 insertions(+) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index e348b31c..45da86e3 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3131,6 +3131,7 @@ "error.monitoring_ack_invalid": "Die Kennung der Meldung ist ungültig.", "error.monitoring_ack_unknown": "Diese Meldung gibt es nicht mehr.", "error.monitoring_save_failed": "Die Quittung konnte nicht gespeichert werden.", + "error.monitoring_unavailable": "Monitoring ist auf dieser Instanz nicht verfügbar.", "error.mqtt_config_forbidden": "Für diese MQTT-Aktion fehlt die Berechtigung", "error.mqtt_config_forbidden.credentials": "Für MQTT-Zugangsdaten fehlt die Berechtigung", "error.mqtt_config_forbidden.reconnect": "Für den Reconnect fehlt die Berechtigung", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index d5d1c2e4..d078e5ef 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3131,6 +3131,7 @@ "error.monitoring_ack_invalid": "The notice ID is not valid.", "error.monitoring_ack_unknown": "This notice no longer exists.", "error.monitoring_save_failed": "The acknowledgement could not be saved.", + "error.monitoring_unavailable": "Monitoring is not available on this instance.", "error.mqtt_config_forbidden": "You do not have permission for this MQTT action", "error.mqtt_config_forbidden.credentials": "You do not have permission for MQTT credentials", "error.mqtt_config_forbidden.reconnect": "You do not have permission to reconnect", From 55f0eb2e643b83c7f7b9df42093f3616eb4d4f2a Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:58:58 +0100 Subject: [PATCH 06/27] feat(monitoring): serve notices and learned values with acknowledgement Adds GET /api/v1/monitoring with the notices, the count of new notices and the learned values, and POST /api/v1/monitoring/ack to acknowledge or take back a notice. Reading needs view_monitoring, acknowledging also needs edit_setup. The learned values are built by the same helper as GET /api/v1/automations/learned. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/httpapi/access.go | 2 + dashboard/internal/httpapi/access_test.go | 13 ++ .../internal/httpapi/automation_learned.go | 57 ++++-- .../httpapi/automation_learned_test.go | 8 +- dashboard/internal/httpapi/httpapi.go | 5 + dashboard/internal/httpapi/monitoring.go | 131 ++++++++++++++ dashboard/internal/httpapi/monitoring_test.go | 170 ++++++++++++++++++ docs/developing/api-auth.md | 1 + docs/developing/api.md | 32 ++++ 9 files changed, 397 insertions(+), 22 deletions(-) create mode 100644 dashboard/internal/httpapi/monitoring.go create mode 100644 dashboard/internal/httpapi/monitoring_test.go diff --git a/dashboard/internal/httpapi/access.go b/dashboard/internal/httpapi/access.go index 5e54080c..defaeb08 100644 --- a/dashboard/internal/httpapi/access.go +++ b/dashboard/internal/httpapi/access.go @@ -172,6 +172,8 @@ var routeTable = map[string]routeAccess{ "/api/v1/automations/suggestions": {group: groupPage, view: auth.RoleViewAutomations}, "/api/v1/automations/suggestions/": {group: groupPage, view: auth.RoleViewAutomations}, "/api/v1/automations/learned": {group: groupPage, view: auth.RoleViewAutomations}, + "/api/v1/monitoring": {group: groupPage, view: auth.RoleViewMonitoring}, + "/api/v1/monitoring/ack": {group: groupPage, view: auth.RoleViewMonitoring}, "/api/v1/learning/status": {group: groupPage, view: auth.RoleViewAutomations}, "/api/v1/energy/": {group: groupPage, view: auth.RoleViewEnergy}, "/api/v1/energy/stats/chains": {group: groupPage, view: auth.RoleViewStats}, diff --git a/dashboard/internal/httpapi/access_test.go b/dashboard/internal/httpapi/access_test.go index 9be66996..4e1785cb 100644 --- a/dashboard/internal/httpapi/access_test.go +++ b/dashboard/internal/httpapi/access_test.go @@ -112,6 +112,19 @@ func TestEfficiencyRoutesNeedTheirOwnView(t *testing.T) { } } +func TestMonitoringRoutesNeedViewMonitoring(t *testing.T) { + cases := map[string]string{ + "/api/v1/monitoring": auth.RoleViewMonitoring, + "/api/v1/monitoring/ack": auth.RoleViewMonitoring, + } + for path, view := range cases { + access, ok := routeTable[path] + if !ok || access.group != groupPage || access.view != view { + t.Errorf("routeTable[%s] = %+v, want a page gate on %s", path, access, view) + } + } +} + func TestConfigurationViewFollowsTheName(t *testing.T) { cases := map[string]string{ "/api/v1/configurations/automation_rules": auth.RoleViewAutomations, diff --git a/dashboard/internal/httpapi/automation_learned.go b/dashboard/internal/httpapi/automation_learned.go index 9d41f07c..59b0b335 100644 --- a/dashboard/internal/httpapi/automation_learned.go +++ b/dashboard/internal/httpapi/automation_learned.go @@ -65,27 +65,48 @@ func handleAutomationLearned(learning *LearningDeps, source learnedValueSource, writeErrorKey(w, http.StatusNotImplemented, "learning_unavailable", "error.learning_unavailable", nil, "Die Lernfunktionen sind nicht verfügbar") return } - body := automationLearnedBody{Enabled: true, Values: []learnedValueView{}} - if learning != nil && learning.Settings != nil { - // Without readable settings everything stays on, as for the suggestions. - if value, err := learning.Settings(); err == nil { - body.Enabled = !value.AutomationPatternsDisabled && !value.AutomationHabitsDisabled - } - } - var weeks []autolearn.Week - if season != nil { - now := time.Now() - from := isoWeekKeyOf(now.AddDate(0, -learnedYearMonths, 0)) - weeks = season.Weeks(from, isoWeekKeyOf(now)) + writeJSON(w, learnedBody(learning, source, exists, season)) + } +} + +// learnedBody builds the learned values for GET /api/v1/automations/learned and +// the monitoring page. Values is never null. Without a source the list stays +// empty. +func learnedBody(learning *LearningDeps, source learnedValueSource, exists func(string) bool, season learnedSeasonSource) automationLearnedBody { + body := automationLearnedBody{Enabled: true, Values: []learnedValueView{}} + if learning != nil && learning.Settings != nil { + // Without readable settings everything stays on, as for the suggestions. + if value, err := learning.Settings(); err == nil { + body.Enabled = !value.AutomationPatternsDisabled && !value.AutomationHabitsDisabled } - for _, entry := range source.Entries() { - if entry.Device != "" && exists != nil && !exists(entry.Device) { - continue - } - body.Values = append(body.Values, learnedValueView{LearnedEntry: entry, Year: learnedYear(entry, weeks)}) + } + if source == nil { + return body + } + var weeks []autolearn.Week + if season != nil { + now := time.Now() + from := isoWeekKeyOf(now.AddDate(0, -learnedYearMonths, 0)) + weeks = season.Weeks(from, isoWeekKeyOf(now)) + } + for _, entry := range source.Entries() { + if entry.Device != "" && exists != nil && !exists(entry.Device) { + continue } - writeJSON(w, body) + body.Values = append(body.Values, learnedValueView{LearnedEntry: entry, Year: learnedYear(entry, weeks)}) + } + return body +} + +// LearnedBody is learnedBody for the monitoring page. The values are the same, +// the device name and icon stay empty. +func LearnedBody(learning *LearningDeps, source learnedValueSource, exists func(string) bool, season learnedSeasonSource) MonitoringLearned { + body := learnedBody(learning, source, exists, season) + out := MonitoringLearned{Enabled: body.Enabled, Values: make([]MonitoringLearnedValue, 0, len(body.Values))} + for _, value := range body.Values { + out.Values = append(out.Values, MonitoringLearnedValue{learnedValueView: value}) } + return out } // learnedYear lists the weeks of the value, oldest first, at most the last diff --git a/dashboard/internal/httpapi/automation_learned_test.go b/dashboard/internal/httpapi/automation_learned_test.go index 6592fbe1..4e9a4ee1 100644 --- a/dashboard/internal/httpapi/automation_learned_test.go +++ b/dashboard/internal/httpapi/automation_learned_test.go @@ -63,13 +63,13 @@ func learnedRouterWithSeason(t *testing.T, source learnedValueSource, learning * return router, manager } -// learnedBody is the answer of GET /api/v1/automations/learned. -type learnedBody struct { +// learnedResponse is the answer of GET /api/v1/automations/learned. +type learnedResponse struct { Enabled bool `json:"enabled"` Values []learnedValueView `json:"values"` } -func getLearned(t *testing.T, router http.Handler, cookie *http.Cookie) (*httptest.ResponseRecorder, learnedBody) { +func getLearned(t *testing.T, router http.Handler, cookie *http.Cookie) (*httptest.ResponseRecorder, learnedResponse) { t.Helper() request := httptest.NewRequest(http.MethodGet, "/api/v1/automations/learned", nil) if cookie != nil { @@ -77,7 +77,7 @@ func getLearned(t *testing.T, router http.Handler, cookie *http.Cookie) (*httpte } recorder := httptest.NewRecorder() router.ServeHTTP(recorder, request) - var body learnedBody + var body learnedResponse if recorder.Code == http.StatusOK { if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil { t.Fatal(err) diff --git a/dashboard/internal/httpapi/httpapi.go b/dashboard/internal/httpapi/httpapi.go index 2799d010..b57d979b 100644 --- a/dashboard/internal/httpapi/httpapi.go +++ b/dashboard/internal/httpapi/httpapi.go @@ -196,6 +196,9 @@ type RouterDependencies struct { // LearnedSeason liefert die Wochen fuer den Jahresverlauf der gelernten // Werte. nil heisst: kein Jahresverlauf. LearnedSeason learnedSeasonSource + // Monitoring liefert Meldungen, Quittungen und Lernwerte fuer die + // Ueberwachung (GET /api/v1/monitoring). nil heisst 501. + Monitoring *MonitoringDeps // HistorySampler fuellt den Ringpuffer der Verlaufsvermittlung einmal // pro Minute mit role:grid und den Szenario-Ausgaben. nil heisst: nur // der Browser schreibt in den Puffer. @@ -413,6 +416,8 @@ func NewRouterWithDependencies(reg *registry.Registry, configs *config.Manager, g.HandleFunc("/api/v1/automations/suggestions", handleAutomationSuggestions(dependencies.Learning, dependencies.AutomationSuggestions, suggestionDeviceExists)) g.HandleFunc("/api/v1/automations/suggestions/", handleAutomationSuggestionAction(dependencies.Auth, dependencies.AutomationSuggestions)) g.HandleFunc("/api/v1/automations/learned", handleAutomationLearned(dependencies.Learning, dependencies.LearnedValues, suggestionDeviceExists, dependencies.LearnedSeason)) + g.HandleFunc("/api/v1/monitoring", handleMonitoring(dependencies.Monitoring)) + g.HandleFunc("/api/v1/monitoring/ack", handleMonitoringAck(dependencies.Auth, dependencies.Monitoring)) g.HandleFunc("/api/v1/learning/status", handleLearningStatus(dependencies.Learning)) g.HandleFunc("/api/v1/learning/reset", handleLearningReset(dependencies.Auth, dependencies.Learning)) g.HandleFunc("/api/v1/energy/interpretation", handleEnergyInterpretation(store, resolver, dependencies.Auth)) diff --git a/dashboard/internal/httpapi/monitoring.go b/dashboard/internal/httpapi/monitoring.go new file mode 100644 index 00000000..3b10cc2f --- /dev/null +++ b/dashboard/internal/httpapi/monitoring.go @@ -0,0 +1,131 @@ +package httpapi + +import ( + "errors" + "net/http" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/auth" + "github.com/Developer-Simon/energy-node-dashboard/internal/monitoring" +) + +const ( + monitoringPath = "/api/v1/monitoring" + monitoringAckPath = "/api/v1/monitoring/ack" +) + +// MonitoringDeps verbindet die Routen mit Sammeln, Speicher und Lernwerten. +// Nil heißt 501. +type MonitoringDeps struct { + // Notices sammelt und wendet den Speicher an, now ist die Zeit der Runde. + Notices func(now time.Time) []monitoring.Notice + // Ack quittiert oder nimmt zurück und speichert. + Ack func(id string, ack bool, user string, now time.Time) error + // Learned liefert die Lernwerte wie GET /api/v1/automations/learned, + // ergänzt um Gerätename und Icon. + Learned func() MonitoringLearned +} + +// MonitoringLearned sind die Lernwerte der Überwachung. +type MonitoringLearned struct { + Enabled bool `json:"enabled"` + Values []MonitoringLearnedValue `json:"values"` +} + +// MonitoringLearnedValue ist ein Lernwert mit Gerätename und Icon. +type MonitoringLearnedValue struct { + learnedValueView + DeviceName string `json:"device_name,omitempty"` + DeviceIcon string `json:"device_icon,omitempty"` +} + +// monitoringBody is the answer of GET /api/v1/monitoring and of the ack POST. +// Notices is never null. +type monitoringBody struct { + Notices []monitoring.Notice `json:"notices"` + NewCount int `json:"new_count"` + Learned MonitoringLearned `json:"learned"` +} + +// monitoringAckBody is the body of POST /api/v1/monitoring/ack. +type monitoringAckBody struct { + ID string `json:"id"` + Ack bool `json:"ack"` +} + +// handleMonitoring serves GET /api/v1/monitoring. Without deps the answer is 501. +func handleMonitoring(deps *MonitoringDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + methodNotAllowed(w, http.MethodGet) + return + } + if deps == nil { + writeError(w, http.StatusNotImplemented, "monitoring_unavailable", "Monitoring ist auf dieser Instanz nicht verfügbar.") + return + } + writeJSON(w, monitoringAnswer(deps, time.Now())) + } +} + +// handleMonitoringAck serves POST /api/v1/monitoring/ack. It needs the edit +// setup role, and answers the monitoring page like GET after the change. +func handleMonitoringAck(manager *auth.Manager, deps *MonitoringDeps) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + methodNotAllowed(w, http.MethodPost) + return + } + if deps == nil || deps.Ack == nil { + writeError(w, http.StatusNotImplemented, "monitoring_unavailable", "Monitoring ist auf dieser Instanz nicht verfügbar.") + return + } + if !requireRole(w, r, manager, auth.RoleEditSetup, "monitoring_ack_forbidden", "error.monitoring_ack_forbidden", "Quittieren braucht das Recht Einrichten") { + return + } + var body monitoringAckBody + if err := decodeBody(r, &body); err != nil || body.ID == "" { + writeErrorKey(w, http.StatusBadRequest, "monitoring_ack_invalid", "error.monitoring_ack_invalid", nil, "Die Kennung der Meldung ist ungültig.") + return + } + user := "" + if current, ok := auth.UserFromContext(r.Context()); ok { + user = current.Username + } + now := time.Now() + if err := deps.Ack(body.ID, body.Ack, user, now); err != nil { + if errors.Is(err, monitoring.ErrUnknown) { + writeErrorKey(w, http.StatusNotFound, "monitoring_ack_unknown", "error.monitoring_ack_unknown", nil, "Diese Meldung gibt es nicht mehr.") + return + } + writeErrorKey(w, http.StatusInternalServerError, "monitoring_save_failed", "error.monitoring_save_failed", nil, "Die Quittung konnte nicht gespeichert werden.") + return + } + writeJSON(w, monitoringAnswer(deps, now)) + } +} + +// monitoringAnswer collects the notices of the round and counts the ones +// without an acknowledgement. Empty lists stay lists, never null. +func monitoringAnswer(deps *MonitoringDeps, now time.Time) monitoringBody { + notices := []monitoring.Notice{} + if deps.Notices != nil { + if collected := deps.Notices(now); collected != nil { + notices = collected + } + } + newCount := 0 + for _, notice := range notices { + if notice.Ack == nil { + newCount++ + } + } + learned := MonitoringLearned{Values: []MonitoringLearnedValue{}} + if deps.Learned != nil { + learned = deps.Learned() + } + if learned.Values == nil { + learned.Values = []MonitoringLearnedValue{} + } + return monitoringBody{Notices: notices, NewCount: newCount, Learned: learned} +} diff --git a/dashboard/internal/httpapi/monitoring_test.go b/dashboard/internal/httpapi/monitoring_test.go new file mode 100644 index 00000000..bb90b6e4 --- /dev/null +++ b/dashboard/internal/httpapi/monitoring_test.go @@ -0,0 +1,170 @@ +package httpapi + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/auth" + "github.com/Developer-Simon/energy-node-dashboard/internal/config" + "github.com/Developer-Simon/energy-node-dashboard/internal/monitoring" + "github.com/Developer-Simon/energy-node-dashboard/internal/registry" + "github.com/Developer-Simon/energy-node-dashboard/internal/settings" +) + +// monitoringRouter builds the authenticated router with the monitoring deps. +func monitoringRouter(t *testing.T, deps *MonitoringDeps) (http.Handler, *auth.Manager) { + t.Helper() + manager, err := auth.NewManager(filepath.Join(t.TempDir(), "users.json"), "admin", "secret") + if err != nil { + t.Fatal(err) + } + router := NewAuthenticatedRouter(registry.New(), config.NewManager(t.TempDir()), settings.NewStore(t.TempDir()), nil, nil, nil, nil, nil, RouterDependencies{Auth: manager, Monitoring: deps}) + return router, manager +} + +// monitoringAckRequest posts an acknowledgement with the cookie and CSRF token. +func monitoringAckRequest(router http.Handler, cookie *http.Cookie, csrf, body string) *httptest.ResponseRecorder { + request := httptest.NewRequest(http.MethodPost, monitoringAckPath, strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + request.Header.Set("X-CSRF-Token", csrf) + request.AddCookie(cookie) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + return recorder +} + +// monitoringGetRequest reads the monitoring page with the cookie. +func monitoringGetRequest(router http.Handler, cookie *http.Cookie) *httptest.ResponseRecorder { + request := httptest.NewRequest(http.MethodGet, monitoringPath, nil) + request.AddCookie(cookie) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + return recorder +} + +func TestMonitoringGetCountsNew(t *testing.T) { + notices := []monitoring.Notice{ + {ID: "energy:a", Source: "energy", Severity: "warn", Code: "a", Ack: &monitoring.Ack{At: 1, User: "x"}}, + {ID: "learn:b", Source: "learn", Severity: "info", Code: "b"}, + } + deps := &MonitoringDeps{ + Notices: func(time.Time) []monitoring.Notice { return notices }, + } + router, manager := monitoringRouter(t, deps) + cookie, _ := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring}) + + recorder := monitoringGetRequest(router, cookie) + if recorder.Code != http.StatusOK { + t.Fatalf("GET status %d: %s", recorder.Code, recorder.Body.String()) + } + var body struct { + Notices []monitoring.Notice `json:"notices"` + NewCount int `json:"new_count"` + } + if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if body.NewCount != 1 { + t.Fatalf("new_count = %d, want 1", body.NewCount) + } + if len(body.Notices) != 2 { + t.Fatalf("notices = %+v, want both notices", body.Notices) + } + raw := recorder.Body.String() + if strings.Contains(raw, `"notices":null`) || strings.Contains(raw, `"values":null`) { + t.Fatalf("answer carries null lists: %s", raw) + } + + // Without notices the lists stay empty, never null. + deps.Notices = func(time.Time) []monitoring.Notice { return nil } + recorder = monitoringGetRequest(router, cookie) + if !strings.Contains(recorder.Body.String(), `"notices":[]`) || !strings.Contains(recorder.Body.String(), `"values":[]`) { + t.Fatalf("empty answer = %s, want empty lists", recorder.Body.String()) + } +} + +func TestMonitoringAckNeedsEditSetup(t *testing.T) { + var acked []string + deps := &MonitoringDeps{ + Notices: func(time.Time) []monitoring.Notice { return nil }, + Ack: func(id string, ack bool, user string, now time.Time) error { + acked = append(acked, id) + return nil + }, + } + router, manager := monitoringRouter(t, deps) + + // A user who sees the monitoring but may not set up must not acknowledge. + viewCookie, viewCSRF := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring}) + recorder := monitoringAckRequest(router, viewCookie, viewCSRF, `{"id":"energy:a","ack":true}`) + if recorder.Code != http.StatusForbidden || !strings.Contains(recorder.Body.String(), `"code":"monitoring_ack_forbidden"`) { + t.Fatalf("view only POST: %d %s", recorder.Code, recorder.Body.String()) + } + if len(acked) != 0 { + t.Fatalf("acknowledged by a view only user: %v", acked) + } + + // With edit_setup the same request is saved and answers the page. + setupCookie, setupCSRF := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring, auth.RoleEditSetup}) + recorder = monitoringAckRequest(router, setupCookie, setupCSRF, `{"id":"energy:a","ack":true}`) + if recorder.Code != http.StatusOK { + t.Fatalf("setup POST: %d %s", recorder.Code, recorder.Body.String()) + } + if len(acked) != 1 || acked[0] != "energy:a" { + t.Fatalf("acked = %v, want energy:a", acked) + } +} + +func TestMonitoringAckUnknownIs404(t *testing.T) { + deps := &MonitoringDeps{ + Notices: func(time.Time) []monitoring.Notice { return nil }, + Ack: func(string, bool, string, time.Time) error { + return monitoring.ErrUnknown + }, + } + router, manager := monitoringRouter(t, deps) + cookie, csrf := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring, auth.RoleEditSetup}) + + recorder := monitoringAckRequest(router, cookie, csrf, `{"id":"gone:x","ack":true}`) + if recorder.Code != http.StatusNotFound || !strings.Contains(recorder.Body.String(), `"code":"monitoring_ack_unknown"`) { + t.Fatalf("unknown ID: %d %s", recorder.Code, recorder.Body.String()) + } +} + +func TestMonitoringAckEmptyIDIs400(t *testing.T) { + var acked []string + deps := &MonitoringDeps{ + Notices: func(time.Time) []monitoring.Notice { return nil }, + Ack: func(id string, ack bool, user string, now time.Time) error { + acked = append(acked, id) + return nil + }, + } + router, manager := monitoringRouter(t, deps) + cookie, csrf := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring, auth.RoleEditSetup}) + + recorder := monitoringAckRequest(router, cookie, csrf, `{"id":"","ack":true}`) + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":"monitoring_ack_invalid"`) { + t.Fatalf("empty ID: %d %s", recorder.Code, recorder.Body.String()) + } + if len(acked) != 0 { + t.Fatalf("Ack called for an empty ID: %v", acked) + } +} + +func TestMonitoringNilDepsIs501(t *testing.T) { + router, manager := monitoringRouter(t, nil) + cookie, csrf := guestCookie(t, router, manager, []string{auth.RoleViewMonitoring, auth.RoleEditSetup}) + + if recorder := monitoringGetRequest(router, cookie); recorder.Code != http.StatusNotImplemented { + t.Fatalf("GET without deps: %d %s", recorder.Code, recorder.Body.String()) + } + if recorder := monitoringAckRequest(router, cookie, csrf, `{"id":"energy:a","ack":true}`); recorder.Code != http.StatusNotImplemented { + t.Fatalf("POST without deps: %d %s", recorder.Code, recorder.Body.String()) + } +} diff --git a/docs/developing/api-auth.md b/docs/developing/api-auth.md index 52106b69..ce8b9b0f 100644 --- a/docs/developing/api-auth.md +++ b/docs/developing/api-auth.md @@ -58,6 +58,7 @@ management page shows them. The source is `internal/auth/roles.go`. | `view_device_map` | view | – | no | yes | | `view_config` | view | – | no | yes | | `view_automations` | view | – | no | yes | +| `view_monitoring` | view | – | no | yes | | `view_diagnostics` | view | – | no | yes | | `operate_devices` | operate | `view_devices` | no | yes | | `operate_automations` | operate | `view_automations` | no | yes | diff --git a/docs/developing/api.md b/docs/developing/api.md index 29106ca3..44843030 100644 --- a/docs/developing/api.md +++ b/docs/developing/api.md @@ -113,6 +113,38 @@ The endpoints are described on four pages: - [System and updates](api-system.md): diagnostics and health, system actions, updates, versions and changelog, and the backup routes. +## Monitoring + +| Method | Path | Gate | Purpose | +|---|---|---|---| +| GET | `/api/v1/monitoring` | view monitoring | The notices of the monitoring page, the number of new ones and the learned values | +| POST | `/api/v1/monitoring/ack` | view monitoring, edit setup, CSRF | Acknowledges a notice (`ack` true) or takes the acknowledgement back (`ack` false), answers like the GET | + +**`GET /api/v1/monitoring`** lists the notices of the round, each with `id`, +`source` (`energy`, `chain` or `learn`), `severity`, `code`, `params`, `steps`, +`first_seen` (unix time of the first sighting) and `ack`, which is `null` or +`{"at","user"}`. `new_count` counts the notices without an acknowledgement. +`learned` has the same values as `GET /api/v1/automations/learned`, with the +device name and icon added. `notices` and `learned.values` are never null. + +**`POST /api/v1/monitoring/ack`** takes `{"id":"energy:unassigned","ack":true}`. The ID +must be the ID of a current notice. The answer is the same as the GET. + +```json +{"notices":[{"id":"energy:unassigned","source":"energy","severity":"info","code":"unassigned","params":{"count":2},"steps":[],"first_seen":1794000000,"ack":null}], + "new_count":1,"learned":{"enabled":true,"values":[]}} +``` + +| Status | Code | When | +|---|---|---| +| 400 | `monitoring_ack_invalid` | The POST body has no notice ID | +| 403 | `view_forbidden` | The account lacks `view_monitoring` | +| 403 | `monitoring_ack_forbidden` | The POST needs `edit_setup` and the account lacks it | +| 403 | `csrf_failed` | The POST has no CSRF token or a wrong one | +| 404 | `monitoring_ack_unknown` | The ID is not a current notice | +| 500 | `monitoring_save_failed` | Saving the acknowledgement failed | +| 501 | `monitoring_unavailable` | The node runs without the monitoring services | + ## Not under `/api/v1/` | Path | Purpose | From d484d92179d73b19bedfdcecf0d19fbcb5e51fae Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:01:37 +0100 Subject: [PATCH 07/27] feat(monitoring): wire the collector into the dashboard The dashboard collects monitoring notices every learning minute and on each request, keeps first-seen times and acknowledgements in autolearn/monitoring.json, and serves the learned values with device name and icon. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/cmd/dashboard/main.go | 63 +++++++++---- dashboard/cmd/dashboard/monitoring.go | 103 +++++++++++++++++++++ dashboard/cmd/dashboard/monitoring_test.go | 59 ++++++++++++ 3 files changed, 207 insertions(+), 18 deletions(-) create mode 100644 dashboard/cmd/dashboard/monitoring.go create mode 100644 dashboard/cmd/dashboard/monitoring_test.go diff --git a/dashboard/cmd/dashboard/main.go b/dashboard/cmd/dashboard/main.go index 4be4beb1..294f3788 100644 --- a/dashboard/cmd/dashboard/main.go +++ b/dashboard/cmd/dashboard/main.go @@ -46,6 +46,7 @@ import ( "github.com/Developer-Simon/energy-node-dashboard/internal/historyexchange" "github.com/Developer-Simon/energy-node-dashboard/internal/httpapi" "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" + "github.com/Developer-Simon/energy-node-dashboard/internal/monitoring" "github.com/Developer-Simon/energy-node-dashboard/internal/mqttclient" "github.com/Developer-Simon/energy-node-dashboard/internal/netmgr" "github.com/Developer-Simon/energy-node-dashboard/internal/nodeagent" @@ -629,6 +630,20 @@ func main() { // Datei liegt unter autolearn/ und wird mit dem Hub gespeichert. learnedStore := autolearn.LoadLearnedStore(filepath.Join(autolearnDir, "learned.json"), log.Printf) learnHub.AddSaver("learned", learnedStore) + // Monitoring: Meldungen aus Energie, Ketten und Regelpruefung, je Minute + // gesammelt, beim Abruf frisch und mit dem Hub gespeichert. + collectMonitoring := func() monitoring.Input { + in := monitoring.Input{Snapshot: energy.Aggregate(reg.Snapshot(), energyResolver, time.Now().UTC())} + if value, err := settingsStore.LoadEnergy(); err == nil { + in.Config = value + } + in.Findings = automationChecker.Findings(time.Now()) + return in + } + monitoringStore := monitoring.OpenStore(filepath.Join(autolearnDir, "monitoring.json"), log.Printf) + monitoringLoop := newMonitoringRunner(monitoringStore, collectMonitoring) + learnHub.AddMinute("monitoring", monitoringLoop) + learnHub.AddSaver("monitoring", monitoringLoop) // Wochenwerte fuer den Saisonvergleich. Fehlt season.json, fuellt die // Energiestatistik der letzten drei Jahre sie einmal nach. seasonPath := filepath.Join(autolearnDir, "season.json") @@ -1278,6 +1293,20 @@ func main() { // root-relative paths, even when a reverse proxy serves the dashboard // under a subpath (see knowhow/dashboard/dashboard-reverse-proxy-unterpfad.md). // Both listeners serve this same handler. + // Lernfunktionen fuer den Router und die Ueberwachung, dieselben Werte. + learningDeps := &httpapi.LearningDeps{ + Settings: settingsStore.LoadSettings, + State: learnStateNow, + Usage: dayStore.Usage, + ChainSuggestInfo: chainSuggest.LearnedSpan, + ChainLearnInfo: chainMonitor.LearnedSpan, + SetupDone: func() bool { return onboardingStore.Load().SetupDone }, + Rules: func() ([]byte, error) { return configManager.Read("automation_rules") }, + Reset: func() error { + resetLearned(learnedStore, client) + return errors.Join(dayStore.Reset(), reactions.Reset(), chainSuggest.ResetLearned(), chainMonitor.ResetLearned(), suggestions.Reset()) + }, + } handler := perfTiming.Middleware(basepath.Middleware(httpapi.NewAuthenticatedRouter(reg, configManager, settingsStore, tinytuya.NewClient( cfg.TinyTuya.ProbePython, cfg.TinyTuya.ProbeScript, @@ -1313,21 +1342,9 @@ func main() { DataDir: dataDir, AutomationHistoryDir: cfg.RuntimePath(devicesDir, ""), Onboarding: onboardingStore, - Learning: &httpapi.LearningDeps{ - Settings: settingsStore.LoadSettings, - State: learnStateNow, - Usage: dayStore.Usage, - ChainSuggestInfo: chainSuggest.LearnedSpan, - ChainLearnInfo: chainMonitor.LearnedSpan, - SetupDone: func() bool { return onboardingStore.Load().SetupDone }, - Rules: func() ([]byte, error) { return configManager.Read("automation_rules") }, - Reset: func() error { - resetLearned(learnedStore, client) - return errors.Join(dayStore.Reset(), reactions.Reset(), chainSuggest.ResetLearned(), chainMonitor.ResetLearned(), suggestions.Reset()) - }, - }, - TourTargets: dashwebui.TourTargets, - Backup: backupDeps, + Learning: learningDeps, + TourTargets: dashwebui.TourTargets, + Backup: backupDeps, Storage: &httpapi.StorageDeps{ DataDir: dataDir, Service: storageService, @@ -1350,9 +1367,19 @@ func main() { AutomationSuggestions: suggestions, LearnedValues: learnedStore, LearnedSeason: seasonStore, - CommandObserver: origin.observeCommand, - StorageFallback: storageFallback, - HistorySampler: historySampler, + Monitoring: &httpapi.MonitoringDeps{ + Notices: monitoringLoop.Notices, + Ack: monitoringLoop.Ack, + Learned: func() httpapi.MonitoringLearned { + devices := reg.Snapshot() + learned := httpapi.LearnedBody(learningDeps, learnedStore, learnedExists, seasonStore) + snap := energy.Aggregate(devices, energyResolver, time.Now().UTC()) + return monitoringLearned(learned, devices, snap, energyResolver) + }, + }, + CommandObserver: origin.observeCommand, + StorageFallback: storageFallback, + HistorySampler: historySampler, InstalledServices: map[string]bool{ "automation": cfg.ServiceInstalled("automation"), "tailscale": cfg.ServiceInstalled("tailscale"), diff --git a/dashboard/cmd/dashboard/monitoring.go b/dashboard/cmd/dashboard/monitoring.go new file mode 100644 index 00000000..5ef1d690 --- /dev/null +++ b/dashboard/cmd/dashboard/monitoring.go @@ -0,0 +1,103 @@ +package main + +import ( + "strings" + "sync" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/energy" + "github.com/Developer-Simon/energy-node-dashboard/internal/httpapi" + "github.com/Developer-Simon/energy-node-dashboard/internal/learnrec" + "github.com/Developer-Simon/energy-node-dashboard/internal/monitoring" + "github.com/Developer-Simon/energy-node-dashboard/internal/registry" +) + +// monitoringRunner sammelt je Minute (Erstsehen auch ohne offene Seite) und +// bei jedem Abruf. Speichern übernimmt der Hub über Save. +type monitoringRunner struct { + mu sync.Mutex + store *monitoring.Store + collect func() monitoring.Input +} + +func newMonitoringRunner(store *monitoring.Store, collect func() monitoring.Input) *monitoringRunner { + return &monitoringRunner{store: store, collect: collect} +} + +// Notices sammelt die Meldungen und setzt Erstsehen und Quittung. +func (m *monitoringRunner) Notices(now time.Time) []monitoring.Notice { + m.mu.Lock() + defer m.mu.Unlock() + notices := monitoring.Collect(m.collect()) + m.store.Apply(notices, now) + return notices +} + +// ObserveMinute sammelt die Meldungen zum Minutenbeginn des Rahmens. +func (m *monitoringRunner) ObserveMinute(f learnrec.Frame) { + m.Notices(f.Minute) +} + +// Ack quittiert oder nimmt zurück und speichert sofort. +func (m *monitoringRunner) Ack(id string, ack bool, user string, now time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + if err := m.store.SetAck(id, ack, user, now); err != nil { + return err + } + return m.store.Save() +} + +// Save schreibt den Speicher, wenn sich etwas geändert hat. +func (m *monitoringRunner) Save() error { + m.mu.Lock() + defer m.mu.Unlock() + return m.store.Save() +} + +// monitoringDeviceIcon wählt das Icon eines Lerngeräts aus seiner Energie-Rolle. +func monitoringDeviceIcon(role energy.Role, switchable bool) string { + switch { + case role == energy.RoleHeatPump: + return "ico-heatpump" + case role == energy.RoleWallbox: + return "ico-wallbox" + case role == energy.RoleBattery: + return "ico-battery" + case role == energy.RolePV: + return "ico-sun" + case role == energy.RoleSwitch: + return "ico-switch" + case role == energy.RoleLoad, strings.HasPrefix(string(role), "custom:"): + return "ico-load" + case switchable: + return "ico-switch" + default: + return "ico-device" + } +} + +// monitoringLearned ergänzt die Lernwerte um Gerätename (Registry) und Icon +// (Energie-Rolle der ersten Entität des Geräts, Schaltbarkeit aus learnDevices). +func monitoringLearned(learned httpapi.MonitoringLearned, devices []registry.DeviceView, snap energy.Snapshot, resolver *energy.Resolver) httpapi.MonitoringLearned { + names := make(map[string]string, len(devices)) + for _, device := range devices { + names[device.ID] = device.Name + } + roles := map[string]energy.Role{} + for _, entity := range snap.Entities { + if _, ok := roles[entity.DeviceID]; !ok { + roles[entity.DeviceID] = entity.Role.Role + } + } + infos := learnDevices(devices, resolver) + for i := range learned.Values { + id := learned.Values[i].Device + if id == "" { + continue + } + learned.Values[i].DeviceName = names[id] + learned.Values[i].DeviceIcon = monitoringDeviceIcon(roles[id], infos[id].Switchable) + } + return learned +} diff --git a/dashboard/cmd/dashboard/monitoring_test.go b/dashboard/cmd/dashboard/monitoring_test.go new file mode 100644 index 00000000..22e9a116 --- /dev/null +++ b/dashboard/cmd/dashboard/monitoring_test.go @@ -0,0 +1,59 @@ +package main + +import ( + "testing" + "time" + + "github.com/Developer-Simon/energy-node-dashboard/internal/autolearn" + "github.com/Developer-Simon/energy-node-dashboard/internal/energy" + "github.com/Developer-Simon/energy-node-dashboard/internal/monitoring" +) + +func TestMonitoringDeviceIcon(t *testing.T) { + cases := []struct { + role energy.Role + switchable bool + want string + }{ + {energy.RoleHeatPump, false, "ico-heatpump"}, + {energy.RoleWallbox, false, "ico-wallbox"}, + {energy.RoleBattery, false, "ico-battery"}, + {energy.RolePV, false, "ico-sun"}, + {energy.RoleSwitch, false, "ico-switch"}, + {energy.RoleLoad, false, "ico-load"}, + {energy.CustomRole("akku"), false, "ico-load"}, + {"", true, "ico-switch"}, + {"", false, "ico-device"}, + } + for _, c := range cases { + if got := monitoringDeviceIcon(c.role, c.switchable); got != c.want { + t.Errorf("monitoringDeviceIcon(%q, %v) = %q, want %q", c.role, c.switchable, got, c.want) + } + } +} + +func TestMonitoringRunnerKeepsFirstSeen(t *testing.T) { + store := monitoring.OpenStore("", t.Logf) + collect := func() monitoring.Input { + return monitoring.Input{Findings: []autolearn.Finding{{ID: "f1", Summary: autolearn.Text{Code: "x"}}}} + } + m := newMonitoringRunner(store, collect) + t0 := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC) + first := findMonitoringNotice(m.Notices(t0), "learn:f1") + second := findMonitoringNotice(m.Notices(t0.Add(time.Minute)), "learn:f1") + if first == nil || second == nil { + t.Fatalf("notice learn:f1 missing: first=%v second=%v", first, second) + } + if first.FirstSeen != t0.Unix() || second.FirstSeen != first.FirstSeen { + t.Fatalf("FirstSeen first=%d second=%d, want %d", first.FirstSeen, second.FirstSeen, t0.Unix()) + } +} + +func findMonitoringNotice(notices []monitoring.Notice, id string) *monitoring.Notice { + for i := range notices { + if notices[i].ID == id { + return ¬ices[i] + } + } + return nil +} From 7ef342f7904f2936cc54135e76db7d80b28dd580 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:04:36 +0100 Subject: [PATCH 08/27] feat(webui): add the monitoring page model Pure page model for the monitoring view: source and filter, sort and group notices, since text, titles, texts, facts, steps with rights, compass and week ranges. Part A of the model, learned values follow. Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/monitoring-model.js | 172 ++++++++++++++++++ dashboard/test/monitoring-model.test.mjs | 116 ++++++++++++ 2 files changed, 288 insertions(+) create mode 100644 dashboard/internal/webui/static/js/monitoring-model.js create mode 100644 dashboard/test/monitoring-model.test.mjs diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js new file mode 100644 index 00000000..fe0ace5a --- /dev/null +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -0,0 +1,172 @@ +// Seitenmodell der Monitoring-Seite: reine Funktionen ohne DOM und Alpine. +// t ist (key, params) => string, can ein Objekt mit Rechten, now Unix-Sekunden. +(() => { + const DAY_S = 86400; + const COMPASS = ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw']; + const SHADE_ID_RE = /^learn:shade:(\d+):(\d+)$/; + const pad = (n) => String(n).padStart(2, '0'); + + // Quelle für Filter und Gruppen: Energie-Bilanz und Messketten zusammen, sonst Lernfunktionen. + function sourceOf(notice) { + return notice.source === 'energy' || notice.source === 'chain' ? 'energy' : 'learn'; + } + + function filterNotices(notices, filter) { + if (filter === 'energy' || filter === 'learn') { + return notices.filter((n) => sourceOf(n) === filter); + } + return notices.slice(); + } + + // Neu vor quittiert, Warnungen vor Hinweisen, dann die neuesten zuerst. + function sortNotices(notices) { + const rank = (n) => (n.severity === 'warn' ? 0 : 1); + return notices.slice().sort((a, b) => (!!a.ack - !!b.ack) + || (rank(a) - rank(b)) + || (b.first_seen - a.first_seen)); + } + + function groups(notices) { + const out = [ + { id: 'new', items: notices.filter((n) => !n.ack) }, + { id: 'known', items: notices.filter((n) => !!n.ack) }, + ]; + return out.filter((g) => g.items.length); + } + + function sinceText(firstSeen, now, t) { + const days = Math.floor((now - firstSeen) / DAY_S); + if (days <= 0) return t('monitoring.since.today'); + if (days === 1) return t('monitoring.since.yesterday'); + return t('monitoring.since.days', { n: days }); + } + + // Himmelsrichtung als Katalogteil: 'n', 'ne', ... 'nw'. Der Aufrufer übersetzt mit monitoring.compass.. + function compass(az) { + const idx = Math.round((((az % 360) + 360) % 360) / 45) % 8; + return COMPASS[idx]; + } + + // Datum für den Kettenbefund als TT.MM. + function shortDate(value) { + const d = new Date(value); + return Number.isNaN(d.getTime()) ? '' : pad(d.getDate()) + '.' + pad(d.getMonth() + 1) + '.'; + } + + // Kalenderwochen als Bereiche: [4,5,6,7,44,45] -> "4 bis 7, 44 und 45". + function weekRanges(weeks, t) { + const sorted = (weeks || []).slice().sort((a, b) => a - b); + const items = []; + for (let i = 0; i < sorted.length;) { + let j = i; + while (j + 1 < sorted.length && sorted[j + 1] === sorted[j] + 1) j++; + if (j - i >= 2) { + items.push(t('monitoring.weeks.range', { from: sorted[i], to: sorted[j] })); + } else { + for (let k = i; k <= j; k++) items.push(String(sorted[k])); + } + i = j + 1; + } + if (items.length < 2) return items.join(''); + return t('monitoring.weeks.and', { a: items.slice(0, -1).join(', '), b: items[items.length - 1] }); + } + + function shadeIdParts(id) { + const m = SHADE_ID_RE.exec(id || ''); + return m ? { az: Number(m[1]), el: Number(m[2]) } : null; + } + + // Zahlen formatiert I18n, damit Zahlenformat und Sprache der Oberfläche gelten. + function kwhText(value) { + const I18n = window.I18n; + return typeof value === 'number' && I18n && I18n.formatNumber ? I18n.formatNumber(value, 1) : (value == null ? '' : String(value)); + } + + function shadeFacts(notice, p, t) { + const rows = [ + [t('monitoring.fact.time'), t('monitoring.fact.time_value', { from: p.from, to: p.to })], + [t('monitoring.fact.weeks'), weekRanges(p.weeks, t)], + ]; + const id = shadeIdParts(notice.id); + if (id) { + rows.push([t('monitoring.fact.direction'), t('monitoring.fact.direction_value', { + az: id.az, compass: t('monitoring.compass.' + compass(id.az)), el: id.el, + })]); + } + rows.push([t('monitoring.fact.loss'), t('monitoring.fact.loss_value', { kwh: kwhText(p.kwh_lost) })]); + return rows; + } + + function title(notice, t) { + const key = sourceOf(notice) === 'learn' + ? 'automations.learn.' + notice.code + '.title' + : 'monitoring.notice.' + notice.code + '.title'; + return t(key, notice.params); + } + + function text(notice, t) { + const p = notice.params || {}; + if (sourceOf(notice) === 'learn') return t('automations.learn.' + notice.code + '.text', notice.params); + if (notice.code === 'measured_no_meter') return t('energy.roles.notices.measured_warning'); + if (notice.code === 'role_needed') return t('energy.chains.role_needed'); + if (notice.code === 'chain') { + return t('chains.finding.' + p.kind, { chain: p.chain, from: p.from, to: p.to, since: shortDate(p.since) }); + } + return t('monitoring.notice.' + notice.code + '.text', notice.params); + } + + function facts(notice, t) { + const p = notice.params || {}; + if (notice.code === 'unassigned') { + const rows = (p.names || []).map((name) => [t('monitoring.fact.value'), name]); + if ((p.more || 0) > 0) rows.push(['', t('monitoring.fact.more', { n: p.more })]); + return rows; + } + if (sourceOf(notice) === 'learn' && p.kind === 'shade') return shadeFacts(notice, p, t); + return []; + } + + // Rechte je Sprungziel. Unbekannte Ziele bekommen kein Recht. + function allowed(target, can) { + if (!target) return false; + if (target === 'learned') return true; + if (target.startsWith('energy')) return !!can.view_energy; + if (target === 'efficiency') return !!can.view_efficiency; + if (target === 'devicemap') return !!can.view_device_map; + if (target === 'action.role_keep') return !!can.edit_energy; + return false; + } + + function steps(notice, can, t) { + const rights = can || {}; + const shade = sourceOf(notice) === 'learn' ? shadeIdParts(notice.id) : null; + return (notice.steps || []).map((s) => { + const key = 'monitoring.step.' + s.code; + const ok = allowed(s.target, rights); + const params = s.code === 'shade_look' && shade + ? { direction: t('monitoring.compass.' + compass(shade.az)), height: shade.el } + : undefined; + return { + text: t(key, params), + target: ok ? s.target : '', + ids: s.ids || [], + chain: s.chain || '', + label: ok ? t(key + '.button') : '', + }; + }); + } + + window.MonitoringModel = { + sourceOf, + filterNotices, + sortNotices, + groups, + sinceText, + title, + text, + facts, + steps, + compass, + weekRanges, + }; +})(); diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs new file mode 100644 index 00000000..6cca472d --- /dev/null +++ b/dashboard/test/monitoring-model.test.mjs @@ -0,0 +1,116 @@ +// Tests for the monitoring page model (part A): groups, order, since text, steps, shade facts, week ranges. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { JSDOM } from 'jsdom'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const jsDir = path.join(here, '..', 'internal', 'webui', 'static', 'js'); +const source = fs.readFileSync(path.join(jsDir, 'monitoring-model.js'), 'utf8'); + +function load() { + const dom = new JSDOM('', { runScripts: 'outside-only' }); + vm.runInContext(source, dom.getInternalVMContext()); + return dom.window.MonitoringModel; +} + +// Results come from the vm realm, so they are copied into this realm before strict comparison. +const plain = (v) => (v === undefined ? v : JSON.parse(JSON.stringify(v))); +const raw = load(); +const M = Object.fromEntries(Object.entries(raw).map(([name, fn]) => [name, (...args) => plain(fn(...args))])); +const t = (key, params) => (params ? key + JSON.stringify(params) : key); +const tWeeks = (key, p) => { + if (key === 'monitoring.weeks.range') return p.from + ' bis ' + p.to; + if (key === 'monitoring.weeks.and') return p.a + ' und ' + p.b; + return key; +}; + +test('groups puts new before known and drops empty groups', () => { + const onlyNew = [{ id: 'a', ack: null }, { id: 'b', ack: null }]; + assert.deepEqual(M.groups(onlyNew), [{ id: 'new', items: onlyNew }]); + const mixed = [{ id: 'k', ack: { at: 1, user: 'x' } }, { id: 'n', ack: null }]; + assert.deepEqual(M.groups(mixed).map((g) => g.id), ['new', 'known']); + const onlyKnown = [{ id: 'k', ack: { at: 1, user: 'x' } }]; + assert.deepEqual(M.groups(onlyKnown).map((g) => g.id), ['known']); +}); + +test('sortNotices orders warn before info inside new', () => { + const notices = [ + { id: 'info-new', severity: 'info', ack: null, first_seen: 300 }, + { id: 'warn-old', severity: 'warn', ack: null, first_seen: 100 }, + { id: 'warn-new', severity: 'warn', ack: null, first_seen: 200 }, + { id: 'acked', severity: 'warn', ack: { at: 1, user: 'x' }, first_seen: 999 }, + ]; + assert.deepEqual(M.sortNotices(notices).map((n) => n.id), ['warn-new', 'warn-old', 'info-new', 'acked']); +}); + +test('sinceText says heute, gestern and vor n Tagen', () => { + const now = 1794000000; + assert.equal(M.sinceText(now - 3600, now, t), 'monitoring.since.today'); + assert.equal(M.sinceText(now - 90000, now, t), 'monitoring.since.yesterday'); + assert.equal(M.sinceText(now - 5 * 86400, now, t), 'monitoring.since.days{"n":5}'); +}); + +test('steps drop targets without the right but keep the text', () => { + const notice = { + code: 'unassigned', + source: 'energy', + steps: [{ code: 'assign_roles', target: 'energy.focus', ids: ['sensor.a'] }], + }; + const withRight = M.steps(notice, { view_energy: true }, t)[0]; + assert.equal(withRight.target, 'energy.focus'); + assert.equal(withRight.label, 'monitoring.step.assign_roles.button'); + + const without = M.steps(notice, { view_energy: false }, t)[0]; + assert.equal(without.text, 'monitoring.step.assign_roles'); + assert.equal(without.target, ''); + assert.equal(without.label, ''); + assert.deepEqual(without.ids, ['sensor.a']); +}); + +test('steps hide role_keep without edit_energy', () => { + const notice = { + code: 'role_needed', + source: 'energy', + steps: [{ code: 'role_keep', target: 'action.role_keep', ids: ['sensor.a'] }], + }; + const off = M.steps(notice, { view_energy: true, edit_energy: false }, t)[0]; + assert.equal(off.text, 'monitoring.step.role_keep'); + assert.equal(off.target, ''); + assert.equal(off.label, ''); + + const on = M.steps(notice, { edit_energy: true }, t)[0]; + assert.equal(on.target, 'action.role_keep'); + assert.equal(on.label, 'monitoring.step.role_keep.button'); +}); + +test('shade facts read direction and height from the id', () => { + const notice = { + id: 'learn:shade:225:15', + source: 'learn', + code: 'shade', + params: { kind: 'shade', from: '14:35', to: '15:49', kwh_lost: 5.7, weeks: [4, 5, 6, 7, 44, 45, 46, 47] }, + }; + const facts = M.facts(notice, t); + assert.deepEqual(facts.map(([label]) => label), [ + 'monitoring.fact.time', + 'monitoring.fact.weeks', + 'monitoring.fact.direction', + 'monitoring.fact.loss', + ]); + assert.deepEqual(facts[2], [ + 'monitoring.fact.direction', + 'monitoring.fact.direction_value{"az":225,"compass":"monitoring.compass.sw","el":15}', + ]); + assert.deepEqual(facts[0], ['monitoring.fact.time', 'monitoring.fact.time_value{"from":"14:35","to":"15:49"}']); +}); + +test('weekRanges joins runs', () => { + assert.equal(M.weekRanges([4, 5, 6, 7, 44, 45], tWeeks), '4 bis 7, 44 und 45'); + assert.equal(M.weekRanges([45, 4], tWeeks), '4 und 45'); + assert.equal(M.weekRanges([12], tWeeks), '12'); + assert.equal(M.weekRanges([], tWeeks), ''); +}); From 96ae9fa9b17495f6483b0562cd5eeeb7a137734e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:06:00 +0100 Subject: [PATCH 09/27] feat(webui): add the learned values to the monitoring model Adds learnedGroups, valueText and spark: site values with fixed keys, device values by name in a fixed order, value texts and the year line. Co-Authored-By: Claude Sonnet 5.5 --- .../webui/static/js/monitoring-model.js | 122 ++++++++++++++++++ dashboard/test/monitoring-model.test.mjs | 54 ++++++++ 2 files changed, 176 insertions(+) diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index fe0ace5a..cca033b1 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -156,7 +156,129 @@ }); } + // Lernwerte: Anlage mit festen Schlüsseln, Geräte nach Name, feste Reihenfolge der Gerätewerte. + const SITE_KEYS = ['day_start', 'night_rest', 'house_state', 'pv_reserve_w', 'surplus_left_wh']; + const RUN_KEYS = ['usual_runtime_s', 'op_power_w', 'cycle_wh']; + const ORDER = ['usual_on', 'usual_off', 'usual_runtime_s', 'op_power_w', 'cycle_wh']; + // Icons aus dem Sprite (base.html), keine neuen Zeichnungen. + const VALUE_ICON = { + usual_on: 'ico-power-on', usual_off: 'ico-power-off', usual_runtime_s: 'ico-history', + op_power_w: 'ico-gauge', cycle_wh: 'ico-flash', + day_start: 'ico-sun', night_rest: 'ico-clock', house_state: 'ico-user', + pv_reserve_w: 'ico-gauge', surplus_left_wh: 'ico-flash', + }; + + const isFiniteNumber = (v) => typeof v === 'number' && Number.isFinite(v); + const clockMin = (v) => { + const m = /^(\d\d):(\d\d)$/.exec(String(v)); + return m ? Number(m[1]) * 60 + Number(m[2]) : null; + }; + const numberText = (v) => (window.I18n && window.I18n.formatNumber ? window.I18n.formatNumber(v) : String(v)); + + function durationText(sec) { + const min = Math.round(Number(sec) / 60); + if (min < 60) return min + ' min'; + const h = Math.floor(min / 60); + const rest = min % 60; + return rest ? h + ' h ' + rest + ' min' : h + ' h'; + } + + // Wert eines Lernwerts als Text: Uhrzeit, Dauer, Zahl mit Einheit oder Zustand. + function valueText(entry, t) { + if (entry.kind === 'time') return entry.value + ' Uhr'; + if (entry.kind === 'duration') return durationText(entry.value); + if (entry.kind === 'state') return t(entry.value === 'active' ? 'automations.learned.state.active' : 'automations.learned.state.quiet'); + return numberText(entry.value) + (entry.unit ? ' ' + entry.unit : ''); + } + + // Alter als kurze Angabe, gleiche Einheiten wie die Lernwerte-Ansicht. + function ageText(sec) { + const v = isFiniteNumber(sec) ? Math.max(0, sec) : 0; + if (v < 60) return Math.round(v) + ' s'; + if (v < 3600) return Math.round(v / 60) + ' min'; + if (v < 86400) return Math.round(v / 3600) + ' h'; + return Math.round(v / 86400) + ' d'; + } + + // Herkunft: Tage oder Läufe, Änderungszeit und vorheriger Wert, mit Trennzeichen. + function metaText(entry, name, now, t) { + const parts = []; + if (name === 'pv_reserve_w') { + parts.push(t('monitoring.learned.origin.minute')); + } else if (entry.n) { + const kind = RUN_KEYS.includes(name) ? 'runs' : 'days'; + parts.push(entry.n === 1 + ? t('monitoring.learned.origin.' + kind + '_one') + : t('monitoring.learned.origin.' + kind, { n: entry.n })); + } + const since = entry.changed_at || entry.at; + if (since) parts.push(t('monitoring.learned.origin.changed', { age: ageText(now - since) })); + if (entry.prev !== undefined && entry.prev !== null) { + parts.push(t('monitoring.learned.origin.prev', { value: valueText(Object.assign({}, entry, { value: entry.prev }), t) })); + } + return parts.join(' · '); + } + + // Jahreslinie als Polyline in einem 100 x 24 Feld. + function spark(entry) { + const pts = (entry.year || []) + .map((p) => (entry.kind === 'time' ? clockMin(p.value) : Number(p.value))) + .filter((x) => x !== null && Number.isFinite(x)); + if (pts.length < 4) return ''; + const lo = Math.min(...pts); + const hi = Math.max(...pts); + const span = hi - lo || 1; + return pts.map((x, i) => (i / (pts.length - 1) * 100).toFixed(1) + ',' + (21 - (x - lo) / span * 18).toFixed(1)).join(' '); + } + + function learnedRow(key, name, entry, now, t) { + return { + key, + label: t('monitoring.learned.short.' + name), + icon: VALUE_ICON[name] || 'ico-learning', + have: !!entry, + value: entry ? valueText(entry, t) : t('monitoring.learned.missing'), + meta: entry ? metaText(entry, name, now, t) : t(name === 'pv_reserve_w' ? 'monitoring.learned.missing_pv' : 'monitoring.learned.missing_days'), + estimate: !!(entry && entry.estimate), + spark: entry ? spark(entry) : '', + }; + } + + function learnedGroups(values, now, t) { + const list = values || []; + const byKey = new Map(list.map((v) => [v.key, v])); + const siteRows = SITE_KEYS.map((n) => learnedRow('site/' + n, n, byKey.get('site/' + n), now, t)); + const site = { + id: 'site', + label: t('monitoring.learned.site'), + icon: 'ico-learning', + have: siteRows.filter((r) => r.have).length, + total: siteRows.length, + rows: siteRows, + }; + + const devices = new Map(); + list.filter((v) => String(v.key).startsWith('device/')).forEach((v) => { + const [, dev, name] = String(v.key).split('/'); + if (!devices.has(dev)) devices.set(dev, { dev, entries: [], name: v.device_name || dev, icon: v.device_icon || 'ico-device' }); + devices.get(dev).entries.push({ name, entry: v }); + }); + const compare = (a, b) => (window.I18n && window.I18n.compare ? window.I18n.compare(a, b) : (a < b ? -1 : (a > b ? 1 : 0))); + const deviceGroups = [...devices.values()] + .sort((a, b) => compare(a.name, b.name)) + .map((d) => { + const rows = d.entries + .sort((a, b) => ORDER.indexOf(a.name) - ORDER.indexOf(b.name)) + .map((r) => learnedRow('device/' + d.dev + '/' + r.name, r.name, r.entry, now, t)); + return { id: 'device/' + d.dev, label: d.name, icon: d.icon, have: rows.filter((r) => r.have).length, total: rows.length, rows }; + }); + return [site].concat(deviceGroups); + } + window.MonitoringModel = { + learnedGroups, + valueText, + spark, sourceOf, filterNotices, sortNotices, diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs index 6cca472d..ffb650a7 100644 --- a/dashboard/test/monitoring-model.test.mjs +++ b/dashboard/test/monitoring-model.test.mjs @@ -13,6 +13,8 @@ const source = fs.readFileSync(path.join(jsDir, 'monitoring-model.js'), 'utf8'); function load() { const dom = new JSDOM('', { runScripts: 'outside-only' }); + // Zahlen kommen aus I18n.formatNumber, hier mit deutschem Tausenderpunkt. + dom.window.I18n = { formatNumber: (value) => Number(value).toLocaleString('de-DE') }; vm.runInContext(source, dom.getInternalVMContext()); return dom.window.MonitoringModel; } @@ -114,3 +116,55 @@ test('weekRanges joins runs', () => { assert.equal(M.weekRanges([12], tWeeks), '12'); assert.equal(M.weekRanges([], tWeeks), ''); }); + +const NOW = 1794000000; + +test('learnedGroups lists all five site keys and marks missing ones', () => { + const values = [{ key: 'site/day_start', kind: 'time', value: '06:10', n: 4, at: NOW - 60, changed_at: NOW - 300 }]; + const groups = M.learnedGroups(values, NOW, t); + assert.equal(groups[0].id, 'site'); + assert.equal(groups[0].total, 5); + assert.equal(groups[0].have, 1); + assert.deepEqual(groups[0].rows.map((r) => r.key), [ + 'site/day_start', 'site/night_rest', 'site/house_state', 'site/pv_reserve_w', 'site/surplus_left_wh', + ]); + const dayStart = groups[0].rows[0]; + assert.equal(dayStart.have, true); + assert.equal(dayStart.value, '06:10 Uhr'); + const missing = groups[0].rows[1]; + assert.equal(missing.have, false); + assert.equal(missing.value, 'monitoring.learned.missing'); + assert.equal(missing.meta, 'monitoring.learned.missing_days'); + assert.equal(groups[0].rows[3].meta, 'monitoring.learned.missing_pv'); +}); + +test('learnedGroups orders device values on, off, runtime, power, cycle', () => { + const values = [ + { key: 'device/pump/usual_runtime_s', kind: 'duration', value: 600, device_name: 'Pumpe', device_icon: 'ico-pump' }, + { key: 'device/pump/cycle_wh', kind: 'number', value: 90, unit: 'Wh', device_name: 'Pumpe', device_icon: 'ico-pump' }, + { key: 'device/pump/usual_on', kind: 'time', value: '06:00', device_name: 'Pumpe', device_icon: 'ico-pump' }, + { key: 'device/pump/op_power_w', kind: 'number', value: 1930, unit: 'W', device_name: 'Pumpe', device_icon: 'ico-pump' }, + { key: 'device/pump/usual_off', kind: 'time', value: '07:00', device_name: 'Pumpe', device_icon: 'ico-pump' }, + ]; + const device = M.learnedGroups(values, NOW, t)[1]; + assert.equal(device.id, 'device/pump'); + assert.equal(device.label, 'Pumpe'); + assert.equal(device.icon, 'ico-pump'); + assert.deepEqual(device.rows.map((r) => r.key.split('/')[2]), ['usual_on', 'usual_off', 'usual_runtime_s', 'op_power_w', 'cycle_wh']); +}); + +test('origin uses singular for one day', () => { + const one = M.learnedGroups([{ key: 'site/day_start', kind: 'time', value: '06:10', n: 1, at: NOW - 60, changed_at: NOW - 300 }], NOW, t)[0].rows[0]; + assert.equal(one.meta.split(' · ')[0], 'monitoring.learned.origin.days_one'); + assert.equal(one.meta.split(' · ')[1], 'monitoring.learned.origin.changed{"age":"5 min"}'); + const many = M.learnedGroups([{ key: 'site/day_start', kind: 'time', value: '06:10', n: 3, at: NOW - 60 }], NOW, t)[0].rows[0]; + assert.equal(many.meta.split(' · ')[0], 'monitoring.learned.origin.days{"n":3}'); +}); + +test('valueText formats time, duration, number and state', () => { + assert.equal(M.valueText({ kind: 'time', value: '22:30' }, t), '22:30 Uhr'); + assert.equal(M.valueText({ kind: 'duration', value: 20520 }, t), '5 h 42 min'); + assert.equal(M.valueText({ kind: 'number', value: 1930, unit: 'W' }, t), '1.930 W'); + assert.equal(M.valueText({ kind: 'state', value: 'active' }, t), 'automations.learned.state.active'); + assert.equal(M.valueText({ kind: 'state', value: 'quiet' }, t), 'automations.learned.state.quiet'); +}); From d55ca28a1efa27dd26d006a96854c0a6160c5031 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:06:35 +0100 Subject: [PATCH 10/27] fix(webui): translate the time value of the monitoring model Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/static/js/monitoring-model.js | 2 +- dashboard/test/monitoring-model.test.mjs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index cca033b1..0a148923 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -185,7 +185,7 @@ // Wert eines Lernwerts als Text: Uhrzeit, Dauer, Zahl mit Einheit oder Zustand. function valueText(entry, t) { - if (entry.kind === 'time') return entry.value + ' Uhr'; + if (entry.kind === 'time') return t('monitoring.value.time', { time: entry.value }); if (entry.kind === 'duration') return durationText(entry.value); if (entry.kind === 'state') return t(entry.value === 'active' ? 'automations.learned.state.active' : 'automations.learned.state.quiet'); return numberText(entry.value) + (entry.unit ? ' ' + entry.unit : ''); diff --git a/dashboard/test/monitoring-model.test.mjs b/dashboard/test/monitoring-model.test.mjs index ffb650a7..72778ab7 100644 --- a/dashboard/test/monitoring-model.test.mjs +++ b/dashboard/test/monitoring-model.test.mjs @@ -130,7 +130,7 @@ test('learnedGroups lists all five site keys and marks missing ones', () => { ]); const dayStart = groups[0].rows[0]; assert.equal(dayStart.have, true); - assert.equal(dayStart.value, '06:10 Uhr'); + assert.equal(dayStart.value, 'monitoring.value.time{"time":"06:10"}'); const missing = groups[0].rows[1]; assert.equal(missing.have, false); assert.equal(missing.value, 'monitoring.learned.missing'); @@ -162,7 +162,7 @@ test('origin uses singular for one day', () => { }); test('valueText formats time, duration, number and state', () => { - assert.equal(M.valueText({ kind: 'time', value: '22:30' }, t), '22:30 Uhr'); + assert.equal(M.valueText({ kind: 'time', value: '22:30' }, t), 'monitoring.value.time{"time":"22:30"}'); assert.equal(M.valueText({ kind: 'duration', value: 20520 }, t), '5 h 42 min'); assert.equal(M.valueText({ kind: 'number', value: 1930, unit: 'W' }, t), '1.930 W'); assert.equal(M.valueText({ kind: 'state', value: 'active' }, t), 'automations.learned.state.active'); From 32f7f581775f1066da9bdf0e0e9e6c5d45575856 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:07:12 +0100 Subject: [PATCH 11/27] feat(i18n): add the monitoring page and energy line texts Template-literal keys keep the catalog scanner from reading prefixes as keys. Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 107 ++++++++++++++++++ dashboard/internal/webui/catalogs/en.json | 107 ++++++++++++++++++ .../webui/static/js/monitoring-model.js | 16 +-- 3 files changed, 222 insertions(+), 8 deletions(-) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 45da86e3..8c07a0ba 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -1,4 +1,7 @@ { + " / ": "aus 1 Lauf", + " / .days": "aus {n} Tagen", + " / .runs": "aus {n} Läufen", "automations.action.add_aria": "Aktion hinzufügen: {type}", "automations.action.add_button_aria": "Aktion hinzufügen", "automations.action.advanced": "Für Fortgeschrittene", @@ -3587,6 +3590,108 @@ "meta.locale": "de-DE", "meta.number.decimal": ",", "meta.number.group": ".", + "monitoring.ack.button": "Zur Kenntnis genommen", + "monitoring.ack.done": "Zur Kenntnis genommen am {date} von {user}", + "monitoring.ack.no_right": "Quittieren können nur Nutzer mit dem Recht Einrichten.", + "monitoring.ack.undo": "Wieder als neu markieren", + "monitoring.badge.new": "neu", + "monitoring.compass.e": "Ost", + "monitoring.compass.n": "Nord", + "monitoring.compass.ne": "Nordost", + "monitoring.compass.nw": "Nordwest", + "monitoring.compass.s": "Süd", + "monitoring.compass.se": "Südost", + "monitoring.compass.sw": "Südwest", + "monitoring.compass.w": "West", + "monitoring.empty.text": "Keine offenen Meldungen. Neue erscheinen hier, der Reiter bekommt dann einen Punkt.", + "monitoring.empty.title": "Alles ruhig", + "monitoring.energy_line.count.one": "{count} Meldung zur Energie", + "monitoring.energy_line.count.other": "{count} Meldungen zur Energie", + "monitoring.energy_line.new": "{count} neu", + "monitoring.energy_line.none": "Keine offenen Meldungen zur Energie", + "monitoring.energy_line.open": "Im Monitoring ansehen", + "monitoring.fact.direction": "Richtung", + "monitoring.fact.direction_value": "{az}° ({compass}), {el}° über dem Horizont", + "monitoring.fact.loss": "Verlust", + "monitoring.fact.loss_value": "etwa {kwh} kWh im Jahr", + "monitoring.fact.more": "und {n} weitere", + "monitoring.fact.time": "Zeit", + "monitoring.fact.time_value": "{from} bis {to} Uhr", + "monitoring.fact.value": "Wert", + "monitoring.fact.weeks": "Kalenderwochen", + "monitoring.filter.all": "Alle", + "monitoring.filter.energy": "Energie", + "monitoring.filter.learn": "Lernfunktionen", + "monitoring.group.known": "Zur Kenntnis genommen", + "monitoring.group.new": "Neu", + "monitoring.learned.count": "{have} von {total}", + "monitoring.learned.missing": "Noch nicht gelernt", + "monitoring.learned.missing_days": "braucht mehr Tage", + "monitoring.learned.missing_pv": "braucht PV-Minuten am Tag", + "monitoring.learned.off": "Muster lernen ist aus. Einschalten unter Einstellungen, Lernfunktionen.", + "monitoring.learned.origin.changed": "geändert vor {age}", + "monitoring.learned.origin.days": "aus {n} Tagen", + "monitoring.learned.origin.days_one": "aus 1 Tag", + "monitoring.learned.origin.minute": "Wert der letzten Minute", + "monitoring.learned.origin.prev": "vorher {value}", + "monitoring.learned.origin.runs": "aus {n} Läufen", + "monitoring.learned.origin.runs_one": "aus 1 Lauf", + "monitoring.learned.short.cycle_wh": "Typische Zyklusenergie", + "monitoring.learned.short.day_start": "Tagesbeginn", + "monitoring.learned.short.house_state": "Hauszustand", + "monitoring.learned.short.night_rest": "Nachtruhe", + "monitoring.learned.short.op_power_w": "Typische Betriebsleistung", + "monitoring.learned.short.pv_reserve_w": "PV-Reserve", + "monitoring.learned.short.surplus_left_wh": "Rest-Überschuss heute", + "monitoring.learned.short.usual_off": "Übliche Ausschaltzeit", + "monitoring.learned.short.usual_on": "Übliche Einschaltzeit", + "monitoring.learned.short.usual_runtime_s": "Übliche Laufzeit", + "monitoring.learned.site": "Anlage", + "monitoring.notice.chain.title": "{chain}: Messkette auffällig", + "monitoring.notice.measured_no_meter.title": "Hausverbrauch gemessen, aber kein Hauszähler", + "monitoring.notice.role_needed.title": "Werte nach einer Messkette ohne Rolle", + "monitoring.notice.soc_capacity.text": "Akkustände ohne Kapazität: {count}. Ohne die Kapazität in kWh fehlt der Energieinhalt des Akkus in der Bilanz.", + "monitoring.notice.soc_capacity.title": "Akkustand ohne Kapazität", + "monitoring.notice.unassigned.text": "Leistungswerte ohne Rolle sind oft die eigentliche Ursache einer Bilanzlücke.", + "monitoring.notice.unassigned.title": "{count} Leistungswerte ohne Rolle", + "monitoring.since.days": "seit {n} Tagen", + "monitoring.since.today": "seit heute", + "monitoring.since.yesterday": "seit gestern", + "monitoring.source.chain": "Messketten", + "monitoring.source.energy": "Energie-Bilanz", + "monitoring.source.learn": "Lernfunktionen", + "monitoring.step.assign_roles": "Jedem Wert, der zur Bilanz gehört, eine Rolle geben", + "monitoring.step.assign_roles.button": "Rollen setzen", + "monitoring.step.chain_open": "Messkette ansehen", + "monitoring.step.chain_open.button": "Messkette öffnen", + "monitoring.step.chain_suggestion": "Vorschlag der Messkette prüfen und übernehmen", + "monitoring.step.chain_suggestion.button": "Zum Vorschlag", + "monitoring.step.devicemap_check": "Messpunkte in der Device-Map prüfen", + "monitoring.step.devicemap_check.button": "Device-Map öffnen", + "monitoring.step.efficiency_open": "Verlauf der Kette in Effizienz ansehen", + "monitoring.step.efficiency_open.button": "Effizienz öffnen", + "monitoring.step.enter_capacity": "Kapazität des Akkus in der Rollentabelle eintragen", + "monitoring.step.enter_capacity.button": "Kapazität eintragen", + "monitoring.step.hide_values": "Werte, die nicht zur Bilanz gehören, in der Rollentabelle ausblenden", + "monitoring.step.hide_values.button": "Zur Rollentabelle", + "monitoring.step.learned_open": "Was die Anlage sonst gelernt hat, steht unter Lernwerte", + "monitoring.step.learned_open.button": "Zu den Lernwerten", + "monitoring.step.load_mode_auto": "Oder den Hausverbrauch wieder auf Automatisch stellen", + "monitoring.step.load_mode_auto.button": "Zur Einstellung", + "monitoring.step.role_keep": "Oder alle ohne Rolle lassen", + "monitoring.step.role_keep.button": "Ohne Rolle lassen", + "monitoring.step.set_load_role": "Dem Hauszähler die Rolle Hauszähler geben", + "monitoring.step.set_load_role.button": "Rolle setzen", + "monitoring.step.set_role": "Rolle der Werte neu setzen", + "monitoring.step.set_role.button": "Rollen setzen", + "monitoring.step.shade_accept": "Lässt sich der Schatten nicht beseitigen, ist nichts zu tun. Rest-Überschuss und Überschussfenster rechnen ihn schon heraus.", + "monitoring.step.shade_look": "Vor Ort nach der Ursache schauen: Baum, Antenne, Nachbarhaus oder Schornstein in Richtung {direction}, etwa {height}° hoch.", + "monitoring.steps.title": "Empfohlene Schritte", + "monitoring.value.time": "{time} Uhr", + "monitoring.view.learned": "Lernwerte", + "monitoring.view.notices": "Meldungen", + "monitoring.weeks.and": "{a} und {b}", + "monitoring.weeks.range": "{from} bis {to}", "mqtt.cannot_configure": "Für Änderungen fehlt entweder die Rolle mqtt_config oder die Verbindung läuft nicht über HTTPS.", "mqtt.chain_sensors.help": "Erklärung zu Messketten-Sensoren", "mqtt.chain_sensors.help_text": "Sendet je Messkette Wirkungsgrad, Verlust und Verlustenergie an Home Assistant.", @@ -3688,6 +3793,7 @@ "nav.history": "Verläufe", "nav.layout": "Layout", "nav.learning_new": "Neue Lernfunktionen", + "nav.monitoring": "Monitoring", "nav.more": "Weitere", "nav.new": "Neu", "nav.no_access": "Hinweis", @@ -4019,6 +4125,7 @@ "panel.energy_loading": "Energie wird geladen ...", "panel.history_loading": "Verläufe werden geladen ...", "panel.load_failed": "Panel konnte nicht geladen werden ({code})", + "panel.monitoring_loading": "Monitoring wird geladen …", "panel.settings_loading": "Einstellungen werden geladen ...", "panel.stats_loading": "Statistik wird geladen ...", "performance.deduction.hot": "Die Temperatur liegt bei 80 °C oder darüber", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index d078e5ef..650eb12c 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -1,4 +1,7 @@ { + " / ": "from 1 run", + " / .days": "from {n} days", + " / .runs": "from {n} runs", "automations.action.add_aria": "Add action: {type}", "automations.action.add_button_aria": "Add action", "automations.action.advanced": "Advanced", @@ -3587,6 +3590,108 @@ "meta.locale": "en-GB", "meta.number.decimal": ".", "meta.number.group": ",", + "monitoring.ack.button": "Acknowledge", + "monitoring.ack.done": "Acknowledged on {date} by {user}", + "monitoring.ack.no_right": "Only users with the setup right can acknowledge.", + "monitoring.ack.undo": "Mark as new again", + "monitoring.badge.new": "new", + "monitoring.compass.e": "east", + "monitoring.compass.n": "north", + "monitoring.compass.ne": "northeast", + "monitoring.compass.nw": "northwest", + "monitoring.compass.s": "south", + "monitoring.compass.se": "southeast", + "monitoring.compass.sw": "southwest", + "monitoring.compass.w": "west", + "monitoring.empty.text": "No open notices. New ones appear here and the tab gets a dot.", + "monitoring.empty.title": "All quiet", + "monitoring.energy_line.count.one": "{count} notice about energy", + "monitoring.energy_line.count.other": "{count} notices about energy", + "monitoring.energy_line.new": "{count} new", + "monitoring.energy_line.none": "No open notices about energy", + "monitoring.energy_line.open": "Open in monitoring", + "monitoring.fact.direction": "Direction", + "monitoring.fact.direction_value": "{az}° ({compass}), {el}° above the horizon", + "monitoring.fact.loss": "Loss", + "monitoring.fact.loss_value": "about {kwh} kWh a year", + "monitoring.fact.more": "and {n} more", + "monitoring.fact.time": "Time", + "monitoring.fact.time_value": "{from} to {to}", + "monitoring.fact.value": "Value", + "monitoring.fact.weeks": "Calendar weeks", + "monitoring.filter.all": "All", + "monitoring.filter.energy": "Energy", + "monitoring.filter.learn": "Learning", + "monitoring.group.known": "Acknowledged", + "monitoring.group.new": "New", + "monitoring.learned.count": "{have} of {total}", + "monitoring.learned.missing": "Not learned yet", + "monitoring.learned.missing_days": "needs more days", + "monitoring.learned.missing_pv": "needs PV minutes by day", + "monitoring.learned.off": "Pattern learning is off. Turn it on under settings, learning.", + "monitoring.learned.origin.changed": "changed {age} ago", + "monitoring.learned.origin.days": "from {n} days", + "monitoring.learned.origin.days_one": "from 1 day", + "monitoring.learned.origin.minute": "value of the last minute", + "monitoring.learned.origin.prev": "before {value}", + "monitoring.learned.origin.runs": "from {n} runs", + "monitoring.learned.origin.runs_one": "from 1 run", + "monitoring.learned.short.cycle_wh": "Typical cycle energy", + "monitoring.learned.short.day_start": "Start of day", + "monitoring.learned.short.house_state": "House state", + "monitoring.learned.short.night_rest": "Night rest", + "monitoring.learned.short.op_power_w": "Typical operating power", + "monitoring.learned.short.pv_reserve_w": "PV reserve", + "monitoring.learned.short.surplus_left_wh": "Remaining surplus today", + "monitoring.learned.short.usual_off": "Usual switch-off time", + "monitoring.learned.short.usual_on": "Usual switch-on time", + "monitoring.learned.short.usual_runtime_s": "Usual runtime", + "monitoring.learned.site": "System", + "monitoring.notice.chain.title": "{chain}: measurement chain looks wrong", + "monitoring.notice.measured_no_meter.title": "House load set to measured, but no house meter", + "monitoring.notice.role_needed.title": "Values left without a role by a measurement chain", + "monitoring.notice.soc_capacity.text": "Battery levels without capacity: {count}. Without the capacity in kWh the battery energy is missing from the balance.", + "monitoring.notice.soc_capacity.title": "Battery level without capacity", + "monitoring.notice.unassigned.text": "Power values without a role are often the real cause of a gap in the balance.", + "monitoring.notice.unassigned.title": "{count} power values without a role", + "monitoring.since.days": "for {n} days", + "monitoring.since.today": "since today", + "monitoring.since.yesterday": "since yesterday", + "monitoring.source.chain": "Measurement chains", + "monitoring.source.energy": "Energy balance", + "monitoring.source.learn": "Learning", + "monitoring.step.assign_roles": "Give every value that belongs to the balance a role", + "monitoring.step.assign_roles.button": "Set roles", + "monitoring.step.chain_open": "Look at the measurement chain", + "monitoring.step.chain_open.button": "Open chain", + "monitoring.step.chain_suggestion": "Check and apply the suggestion of the chain", + "monitoring.step.chain_suggestion.button": "To the suggestion", + "monitoring.step.devicemap_check": "Check the measuring points in the device map", + "monitoring.step.devicemap_check.button": "Open device map", + "monitoring.step.efficiency_open": "See the course of the chain in efficiency", + "monitoring.step.efficiency_open.button": "Open efficiency", + "monitoring.step.enter_capacity": "Enter the battery capacity in the role table", + "monitoring.step.enter_capacity.button": "Enter capacity", + "monitoring.step.hide_values": "Hide values that do not belong to the balance in the role table", + "monitoring.step.hide_values.button": "To the role table", + "monitoring.step.learned_open": "What else the system has learned is under learned values", + "monitoring.step.learned_open.button": "To the learned values", + "monitoring.step.load_mode_auto": "Or set the house load back to automatic", + "monitoring.step.load_mode_auto.button": "To the setting", + "monitoring.step.role_keep": "Or leave all of them without a role", + "monitoring.step.role_keep.button": "Leave without role", + "monitoring.step.set_load_role": "Give the house meter the role house meter", + "monitoring.step.set_load_role.button": "Set role", + "monitoring.step.set_role": "Set the role of the values again", + "monitoring.step.set_role.button": "Set roles", + "monitoring.step.shade_accept": "If the shade cannot be removed, there is nothing to do. The remaining surplus and the surplus window already leave it out.", + "monitoring.step.shade_look": "Look for the cause on site: a tree, an antenna, a neighbouring house or a chimney towards the {direction}, about {height}° high.", + "monitoring.steps.title": "Recommended steps", + "monitoring.value.time": "{time}", + "monitoring.view.learned": "Learned values", + "monitoring.view.notices": "Notices", + "monitoring.weeks.and": "{a} and {b}", + "monitoring.weeks.range": "{from} to {to}", "mqtt.cannot_configure": "Changes need the mqtt_config role and a connection over HTTPS.", "mqtt.chain_sensors.help": "Explanation of measurement chain sensors", "mqtt.chain_sensors.help_text": "Sends the efficiency, loss and loss energy of each measurement chain to Home Assistant.", @@ -3688,6 +3793,7 @@ "nav.history": "History", "nav.layout": "Layout", "nav.learning_new": "New learning features", + "nav.monitoring": "Monitoring", "nav.more": "More", "nav.new": "New", "nav.no_access": "Notice", @@ -4019,6 +4125,7 @@ "panel.energy_loading": "Loading energy ...", "panel.history_loading": "Loading history ...", "panel.load_failed": "Could not load panel ({code})", + "panel.monitoring_loading": "Loading monitoring …", "panel.settings_loading": "Loading settings ...", "panel.stats_loading": "Loading statistics ...", "performance.deduction.hot": "The temperature is 80 °C or higher", diff --git a/dashboard/internal/webui/static/js/monitoring-model.js b/dashboard/internal/webui/static/js/monitoring-model.js index 0a148923..73912f38 100644 --- a/dashboard/internal/webui/static/js/monitoring-model.js +++ b/dashboard/internal/webui/static/js/monitoring-model.js @@ -90,7 +90,7 @@ const id = shadeIdParts(notice.id); if (id) { rows.push([t('monitoring.fact.direction'), t('monitoring.fact.direction_value', { - az: id.az, compass: t('monitoring.compass.' + compass(id.az)), el: id.el, + az: id.az, compass: t(`monitoring.compass.${compass(id.az)}`), el: id.el, })]); } rows.push([t('monitoring.fact.loss'), t('monitoring.fact.loss_value', { kwh: kwhText(p.kwh_lost) })]); @@ -106,13 +106,13 @@ function text(notice, t) { const p = notice.params || {}; - if (sourceOf(notice) === 'learn') return t('automations.learn.' + notice.code + '.text', notice.params); + if (sourceOf(notice) === 'learn') return t(`automations.learn.${notice.code}.text`, notice.params); if (notice.code === 'measured_no_meter') return t('energy.roles.notices.measured_warning'); if (notice.code === 'role_needed') return t('energy.chains.role_needed'); if (notice.code === 'chain') { - return t('chains.finding.' + p.kind, { chain: p.chain, from: p.from, to: p.to, since: shortDate(p.since) }); + return t(`chains.finding.${p.kind}`, { chain: p.chain, from: p.from, to: p.to, since: shortDate(p.since) }); } - return t('monitoring.notice.' + notice.code + '.text', notice.params); + return t(`monitoring.notice.${notice.code}.text`, notice.params); } function facts(notice, t) { @@ -144,7 +144,7 @@ const key = 'monitoring.step.' + s.code; const ok = allowed(s.target, rights); const params = s.code === 'shade_look' && shade - ? { direction: t('monitoring.compass.' + compass(shade.az)), height: shade.el } + ? { direction: t(`monitoring.compass.${compass(shade.az)}`), height: shade.el } : undefined; return { text: t(key, params), @@ -208,8 +208,8 @@ } else if (entry.n) { const kind = RUN_KEYS.includes(name) ? 'runs' : 'days'; parts.push(entry.n === 1 - ? t('monitoring.learned.origin.' + kind + '_one') - : t('monitoring.learned.origin.' + kind, { n: entry.n })); + ? t(`monitoring.learned.origin.${kind}_one`) + : t(`monitoring.learned.origin.${kind}`, { n: entry.n })); } const since = entry.changed_at || entry.at; if (since) parts.push(t('monitoring.learned.origin.changed', { age: ageText(now - since) })); @@ -234,7 +234,7 @@ function learnedRow(key, name, entry, now, t) { return { key, - label: t('monitoring.learned.short.' + name), + label: t(`monitoring.learned.short.${name}`), icon: VALUE_ICON[name] || 'ico-learning', have: !!entry, value: entry ? valueText(entry, t) : t('monitoring.learned.missing'), From 24907a447a1af47be4fd2222c571a420f384c484 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:11:15 +0100 Subject: [PATCH 12/27] feat(webui): add the monitoring panel files Template, stylesheet and Alpine component of the monitoring page, with its JS test for loading, acknowledging and the acknowledge right. Co-Authored-By: Claude Sonnet 5.5 --- .../internal/webui/static/css/monitoring.css | 149 ++++++++ .../webui/static/js/monitoring.page.js | 318 ++++++++++++++++++ .../internal/webui/templates/monitoring.html | 106 ++++++ dashboard/test/monitoring.page.test.mjs | 95 ++++++ 4 files changed, 668 insertions(+) create mode 100644 dashboard/internal/webui/static/css/monitoring.css create mode 100644 dashboard/internal/webui/static/js/monitoring.page.js create mode 100644 dashboard/internal/webui/templates/monitoring.html create mode 100644 dashboard/test/monitoring.page.test.mjs diff --git a/dashboard/internal/webui/static/css/monitoring.css b/dashboard/internal/webui/static/css/monitoring.css new file mode 100644 index 00000000..7b406ccb --- /dev/null +++ b/dashboard/internal/webui/static/css/monitoring.css @@ -0,0 +1,149 @@ +/* Monitoring-Seite. Kein globales box-sizing, nur eigene Klassen. + Bewegung: --ease-out (Ein/Aus), --ease-in-out (Umzug auf dem Bildschirm), Werte unter 300 ms. */ + +/* Leiste wie auf Automationen: Umschaltung links (auto-segment aus automations.css), Filter rechts */ +.monitoring-bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .6rem 1rem; margin: 0 0 1rem; } +.monitoring-bar .monitoring-filters { margin: 0; } +.monitoring-seg-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); } +.monitoring-muted { color: var(--text-muted); margin: 0; line-height: 1.5; } + +/* Filter */ +.monitoring-filters { display: flex; flex-wrap: wrap; gap: .35rem; } +.monitoring-chip { display: inline-flex; align-items: center; gap: .4rem; height: 1.9rem; padding: 0 .75rem; border-radius: 999px; + border: 1px solid var(--border-soft); background: none; color: var(--text-muted); font: inherit; font-size: .9rem; cursor: pointer; + transition: background-color 160ms ease, color 160ms ease, border-color 160ms ease, transform 120ms var(--ease-out); } +.monitoring-chip.is-on { background: var(--accent-bg); border-color: var(--accent-line); color: var(--accent); } +.monitoring-chip-count { font-variant-numeric: tabular-nums; opacity: .75; } + +/* Liste und Detail */ +.monitoring-split { display: grid; grid-template-columns: minmax(17rem, 23rem) minmax(0, 1fr); gap: 1.25rem; align-items: start; } +.monitoring-master { display: grid; gap: 1.1rem; } +.monitoring-list-head { display: flex; align-items: baseline; gap: .45rem; margin: 0 0 .4rem .75rem; font-size: .78rem; font-weight: 600; + letter-spacing: .04em; text-transform: uppercase; color: var(--text-subtle); } +.monitoring-count { font-weight: 400; letter-spacing: 0; color: var(--text-faint); font-variant-numeric: tabular-nums; } +.monitoring-rows { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; } +.monitoring-li { position: relative; } +.monitoring-row { width: 100%; display: flex; align-items: center; gap: .7rem; padding: .65rem .75rem; border-radius: 10px; border: 0; + background: none; color: var(--text); font: inherit; text-align: left; cursor: pointer; + transition: background-color 160ms ease, transform 120ms var(--ease-out); } +.monitoring-row.is-on { background: var(--panel); box-shadow: 0 0 0 1px var(--border-soft); } +.monitoring-row-badge { display: inline-grid; place-items: center; width: 30px; height: 30px; flex: none; border-radius: 9px; background: var(--accent-bg); } +.monitoring-row-badge.is-warn { background: var(--warn-bg); } +.monitoring-row-badge svg { width: 16px; height: 16px; fill: none; stroke: var(--accent); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.monitoring-row-badge.is-warn svg { stroke: var(--warn); } +.monitoring-row-main { flex: 1; min-width: 0; display: grid; gap: .1rem; } +.monitoring-row-title { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; line-height: 1.3; } +.monitoring-row.is-new .monitoring-row-title { font-weight: 600; color: var(--text-strong); } +.monitoring-row-meta { font-size: .8rem; color: var(--text-muted); } +.monitoring-row-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex: none; opacity: 0; transform: scale(.6); + transition: opacity 180ms var(--ease-out), transform 180ms var(--ease-out); } +.monitoring-row.is-new .monitoring-row-dot { opacity: 1; transform: none; } +.monitoring-row-chev { display: none; width: 14px; height: 14px; flex: none; fill: none; stroke: var(--text-faint); stroke-width: 2.2; + transition: transform 220ms var(--ease-out); } +.monitoring-li:has(.monitoring-row:not(.is-new)) .monitoring-row-badge { filter: saturate(.3); opacity: .75; } + +.monitoring-detail { position: sticky; top: 1rem; min-width: 0; } +.monitoring-acc { display: none; } + +/* Karte */ +.monitoring-card { display: grid; gap: .75rem; padding: 1.1rem 1.2rem; border-radius: 14px; background: var(--panel); + box-shadow: 0 0 0 1px var(--border-soft), 0 8px 24px -16px rgb(0 0 0 / .45); } +.monitoring-card-head { display: flex; gap: .75rem; align-items: flex-start; } +.monitoring-card-titles { min-width: 0; } +.monitoring-card-title { margin: 0; font-size: 1.12rem; line-height: 1.25; letter-spacing: -0.01em; color: var(--text-strong); } +.monitoring-card-meta { display: flex; flex-wrap: wrap; gap: .25rem .6rem; margin: .25rem 0 0; font-size: .82rem; color: var(--text-muted); } +.monitoring-badge-new { display: inline-block; padding: 0 .45rem; border-radius: 999px; background: var(--accent-bg); color: var(--accent); font-size: .75rem; line-height: 1.5; } +.monitoring-card-text { margin: 0; color: var(--text); line-height: 1.55; max-width: 52rem; } +.monitoring-facts { display: grid; grid-template-columns: max-content 1fr; gap: .3rem 1rem; margin: 0; padding: .7rem .85rem; border-radius: 10px; + background: var(--panel-alt); font-size: .9rem; } +.monitoring-facts dt { color: var(--text-muted); } +.monitoring-facts dd { margin: 0; color: var(--text); overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } +.monitoring-evidence { max-width: 42rem; } +.monitoring-steps h4 { margin: .15rem 0 .45rem; font-size: .78rem; letter-spacing: .04em; text-transform: uppercase; color: var(--text-subtle); font-weight: 600; } +.monitoring-steps ol { margin: 0; padding-left: 1.2rem; display: grid; gap: .55rem; } +.monitoring-steps li { padding-left: .2rem; line-height: 1.45; } +.monitoring-steps li > span { margin-right: .5rem; } +.monitoring-card-foot { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem .9rem; padding-top: .75rem; border-top: 1px solid var(--border-soft); } +.monitoring-acked { display: inline-flex; align-items: center; gap: .4rem; font-size: .88rem; color: var(--text-muted); animation: monitoring-in 220ms var(--ease-out); } +.monitoring-acked svg { width: 16px; height: 16px; fill: none; stroke: var(--ok); stroke-width: 2.4; } +@keyframes monitoring-in { from { opacity: 0; transform: scale(.96); } } + +/* Knöpfe */ +.monitoring-btn { display: inline-flex; align-items: center; gap: .35rem; height: 2.1rem; padding: 0 .95rem; border-radius: 999px; border: 0; + background: var(--accent-bg); color: var(--accent); font: inherit; font-size: .9rem; font-weight: 600; cursor: pointer; white-space: nowrap; + transition: background-color 160ms ease, transform 120ms var(--ease-out); } +.monitoring-btn svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2.4; stroke-linecap: round; stroke-linejoin: round; } +.monitoring-btn-primary { background: var(--accent); color: var(--bg); } +.monitoring-btn-quiet { background: none; color: var(--text-muted); font-weight: 400; padding: 0 .4rem; } +.monitoring-btn-link { height: 1.75rem; padding: 0 .55rem 0 .75rem; font-size: .85rem; vertical-align: middle; } + +/* Sofortiges Feedback beim Drücken, Hover nur mit Maus */ +.monitoring-row:active, .monitoring-btn:active, .monitoring-chip:active { transform: scale(.97); } +@media (hover: hover) and (pointer: fine) { + .monitoring-row:not(.is-on):hover { background: var(--panel-alt); } + .monitoring-btn:hover { background: color-mix(in srgb, var(--accent-bg) 70%, var(--accent-line)); } + .monitoring-btn-primary:hover { background: color-mix(in srgb, var(--accent) 88%, var(--text-strong)); } + .monitoring-btn-quiet:hover { background: none; color: var(--text); } + .monitoring-chip:not(.is-on):hover { color: var(--text); border-color: var(--border); } +} +.monitoring-btn:focus-visible, .monitoring-chip:focus-visible, .monitoring-row:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } + +/* Leer */ +.monitoring-empty { display: grid; justify-items: center; gap: .35rem; padding: 3rem 1rem; text-align: center; } +.monitoring-empty-badge { display: grid; place-items: center; width: 52px; height: 52px; border-radius: 16px; background: var(--ok-bg); margin-bottom: .3rem; } +.monitoring-empty-badge svg { width: 26px; height: 26px; fill: none; stroke: var(--ok); stroke-width: 2.4; } +.monitoring-empty-title { margin: 0; font-size: 1.1rem; font-weight: 600; color: var(--text-strong); } + +/* Lernwerte: Gruppenkarten in zwei Spalten */ +.monitoring-learned { column-count: 2; column-gap: 1.25rem; } +.monitoring-lgroup { break-inside: avoid; margin: 0 0 1.25rem; border-radius: 14px; background: var(--panel); + box-shadow: 0 0 0 1px var(--border-soft), 0 8px 24px -18px rgb(0 0 0 / .5); overflow: hidden; } +.monitoring-lgroup-head { display: flex; align-items: center; gap: .6rem; padding: .8rem 1rem .7rem; border-bottom: 1px solid var(--border-soft); } +.monitoring-lgroup-icon { display: grid; place-items: center; width: 30px; height: 30px; border-radius: 9px; background: var(--accent-bg); flex: none; } +.monitoring-lgroup-icon svg { width: 17px; height: 17px; fill: none; stroke: var(--accent); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.monitoring-lgroup-name { flex: 1; min-width: 0; font-weight: 600; color: var(--text-strong); letter-spacing: -0.005em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.monitoring-lrows { display: grid; } +.monitoring-lrow { display: flex; align-items: center; gap: .75rem; padding: .7rem 1rem; border-top: 1px solid var(--border-soft); + transition: background-color 600ms ease; } +.monitoring-lrow:first-child { border-top: 0; } +.monitoring-lrow.is-flash { background: var(--accent-bg); transition-duration: 160ms; } +.monitoring-lrow-icon { display: grid; place-items: center; width: 26px; height: 26px; border-radius: 8px; background: var(--panel-alt); flex: none; } +.monitoring-lrow-icon svg { width: 15px; height: 15px; fill: none; stroke: var(--text-muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; } +.monitoring-lrow-main { flex: 1; min-width: 0; display: grid; gap: .1rem; } +.monitoring-lrow-label { color: var(--text); } +.monitoring-lrow-meta { font-size: .78rem; color: var(--text-muted); } +.monitoring-lrow-value { display: grid; justify-items: end; gap: .2rem; flex: none; text-align: right; } +.monitoring-lrow-num { font-size: 1.05rem; font-weight: 600; color: var(--text-strong); font-variant-numeric: tabular-nums; letter-spacing: -0.01em; } +.monitoring-lrow.is-missing .monitoring-lrow-num { font-size: .88rem; font-weight: 400; color: var(--text-faint); } +.monitoring-lrow.is-missing .monitoring-lrow-label { color: var(--text-muted); } +.monitoring-lrow.is-missing .monitoring-lrow-icon { opacity: .55; } +.monitoring-est { padding: 0 .45rem; border-radius: 999px; background: var(--warn-bg); color: var(--warn); font-size: .72rem; line-height: 1.6; } +.monitoring-spark { width: 64px; height: 18px; } +.monitoring-spark polyline { fill: none; stroke: var(--accent); stroke-width: 1.6; vector-effect: non-scaling-stroke; stroke-linejoin: round; stroke-linecap: round; } + +/* Schmal: Liste mit aufklappendem Detail (Akkordeon über grid-template-rows) */ +@media (max-width: 720px) { + .monitoring-bar > .auto-segment { width: 100%; display: grid; grid-template-columns: 1fr 1fr; } + .monitoring-learned { column-count: 1; } + .monitoring-split { grid-template-columns: 1fr; } + .monitoring-detail { display: none; } + .monitoring-row-chev { display: block; } + .monitoring-row[aria-expanded="true"] .monitoring-row-chev { transform: rotate(90deg); } + .monitoring-acc { display: grid; grid-template-rows: 0fr; opacity: 0; transition: grid-template-rows 240ms var(--ease-out), opacity 200ms var(--ease-out); } + .monitoring-acc.is-open { grid-template-rows: 1fr; opacity: 1; } + .monitoring-acc-inner { overflow: hidden; min-height: 0; } + .monitoring-acc .monitoring-card { margin: .35rem 0 .6rem; padding: .9rem .9rem; box-shadow: 0 0 0 1px var(--border-soft); } + .monitoring-acc .monitoring-card-head { display: none; } + .monitoring-facts { grid-template-columns: 1fr; gap: 0; } + .monitoring-facts dd { margin-bottom: .4rem; } + .monitoring-steps li > span { display: block; margin: 0 0 .35rem; } + .monitoring-lrow { gap: .6rem; padding: .7rem .85rem; } + .monitoring-spark { display: none; } +} + +@media (prefers-reduced-motion: reduce) { + .monitoring-row-chev, .monitoring-row-dot { transition: none; } + .monitoring-acc { transition: opacity 150ms ease; } + .monitoring-row:active, .monitoring-btn:active, .monitoring-chip:active { transform: none; } + .monitoring-acked { animation: none; } +} diff --git a/dashboard/internal/webui/static/js/monitoring.page.js b/dashboard/internal/webui/static/js/monitoring.page.js new file mode 100644 index 00000000..137440d4 --- /dev/null +++ b/dashboard/internal/webui/static/js/monitoring.page.js @@ -0,0 +1,318 @@ +// Monitoring-Seite: Meldungen (Liste und Karte) und Lernwerte. Die Daten kommen +// aus GET /api/v1/monitoring, das Quittieren geht per POST /api/v1/monitoring/ack +// mit dem CSRF-Token der Sitzung. Die Texte baut window.MonitoringModel. +// +// i18n-keys: monitoring.filter.all, monitoring.filter.energy, monitoring.filter.learn, +// monitoring.source.energy, monitoring.source.chain, monitoring.source.learn, +// monitoring.group.new, monitoring.group.known, monitoring.steps.title, +// monitoring.ack.button, monitoring.ack.done, monitoring.ack.undo, monitoring.ack.no_right, +// monitoring.badge.new, monitoring.learned.count +(() => { + const t = (key, params) => (window.I18n ? window.I18n.t(key, params) : key); + const base = () => window.__DASHBOARD_BASE_PATH__ || ''; + const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + const wide = () => Boolean(window.matchMedia) && window.matchMedia('(min-width: 721px)').matches; + const reduced = () => Boolean(window.matchMedia) && window.matchMedia('(prefers-reduced-motion: reduce)').matches; + const nowSeconds = () => Date.now() / 1000; + + const FILTERS = [ + { id: 'all', key: 'monitoring.filter.all' }, + { id: 'energy', key: 'monitoring.filter.energy' }, + { id: 'learn', key: 'monitoring.filter.learn' }, + ]; + const SOURCE_KEYS = { + energy: 'monitoring.source.energy', + chain: 'monitoring.source.chain', + learn: 'monitoring.source.learn', + }; + const GROUP_KEYS = { new: 'monitoring.group.new', known: 'monitoring.group.known' }; + // Sprungziel der Schritte auf die Seite (Reiter) und das Panel, das den Reiter besitzt. + const TARGET_PANELS = { efficiency: 'efficiency-panel', devicemap: 'devicemap-panel' }; + + async function requestJSON(path, options) { + const response = await fetch(base() + path, options || { credentials: 'same-origin', headers: { Accept: 'application/json' } }); + if (!response.ok) throw new Error(path + ' ' + response.status); + return response.json(); + } + + function panelFor(target) { + if (String(target || '').startsWith('energy')) return 'energy-panel'; + return TARGET_PANELS[target] || ''; + } + + function openTab(panel) { + const tab = document.querySelector('[role="tab"][aria-controls="' + panel + '"]'); + if (tab) tab.click(); + } + + function monitoringPanel() { + return { + notices: [], + newCount: 0, + learned: { enabled: false, values: [] }, + loaded: false, + failed: false, + // Rollen aus der Sitzung; ohne Antwort gibt es keine Rechte (nichts quittieren). + sessionRoles: [], + csrfToken: '', + view: 'notices', + filter: 'all', + pick: '', + flashKey: '', + + init() { + window.addEventListener('monitoring-open', (event) => { + this.view = 'notices'; + this.filter = (event.detail && event.detail.filter) || 'all'; + this.pick = ''; + openTab('monitoring-panel'); + }); + this.load(); + }, + + async load() { + try { + const [body, session] = await Promise.all([ + requestJSON('/api/v1/monitoring'), + requestJSON('/api/v1/auth/session').catch(() => null), + ]); + this.apply(body); + this.sessionRoles = session && Array.isArray(session.roles) ? session.roles : []; + this.csrfToken = (session && session.csrf_token) || ''; + this.failed = false; + } catch (error) { + this.failed = true; + } + this.loaded = true; + }, + + apply(body) { + const doc = body || {}; + this.notices = Array.isArray(doc.notices) ? doc.notices : []; + this.newCount = Number(doc.new_count) || 0; + const learned = doc.learned || {}; + this.learned = { enabled: Boolean(learned.enabled), values: Array.isArray(learned.values) ? learned.values : [] }; + }, + + notify(error) { + if (this.$store && this.$store.toasts) this.$store.toasts.push(error.message, 'critical'); + }, + + rights() { + const roles = this.sessionRoles || []; + return { + view_energy: roles.includes('view_energy'), + view_efficiency: roles.includes('view_efficiency'), + view_device_map: roles.includes('view_device_map'), + edit_energy: roles.includes('edit_energy'), + }; + }, + canAck() { return (this.sessionRoles || []).includes('edit_setup'); }, + + sourceLabel(source) { return SOURCE_KEYS[source] ? t(SOURCE_KEYS[source]) : ''; }, + setView(view) { + if (this.view === view) return; + this.view = view; + this.$nextTick(() => this.fadeIn(this.$el && this.$el.querySelector(view === 'learned' ? '.monitoring-learned' : '.monitoring-split'), 6)); + }, + setFilter(id) { this.filter = id; this.pick = ''; }, + + filters() { + return FILTERS.map((f) => ({ + id: f.id, + label: t(f.key), + count: window.MonitoringModel.filterNotices(this.notices, f.id).length, + })); + }, + list() { + return window.MonitoringModel.sortNotices(window.MonitoringModel.filterNotices(this.notices, this.filter)); + }, + groups() { + return window.MonitoringModel.groups(this.list()).map((g) => ({ id: g.id, label: t(GROUP_KEYS[g.id]), items: g.items })); + }, + selected() { + const list = this.list(); + if (!wide()) return list.find((item) => item.id === this.pick) || null; + return list.find((item) => item.id === this.pick) || list[0] || null; + }, + isSelected(item) { const s = this.selected(); return Boolean(s) && s.id === item.id; }, + + // Auswahl: schmal klappt eine zweite Berührung die Zeile wieder zu. + select(id) { + const before = this.selected(); + if (!wide() && before && before.id === id) { this.pick = ''; return; } + this.pick = id; + if (wide() && (!before || before.id !== id) && this.$el) { + this.$nextTick(() => this.fadeIn(this.$el.querySelector('.monitoring-detail-inner'), 4)); + } + }, + + // Ruhiger Wechsel: nur Deckkraft und ein paar Pixel, damit Lesen nie springt. + fadeIn(el, dy) { + if (!el || !el.animate) return; + const frames = reduced() + ? [{ opacity: 0 }, { opacity: 1 }] + : [{ opacity: 0, transform: 'translateY(' + dy + 'px)' }, { opacity: 1, transform: 'none' }]; + el.animate(frames, { duration: reduced() ? 120 : 180, easing: 'cubic-bezier(0.23, 1, 0.32, 1)' }); + }, + + // Quittieren: die Zeile zieht sichtbar in die andere Gruppe (FLIP). + moveRows(change) { + if (!this.$el) { change(); return; } + const rows = () => [...this.$el.querySelectorAll('.monitoring-master [data-row]')]; + const first = new Map(rows().map((el) => [el.dataset.row, el.getBoundingClientRect().top])); + change(); + this.$nextTick(() => { + if (reduced()) return; + rows().forEach((el) => { + const top = first.get(el.dataset.row); + if (top === undefined) return; + const dy = top - el.getBoundingClientRect().top; + if (Math.abs(dy) < 1) return; + el.animate([{ transform: 'translateY(' + dy + 'px)' }, { transform: 'none' }], + { duration: 260, easing: 'cubic-bezier(0.77, 0, 0.175, 1)' }); + }); + }); + }, + + async setAck(id, ack) { + if (!this.canAck()) return; + let body; + try { + body = await requestJSON('/api/v1/monitoring/ack', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': this.csrfToken }, // i18n-ignore + body: JSON.stringify({ id, ack }), + }); + } catch (error) { + this.notify(error); + return; + } + if (!wide()) this.pick = id; + this.moveRows(() => this.apply(body)); + window.dispatchEvent(new CustomEvent('monitoring-changed')); + }, + ack(id) { return this.setAck(id, true); }, + unack(id) { return this.setAck(id, false); }, + + async roleKeep(ids) { + if (!this.rights().edit_energy || !ids.length) return; + const roleNeeded = {}; + ids.forEach((id) => { roleNeeded[id] = false; }); + try { + await requestJSON('/api/v1/energy/roles', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': this.csrfToken }, // i18n-ignore + body: JSON.stringify({ role_needed: roleNeeded }), + }); + } catch (error) { + this.notify(error); + return; + } + await this.load(); + window.dispatchEvent(new CustomEvent('monitoring-changed')); + }, + + // Schritt mit Sprungziel: Energie, Effizienz, Gerätekarte oder Lernwerte. + runStep(notice, index) { + const step = this.stepsOf(notice)[index]; + if (!step || !step.target) return; + if (step.target === 'learned') { this.goLearned(); return; } + if (step.target === 'action.role_keep') { this.roleKeep(step.ids); return; } + const panel = panelFor(step.target); + if (!panel) return; + const detail = { panel }; + if (step.ids && step.ids.length) detail.focus = step.ids; + if (step.chain) detail.chain = step.chain; + window.dispatchEvent(new CustomEvent('monitoring-goto', { detail })); + openTab(panel); + }, + + goLearned() { + this.setView('learned'); + this.$nextTick(() => { + const el = this.$el && this.$el.querySelector('.monitoring-learned'); + if (el && el.scrollIntoView) el.scrollIntoView({ block: 'start', behavior: reduced() ? 'auto' : 'smooth' }); + }); + }, + + learnedGroups() { + return window.MonitoringModel.learnedGroups(this.learned.values, nowSeconds(), t); + }, + countText(group) { + return t('monitoring.learned.count', { have: group.have, total: group.total }); + }, + + titleOf(notice) { return window.MonitoringModel.title(notice, t); }, + rowMeta(notice) { + return [this.sourceLabel(notice.source), window.MonitoringModel.sinceText(notice.first_seen, nowSeconds(), t)].join(' · '); + }, + + stepsOf(notice) { + return window.MonitoringModel.steps(notice, this.rights(), t); + }, + + // Karte einer Meldung als HTML. Ohne Recht Einrichten keine Quittier-Knöpfe. + cardHtml(notice) { + const model = window.MonitoringModel; + const acked = Boolean(notice.ack); + const severity = notice.severity === 'warn' ? 'warn' : 'info'; + const icon = severity === 'info' ? '#ico-info' : '#ico-warning'; + const since = model.sinceText(notice.first_seen, nowSeconds(), t); + const facts = model.facts(notice, t); + const factsHtml = facts.length + ? '
' + facts.map(([k, v]) => '
' + esc(k) + '
' + esc(v) + '
').join('') + '
' + : ''; + let evidenceHtml = ''; + if (notice.evidence && window.AutomationEvidence && typeof window.AutomationEvidence.render === 'function') { + evidenceHtml = '
' + window.AutomationEvidence.render(notice.evidence, t, {}) + '
'; + } + const steps = this.stepsOf(notice); + const stepsHtml = steps.length + ? '

' + esc(t('monitoring.steps.title')) + '

    ' + steps.map((s, index) => '
  1. ' + esc(s.text) + '' + + (s.target && s.label ? '' : '') + + '
  2. ').join('') + '
' + : ''; + const id = esc(notice.id); + let foot = ''; + if (acked) { + const at = new Date(Number(notice.ack.at) * 1000); + const date = window.I18n.formatDate(at, { day: '2-digit', month: '2-digit', year: 'numeric' }); + foot += '' + esc(t('monitoring.ack.done', { date, user: notice.ack.user || '' })) + ''; + } + if (this.canAck()) { + foot += acked + ? '' + : ''; + } else { + foot += '

' + esc(t('monitoring.ack.no_right')) + '

'; + } + return '
' + + '
' + + '

' + esc(model.title(notice, t)) + '

' + + '

' + esc(this.sourceLabel(notice.source)) + '' + esc(since) + '' + + (acked ? '' : '' + esc(t('monitoring.badge.new')) + '') + '

' + + '

' + esc(model.text(notice, t)) + '

' + + factsHtml + evidenceHtml + stepsHtml + + '
' + foot + '
'; + }, + + onClick(event) { + const btn = event.target.closest && event.target.closest('[data-act]'); + if (!btn || (this.$el && !this.$el.contains(btn))) return; + const id = btn.dataset.id; + if (btn.dataset.act === 'ack') this.ack(id); + else if (btn.dataset.act === 'unack') this.unack(id); + else if (btn.dataset.act === 'step') { + const notice = this.notices.find((n) => n.id === id); + if (notice) this.runStep(notice, Number(btn.dataset.index)); + } + }, + }; + } + + const register = () => { + if (window.Alpine) window.Alpine.data('monitoringPanel', monitoringPanel); + }; + if (window.Alpine) register(); else document.addEventListener('alpine:init', register, { once: true }); +})(); diff --git a/dashboard/internal/webui/templates/monitoring.html b/dashboard/internal/webui/templates/monitoring.html new file mode 100644 index 00000000..9fa2ccef --- /dev/null +++ b/dashboard/internal/webui/templates/monitoring.html @@ -0,0 +1,106 @@ +{{define "monitoring"}} +
+ + +
+
+ + +
+
+ +
+
+ + +
+ + + +
+
+ +
+
+
+
+
+
+ + +
+ +
+ +
+
+
+{{end}} diff --git a/dashboard/test/monitoring.page.test.mjs b/dashboard/test/monitoring.page.test.mjs new file mode 100644 index 00000000..485952e5 --- /dev/null +++ b/dashboard/test/monitoring.page.test.mjs @@ -0,0 +1,95 @@ +// Tests for the monitoring page component. The component is called directly +// (the automations.page.test.mjs convention): fetch is faked, Alpine is a stub +// that only captures the factory. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import { fileURLToPath } from 'node:url'; +import path from 'node:path'; +import { JSDOM } from 'jsdom'; +import { installI18n } from './helpers/i18n.mjs'; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const jsDir = path.join(here, '..', 'internal', 'webui', 'static', 'js'); +const modelSource = fs.readFileSync(path.join(jsDir, 'monitoring-model.js'), 'utf8'); +const pageSource = fs.readFileSync(path.join(jsDir, 'monitoring.page.js'), 'utf8'); + +const NOW = Math.floor(Date.now() / 1000); + +function response(body) { + return { ok: true, status: 200, json: async () => JSON.parse(JSON.stringify(body)) }; +} + +function createPanel({ roles = ['edit_setup'], notices = null, ackReply = null } = {}) { + const dom = new JSDOM('', { runScripts: 'outside-only' }); + const context = dom.getInternalVMContext(); + installI18n(dom.window); + let factory; + dom.window.Alpine = { data: (_name, fn) => { factory = fn; } }; + const calls = []; + const list = notices || [ + { + id: 'learn:shade:225:15', source: 'learn', severity: 'info', code: 'shade', + params: { kind: 'shade', from: '14:35', to: '15:49', kwh_lost: 5.7, weeks: [4, 5, 6] }, + steps: [], first_seen: NOW - 3600, ack: null, + }, + { + id: 'energy:unassigned', source: 'energy', severity: 'info', code: 'unassigned', + params: { count: 2, names: ['Werkstatt', 'Garage'], more: 0 }, + steps: [{ code: 'assign_roles', target: 'energy.focus', ids: ['a'] }], + first_seen: NOW - 2 * 86400, ack: { at: NOW - 60, user: 'admin' }, + }, + ]; + dom.window.fetch = async (url, options) => { + calls.push({ url, options }); + if (url === '/api/v1/monitoring') { + return response({ notices: list, new_count: list.filter((n) => !n.ack).length, learned: { enabled: true, values: [] } }); + } + if (url === '/api/v1/auth/session') { + return response({ csrf_token: 'tok-1', roles }); + } + if (url === '/api/v1/monitoring/ack') { + return response(ackReply || { notices: list, new_count: 0, learned: { enabled: true, values: [] } }); + } + throw new Error('unexpected fetch ' + url); + }; + vm.runInContext(modelSource, context); + vm.runInContext(pageSource, context); + const component = factory(); + component.$refs = {}; + component.$nextTick = (callback) => callback(); + component.$watch = () => {}; + return { component, calls }; +} + +test('load() splits the notices into a new and an acknowledged group', async () => { + const { component } = createPanel(); + await component.load(); + const groups = component.groups(); + assert.equal(groups.length, 2); + assert.equal(groups.map((g) => g.id).join(','), 'new,known'); + assert.equal(groups[0].items[0].id, 'learn:shade:225:15'); + assert.equal(groups[1].items[0].id, 'energy:unassigned'); + assert.equal(component.newCount, 1); +}); + +test('ack() posts the id and the acknowledgement with the session token', async () => { + const { component, calls } = createPanel(); + await component.load(); + await component.ack('learn:shade:225:15'); + const post = calls.find((call) => call.url === '/api/v1/monitoring/ack'); + assert.ok(post, 'ack request was sent'); + assert.equal(post.options.method, 'POST'); + assert.equal(post.options.headers['X-CSRF-Token'], 'tok-1'); + assert.deepEqual(JSON.parse(post.options.body), { id: 'learn:shade:225:15', ack: true }); +}); + +test('without edit_setup the card offers no acknowledge button', async () => { + const { component } = createPanel({ roles: ['view_energy'] }); + await component.load(); + const html = component.cardHtml(component.notices[0]); + assert.equal(html.includes('data-act="ack"'), false); + assert.equal(html.includes('data-act="unack"'), false); + assert.ok(html.includes('Quittieren können nur Nutzer mit dem Recht Einrichten.')); +}); From c5aa6b795e4b2c610a51107e7e7f90362a51d22e Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:11:36 +0100 Subject: [PATCH 13/27] feat(i18n): add the monitoring labels and load error Co-Authored-By: Claude Sonnet 5.5 --- dashboard/internal/webui/catalogs/de.json | 3 +++ dashboard/internal/webui/catalogs/en.json | 3 +++ 2 files changed, 6 insertions(+) diff --git a/dashboard/internal/webui/catalogs/de.json b/dashboard/internal/webui/catalogs/de.json index 8c07a0ba..a865f1ab 100644 --- a/dashboard/internal/webui/catalogs/de.json +++ b/dashboard/internal/webui/catalogs/de.json @@ -3621,6 +3621,7 @@ "monitoring.fact.weeks": "Kalenderwochen", "monitoring.filter.all": "Alle", "monitoring.filter.energy": "Energie", + "monitoring.filter.label": "Quelle", "monitoring.filter.learn": "Lernfunktionen", "monitoring.group.known": "Zur Kenntnis genommen", "monitoring.group.new": "Neu", @@ -3647,6 +3648,7 @@ "monitoring.learned.short.usual_on": "Übliche Einschaltzeit", "monitoring.learned.short.usual_runtime_s": "Übliche Laufzeit", "monitoring.learned.site": "Anlage", + "monitoring.load_failed": "Monitoring konnte nicht geladen werden.", "monitoring.notice.chain.title": "{chain}: Messkette auffällig", "monitoring.notice.measured_no_meter.title": "Hausverbrauch gemessen, aber kein Hauszähler", "monitoring.notice.role_needed.title": "Werte nach einer Messkette ohne Rolle", @@ -3688,6 +3690,7 @@ "monitoring.step.shade_look": "Vor Ort nach der Ursache schauen: Baum, Antenne, Nachbarhaus oder Schornstein in Richtung {direction}, etwa {height}° hoch.", "monitoring.steps.title": "Empfohlene Schritte", "monitoring.value.time": "{time} Uhr", + "monitoring.view.label": "Ansicht", "monitoring.view.learned": "Lernwerte", "monitoring.view.notices": "Meldungen", "monitoring.weeks.and": "{a} und {b}", diff --git a/dashboard/internal/webui/catalogs/en.json b/dashboard/internal/webui/catalogs/en.json index 650eb12c..bf003fe4 100644 --- a/dashboard/internal/webui/catalogs/en.json +++ b/dashboard/internal/webui/catalogs/en.json @@ -3621,6 +3621,7 @@ "monitoring.fact.weeks": "Calendar weeks", "monitoring.filter.all": "All", "monitoring.filter.energy": "Energy", + "monitoring.filter.label": "Source", "monitoring.filter.learn": "Learning", "monitoring.group.known": "Acknowledged", "monitoring.group.new": "New", @@ -3647,6 +3648,7 @@ "monitoring.learned.short.usual_on": "Usual switch-on time", "monitoring.learned.short.usual_runtime_s": "Usual runtime", "monitoring.learned.site": "System", + "monitoring.load_failed": "Monitoring could not be loaded.", "monitoring.notice.chain.title": "{chain}: measurement chain looks wrong", "monitoring.notice.measured_no_meter.title": "House load set to measured, but no house meter", "monitoring.notice.role_needed.title": "Values left without a role by a measurement chain", @@ -3688,6 +3690,7 @@ "monitoring.step.shade_look": "Look for the cause on site: a tree, an antenna, a neighbouring house or a chimney towards the {direction}, about {height}° high.", "monitoring.steps.title": "Recommended steps", "monitoring.value.time": "{time}", + "monitoring.view.label": "View", "monitoring.view.learned": "Learned values", "monitoring.view.notices": "Notices", "monitoring.weeks.and": "{a} and {b}", From 79ad0f373070bab327fb40655c42651904ed9480 Mon Sep 17 00:00:00 2001 From: DevSimon <73778205+Developer-Simon@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:12:11 +0100 Subject: [PATCH 14/27] fix(webui): add labels and load error to the monitoring panel Co-Authored-By: Claude Sonnet 5.5 --- .../internal/webui/static/css/monitoring.css | 1 + .../internal/webui/templates/monitoring.html | 6 +++-- dashboard/test/monitoring.page.test.mjs | 22 +++++++++++++++++-- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/dashboard/internal/webui/static/css/monitoring.css b/dashboard/internal/webui/static/css/monitoring.css index 7b406ccb..f1bff0c9 100644 --- a/dashboard/internal/webui/static/css/monitoring.css +++ b/dashboard/internal/webui/static/css/monitoring.css @@ -6,6 +6,7 @@ .monitoring-bar .monitoring-filters { margin: 0; } .monitoring-seg-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent); } .monitoring-muted { color: var(--text-muted); margin: 0; line-height: 1.5; } +.monitoring-error { color: var(--warn); margin: 0 0 1rem; line-height: 1.5; } /* Filter */ .monitoring-filters { display: flex; flex-wrap: wrap; gap: .35rem; } diff --git a/dashboard/internal/webui/templates/monitoring.html b/dashboard/internal/webui/templates/monitoring.html index 9fa2ccef..203d659a 100644 --- a/dashboard/internal/webui/templates/monitoring.html +++ b/dashboard/internal/webui/templates/monitoring.html @@ -3,7 +3,7 @@
-
+
-
+