diff --git a/CMBNet/README_CMBNet.md b/CMBNet/README_CMBNet.md index 91b62b1..5b9dfd8 100644 --- a/CMBNet/README_CMBNet.md +++ b/CMBNet/README_CMBNet.md @@ -18,6 +18,30 @@ flask --app cmbnet run --debug --host 127.0.0.1 --port 5000 Öffne http://127.0.0.1:5000 und wähle einen Mandanten (BV, RV, SV). +## Administrator-Dashboard + +Das Dashboard unter `//admin/dashboard` bietet zusätzlich: + +- **Datenbank-Backup herunterladen:** erzeugt über die SQLite-Backup-API + einen konsistenten Snapshot der laufenden Datenbank (`.sqlite3`). +- **Backup wiederherstellen:** lädt eine solche Datei hoch, prüft Integrität + und Grundschema und ersetzt anschließend die Live-Datenbank. Währenddessen + sollten keine anderen Benutzer aktiv arbeiten. +- **Konfiguration anzeigen/herunterladen:** listet alle + Konfigurationsparameter als `Key: Value` und exportiert sie als Textdatei. + Geheimnisse wie `SECRET_KEY` und `FCM_SERVICE_ACCOUNT_JSON` werden maskiert. + +Die maximale Upload-Größe wird über `CMBNET_BACKUP_MAX_UPLOAD_MB` +(Default `256`) festgelegt. + +## Dispatcher: Gruppenposition teilen + +Der Nadel-Button (📍) einer Gruppe zentriert die Karte auf die letzte +Gruppenposition. Die Zoomstufe ist über `CMBNET_GROUP_POSITION_ZOOM` +(Default `18`) konfigurierbar. Zusätzlich öffnet der Button ein Karten-Popup +mit einem QR-Code. Der QR-Code verweist auf einen WhatsApp-Deep-Link, der die +Position als Google-Maps-Link teilt. + ## Mandantenspezifische Straßen-Polylines Die Karten-Views laden `static/js/str2pl-.js`, sofern diese Datei diff --git a/CMBNet/cmbnet/__init__.py b/CMBNet/cmbnet/__init__.py index 8761a7a..af77ec9 100644 --- a/CMBNet/cmbnet/__init__.py +++ b/CMBNet/cmbnet/__init__.py @@ -149,6 +149,7 @@ def create_app(config_name=None): from cmbnet.admin.gruppen import admin_gruppen_bp from cmbnet.admin.strassen import admin_strassen_bp from cmbnet.admin.api import admin_api_bp + from cmbnet.admin.backup import admin_backup_bp from cmbnet.api.init import api_init_bp from cmbnet.api.auth import api_auth_bp from cmbnet.api.groups import api_groups_bp @@ -164,6 +165,7 @@ def create_app(config_name=None): app.register_blueprint(admin_gruppen_bp, url_prefix='//admin') app.register_blueprint(admin_strassen_bp, url_prefix='//admin') app.register_blueprint(admin_api_bp, url_prefix='//admin/api') + app.register_blueprint(admin_backup_bp, url_prefix='//admin') app.register_blueprint(api_init_bp, url_prefix='//api') app.register_blueprint(api_auth_bp, url_prefix='//api') app.register_blueprint(api_groups_bp, url_prefix='//api') diff --git a/CMBNet/cmbnet/admin/__init__.py b/CMBNet/cmbnet/admin/__init__.py index e16aa9c..7d6a66b 100644 --- a/CMBNet/cmbnet/admin/__init__.py +++ b/CMBNet/cmbnet/admin/__init__.py @@ -2,5 +2,6 @@ from .accounts import admin_accounts_bp from .gruppen import admin_gruppen_bp from .strassen import admin_strassen_bp from .api import admin_api_bp +from .backup import admin_backup_bp admin_bp = admin_accounts_bp diff --git a/CMBNet/cmbnet/admin/accounts.py b/CMBNet/cmbnet/admin/accounts.py index 5245fc3..3bde051 100644 --- a/CMBNet/cmbnet/admin/accounts.py +++ b/CMBNet/cmbnet/admin/accounts.py @@ -5,6 +5,7 @@ from flask import Blueprint, make_response, render_template, g from cmbnet.auth import role_required from cmbnet.db import get_db from cmbnet.services.api_token_service import ApiTokenService +from cmbnet.admin.backup import collect_config_items admin_accounts_bp = Blueprint('admin', __name__) @@ -15,7 +16,8 @@ def dashboard(**kwargs): """Admin Dashboard""" response = make_response(render_template( 'admin/dashboard.html', - api_tokens=ApiTokenService.list_for_tenant(g.tenant_id) + api_tokens=ApiTokenService.list_for_tenant(g.tenant_id), + config_items=collect_config_items() )) # Die Seite enthält Zugriffstoken und darf nicht im Browser-Cache landen. response.headers['Cache-Control'] = 'no-store' diff --git a/CMBNet/cmbnet/admin/backup.py b/CMBNet/cmbnet/admin/backup.py new file mode 100644 index 0000000..fd2cb55 --- /dev/null +++ b/CMBNet/cmbnet/admin/backup.py @@ -0,0 +1,253 @@ +"""Datenbank-Backup, Wiederherstellung und Konfigurationsexport. + +Die Backup-Datei ist eine vollständige SQLite-Datenbank. Sie wird über die +SQLite-Backup-API erzeugt und kann deshalb auch bei aktivem WAL-Modus +konsistent heruntergeladen werden. Beim Hochladen wird die Datei vor dem +Ersetzen der Live-Datenbank auf Integrität und die wichtigsten Tabellen +geprüft. +""" +from __future__ import annotations + +import json +import sqlite3 +import tempfile +from datetime import datetime +from pathlib import Path + +from flask import ( + Blueprint, + Response, + abort, + after_this_request, + current_app, + flash, + redirect, + request, + send_file, + url_for, +) + +from cmbnet.auth import role_required +from cmbnet.db import get_db +from cmbnet.db.database import ensure_schema +from cmbnet.services.groups_service import GroupsService +from cmbnet.utils.helpers import notify_reload + +admin_backup_bp = Blueprint('admin_backup', __name__) + +# Mindestens diese Tabellen muss ein gültiges CMBNet-Backup enthalten. Ältere +# Backups werden nach der Wiederherstellung durch ``ensure_schema`` ergänzt. +REQUIRED_TABLES = frozenset({'tenants', 'accounts', 'groups', 'streets'}) + +# Werte dieser Schlüssel werden in der Konfigurationsanzeige und im Export +# maskiert. Der Administrator sieht alle Schlüssel, aber keine Geheimnisse, +# mit denen sich Sessions oder FCM-Zugänge übernehmen lassen. +SECRET_CONFIG_KEYS = frozenset({ + 'SECRET_KEY', + 'FCM_SERVICE_ACCOUNT_JSON', +}) + + +def _format_config_value(value): + if isinstance(value, bool): + return 'true' if value else 'false' + if value is None: + return '' + if isinstance(value, (dict, list, tuple, set)): + return json.dumps(value, ensure_ascii=False, default=str, sort_keys=True) + return str(value) + + +def _is_secret_config_key(key): + upper = str(key).upper() + return upper in SECRET_CONFIG_KEYS or 'PASSWORD' in upper + + +def collect_config_items(): + """Liefert alle Konfigurationswerte als sortierte ``(Key, Value)``-Liste. + + Geheimnisse werden maskiert, damit ein versehentlich weitergegebener + Export keine Session- oder Service-Account-Schlüssel enthält. Der + Schlüssel selbst bleibt sichtbar, sodass die Liste vollständig ist. + """ + items = [] + for key in sorted(current_app.config): + if _is_secret_config_key(key): + value = '*** maskiert ***' + else: + value = _format_config_value(current_app.config[key]) + items.append((key, value)) + return items + + +@admin_backup_bp.route('/backup/download') +@role_required('Administrator') +def download_backup(**kwargs): + """Erzeugt einen konsistenten SQLite-Snapshot und liefert ihn als Datei.""" + source = get_db() + source.commit() + + temp = tempfile.NamedTemporaryFile( + prefix='cmbnet-backup-', + suffix='.sqlite3', + delete=False, + ) + temp_path = Path(temp.name) + temp.close() + + destination = None + try: + destination = sqlite3.connect(str(temp_path)) + source.backup(destination) + destination.commit() + except Exception: + current_app.logger.exception('Datenbank-Backup konnte nicht erstellt werden.') + try: + destination.close() + except Exception: + pass + try: + temp_path.unlink() + except OSError: + pass + abort(500, 'Backup konnte nicht erstellt werden.') + + try: + destination.close() + except Exception: + pass + + @after_this_request + def remove_temp_file(response): + try: + temp_path.unlink() + except OSError: + pass + return response + + filename = f'cmbnet-backup-{datetime.now():%Y%m%d-%H%M%S}.sqlite3' + return send_file( + temp_path, + mimetype='application/vnd.sqlite3', + as_attachment=True, + download_name=filename, + max_age=0, + ) + + +def _validate_backup_file(path): + """Prüft Integrität und Grundschema einer hochgeladenen SQLite-Datei.""" + conn = sqlite3.connect(str(path)) + try: + result = conn.execute('PRAGMA integrity_check').fetchone() + if not result or str(result[0]).lower() != 'ok': + raise ValueError('Die Datei ist keine gültige SQLite-Datenbank.') + + tables = { + str(row[0]) + for row in conn.execute( + "SELECT name FROM sqlite_master WHERE type = 'table'" + ).fetchall() + } + missing = REQUIRED_TABLES - tables + if missing: + raise ValueError( + 'Das Backup ist unvollständig. Fehlende Tabellen: ' + + ', '.join(sorted(missing)) + ) + finally: + conn.close() + + +@admin_backup_bp.route('/backup/restore', methods=['POST']) +@role_required('Administrator') +def restore_backup(**kwargs): + """Ersetzt die Live-Datenbank durch ein hochgeladenes Backup.""" + upload = request.files.get('backup') + if upload is None or not upload.filename: + flash('Bitte eine Backup-Datei auswählen.', 'error') + return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant'))) + + max_bytes = int(current_app.config.get( + 'BACKUP_MAX_UPLOAD_BYTES', 256 * 1024 * 1024 + )) + if request.content_length and request.content_length > max_bytes: + flash('Die Backup-Datei ist zu groß.', 'error') + return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant'))) + + temp = tempfile.NamedTemporaryFile( + prefix='cmbnet-restore-', + suffix='.sqlite3', + delete=False, + ) + temp_path = Path(temp.name) + temp.close() + source = None + destination = None + + try: + upload.save(temp_path) + if temp_path.stat().st_size > max_bytes: + raise ValueError('Die Backup-Datei ist zu groß.') + if temp_path.stat().st_size < 512: + raise ValueError('Die Backup-Datei ist leer oder beschädigt.') + + _validate_backup_file(temp_path) + + destination = get_db() + destination.commit() + source = sqlite3.connect(str(temp_path)) + source.backup(destination) + destination.commit() + + # Die Backup-Datei kann im DELETE-Journalmodus erzeugt worden sein. + # Für den Mehr-Worker-Betrieb wird die Live-Datenbank wieder auf WAL + # umgestellt. + destination.execute('PRAGMA journal_mode = WAL') + destination.execute('PRAGMA synchronous = NORMAL') + destination.commit() + + # Nach dem Einspielen fehlende Spalten/Tabellen älterer Backups + # ergänzen und alle prozesslokalen Caches verwerfen. + ensure_schema() + GroupsService.invalidate_all() + except Exception as exc: + current_app.logger.exception('Datenbank-Wiederherstellung fehlgeschlagen.') + try: + if destination is not None: + destination.rollback() + except Exception: + pass + flash(f'Wiederherstellung fehlgeschlagen: {exc}', 'error') + return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant'))) + finally: + try: + if source is not None: + source.close() + except Exception: + pass + try: + temp_path.unlink() + except OSError: + pass + + try: + notify_reload('Administration: Die Datenbank wurde aus einem Backup wiederhergestellt.') + except Exception: + current_app.logger.warning('Reload-Hinweis nach Restore fehlgeschlagen.', exc_info=True) + + flash('Datenbank wurde erfolgreich wiederhergestellt.', 'success') + return redirect(url_for('admin.dashboard', tenant=kwargs.get('tenant'))) + + +@admin_backup_bp.route('/config/export') +@role_required('Administrator') +def export_config(**kwargs): + """Liefert alle Konfigurationsparameter als Key:Value-Textdatei.""" + lines = [f'{key}: {value}' for key, value in collect_config_items()] + body = '\n'.join(lines) + '\n' + filename = f'cmbnet-config-{datetime.now():%Y%m%d-%H%M%S}.txt' + response = Response(body, mimetype='text/plain; charset=utf-8') + response.headers['Content-Disposition'] = f'attachment; filename="{filename}"' + response.headers['Cache-Control'] = 'no-store' + return response diff --git a/CMBNet/config.py b/CMBNet/config.py index f816131..1fac2c3 100644 --- a/CMBNet/config.py +++ b/CMBNet/config.py @@ -47,6 +47,19 @@ class Config: WS_WORKER_ID = os.environ.get('CMBNET_WS_WORKER_ID', '') LATE_ENTRY_MAX_AGE_HOURS = int(os.environ.get('CMBNET_LATE_ENTRY_MAX_AGE_HOURS', '8')) + # Zoomstufe, auf die der Nadel-Button im Dispatcher eine Gruppenposition + # zentriert. Der Wert wird clientseitig auf den gültigen Leaflet-Bereich + # begrenzt. + GROUP_POSITION_ZOOM = int(os.environ.get( + 'CMBNET_GROUP_POSITION_ZOOM', '18' + )) + + # Maximale Größe eines hochgeladenen Datenbank-Backups. Schützt vor + # versehentlich großen Uploads; der Download ist davon nicht betroffen. + BACKUP_MAX_UPLOAD_BYTES = int(os.environ.get( + 'CMBNET_BACKUP_MAX_UPLOAD_MB', '256' + )) * 1024 * 1024 + # ------------------------------------------------------------------ # Firebase Cloud Messaging (nur Aufwachsignal, keine Nutzdaten) # ------------------------------------------------------------------ diff --git a/CMBNet/static/css/admin.css b/CMBNet/static/css/admin.css index 9d61f53..690165b 100644 --- a/CMBNet/static/css/admin.css +++ b/CMBNet/static/css/admin.css @@ -16,6 +16,34 @@ table td { font-size: 0.82rem; } +.config-table-wrapper { + max-height: 28rem; + overflow: auto; + border: 1px solid var(--pico-muted-border-color, #d6d9dd); + border-radius: 0.5rem; +} + +.config-table-wrapper table { + margin: 0; +} + +#configTable { + width: 100%; +} + +#configTable td:first-child { + white-space: nowrap; + vertical-align: top; +} + +.config-value { + display: inline-block; + max-width: 42rem; + white-space: pre-wrap; + overflow-wrap: anywhere; + font-size: 0.82rem; +} + dialog article { max-width: 600px; width: min(90vw, 600px); diff --git a/CMBNet/static/css/dispatcher.css b/CMBNet/static/css/dispatcher.css index af7b805..1e9ee0c 100644 --- a/CMBNet/static/css/dispatcher.css +++ b/CMBNet/static/css/dispatcher.css @@ -1002,6 +1002,52 @@ dialog.group-streets-dialog.is-dragging article header { /* Leaflet setzt role="button"; Pico würde sonst Button-Padding und Zeilenhöhe anwenden und den Marker gegenüber der gesetzten Position verschieben. */ +.group-position-share { + text-align: center; +} + +.group-position-share-title { + font-weight: 600; + font-size: 0.95rem; +} + +.group-position-share-coords { + margin-top: 0.15rem; + font-size: 0.78rem; + opacity: 0.75; + font-variant-numeric: tabular-nums; +} + +.group-position-share-qr { + display: block; + width: 200px; + height: 200px; + max-width: 100%; + margin: 0.55rem auto 0.25rem; + image-rendering: pixelated; + background: #fff; +} + +.group-position-share-links { + font-size: 0.8rem; + line-height: 1.5; +} + +.group-position-share-links a { + color: var(--primary, #2f6fdb); +} + +html[data-theme="dark"] .leaflet-popup-content-wrapper, +html[data-theme="dark"] .leaflet-popup-tip { + background: #141e26; + color: var(--color, #c8d1d8); + box-shadow: 0 1px 8px rgba(0, 0, 0, 0.6); +} + +html[data-theme="dark"] .group-position-share-links a { + color: var(--primary, #35b9e0); +} + .group-marker-icon { display: flex; align-items: center; diff --git a/CMBNet/static/css/mobile.css b/CMBNet/static/css/mobile.css index 0ab736e..5553104 100644 --- a/CMBNet/static/css/mobile.css +++ b/CMBNet/static/css/mobile.css @@ -274,6 +274,17 @@ html[data-theme="dark"] .mobile-ws-status.is-error { background: rgba(153, 27, 27, 0.96); } +.firebase-debug-payload { + max-height: 16rem; + overflow: auto; + padding: 0.6rem; + border-radius: 0.45rem; + background: rgba(15, 23, 42, 0.06); + font-size: 0.75rem; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + .mobile-work-btn { position: absolute; left: 50%; diff --git a/CMBNet/static/js/sw.js b/CMBNet/static/js/sw.js index 51f9c51..f6f20f7 100644 --- a/CMBNet/static/js/sw.js +++ b/CMBNet/static/js/sw.js @@ -5,7 +5,7 @@ * damit er sowohl die mobilen Views als auch die statischen Assets * kontrolliert. Der Cache-Name wird pro App-Wurzel gebildet. */ -const VERSION = 'cmbnet-pwa-v23'; +const VERSION = 'cmbnet-pwa-v24'; const BASE = new URL('./', self.location).href; const SHELL_CACHE = `${VERSION}-shell`; const TILE_CACHE = `${VERSION}-tiles`; diff --git a/CMBNet/static/js/views/admin_dashboard.js b/CMBNet/static/js/views/admin_dashboard.js index cc643e0..9c7cb95 100644 --- a/CMBNet/static/js/views/admin_dashboard.js +++ b/CMBNet/static/js/views/admin_dashboard.js @@ -85,5 +85,16 @@ if (createApiTokenBtn) { createApiTokenBtn.addEventListener('click', createApiToken); } +const restoreBackupForm = document.getElementById('restoreBackupForm'); +if (restoreBackupForm) { + restoreBackupForm.addEventListener('submit', event => { + const confirmed = confirm( + 'Die aktuelle Datenbank wird vollständig durch das Backup ersetzt. ' + + 'Dabei gehen alle Änderungen seit dem Backup verloren. Fortfahren?' + ); + if (!confirmed) event.preventDefault(); + }); +} + loadBrokerStatus(); setInterval(loadBrokerStatus, 5000); diff --git a/CMBNet/static/js/views/dispatcher.js b/CMBNet/static/js/views/dispatcher.js index a67290b..1dbde3a 100644 --- a/CMBNet/static/js/views/dispatcher.js +++ b/CMBNet/static/js/views/dispatcher.js @@ -26,6 +26,9 @@ const DEFAULT_SETTINGS = { const STREET_STATES = ['unbearbeitet', 'zugewiesen', 'erledigt']; const GROUP_STATES = ['offen', 'unterwegs', 'online', 'pausierend', 'fertig']; const GROUP_MARKER_MAX_AGE_SECONDS = 30 * 60; +const GROUP_POSITION_ZOOM_DEFAULT = 18; +const GROUP_POSITION_ZOOM_MIN = 1; +const GROUP_POSITION_ZOOM_MAX = 22; const GROUP_STREET_HOVER_COLOR = '#f5c518'; const STREET_COLORS = { unbearbeitet: '#1f6feb', @@ -1417,10 +1420,119 @@ async function saveGroupAssignments() { } } +function groupPositionZoomLevel() { + const configured = Number(window.CMBNET_GROUP_POSITION_ZOOM); + if (!Number.isFinite(configured)) return GROUP_POSITION_ZOOM_DEFAULT; + return Math.min( + GROUP_POSITION_ZOOM_MAX, + Math.max(GROUP_POSITION_ZOOM_MIN, Math.round(configured)) + ); +} + +function buildGroupPositionShare(group) { + const lat = Number(group.last_lat); + const lon = Number(group.last_lon); + const mapsUrl = `https://www.google.com/maps?q=${lat.toFixed(6)},${lon.toFixed(6)}`; + const text = `Position von ${groupDisplayName(group)}: ${mapsUrl}`; + return { + lat, + lon, + mapsUrl, + whatsappUrl: `https://api.whatsapp.com/send?text=${encodeURIComponent(text)}` + }; +} + +function openGroupPositionSharePopup(group) { + let marker = dispatcherState.markersByGroupId.get(Number(group.id)); + if (!marker) { + marker = createGroupMarker(group, [ + Number(group.last_lat), + Number(group.last_lon) + ]); + } + if (!marker) return; + + const share = buildGroupPositionShare(group); + const container = document.createElement('div'); + container.className = 'group-position-share'; + + const title = document.createElement('div'); + title.className = 'group-position-share-title'; + title.textContent = groupDisplayName(group); + + const coordinates = document.createElement('div'); + coordinates.className = 'group-position-share-coords'; + coordinates.textContent = `${share.lat.toFixed(5)}, ${share.lon.toFixed(5)}`; + + const canvas = document.createElement('canvas'); + canvas.className = 'group-position-share-qr'; + canvas.width = 200; + canvas.height = 200; + canvas.setAttribute( + 'aria-label', + `QR-Code zum Teilen der Position von ${groupDisplayName(group)} über WhatsApp` + ); + + let qrRendered = false; + if (typeof QRious !== 'undefined') { + try { + new QRious({ + element: canvas, + value: share.whatsappUrl, + size: 200, + level: 'M' + }); + qrRendered = true; + } catch (error) { + console.error('QRious error', error); + } + } + + const links = document.createElement('div'); + links.className = 'group-position-share-links'; + const whatsappLink = document.createElement('a'); + whatsappLink.href = share.whatsappUrl; + whatsappLink.target = '_blank'; + whatsappLink.rel = 'noopener'; + whatsappLink.textContent = 'Per WhatsApp teilen'; + const separator = document.createTextNode(' · '); + const mapsLink = document.createElement('a'); + mapsLink.href = share.mapsUrl; + mapsLink.target = '_blank'; + mapsLink.rel = 'noopener'; + mapsLink.textContent = 'Kartenlink'; + links.append(whatsappLink, separator, mapsLink); + + container.append(title, coordinates); + if (qrRendered) { + container.appendChild(canvas); + } else { + const fallback = document.createElement('p'); + fallback.textContent = 'QR-Code nicht verfügbar.'; + container.appendChild(fallback); + } + container.appendChild(links); + + marker.bindPopup(container, { + className: 'group-position-share-popup', + minWidth: 210, + maxWidth: 250, + autoClose: false, + closeOnClick: false, + closeButton: true, + offset: [0, -6] + }); + marker.openPopup(); +} + function locateGroup(groupId) { const group = dispatcherState.groupById.get(Number(groupId)); if (!group || !hasPosition(group)) return; - map.setView([Number(group.last_lat), Number(group.last_lon)], 15); + map.setView( + [Number(group.last_lat), Number(group.last_lon)], + groupPositionZoomLevel() + ); + openGroupPositionSharePopup(group); } function toggleCrosshair(groupId) { diff --git a/CMBNet/static/js/views/mobile.js b/CMBNet/static/js/views/mobile.js index b35ad57..8152a36 100644 --- a/CMBNet/static/js/views/mobile.js +++ b/CMBNet/static/js/views/mobile.js @@ -19,7 +19,9 @@ const DEFAULT_SETTINGS = { opacity: 0.7, weight: 20, baseLayer: 'osm', - autoSendPosition: true + // Die automatische Übertragung der Eigenposition ist bewusst opt-in. + // Bestehende gespeicherte Einstellungen bleiben unverändert. + autoSendPosition: false }; const AUTO_POSITION_INTERVAL_MS = 30000; @@ -386,6 +388,9 @@ async function initFirebasePush(registration = null, force = false) { && payload.data.reason ? payload.data.reason : 'wake'; + // Debugging: Jede im Vordergrund empfangene Firebase-Nachricht + // wird sichtbar angezeigt, bevor die Synchronisierung läuft. + showFirebaseDebugPopup(reason, payload); handlePushWake(reason); }); } @@ -438,10 +443,70 @@ function initPushWakeListener() { navigator.serviceWorker.addEventListener('message', event => { if (!event.data || event.data.type !== 'cmbnet-wake') return; const port = event.ports && event.ports[0]; - handlePushWake(event.data.reason || 'wake', port); + const reason = event.data.reason || 'wake'; + // Ein Klick auf eine Benachrichtigung ist kein neuer Firebase-Empfang. + if (reason !== 'notification') { + showFirebaseDebugPopup(reason, event.data); + } + handlePushWake(reason, port); }); } +function showFirebaseDebugPopup(reason, payload) { + let dialog = document.getElementById('firebaseDebugDialog'); + if (!dialog) { + dialog = document.createElement('dialog'); + dialog.id = 'firebaseDebugDialog'; + dialog.setAttribute('aria-labelledby', 'firebaseDebugTitle'); + + const article = document.createElement('article'); + const header = document.createElement('header'); + const title = document.createElement('h3'); + title.id = 'firebaseDebugTitle'; + title.textContent = 'Firebase-Nachricht'; + header.appendChild(title); + + const body = document.createElement('div'); + body.className = 'dialog-body'; + const reasonEl = document.createElement('p'); + reasonEl.id = 'firebaseDebugReason'; + const payloadEl = document.createElement('pre'); + payloadEl.id = 'firebaseDebugPayload'; + payloadEl.className = 'firebase-debug-payload'; + body.append(reasonEl, payloadEl); + + const footer = document.createElement('footer'); + const closeButton = document.createElement('button'); + closeButton.type = 'button'; + closeButton.className = 'secondary'; + closeButton.textContent = 'Schließen'; + closeButton.addEventListener('click', () => dialog.close()); + footer.appendChild(closeButton); + + article.append(header, body, footer); + dialog.appendChild(article); + document.body.appendChild(dialog); + } + + const reasonEl = dialog.querySelector('#firebaseDebugReason'); + const payloadEl = dialog.querySelector('#firebaseDebugPayload'); + if (reasonEl) reasonEl.textContent = `Grund: ${reason || 'wake'}`; + if (payloadEl) { + let text = ''; + try { + text = payload ? JSON.stringify(payload, null, 2) : ''; + } catch (error) { + text = String(payload || ''); + } + payloadEl.textContent = text; + } + + if (!dialog.open) { + if (typeof dialog.showModal === 'function') dialog.showModal(); + else if (typeof dialog.show === 'function') dialog.show(); + } +} + function waitForWsAuthentication(timeoutMs = PUSH_WAKE_AUTH_TIMEOUT_MS) { if (state.authenticated) return Promise.resolve(true); return new Promise(resolve => { @@ -586,7 +651,7 @@ function loadSettings() { state.settings.opacity = typeof saved.opacity === 'number' ? saved.opacity : DEFAULT_SETTINGS.opacity; state.settings.weight = typeof saved.weight === 'number' ? saved.weight : DEFAULT_SETTINGS.weight; state.settings.baseLayer = saved.baseLayer === 'aerial' ? 'aerial' : 'osm'; - state.settings.autoSendPosition = saved.autoSendPosition !== false; + state.settings.autoSendPosition = saved.autoSendPosition === true; } } catch(e) {} } diff --git a/CMBNet/templates/admin/dashboard.html b/CMBNet/templates/admin/dashboard.html index b12bc45..11af366 100644 --- a/CMBNet/templates/admin/dashboard.html +++ b/CMBNet/templates/admin/dashboard.html @@ -13,6 +13,64 @@ +
+

Datenbank-Backup

+

+ Das Backup enthält eine vollständige, konsistente Kopie der + SQLite-Datenbank. Es kann später über die Schaltfläche unten wieder + eingespielt werden. Während der Wiederherstellung sollten keine + anderen Benutzer aktiv arbeiten. +

+

+ Backup herunterladen +

+
+ + + +
+

+ + Die Wiederherstellung ersetzt alle aktuellen Daten durch den + Inhalt der Backup-Datei. Die Datei wird vor dem Einspielen auf + Integrität und das CMBNet-Grundschema geprüft. + +

+
+ +
+

Konfiguration

+

+ Alle Konfigurationsparameter als Key:Value-Liste. Geheimnisse wie + SECRET_KEY und Service-Account-Inhalte werden maskiert. +

+

+ Konfiguration herunterladen +

+
+ + + + + + + + + {% for key, value in config_items %} + + + + + {% endfor %} + +
KeyValue
{{ key }}{{ value }}
+
+
+

API-Zugriffstoken

diff --git a/CMBNet/templates/dispatcher.html b/CMBNet/templates/dispatcher.html index c024b2e..9f0b1a9 100644 --- a/CMBNet/templates/dispatcher.html +++ b/CMBNet/templates/dispatcher.html @@ -318,6 +318,7 @@ window.CMBNET_TENANT = {{ session.tenant_code|tojson }}; window.CMBNET_ACCOUNT_ID = {{ session.account_id|tojson }}; window.CMBNET_LOGOUT_URL = {{ url_for('auth.logout', tenant=session.tenant_code)|tojson }}; + window.CMBNET_GROUP_POSITION_ZOOM = {{ config.GROUP_POSITION_ZOOM|tojson }}; diff --git a/CMBNet/templates/gruppen.html b/CMBNet/templates/gruppen.html index 578226a..b99a42f 100644 --- a/CMBNet/templates/gruppen.html +++ b/CMBNet/templates/gruppen.html @@ -124,7 +124,7 @@

Eigenposition automatisch senden + aria-label="Eigenposition automatisch senden">

Ist die automatische Versendung deaktiviert, kann die Position