From 6930a14d6b05c7152e48aa334eeb46e50c8faaf0 Mon Sep 17 00:00:00 2001 From: Lars Gebhardt-Kusche Date: Wed, 17 Jun 2026 22:56:22 +0200 Subject: [PATCH] Self management --- .gitignore | 1 + config/apps.php | 14 + config/widgets.php | 12 + partials/desktop/shell.php | 13 +- public/api/user-self-management/index.php | 89 ++++ public/apps/user-self-management/index.php | 39 ++ .../assets/apps/user-self-management/app.css | 309 ++++++++++++ .../assets/apps/user-self-management/app.js | 449 ++++++++++++++++++ public/assets/desktop/desktop.css | 22 + public/assets/desktop/desktop.js | 166 +++++-- src/App/App.php | 51 +- src/App/UserSelfManagementService.php | 314 ++++++++++++ src/Desktop/AppIconResolver.php | 3 + src/Desktop/AppVisibility.php | 59 +++ src/Desktop/DesktopState.php | 10 +- 15 files changed, 1475 insertions(+), 76 deletions(-) create mode 100644 public/api/user-self-management/index.php create mode 100644 public/apps/user-self-management/index.php create mode 100644 public/assets/apps/user-self-management/app.css create mode 100644 public/assets/apps/user-self-management/app.js create mode 100644 src/App/UserSelfManagementService.php create mode 100644 src/Desktop/AppVisibility.php diff --git a/.gitignore b/.gitignore index c9eafe71..cf85fe3c 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ Umsetzungsanweisung/Old-Nexus/ +data/ diff --git a/config/apps.php b/config/apps.php index 7d8c4f84..bf724e90 100644 --- a/config/apps.php +++ b/config/apps.php @@ -42,6 +42,20 @@ return [ 'module_name' => 'desktop', 'summary' => 'Vorbereitung fuer mehrere persoenliche Dashboards und Workspace-Verwaltung.', ], + [ + 'app_id' => 'user-self-management', + 'title' => 'User Self Management', + 'icon' => 'US', + 'entry_route' => '/apps/user-self-management', + 'window_mode' => 'window', + 'content_mode' => 'native-module', + 'default_width' => 980, + 'default_height' => 700, + 'supports_widget' => true, + 'supports_tray' => false, + 'module_name' => 'desktop', + 'summary' => 'Persoenliche Einstellungen fuer Desktop-Typ, Benutzerdaten, Apps und Widgets in einem gemeinsamen Setup-Bereich.', + ], [ 'app_id' => 'admin-apps', 'title' => 'Admin Apps', diff --git a/config/widgets.php b/config/widgets.php index 93f25507..25782d12 100644 --- a/config/widgets.php +++ b/config/widgets.php @@ -3,6 +3,18 @@ declare(strict_types=1); return [ + [ + 'widget_id' => 'setup-launcher', + 'title' => 'Setup', + 'icon' => 'ST', + 'zone' => 'sidebar', + 'default_enabled' => true, + 'supports_public_home' => true, + 'summary' => 'Startet die persoenlichen Desktop-Einstellungen fuer Skin, Apps, Widgets und Benutzerdaten.', + 'content' => 'Oeffnet den zentralen Setup-Bereich mit linker Navigation und lokaler Persistenz pro Benutzer.', + 'launch_app_id' => 'user-self-management', + 'action_label' => 'Setup oeffnen', + ], [ 'widget_id' => 'public-home', 'title' => 'Public Home', diff --git a/partials/desktop/shell.php b/partials/desktop/shell.php index 55a7f53c..82b1152b 100644 --- a/partials/desktop/shell.php +++ b/partials/desktop/shell.php @@ -21,10 +21,14 @@ $assetVersion = static function (string $publicPath): string { }; $hasMiningChecker = false; +$hasUserSelfManagement = false; foreach ($desktopPayload['apps'] as $desktopApp) { if (($desktopApp['app_id'] ?? null) === 'mining-checker') { $hasMiningChecker = true; - break; + } + + if (($desktopApp['app_id'] ?? null) === 'user-self-management') { + $hasUserSelfManagement = true; } } @@ -71,8 +75,6 @@ $renderStartIcon = static function (array $profile): string { Fenster
-
-
@@ -135,7 +137,6 @@ $renderStartIcon = static function (array $profile): string { Logout -
@@ -156,5 +157,9 @@ $renderStartIcon = static function (array $profile): string { + + + + diff --git a/public/api/user-self-management/index.php b/public/api/user-self-management/index.php new file mode 100644 index 00000000..f5194a2a --- /dev/null +++ b/public/api/user-self-management/index.php @@ -0,0 +1,89 @@ +isAuthenticated(); +$authUser = $isAuthenticated && is_array($_SESSION['desktop_auth']['user'] ?? null) + ? $_SESSION['desktop_auth']['user'] + : []; +$authGroups = array_values(array_map('strval', (array) ($authUser['groups'] ?? []))); +$visibleApps = AppVisibility::filterByGroups($registry->all(), $authGroups); +$widgets = $widgetRegistry->all(); +$skins = SkinResolver::all(); + +if ($method === 'GET') { + respond($service->buildBootstrapPayload($authUser, $visibleApps, $widgets, $skins)); +} + +if ($method !== 'PUT') { + respond(['error' => 'Method not allowed.'], 405); +} + +$rawBody = file_get_contents('php://input'); +$decoded = json_decode($rawBody !== false ? $rawBody : '', true); + +if (!is_array($decoded)) { + respond(['error' => 'Invalid JSON payload.'], 400); +} + +$before = $service->load($authUser, $visibleApps, $widgets, $skins); +$after = $service->save($decoded, $authUser, $visibleApps, $widgets, $skins); +$payload = $service->buildBootstrapPayload($authUser, $visibleApps, $widgets, $skins); +$payload['preferences'] = $after; +$payload['meta']['requires_reload'] = requiresReload($before, $after); + +respond($payload); + +/** + * @param array $payload + */ +function respond(array $payload, int $statusCode = 200): never +{ + http_response_code($statusCode); + echo json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); + exit; +} + +/** + * @param array $before + * @param array $after + */ +function requiresReload(array $before, array $after): bool +{ + $beforeSkin = (string) ($before['desktop']['active_skin'] ?? ''); + $afterSkin = (string) ($after['desktop']['active_skin'] ?? ''); + $beforeApps = array_values(array_map('strval', (array) ($before['apps']['enabled_ids'] ?? []))); + $afterApps = array_values(array_map('strval', (array) ($after['apps']['enabled_ids'] ?? []))); + + sort($beforeApps); + sort($afterApps); + + return $beforeSkin !== $afterSkin || $beforeApps !== $afterApps; +} diff --git a/public/apps/user-self-management/index.php b/public/apps/user-self-management/index.php new file mode 100644 index 00000000..8e9c7a58 --- /dev/null +++ b/public/apps/user-self-management/index.php @@ -0,0 +1,39 @@ + + + + + + User Self Management + + + +
+ + + + diff --git a/public/assets/apps/user-self-management/app.css b/public/assets/apps/user-self-management/app.css new file mode 100644 index 00000000..b1e0596d --- /dev/null +++ b/public/assets/apps/user-self-management/app.css @@ -0,0 +1,309 @@ +#user-self-management-app { + min-height: 100%; + color: #0f172a; + font-family: "IBM Plex Sans", "Segoe UI", sans-serif; +} + +#user-self-management-app, +#user-self-management-app * { + box-sizing: border-box; +} + +#user-self-management-app .usm-shell { + min-height: 100%; + background: + linear-gradient(180deg, rgba(255, 255, 255, 0.95), rgba(241, 245, 249, 0.98)), + radial-gradient(circle at top right, rgba(96, 165, 250, 0.12), transparent 36%); +} + +#user-self-management-app .usm-frame { + display: grid; + grid-template-columns: 240px minmax(0, 1fr); + min-height: 100%; +} + +#user-self-management-app .usm-nav { + padding: 22px 16px; + border-right: 1px solid rgba(148, 163, 184, 0.25); + background: linear-gradient(180deg, #dbeafe 0%, #eff6ff 100%); +} + +#user-self-management-app .usm-brand { + margin-bottom: 18px; +} + +#user-self-management-app .usm-brand h1 { + margin: 0 0 8px; + font-size: 24px; + line-height: 1.1; +} + +#user-self-management-app .usm-brand p, +#user-self-management-app .usm-copy, +#user-self-management-app .usm-meta, +#user-self-management-app .usm-note, +#user-self-management-app .usm-status { + margin: 0; + font-size: 14px; + line-height: 1.5; + color: #475569; +} + +#user-self-management-app .usm-nav-list { + display: grid; + gap: 8px; +} + +#user-self-management-app .usm-nav-button { + width: 100%; + padding: 12px 14px; + border: 1px solid rgba(148, 163, 184, 0.25); + border-radius: 14px; + background: rgba(255, 255, 255, 0.82); + color: inherit; + text-align: left; + font: inherit; + cursor: pointer; +} + +#user-self-management-app .usm-nav-button.is-active { + background: #0f172a; + color: #f8fafc; + border-color: #0f172a; +} + +#user-self-management-app .usm-main { + padding: 24px; +} + +#user-self-management-app .usm-panel { + display: grid; + gap: 18px; + max-width: 1080px; + margin: 0 auto; +} + +#user-self-management-app .usm-hero, +#user-self-management-app .usm-card, +#user-self-management-app .usm-actions { + padding: 22px; + border-radius: 20px; + border: 1px solid rgba(148, 163, 184, 0.24); + background: rgba(255, 255, 255, 0.92); + box-shadow: 0 18px 42px rgba(15, 23, 42, 0.08); +} + +#user-self-management-app .usm-hero { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 18px; +} + +#user-self-management-app .usm-kicker { + margin: 0 0 10px; + font-size: 12px; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; + color: #2563eb; +} + +#user-self-management-app .usm-title { + margin: 0 0 8px; + font-size: 32px; + line-height: 1.1; +} + +#user-self-management-app .usm-pill-row { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +#user-self-management-app .usm-pill { + display: inline-flex; + align-items: center; + min-height: 30px; + padding: 0 12px; + border-radius: 999px; + background: #e2e8f0; + font-size: 12px; + font-weight: 700; + color: #334155; +} + +#user-self-management-app .usm-grid, +#user-self-management-app .usm-choice-grid, +#user-self-management-app .usm-list { + display: grid; + gap: 16px; +} + +#user-self-management-app .usm-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +#user-self-management-app .usm-choice-grid { + grid-template-columns: repeat(3, minmax(0, 1fr)); +} + +#user-self-management-app .usm-field { + display: grid; + gap: 8px; +} + +#user-self-management-app .usm-label { + font-size: 13px; + font-weight: 700; + color: #334155; +} + +#user-self-management-app .usm-input, +#user-self-management-app .usm-textarea { + width: 100%; + min-height: 42px; + padding: 10px 12px; + border: 1px solid #cbd5e1; + border-radius: 12px; + background: #fff; + color: inherit; + font: inherit; +} + +#user-self-management-app .usm-textarea { + min-height: 112px; + resize: vertical; +} + +#user-self-management-app .usm-input:focus, +#user-self-management-app .usm-textarea:focus { + outline: 2px solid rgba(37, 99, 235, 0.18); + border-color: #3b82f6; +} + +#user-self-management-app .usm-choice { + display: grid; + gap: 8px; + padding: 16px; + border: 1px solid #cbd5e1; + border-radius: 16px; + background: #fff; + cursor: pointer; +} + +#user-self-management-app .usm-choice.is-active { + border-color: #2563eb; + box-shadow: inset 0 0 0 1px #2563eb; + background: #eff6ff; +} + +#user-self-management-app .usm-choice strong, +#user-self-management-app .usm-item-main strong { + display: block; + margin: 0 0 4px; + font-size: 15px; +} + +#user-self-management-app .usm-choice p, +#user-self-management-app .usm-item-main p { + margin: 0; + font-size: 13px; + color: #475569; +} + +#user-self-management-app .usm-item { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: start; + gap: 12px; + padding: 14px 16px; + border: 1px solid #dbe2ea; + border-radius: 16px; + background: #fff; +} + +#user-self-management-app .usm-item input { + margin-top: 4px; +} + +#user-self-management-app .usm-item-main { + min-width: 0; +} + +#user-self-management-app .usm-item-meta { + margin-top: 8px; + font-size: 12px; + font-weight: 700; + color: #1d4ed8; +} + +#user-self-management-app .usm-actions { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; +} + +#user-self-management-app .usm-button { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 42px; + padding: 0 18px; + border: 0; + border-radius: 999px; + background: #2563eb; + color: #f8fafc; + font: inherit; + font-weight: 700; + cursor: pointer; +} + +#user-self-management-app .usm-button:disabled { + cursor: default; + opacity: 0.6; +} + +#user-self-management-app .usm-message { + font-size: 13px; + color: #334155; +} + +#user-self-management-app .usm-message.is-error { + color: #b91c1c; +} + +#user-self-management-app .usm-message.is-success { + color: #047857; +} + +#user-self-management-app .usm-loading, +#user-self-management-app .usm-error-state { + display: grid; + place-items: center; + min-height: 320px; + padding: 24px; +} + +@media (max-width: 900px) { + #user-self-management-app .usm-frame { + grid-template-columns: 1fr; + } + + #user-self-management-app .usm-nav { + border-right: 0; + border-bottom: 1px solid rgba(148, 163, 184, 0.25); + } + + #user-self-management-app .usm-grid, + #user-self-management-app .usm-choice-grid { + grid-template-columns: 1fr; + } + + #user-self-management-app .usm-hero, + #user-self-management-app .usm-actions { + grid-template-columns: 1fr; + display: grid; + } +} diff --git a/public/assets/apps/user-self-management/app.js b/public/assets/apps/user-self-management/app.js new file mode 100644 index 00000000..2b399b20 --- /dev/null +++ b/public/assets/apps/user-self-management/app.js @@ -0,0 +1,449 @@ +(() => { + const SECTIONS = [ + { id: 'desktop', label: 'Desktop Type' }, + { id: 'profile', label: 'Benutzerdaten' }, + { id: 'apps', label: 'App-Installation' }, + { id: 'widgets', label: 'Widget-Installation' }, + ]; + + const escapeHtml = (value) => String(value) + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); + + const clone = (value) => JSON.parse(JSON.stringify(value)); + + const sameSelection = (left, right) => { + const nextLeft = [...left].sort(); + const nextRight = [...right].sort(); + + return JSON.stringify(nextLeft) === JSON.stringify(nextRight); + }; + + const summarizeSection = (sectionId) => { + if (sectionId === 'desktop') { + return 'Windows-aehnlicher Standard fuer Desktop-Typ und Skin-Auswahl.'; + } + + if (sectionId === 'profile') { + return 'Lokales Profil fuer Name, E-Mail, Telefon und spaetere LDAP-/Keycloak-Synchronisierung.'; + } + + if (sectionId === 'apps') { + return 'Bestimmt, welche Desktop-Apps fuer diesen Benutzer sichtbar bleiben.'; + } + + return 'Steuert, welche Widgets in der rechten Leiste des Desktops aktiv sind.'; + }; + + const renderSkinChoices = (state) => state.bootstrap.options.skins.map((skin) => { + const isActive = state.draft.desktop.active_skin === skin.skin_id; + + return ` + + `; + }).join(''); + + const summarizeSkin = (skinId) => { + if (skinId === 'apple') { + return 'Top-Bar, rechte Icon-Anordnung und Finder-nahe Fensterelemente.'; + } + + if (skinId === 'linux') { + return 'Klassische Arbeitsflaeche mit neutralem Fensterstil und Linux-Taskbar.'; + } + + return 'Standardisiertes Control-Panel-Muster mit Windows-naher Einstellungslogik.'; + }; + + const renderAppItems = (state) => state.bootstrap.options.apps.map((app) => { + const checked = state.draft.apps.enabled_ids.includes(app.app_id); + + return ` + + `; + }).join(''); + + const renderWidgetItems = (state) => state.bootstrap.options.widgets.map((widget) => { + const checked = state.draft.widgets.active_ids.includes(widget.widget_id); + + return ` + + `; + }).join(''); + + const renderProfileFields = (state) => ` +
+ ${renderField('name', 'Name', state.draft.profile.name)} + ${renderField('email', 'E-Mail', state.draft.profile.email, 'email')} + ${renderField('phone', 'Telefon', state.draft.profile.phone, 'tel')} + ${renderField('birthdate', 'Geburtsdatum', state.draft.profile.birthdate, 'date')} + ${renderField('title', 'Titel', state.draft.profile.title)} + ${renderField('department', 'Abteilung', state.draft.profile.department)} + ${renderField('city', 'Ort', state.draft.profile.city)} + ${renderField('website', 'Website', state.draft.profile.website, 'url')} +
+
+ + +
+ `; + + const renderField = (fieldId, label, value, type = 'text') => ` +
+ + +
+ `; + + const sectionContent = (state) => { + if (state.activeSection === 'desktop') { + return ` +
+

Desktop Type

+

Skin-Auswahl

+

Die direkte Skin-Umschaltung liegt jetzt im Setup. Die Auswahl wird pro Benutzer gespeichert.

+
+ ${renderSkinChoices(state)} +
+
+ `; + } + + if (state.activeSection === 'profile') { + return ` +
+

Benutzerdaten

+

Persoenliches Profil

+

Diese Daten werden zunaechst lokal gespeichert und spaeter an LDAP oder Keycloak angebunden.

+ ${renderProfileFields(state)} +
+ `; + } + + if (state.activeSection === 'apps') { + return ` +
+

App-Auswahl

+

Sichtbare Desktop-Apps

+

Aenderungen an der App-Auswahl werden nach dem Speichern mit einem Desktop-Reload sauber uebernommen.

+
+ ${renderAppItems(state)} +
+
+ `; + } + + return ` +
+

Widget-Auswahl

+

Aktive Widget-Leiste

+

Widgets bleiben Teil der Desktop-Mechanik und werden hier nur benutzerbezogen ein- oder ausgeblendet.

+
+ ${renderWidgetItems(state)} +
+
+ `; + }; + + const renderApp = (root, state) => { + if (state.loading) { + root.innerHTML = '

Einstellungen werden geladen.

'; + return; + } + + if (state.error && !state.bootstrap) { + root.innerHTML = `

${escapeHtml(state.error)}

`; + return; + } + + root.innerHTML = ` +
+
+ +
+
+
+
+

Desktop Setup

+

${escapeHtml(sectionTitle(state.activeSection))}

+

${escapeHtml(summarizeSection(state.activeSection))}

+
+
+ LDAP: geplant + Keycloak: geplant + Scope: ${escapeHtml(state.bootstrap.meta.storage_scope || 'guest')} +
+
+ ${sectionContent(state)} +
+
+

Skin- und App-Aenderungen koennen einen Reload ausloesen, damit Fenster, Icons und Menue sauber synchron bleiben.

+

${escapeHtml(state.error || state.success || '')}

+
+ +
+
+
+
+
+ `; + }; + + const sectionTitle = (sectionId) => { + const current = SECTIONS.find((section) => section.id === sectionId); + return current ? current.label : 'Setup'; + }; + + const setDraftValue = (draft, path, value) => { + const segments = path.split('.'); + let cursor = draft; + + segments.slice(0, -1).forEach((segment) => { + cursor = cursor[segment]; + }); + + cursor[segments[segments.length - 1]] = value; + }; + + const toggleSelection = (collection, value) => { + const next = new Set(collection); + + if (next.has(value)) { + next.delete(value); + } else { + next.add(value); + } + + return Array.from(next); + }; + + const buildPatch = (state) => ({ + profile: state.draft.profile, + desktop: { + active_skin: state.draft.desktop.active_skin, + }, + apps: { + enabled_ids: state.draft.apps.enabled_ids, + }, + widgets: { + active_ids: state.draft.widgets.active_ids, + }, + }); + + const requiresReload = (before, after) => before.desktop.active_skin !== after.desktop.active_skin + || !sameSelection(before.apps.enabled_ids, after.apps.enabled_ids); + + const attachInteractions = (root, state, options) => { + root.addEventListener('click', async (event) => { + const button = event.target instanceof Element ? event.target.closest('[data-action]') : null; + + if (!button) { + return; + } + + const action = button.dataset.action; + + if (action === 'open-section') { + state.activeSection = button.dataset.sectionId || 'desktop'; + renderApp(root, state); + return; + } + + if (action === 'select-skin') { + state.draft.desktop.active_skin = button.dataset.skinId || state.draft.desktop.active_skin; + renderApp(root, state); + return; + } + + if (action === 'save-settings') { + if (!options.apiBase || state.saving) { + return; + } + + state.saving = true; + state.error = ''; + state.success = ''; + renderApp(root, state); + + try { + const before = clone(state.bootstrap.preferences); + const response = await window.fetch(options.apiBase, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + body: JSON.stringify(buildPatch(state)), + }); + + if (!response.ok) { + throw new Error(`save-failed:${response.status}`); + } + + const payload = await response.json(); + const after = payload.preferences; + state.bootstrap = payload; + state.draft = clone(after); + state.success = payload.meta?.requires_reload + ? 'Gespeichert. Desktop wird fuer Skin- oder App-Aenderungen neu geladen.' + : 'Einstellungen wurden gespeichert.'; + state.saving = false; + renderApp(root, state); + + if (window.desktopShell?.dispatchUserSettingsUpdate) { + window.desktopShell.dispatchUserSettingsUpdate({ + preferences: after, + requiresReload: payload.meta?.requires_reload || requiresReload(before, after), + }); + } + + return; + } catch (error) { + state.saving = false; + state.error = 'Speichern fehlgeschlagen. Die lokalen Einstellungen bleiben unveraendert.'; + renderApp(root, state); + return; + } + } + }); + + root.addEventListener('change', (event) => { + const target = event.target; + + if (!(target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement)) { + return; + } + + if (target.dataset.field) { + setDraftValue(state.draft, target.dataset.field, target.value); + return; + } + + if (target.dataset.appId) { + state.draft.apps.enabled_ids = toggleSelection(state.draft.apps.enabled_ids, target.dataset.appId); + renderApp(root, state); + return; + } + + if (target.dataset.widgetId) { + state.draft.widgets.active_ids = toggleSelection(state.draft.widgets.active_ids, target.dataset.widgetId); + renderApp(root, state); + } + }); + }; + + window.initUserSelfManagementApp = (root, options = {}) => { + if (!(root instanceof HTMLElement) || root.dataset.usmInitialized === 'true') { + return; + } + + root.dataset.usmInitialized = 'true'; + + const state = { + loading: true, + saving: false, + error: '', + success: '', + activeSection: 'desktop', + bootstrap: null, + draft: null, + }; + + attachInteractions(root, state, options); + renderApp(root, state); + + if (!options.apiBase) { + state.loading = false; + state.error = 'Die Setup-API ist nicht konfiguriert.'; + renderApp(root, state); + return; + } + + window.fetch(options.apiBase, { + headers: { + Accept: 'application/json', + }, + }) + .then((response) => { + if (!response.ok) { + throw new Error(`load-failed:${response.status}`); + } + + return response.json(); + }) + .then((payload) => { + state.loading = false; + state.bootstrap = payload; + state.draft = clone(payload.preferences); + renderApp(root, state); + }) + .catch(() => { + state.loading = false; + state.error = 'Die Einstellungen konnten nicht geladen werden.'; + renderApp(root, state); + }); + }; +})(); diff --git a/public/assets/desktop/desktop.css b/public/assets/desktop/desktop.css index 03fae66b..e027df77 100644 --- a/public/assets/desktop/desktop.css +++ b/public/assets/desktop/desktop.css @@ -284,6 +284,28 @@ h1 { margin-bottom: 10px; } +.widget-card-actions { + margin-top: 14px; +} + +.widget-card-action { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 36px; + padding: 0 14px; + border: 0; + border-radius: 999px; + background: rgba(15, 23, 42, 0.82); + color: #f8fafc; + font: inherit; + cursor: pointer; +} + +.widget-card-action:hover { + background: #0f172a; +} + .widget-badge { display: inline-grid; place-items: center; diff --git a/public/assets/desktop/desktop.js b/public/assets/desktop/desktop.js index b1c30572..d3f13b08 100644 --- a/public/assets/desktop/desktop.js +++ b/public/assets/desktop/desktop.js @@ -12,14 +12,14 @@ if (payloadNode) { const startMenuApps = document.getElementById('start-menu-apps'); const startMenuWidgets = document.getElementById('start-menu-widgets'); const startMenuActions = document.getElementById('start-menu-actions'); - const traySkins = document.getElementById('tray-skins'); - const traySkinsTop = document.getElementById('tray-skins-top'); const clockNode = document.getElementById('clock'); const clockTopNode = document.getElementById('clock-top'); const windows = new Map(); const activeWidgets = new Set(payload.widgets.active_ids); const activeSkin = payload.meta.active_skin; const skinProfile = payload.meta.skin_profile || {}; + const settingsApi = payload.desktop.settings_api || ''; + let currentUserPreferences = payload.desktop.user_preferences || {}; const maximizeOverSystemBar = Boolean(skinProfile.maximize_over_system_bar); const storageScope = payload.desktop.storage_scope || 'guest'; const storageKey = `desktop.kusche.berlin.window-state.${storageScope}`; @@ -172,13 +172,40 @@ if (payloadNode) { return; } - const displayName = payload.session?.display_name; + const displayName = currentUserPreferences?.profile?.name || payload.session?.display_name; if (typeof displayName === 'string' && displayName.trim() !== '') { accountNode.textContent = displayName; } }; + const findAppById = (appId) => payload.apps.find((app) => app.app_id === appId) || null; + + const dispatchUserSettingsUpdate = (detail) => { + window.dispatchEvent(new CustomEvent('desktop:user-settings-updated', { detail })); + }; + + const persistSettingsPatch = async (patch) => { + if (!settingsApi) { + return null; + } + + const response = await window.fetch(settingsApi, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + Accept: 'application/json', + }, + body: JSON.stringify(patch), + }); + + if (!response.ok) { + throw new Error(`settings-save-failed:${response.status}`); + } + + return response.json(); + }; + const buildTaskbarButtonContent = (record) => ` ${buildAppIconMarkup(record.definition, 'taskbar-app-icon')} ${escapeHtml(record.title)} @@ -236,6 +263,14 @@ if (payloadNode) { `; } + if (definition.content_mode === 'native-module' && definition.app_id === 'user-self-management') { + return ` +
+
+
+ `; + } + if (definition.content_mode === 'iframe' && typeof definition.entry_route === 'string' && definition.entry_route !== '') { const title = escapeHtml(definition.title); const src = escapeHtml(definition.entry_route); @@ -557,30 +592,6 @@ if (payloadNode) { } }; - const navigateToSkin = (skin) => { - window.location.search = `?skin=${encodeURIComponent(skin)}`; - }; - - const renderTraySkins = () => { - [traySkins, traySkinsTop].forEach((container) => { - if (!container) { - return; - } - - container.innerHTML = ''; - - payload.meta.available_skins.forEach((skin) => { - const button = document.createElement('button'); - button.type = 'button'; - button.className = `tray-skin-button${skin === activeSkin ? ' is-active' : ''}`; - button.textContent = skin.slice(0, 3).toUpperCase(); - button.title = skin; - button.addEventListener('click', () => navigateToSkin(skin)); - container.appendChild(button); - }); - }); - }; - const focusWindow = (windowId) => { windows.forEach((record) => { record.node.classList.remove('is-focused'); @@ -993,6 +1004,17 @@ if (payloadNode) { } } + if (moduleHost && definition.content_mode === 'native-module' && definition.app_id === 'user-self-management') { + if (typeof window.initUserSelfManagementApp === 'function') { + window.initUserSelfManagementApp(moduleHost, { + apiBase: settingsApi, + activeSkin, + }); + } else { + moduleHost.innerHTML = '
User Self Management konnte nicht initialisiert werden.
'; + } + } + node.querySelectorAll('.window-action').forEach((action) => { action.addEventListener('click', (event) => { event.stopPropagation(); @@ -1060,6 +1082,15 @@ if (payloadNode) { .forEach((widget) => { const card = document.createElement('article'); card.className = 'widget-card'; + const actionMarkup = widget.launch_app_id + ? ` +
+ +
+ ` + : ''; card.innerHTML = `
@@ -1069,7 +1100,19 @@ if (payloadNode) { ${widget.icon || 'WG'}

${widget.content || ''}

+ ${actionMarkup} `; + + const actionButton = card.querySelector('.widget-card-action'); + if (actionButton instanceof HTMLButtonElement && widget.launch_app_id) { + actionButton.addEventListener('click', () => { + const app = findAppById(widget.launch_app_id); + if (app) { + openApp(app); + } + }); + } + widgetZoneRoot.appendChild(card); }); }; @@ -1104,14 +1147,30 @@ if (payloadNode) { renderWidgets(); renderMenuWidgets(); + persistSettingsPatch({ + widgets: { + active_ids: Array.from(activeWidgets), + }, + }).catch(() => { + // Keep current desktop state even if persistence fails. + }); }); startMenuWidgets.appendChild(button); }); }; const runQuickAction = (actionId) => { + if (actionId === 'open-user-self-management') { + const userSetup = findAppById('user-self-management'); + if (userSetup) { + openApp(userSetup); + closeStartMenu(); + } + return; + } + if (actionId === 'open-public-dashboard') { - const publicDashboard = payload.apps.find((app) => app.app_id === 'public-dashboard'); + const publicDashboard = findAppById('public-dashboard'); if (publicDashboard) { openApp(publicDashboard); } @@ -1128,14 +1187,13 @@ if (payloadNode) { renderWidgets(); renderMenuWidgets(); - return; - } - - if (actionId === 'cycle-skin') { - const skins = payload.meta.available_skins; - const currentIndex = skins.indexOf(activeSkin); - const nextSkin = skins[(currentIndex + 1) % skins.length]; - navigateToSkin(nextSkin); + persistSettingsPatch({ + widgets: { + active_ids: Array.from(activeWidgets), + }, + }).catch(() => { + // Keep current desktop state even if persistence fails. + }); } }; @@ -1235,9 +1293,33 @@ if (payloadNode) { setStartMenuOpen(isClosed); }); + window.addEventListener('desktop:user-settings-updated', (event) => { + const preferences = event.detail?.preferences; + const requiresReload = Boolean(event.detail?.requiresReload); + + if (preferences && typeof preferences === 'object') { + currentUserPreferences = preferences; + + const nextWidgetIds = Array.isArray(preferences.widgets?.active_ids) + ? preferences.widgets.active_ids + : []; + + activeWidgets.clear(); + nextWidgetIds.forEach((widgetId) => activeWidgets.add(widgetId)); + renderWidgets(); + renderMenuWidgets(); + updateSessionDisplay(); + } + + if (requiresReload) { + const nextSkin = preferences?.desktop?.active_skin || activeSkin; + const nextUrl = `${window.location.pathname}?skin=${encodeURIComponent(nextSkin)}`; + window.location.assign(nextUrl); + } + }); + renderWidgets(); renderStartMenu(); - renderTraySkins(); setStartMenuOpen(false); measureDesktopBounds(); applyStoredIconLayout(); @@ -1270,4 +1352,14 @@ if (payloadNode) { }); window.refreshDesktopIconContrast = applyDesktopIconContrast; + window.desktopShell = { + openAppById: (appId) => { + const app = findAppById(appId); + if (app) { + openApp(app); + } + }, + persistSettingsPatch, + dispatchUserSettingsUpdate, + }; } diff --git a/src/App/App.php b/src/App/App.php index 51cd9e91..4b163932 100644 --- a/src/App/App.php +++ b/src/App/App.php @@ -6,6 +6,7 @@ namespace App; use Desktop\AppRegistry; use Desktop\AppIconResolver; +use Desktop\AppVisibility; use Desktop\DesktopState; use Desktop\SkinResolver; use Desktop\WidgetRegistry; @@ -28,16 +29,30 @@ final class App $registry = new AppRegistry($this->projectRoot . '/config/apps.php'); $widgetRegistry = new WidgetRegistry($this->projectRoot . '/config/widgets.php'); $skins = SkinResolver::all(); - $activeSkin = SkinResolver::resolve($_GET['skin'] ?? null); $isAuthenticated = isset($_SESSION['desktop_auth']) && is_array($_SESSION['desktop_auth']); $authUser = $isAuthenticated && is_array($_SESSION['desktop_auth']['user'] ?? null) ? $_SESSION['desktop_auth']['user'] : []; $authGroups = array_values(array_map('strval', (array) ($authUser['groups'] ?? []))); - $visibleApps = $this->filterAppsForGroups($registry->all(), $authGroups); - $apps = AppIconResolver::decorate($visibleApps, $activeSkin); + $visibleApps = AppVisibility::filterByGroups($registry->all(), $authGroups); + $userSelfManagement = new UserSelfManagementService($this->projectRoot); + $resolvedSkin = $userSelfManagement->resolveActiveSkin( + isset($_GET['skin']) ? (string) $_GET['skin'] : null, + $authUser, + $visibleApps, + $widgetRegistry->all(), + $skins + ); + $userSettings = $resolvedSkin['settings']; + $activeSkin = (string) $resolvedSkin['skin']; + $enabledApps = AppVisibility::filterByEnabledIds( + $visibleApps, + array_values(array_map('strval', (array) ($userSettings['apps']['enabled_ids'] ?? []))), + [UserSelfManagementService::APP_ID] + ); + $apps = AppIconResolver::decorate($enabledApps, $activeSkin); $windows = (new WindowManager($registry))->defaultWindows(); - $activeWidgetIds = DesktopState::defaultWidgetIds(); + $activeWidgetIds = array_values(array_map('strval', (array) ($userSettings['widgets']['active_ids'] ?? DesktopState::defaultWidgetIds()))); $displayName = (string) ($authUser['name'] ?? $authUser['username'] ?? 'Gast'); $storageScope = $isAuthenticated ? strtolower((string) ($authUser['username'] ?? $authUser['sub'] ?? 'user')) @@ -56,6 +71,8 @@ final class App 'wallpaper' => SkinResolver::wallpaper($activeSkin), 'storage_scope' => preg_replace('/[^a-z0-9._-]+/i', '-', $storageScope) ?: 'guest', 'workspace' => DesktopState::defaultWorkspace(), + 'settings_api' => '/api/user-self-management/index.php', + 'user_preferences' => $userSettings, 'login' => [ 'authenticated' => $isAuthenticated, 'mode' => $isAuthenticated ? 'authenticated' : 'login-required', @@ -85,30 +102,4 @@ final class App ], ]; } - - /** - * @param array> $apps - * @param array $groups - * @return array> - */ - private function filterAppsForGroups(array $apps, array $groups): array - { - $normalizedGroups = array_map(static fn (string $group): string => strtolower(trim($group, '/')), $groups); - - return array_values(array_filter($apps, static function (array $app) use ($normalizedGroups): bool { - $requiredGroups = array_values(array_map('strval', (array) ($app['required_groups'] ?? []))); - - if ($requiredGroups === []) { - return true; - } - - foreach ($requiredGroups as $group) { - if (in_array(strtolower(trim($group, '/')), $normalizedGroups, true)) { - return true; - } - } - - return false; - })); - } } diff --git a/src/App/UserSelfManagementService.php b/src/App/UserSelfManagementService.php new file mode 100644 index 00000000..edf09527 --- /dev/null +++ b/src/App/UserSelfManagementService.php @@ -0,0 +1,314 @@ + $authUser + * @param array> $visibleApps + * @param array> $widgets + * @param array $availableSkins + * @return array + */ + public function load(array $authUser, array $visibleApps, array $widgets, array $availableSkins): array + { + return $this->normalizeSettings( + $this->store($this->storageScope($authUser))->read(), + $authUser, + $visibleApps, + $widgets, + $availableSkins + ); + } + + /** + * @param array $patch + * @param array $authUser + * @param array> $visibleApps + * @param array> $widgets + * @param array $availableSkins + * @return array + */ + public function save(array $patch, array $authUser, array $visibleApps, array $widgets, array $availableSkins): array + { + $current = $this->load($authUser, $visibleApps, $widgets, $availableSkins); + $merged = $this->mergeRecursive($current, $patch); + $normalized = $this->normalizeSettings($merged, $authUser, $visibleApps, $widgets, $availableSkins); + $normalized['updated_at'] = gmdate(DATE_ATOM); + + $this->store($this->storageScope($authUser))->write($normalized); + + return $normalized; + } + + /** + * @param array $authUser + * @param array> $visibleApps + * @param array> $widgets + * @param array $availableSkins + * @return array{skin: string, settings: array} + */ + public function resolveActiveSkin(?string $requestedSkin, array $authUser, array $visibleApps, array $widgets, array $availableSkins): array + { + $settings = $this->load($authUser, $visibleApps, $widgets, $availableSkins); + $storedSkin = (string) (($settings['desktop']['active_skin'] ?? '') ?: SkinResolver::DEFAULT_SKIN); + $resolvedSkin = SkinResolver::resolve($requestedSkin !== null && $requestedSkin !== '' ? $requestedSkin : $storedSkin); + + if ($resolvedSkin !== $storedSkin) { + $settings = $this->save( + ['desktop' => ['active_skin' => $resolvedSkin]], + $authUser, + $visibleApps, + $widgets, + $availableSkins + ); + } + + return [ + 'skin' => $resolvedSkin, + 'settings' => $settings, + ]; + } + + /** + * @param array $authUser + * @param array> $visibleApps + * @param array> $widgets + * @param array $availableSkins + * @return array + */ + public function buildBootstrapPayload(array $authUser, array $visibleApps, array $widgets, array $availableSkins): array + { + $settings = $this->load($authUser, $visibleApps, $widgets, $availableSkins); + $enabledAppIds = array_values(array_map('strval', (array) ($settings['apps']['enabled_ids'] ?? []))); + $activeWidgetIds = array_values(array_map('strval', (array) ($settings['widgets']['active_ids'] ?? []))); + + return [ + 'preferences' => $settings, + 'options' => [ + 'skins' => array_map( + static fn (string $skin): array => [ + 'skin_id' => $skin, + 'label' => (string) (SkinResolver::profile($skin)['label'] ?? ucfirst($skin)), + ], + $availableSkins + ), + 'apps' => array_map( + static fn (array $app): array => [ + 'app_id' => (string) ($app['app_id'] ?? ''), + 'title' => (string) ($app['title'] ?? ''), + 'summary' => (string) ($app['summary'] ?? ''), + 'module_name' => (string) ($app['module_name'] ?? ''), + 'required' => in_array((string) ($app['app_id'] ?? ''), [self::APP_ID], true), + 'enabled' => in_array((string) ($app['app_id'] ?? ''), $enabledAppIds, true), + ], + $visibleApps + ), + 'widgets' => array_map( + static fn (array $widget): array => [ + 'widget_id' => (string) ($widget['widget_id'] ?? ''), + 'title' => (string) ($widget['title'] ?? ''), + 'summary' => (string) ($widget['summary'] ?? ''), + 'default_enabled' => (bool) ($widget['default_enabled'] ?? false), + 'enabled' => in_array((string) ($widget['widget_id'] ?? ''), $activeWidgetIds, true), + ], + $widgets + ), + ], + 'meta' => [ + 'storage_scope' => $this->storageScope($authUser), + 'authenticated' => ($authUser['sub'] ?? '') !== '' || ($authUser['username'] ?? '') !== '', + 'sync_mode' => 'local-profile', + 'sync_targets' => [ + 'ldap' => 'planned', + 'keycloak' => 'planned', + ], + ], + ]; + } + + /** + * @param array $authUser + */ + public function storageScope(array $authUser): string + { + $rawScope = (string) ($authUser['username'] ?? $authUser['sub'] ?? 'guest'); + $sanitized = preg_replace('/[^a-z0-9._-]+/i', '-', strtolower($rawScope)); + + return $sanitized !== null && $sanitized !== '' ? $sanitized : 'guest'; + } + + private function store(string $scope): JsonStore + { + return new JsonStore($this->projectRoot . '/data/user-self-management/users/' . $scope . '.json'); + } + + /** + * @param array $settings + * @param array $authUser + * @param array> $visibleApps + * @param array> $widgets + * @param array $availableSkins + * @return array + */ + private function normalizeSettings(array $settings, array $authUser, array $visibleApps, array $widgets, array $availableSkins): array + { + $visibleAppIds = array_values(array_filter(array_map( + static fn (array $app): string => (string) ($app['app_id'] ?? ''), + $visibleApps + ))); + $defaultWidgetIds = array_values(array_filter(array_map( + static fn (array $widget): ?string => ($widget['default_enabled'] ?? false) ? (string) ($widget['widget_id'] ?? '') : null, + $widgets + ))); + $allWidgetIds = array_values(array_filter(array_map( + static fn (array $widget): string => (string) ($widget['widget_id'] ?? ''), + $widgets + ))); + $enabledAppIds = $this->sanitizeSelection( + $settings['apps']['enabled_ids'] ?? $visibleAppIds, + $visibleAppIds, + [self::APP_ID] + ); + $activeWidgetIds = $this->sanitizeSelection( + $settings['widgets']['active_ids'] ?? $defaultWidgetIds, + $allWidgetIds + ); + $profile = []; + + foreach (self::PROFILE_FIELDS as $field) { + $fallback = match ($field) { + 'name' => (string) ($authUser['name'] ?? ''), + 'email' => (string) ($authUser['email'] ?? ''), + default => '', + }; + + $profile[$field] = $this->limitString( + (string) (($settings['profile'][$field] ?? '') ?: $fallback), + $field === 'notes' ? 2000 : 255 + ); + } + + return [ + 'schema_version' => 1, + 'updated_at' => (string) ($settings['updated_at'] ?? ''), + 'profile' => $profile, + 'desktop' => [ + 'active_skin' => $this->sanitizeSkin( + (string) ($settings['desktop']['active_skin'] ?? SkinResolver::DEFAULT_SKIN), + $availableSkins + ), + ], + 'apps' => [ + 'enabled_ids' => $enabledAppIds, + ], + 'widgets' => [ + 'active_ids' => $activeWidgetIds, + ], + 'integration' => [ + 'ldap_write_status' => 'planned', + 'keycloak_write_status' => 'planned', + ], + ]; + } + + /** + * @param mixed $selected + * @param array $allowedIds + * @param array $mandatoryIds + * @return array + */ + private function sanitizeSelection(mixed $selected, array $allowedIds, array $mandatoryIds = []): array + { + $allowedLookup = array_fill_keys($allowedIds, true); + $result = []; + + foreach ((array) $selected as $id) { + $stringId = (string) $id; + + if ($stringId !== '' && isset($allowedLookup[$stringId])) { + $result[$stringId] = true; + } + } + + foreach ($mandatoryIds as $mandatoryId) { + if ($mandatoryId !== '' && isset($allowedLookup[$mandatoryId])) { + $result[$mandatoryId] = true; + } + } + + return array_keys($result); + } + + /** + * @param array $availableSkins + */ + private function sanitizeSkin(string $skin, array $availableSkins): string + { + $resolved = SkinResolver::resolve($skin); + + return in_array($resolved, $availableSkins, true) ? $resolved : SkinResolver::DEFAULT_SKIN; + } + + /** + * @param array $base + * @param array $patch + * @return array + */ + private function mergeRecursive(array $base, array $patch): array + { + foreach ($patch as $key => $value) { + if (is_array($value) && isset($base[$key]) && is_array($base[$key]) && !$this->isList($value)) { + /** @var array $baseItem */ + $baseItem = $base[$key]; + /** @var array $patchItem */ + $patchItem = $value; + $base[$key] = $this->mergeRecursive($baseItem, $patchItem); + continue; + } + + $base[$key] = $value; + } + + return $base; + } + + /** + * @param array $value + */ + private function isList(array $value): bool + { + return array_keys($value) === range(0, count($value) - 1); + } + + private function limitString(string $value, int $maxLength): string + { + $trimmed = trim($value); + + return mb_substr($trimmed, 0, $maxLength); + } +} diff --git a/src/Desktop/AppIconResolver.php b/src/Desktop/AppIconResolver.php index 64e65c38..32aee04c 100644 --- a/src/Desktop/AppIconResolver.php +++ b/src/Desktop/AppIconResolver.php @@ -40,6 +40,7 @@ final class AppIconResolver 'public-dashboard' => '/assets/desktop/skin-icons/windows/public-dashboard.ico', 'workspace-manager' => '/assets/desktop/skin-icons/windows/workspace-manager.ico', 'admin-apps' => '/assets/desktop/skin-icons/windows/admin-apps.ico', + 'user-self-management' => '/assets/desktop/skin-icons/windows/admin-apps.ico', 'desktop-login' => '/assets/desktop/skin-icons/windows/desktop-login.ico', 'mining-checker' => '/assets/desktop/skin-icons/windows/admin-apps.ico', ], @@ -48,6 +49,7 @@ final class AppIconResolver 'public-dashboard' => '/assets/desktop/skin-icons/apple/public-dashboard.svg', 'workspace-manager' => '/assets/desktop/skin-icons/apple/workspace-manager.svg', 'admin-apps' => '/assets/desktop/skin-icons/apple/admin-apps.svg', + 'user-self-management' => '/assets/desktop/skin-icons/apple/admin-apps.svg', 'desktop-login' => '/assets/desktop/skin-icons/apple/desktop-login.svg', 'mining-checker' => '/assets/desktop/skin-icons/apple/admin-apps.svg', ], @@ -56,6 +58,7 @@ final class AppIconResolver 'public-dashboard' => '/assets/desktop/skin-icons/linux/public-dashboard.svg', 'workspace-manager' => '/assets/desktop/skin-icons/linux/workspace-manager.svg', 'admin-apps' => '/assets/desktop/skin-icons/linux/admin-apps.svg', + 'user-self-management' => '/assets/desktop/skin-icons/linux/admin-apps.svg', 'desktop-login' => '/assets/desktop/skin-icons/linux/desktop-login.svg', 'mining-checker' => '/assets/desktop/skin-icons/linux/admin-apps.svg', ], diff --git a/src/Desktop/AppVisibility.php b/src/Desktop/AppVisibility.php new file mode 100644 index 00000000..321460bf --- /dev/null +++ b/src/Desktop/AppVisibility.php @@ -0,0 +1,59 @@ +> $apps + * @param array $groups + * @return array> + */ + public static function filterByGroups(array $apps, array $groups): array + { + $normalizedGroups = array_map( + static fn (string $group): string => strtolower(trim($group, '/')), + $groups + ); + + return array_values(array_filter($apps, static function (array $app) use ($normalizedGroups): bool { + $requiredGroups = array_values(array_map('strval', (array) ($app['required_groups'] ?? []))); + + if ($requiredGroups === []) { + return true; + } + + foreach ($requiredGroups as $group) { + if (in_array(strtolower(trim($group, '/')), $normalizedGroups, true)) { + return true; + } + } + + return false; + })); + } + + /** + * @param array> $apps + * @param array $enabledAppIds + * @param array $mandatoryAppIds + * @return array> + */ + public static function filterByEnabledIds(array $apps, array $enabledAppIds, array $mandatoryAppIds = []): array + { + $lookup = array_fill_keys($enabledAppIds, true); + $mandatoryLookup = array_fill_keys($mandatoryAppIds, true); + + return array_values(array_filter($apps, static function (array $app) use ($lookup, $mandatoryLookup): bool { + $appId = (string) ($app['app_id'] ?? ''); + + if ($appId === '') { + return false; + } + + return isset($lookup[$appId]) || isset($mandatoryLookup[$appId]); + })); + } +} diff --git a/src/Desktop/DesktopState.php b/src/Desktop/DesktopState.php index c201661f..6c82b7bc 100644 --- a/src/Desktop/DesktopState.php +++ b/src/Desktop/DesktopState.php @@ -45,6 +45,11 @@ final class DesktopState public static function quickActions(): array { return [ + [ + 'action_id' => 'open-user-self-management', + 'label' => 'Setup', + 'description' => 'Oeffnet die persoenlichen Desktop-Einstellungen.', + ], [ 'action_id' => 'open-public-dashboard', 'label' => 'Public Dashboard', @@ -55,11 +60,6 @@ final class DesktopState 'label' => 'Widgets umschalten', 'description' => 'Blendet alle registrierten Widgets ein oder aus.', ], - [ - 'action_id' => 'cycle-skin', - 'label' => 'Skin wechseln', - 'description' => 'Wechselt zyklisch zwischen Windows, Apple und Linux.', - ], ]; } }