From 02c017d53dec084fc6f0fd8f5a4ee9f45e88699a Mon Sep 17 00:00:00 2001 From: Thomas Date: Fri, 30 Oct 2026 09:02:46 +0100 Subject: [PATCH] Neue Verwaltung der Gruppenzuordnung 1:n --- CMBNet/cmbnet/__init__.py | 10 + CMBNet/cmbnet/admin/api.py | 87 +++--- CMBNet/cmbnet/admin/gruppen.py | 8 +- CMBNet/cmbnet/api/groups.py | 92 ++++++- CMBNet/cmbnet/db/database.py | 99 +++++++ CMBNet/cmbnet/models/accounts.py | 11 + CMBNet/cmbnet/models/groups.py | 44 ++- CMBNet/cmbnet/services/groups_service.py | 29 +- CMBNet/cmbnet/utils/helpers.py | 29 +- CMBNet/cmbnet/views/main.py | 15 +- CMBNet/cmbnet/ws/broker.py | 73 +++-- CMBNet/config.py | 4 + CMBNet/migrations/schema.sql | 16 +- CMBNet/static/css/dispatcher.css | 319 ++++++++++++++++++---- CMBNet/static/css/style.css | 59 ++++ CMBNet/static/js/reload_notice.js | 174 ++++++++++++ CMBNet/static/js/sw.js | 7 +- CMBNet/static/js/views/admin_gruppen.js | 26 +- CMBNet/static/js/views/dispatcher.js | 308 +++++++++++++++++++-- CMBNet/static/js/views/mobile.js | 25 +- CMBNet/templates/_pwa_install_dialog.html | 2 +- CMBNet/templates/admin/accounts.html | 3 +- CMBNet/templates/admin/dashboard.html | 3 +- CMBNet/templates/admin/gruppen.html | 20 +- CMBNet/templates/admin/strassen.html | 3 +- CMBNet/templates/base.html | 4 +- CMBNet/templates/beobachter.html | 4 +- CMBNet/templates/dispatcher.html | 63 ++++- CMBNet/templates/dispatcher_mobil.html | 4 +- CMBNet/templates/gruppen.html | 4 +- CMBNet/templates/login.html | 4 +- CMBNet/templates/login_select.html | 4 +- CMBNet/templates/oeffentlich.html | 2 +- CMBNet/templates/praesentation.html | 2 +- 34 files changed, 1306 insertions(+), 251 deletions(-) create mode 100644 CMBNet/static/js/reload_notice.js diff --git a/CMBNet/cmbnet/__init__.py b/CMBNet/cmbnet/__init__.py index e7eb863..2ff8a2a 100644 --- a/CMBNet/cmbnet/__init__.py +++ b/CMBNet/cmbnet/__init__.py @@ -91,6 +91,11 @@ def create_app(config_name=None): template_folder='../templates', static_folder='../static') app.config.from_object(config[config_name]) + + # Anzeigetitel für alle Web-Views. Der interne Projektname bleibt CMBNet. + app.jinja_env.globals['APP_TITLE'] = app.config.get( + 'DISPLAY_TITLE', '20*C+M+B+27' + ) # Middleware registrieren app.wsgi_app = PrefixMiddleware(app.wsgi_app) @@ -104,8 +109,13 @@ def create_app(config_name=None): # Datenbank-Setup from cmbnet.db import close_db, init_db_command + from cmbnet.db.database import ensure_schema app.teardown_appcontext(close_db) app.cli.add_command(init_db_command) + + # Bestehende Installationen idempotent auf das aktuelle Schema heben. + with app.app_context(): + ensure_schema() # Tenant und Account für Requests laden @app.before_request diff --git a/CMBNet/cmbnet/admin/api.py b/CMBNet/cmbnet/admin/api.py index ddf93a1..81059ec 100644 --- a/CMBNet/cmbnet/admin/api.py +++ b/CMBNet/cmbnet/admin/api.py @@ -10,7 +10,7 @@ from cmbnet.models.groups import GroupModel from cmbnet.models.streets import StreetModel from cmbnet.services.groups_service import GroupsService from cmbnet.services.history_service import HistoryService -from cmbnet.utils.helpers import log_transaction +from cmbnet.utils.helpers import log_transaction, notify_reload from cmbnet.utils.csv_utils import parse_streets_csv, parse_house_numbers_csv from cmbnet.ws import broker from cmbnet.ws.protocol import WSMessage @@ -38,7 +38,8 @@ def create_account(**kwargs): password_hash = hash_password(password) account_id = AccountModel.create(g.tenant_id, name, password_hash, role) log_transaction('account.create', 'account', account_id, {'name': name, 'role': role}) - + notify_reload(f'Administration: Account „{name}“ wurde erstellt.') + return jsonify({'success': True, 'id': account_id}) @@ -47,9 +48,12 @@ def create_account(**kwargs): def update_account_role(account_id, **kwargs): data = request.get_json() role = data.get('role') + account = AccountModel.get_by_id(account_id, g.tenant_id) AccountModel.update_role(account_id, g.tenant_id, role) log_transaction('account.role_change', 'account', account_id, {'role': role}) GroupsService.invalidate(g.tenant_id) + name = account['name'] if account else f'#{account_id}' + notify_reload(f'Administration: Rolle von Account „{name}“ wurde geändert.') return jsonify({'success': True}) @@ -61,17 +65,23 @@ def reset_password(account_id, **kwargs): if not password: return jsonify({'error': 'Passwort erforderlich'}), 400 password_hash = hash_password(password) + account = AccountModel.get_by_id(account_id, g.tenant_id) AccountModel.set_password(account_id, g.tenant_id, password_hash) log_transaction('account.password_reset', 'account', account_id, {}) + name = account['name'] if account else f'#{account_id}' + notify_reload(f'Administration: Passwort für Account „{name}“ wurde zurückgesetzt.') return jsonify({'success': True}) @admin_api_bp.route('/accounts/', methods=['DELETE']) @role_required('Administrator') def delete_account(account_id, **kwargs): + account = AccountModel.get_by_id(account_id, g.tenant_id) AccountModel.delete(account_id, g.tenant_id) log_transaction('account.delete', 'account', account_id, {}) GroupsService.invalidate(g.tenant_id) + name = account['name'] if account else f'#{account_id}' + notify_reload(f'Administration: Account „{name}“ wurde gelöscht.') return jsonify({'success': True}) @@ -81,37 +91,18 @@ def delete_account(account_id, **kwargs): def create_group(**kwargs): data = request.get_json() or {} aliasname = str(data.get('aliasname') or '').strip() - account_id = data.get('account_id') db = get_db() - if account_id == '' or account_id is None: - account_id = None - else: - try: - account_id = int(account_id) - except (TypeError, ValueError): - return jsonify({'error': 'Ungültiger Account'}), 400 - - account = AccountModel.get_by_id(account_id, g.tenant_id) - if not account or account['role'] != 'Gruppe': - return jsonify({'error': 'Account muss die Rolle "Gruppe" haben'}), 400 - - linked = db.execute( - 'SELECT id FROM groups WHERE tenant_id = ? AND account_id = ?', - (g.tenant_id, account_id) - ).fetchone() - if linked: - return jsonify({'error': 'Dieser Account ist bereits mit einer Gruppe verknüpft'}), 400 - - group_id = GroupModel.create(g.tenant_id, aliasname, account_id, 'offen') + group_id = GroupModel.create(g.tenant_id, aliasname, 'offen') db.execute( 'INSERT INTO group_state_history (tenant_id, group_id, from_state, to_state, actor_account_id) VALUES (?, ?, ?, ?, ?)', (g.tenant_id, group_id, None, 'offen', session['account_id']) ) db.commit() - log_transaction('group.create', 'group', group_id, {'aliasname': aliasname, 'account_id': account_id}) + log_transaction('group.create', 'group', group_id, {'aliasname': aliasname}) GroupsService.invalidate(g.tenant_id) GroupsService.load_from_db(g.tenant_id) + notify_reload(f'Administration: Gruppe „{aliasname or group_id}“ wurde erstellt.') return jsonify({'success': True, 'id': group_id}) @@ -128,30 +119,6 @@ def update_group(group_id, **kwargs): if 'aliasname' in data: updates['aliasname'] = data['aliasname'] - if 'account_id' in data: - account_id = data['account_id'] - if account_id in ('', None): - account_id = None - else: - try: - account_id = int(account_id) - except (TypeError, ValueError): - return jsonify({'error': 'Ungültiger Account'}), 400 - - account = AccountModel.get_by_id(account_id, g.tenant_id) - if not account or account['role'] != 'Gruppe': - return jsonify({'error': 'Account muss die Rolle "Gruppe" haben'}), 400 - - linked = db.execute( - 'SELECT id FROM groups WHERE tenant_id = ? AND account_id = ? AND id != ?', - (g.tenant_id, account_id, group_id) - ).fetchone() - if linked: - return jsonify({'error': 'Dieser Account ist bereits mit einer Gruppe verknüpft'}), 400 - - if account_id != old['account_id']: - updates['account_id'] = account_id - allowed_states = {'offen', 'unterwegs', 'online', 'pausierend', 'fertig'} state_changed = False if 'state' in data: @@ -183,15 +150,20 @@ def update_group(group_id, **kwargs): log_transaction('group.update', 'group', group_id, updates) GroupsService.invalidate(g.tenant_id) GroupsService.load_from_db(g.tenant_id) + display_name = updates.get('aliasname', old['aliasname']) or group_id + notify_reload(f'Administration: Gruppe „{display_name}“ wurde geändert.') return jsonify({'success': True}) @admin_api_bp.route('/gruppen/', methods=['DELETE']) @role_required('Administrator') def delete_group(group_id, **kwargs): + group = GroupModel.get_by_id(group_id, g.tenant_id) GroupModel.delete(group_id, g.tenant_id) log_transaction('group.delete', 'group', group_id, {}) GroupsService.invalidate(g.tenant_id) + display_name = (group['aliasname'] if group and group['aliasname'] else group_id) + notify_reload(f'Administration: Gruppe „{display_name}“ wurde gelöscht.') return jsonify({'success': True}) @@ -212,6 +184,7 @@ def revert_group_hist(group_id, hist_id, **kwargs): success, msg = HistoryService.revert_group(g.tenant_id, group_id, hist_id, session['account_id']) if not success: return jsonify({'error': msg}), 400 + notify_reload('Administration: Gruppenhistorie wurde wiederhergestellt.') return jsonify({'success': True, 'message': msg}) @@ -223,6 +196,7 @@ def set_group_position_from_history(group_id, hist_id, **kwargs): ) if not success: return jsonify({'error': msg}), 400 + notify_reload('Administration: Gruppenposition wurde aus der Historie gesetzt.') return jsonify({'success': True, 'message': msg}) @@ -234,6 +208,7 @@ def clear_group_position(group_id, **kwargs): ) if not success: return jsonify({'error': msg}), 400 + notify_reload('Administration: Gruppenposition wurde gelöscht.') return jsonify({'success': True, 'message': msg}) @@ -258,6 +233,7 @@ def create_street(**kwargs): ) db.commit() log_transaction('street.create', 'street', street_id, {'name': name}) + notify_reload(f'Administration: Straße „{name}“ wurde erstellt.') return jsonify({'success': True, 'id': street_id}) @@ -303,7 +279,9 @@ def update_street(street_id, **kwargs): if changes: StreetModel.update(street_id, g.tenant_id, **changes) log_transaction('street.update', 'street', street_id, changes) - + display_name = changes.get('name', old['name']) + notify_reload(f'Administration: Straße „{display_name}“ wurde geändert.') + db.commit() return jsonify({'success': True}) @@ -311,8 +289,11 @@ def update_street(street_id, **kwargs): @admin_api_bp.route('/strassen/', methods=['DELETE']) @role_required('Administrator') def delete_street(street_id, **kwargs): + street = StreetModel.get_by_id(street_id, g.tenant_id) StreetModel.delete(street_id, g.tenant_id) log_transaction('street.delete', 'street', street_id, {}) + name = street['name'] if street else f'#{street_id}' + notify_reload(f'Administration: Straße „{name}“ wurde gelöscht.') return jsonify({'success': True}) @@ -333,6 +314,7 @@ def revert_street_hist(street_id, hist_id, **kwargs): success, msg = HistoryService.revert_street(g.tenant_id, street_id, hist_id, session['account_id']) if not success: return jsonify({'error': msg}), 400 + notify_reload('Administration: Straßenhistorie wurde wiederhergestellt.') return jsonify({'success': True, 'message': msg}) @@ -367,6 +349,7 @@ def import_streets(**kwargs): count += 1 db.commit() + notify_reload(f'Administration: {count} Straßen wurden importiert.') return jsonify({'success': True, 'count': count}) @@ -392,7 +375,10 @@ def broker_status(**kwargs): } if account['role'] == 'Gruppe': group = get_db().execute( - 'SELECT id, aliasname FROM groups WHERE account_id = ? AND tenant_id = ?', + '''SELECT g.id, g.aliasname FROM groups g + JOIN group_accounts ga + ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id + WHERE ga.account_id = ? AND g.tenant_id = ?''', (account['id'], g.tenant_id) ).fetchone() if group: @@ -447,4 +433,5 @@ def import_house_numbers(**kwargs): None, {'count': len(house_numbers)} ) + notify_reload(f'Administration: {len(house_numbers)} Hausnummern wurden importiert.') return jsonify({'success': True, 'count': len(house_numbers)}) diff --git a/CMBNet/cmbnet/admin/gruppen.py b/CMBNet/cmbnet/admin/gruppen.py index 3c8c7b9..b4de65f 100644 --- a/CMBNet/cmbnet/admin/gruppen.py +++ b/CMBNet/cmbnet/admin/gruppen.py @@ -14,11 +14,7 @@ def gruppen(**kwargs): """Gruppenverwaltung""" db = get_db() gruppen = db.execute( - 'SELECT g.*, a.name as account_name FROM groups g LEFT JOIN accounts a ON g.account_id = a.id WHERE g.tenant_id = ? ORDER BY g.id', + 'SELECT * FROM groups WHERE tenant_id = ? ORDER BY id', (g.tenant_id,) ).fetchall() - accounts = db.execute( - "SELECT * FROM accounts WHERE tenant_id = ? AND role = 'Gruppe'", - (g.tenant_id,) - ).fetchall() - return render_template('admin/gruppen.html', gruppen=gruppen, accounts=accounts) + return render_template('admin/gruppen.html', gruppen=gruppen) diff --git a/CMBNet/cmbnet/api/groups.py b/CMBNet/cmbnet/api/groups.py index 38b2a03..fa5f7f0 100644 --- a/CMBNet/cmbnet/api/groups.py +++ b/CMBNet/cmbnet/api/groups.py @@ -4,9 +4,10 @@ API-Endpunkte für Gruppen im Dispatcher-View. from flask import Blueprint, jsonify, g, request from cmbnet.auth import role_required +from cmbnet.db import get_db from cmbnet.models.groups import GroupModel from cmbnet.services.groups_service import GroupsService -from cmbnet.utils.helpers import log_transaction +from cmbnet.utils.helpers import log_transaction, notify_reload api_groups_bp = Blueprint('api_groups', __name__) @@ -16,9 +17,10 @@ api_groups_bp = Blueprint('api_groups', __name__) def get_my_group(**kwargs): from cmbnet.services.groups_service import GroupsService groups = GroupsService.get_all(g.tenant_id) - account_id = g.current_account['id'] + account_id = int(g.current_account['id']) for group in groups.values(): - if group.get('account_id') == account_id: + account_ids = {int(value) for value in group.get('account_ids', [])} + if account_id in account_ids: return jsonify(group) return jsonify({'error': 'Gruppe nicht gefunden'}), 404 @@ -47,3 +49,87 @@ def update_group_alias(group_id, **kwargs): GroupsService.load_from_db(g.tenant_id) return jsonify({'success': True, 'aliasname': aliasname}) + + +@api_groups_bp.route('/groups/assignments', methods=['POST']) +@role_required(['Dispatcher', 'Administrator']) +def update_group_assignments(**kwargs): + '''Speichert die Zuordnung von Gruppen-Accounts zu Gruppen. + + Die Tabelle ``group_accounts`` erzwingt über ``UNIQUE(tenant_id, + account_id)``, dass ein Gruppen-Account höchstens einer Gruppe zugeordnet + ist. Ein ``null``-Wert in ``assignments`` bedeutet "Nicht dabei". + ''' + data = request.get_json(silent=True) or {} + raw_assignments = data.get('assignments') + if not isinstance(raw_assignments, dict): + return jsonify({'error': 'Ungültige Zuordnungen'}), 400 + + db = get_db() + account_rows = db.execute( + "SELECT id FROM accounts WHERE tenant_id = ? AND role = 'Gruppe'", + (g.tenant_id,) + ).fetchall() + allowed_accounts = {int(row['id']) for row in account_rows} + + group_rows = db.execute( + 'SELECT id FROM groups WHERE tenant_id = ?', + (g.tenant_id,) + ).fetchall() + allowed_groups = {int(row['id']) for row in group_rows} + + normalized = {} + for raw_account_id, raw_group_id in raw_assignments.items(): + try: + account_id = int(raw_account_id) + except (TypeError, ValueError): + return jsonify({'error': 'Ungültiger Account'}), 400 + if account_id not in allowed_accounts: + return jsonify({'error': 'Account muss die Rolle "Gruppe" haben'}), 400 + + if raw_group_id in (None, '', 'none'): + group_id = None + else: + try: + group_id = int(raw_group_id) + except (TypeError, ValueError): + return jsonify({'error': 'Ungültige Gruppe'}), 400 + if group_id not in allowed_groups: + return jsonify({'error': 'Gruppe nicht gefunden'}), 400 + + normalized[account_id] = group_id + + changes = [] + for account_id, group_id in normalized.items(): + current = db.execute( + '''SELECT group_id FROM group_accounts + WHERE tenant_id = ? AND account_id = ?''', + (g.tenant_id, account_id) + ).fetchone() + current_group_id = current['group_id'] if current else None + if current_group_id == group_id: + continue + + db.execute( + 'DELETE FROM group_accounts WHERE tenant_id = ? AND account_id = ?', + (g.tenant_id, account_id) + ) + if group_id is not None: + db.execute( + '''INSERT INTO group_accounts (tenant_id, group_id, account_id) + VALUES (?, ?, ?)''', + (g.tenant_id, group_id, account_id) + ) + changes.append({'account_id': account_id, 'group_id': group_id}) + + if changes: + db.commit() + log_transaction( + 'group.assignment_update', 'group', None, + {'changes': changes} + ) + GroupsService.invalidate(g.tenant_id) + GroupsService.load_from_db(g.tenant_id) + + notify_reload('Gruppenzuordnungen wurden geändert.') + return jsonify({'success': True, 'changes': len(changes)}) diff --git a/CMBNet/cmbnet/db/database.py b/CMBNet/cmbnet/db/database.py index df365b6..ffff2f9 100644 --- a/CMBNet/cmbnet/db/database.py +++ b/CMBNet/cmbnet/db/database.py @@ -23,6 +23,104 @@ def close_db(e=None): db.close() +def ensure_schema(): + """Ergänzt bestehende Datenbanken um das Gruppen-Account-Zuordnungsmodell. + + Neue Installationen erhalten das Schema über ``migrations/schema.sql``. + Für bestehende Datenbanken wird die frühere 1:1-Verknüpfung + ``groups.account_id`` in die neue Tabelle ``group_accounts`` übernommen + und die alte Spalte durch einen Tabellen-Neubau entfernt. + """ + db = get_db() + groups_table = db.execute( + "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'groups'" + ).fetchone() + if not groups_table: + return + + db.executescript(''' + CREATE TABLE IF NOT EXISTS group_accounts ( + tenant_id INTEGER NOT NULL, + group_id INTEGER NOT NULL, + account_id INTEGER NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (tenant_id, group_id, account_id), + UNIQUE (tenant_id, account_id), + FOREIGN KEY (tenant_id) REFERENCES tenants(id), + FOREIGN KEY (group_id) REFERENCES groups(id), + FOREIGN KEY (account_id) REFERENCES accounts(id) + ); + CREATE INDEX IF NOT EXISTS idx_group_accounts_group + ON group_accounts(tenant_id, group_id); + CREATE INDEX IF NOT EXISTS idx_groups_tenant ON groups(tenant_id); + ''') + db.commit() + + columns = { + row['name'] for row in db.execute('PRAGMA table_info(groups)').fetchall() + } + if 'account_id' not in columns: + return + + db.execute( + '''INSERT OR IGNORE INTO group_accounts (tenant_id, group_id, account_id) + SELECT g.tenant_id, g.id, g.account_id + FROM groups g + JOIN accounts a + ON a.id = g.account_id AND a.tenant_id = g.tenant_id + WHERE g.account_id IS NOT NULL AND a.role = 'Gruppe' ''' + ) + db.commit() + + # SQLite kann eine UNIQUE-Spalte nicht per ALTER TABLE DROP COLUMN + # entfernen. Deshalb wird die Tabelle ohne die alte Spalte neu aufgebaut. + # Die bereits kopierten Zuordnungen bleiben dabei erhalten. + fk_enabled = db.execute('PRAGMA foreign_keys').fetchone()[0] + db.execute('PRAGMA foreign_keys = OFF') + try: + db.execute('DROP TABLE IF EXISTS groups_new') + db.execute('BEGIN IMMEDIATE') + db.execute(''' + CREATE TABLE groups_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + tenant_id INTEGER NOT NULL, + aliasname TEXT, + state TEXT NOT NULL DEFAULT 'offen' + CHECK(state IN ('offen', 'unterwegs', 'online', 'pausierend', 'fertig')), + last_lat REAL, + last_lon REAL, + last_pos_at TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (tenant_id) REFERENCES tenants(id) + ) + ''') + db.execute(''' + INSERT INTO groups_new + (id, tenant_id, aliasname, state, last_lat, last_lon, + last_pos_at, created_at, updated_at) + SELECT id, tenant_id, aliasname, state, last_lat, last_lon, + last_pos_at, created_at, updated_at + FROM groups + ''') + db.execute('DROP TABLE groups') + db.execute('ALTER TABLE groups_new RENAME TO groups') + db.execute('CREATE INDEX IF NOT EXISTS idx_groups_tenant ON groups(tenant_id)') + db.commit() + except sqlite3.DatabaseError as exc: + db.rollback() + try: + db.execute('DROP TABLE IF EXISTS groups_new') + db.commit() + except sqlite3.DatabaseError: + pass + current_app.logger.warning( + 'groups.account_id konnte nicht entfernt werden: %s', exc + ) + finally: + db.execute('PRAGMA foreign_keys = ON' if fk_enabled else 'PRAGMA foreign_keys = OFF') + + def init_db(): """Initialisiert die Datenbank mit dem Schema""" db = get_db() @@ -30,6 +128,7 @@ def init_db(): with open(schema_path, 'r', encoding='utf-8') as f: db.executescript(f.read()) db.commit() + ensure_schema() @click.command('init-db') diff --git a/CMBNet/cmbnet/models/accounts.py b/CMBNet/cmbnet/models/accounts.py index 8c9659e..09b6100 100644 --- a/CMBNet/cmbnet/models/accounts.py +++ b/CMBNet/cmbnet/models/accounts.py @@ -48,6 +48,13 @@ class AccountModel: 'UPDATE accounts SET role = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?', (role, account_id, tenant_id) ) + # Ein Account, der nicht mehr die Rolle "Gruppe" hat, darf keine + # Gruppenzuordnung behalten. + if role != 'Gruppe': + db.execute( + 'DELETE FROM group_accounts WHERE tenant_id = ? AND account_id = ?', + (tenant_id, account_id) + ) db.commit() @staticmethod @@ -62,5 +69,9 @@ class AccountModel: @staticmethod def delete(account_id, tenant_id): db = get_db() + db.execute( + 'DELETE FROM group_accounts WHERE tenant_id = ? AND account_id = ?', + (tenant_id, account_id) + ) db.execute('DELETE FROM accounts WHERE id = ? AND tenant_id = ?', (account_id, tenant_id)) db.commit() diff --git a/CMBNet/cmbnet/models/groups.py b/CMBNet/cmbnet/models/groups.py index 5e01e65..641251f 100644 --- a/CMBNet/cmbnet/models/groups.py +++ b/CMBNet/cmbnet/models/groups.py @@ -25,16 +25,44 @@ class GroupModel: def get_by_account_id(account_id, tenant_id): db = get_db() return db.execute( - 'SELECT * FROM groups WHERE account_id = ? AND tenant_id = ?', + '''SELECT g.* FROM groups g + JOIN group_accounts ga + ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id + WHERE ga.account_id = ? AND g.tenant_id = ?''', (account_id, tenant_id) ).fetchone() - + @staticmethod - def create(tenant_id, aliasname, account_id=None, state='offen'): + def get_account_ids_for_group(group_id, tenant_id): + db = get_db() + rows = db.execute( + '''SELECT account_id FROM group_accounts + WHERE group_id = ? AND tenant_id = ? + ORDER BY account_id''', + (group_id, tenant_id) + ).fetchall() + return [row['account_id'] for row in rows] + + @staticmethod + def get_account_ids_by_group(tenant_id): + db = get_db() + rows = db.execute( + '''SELECT group_id, account_id FROM group_accounts + WHERE tenant_id = ? + ORDER BY group_id, account_id''', + (tenant_id,) + ).fetchall() + result = {} + for row in rows: + result.setdefault(row['group_id'], []).append(row['account_id']) + return result + + @staticmethod + def create(tenant_id, aliasname, state='offen'): db = get_db() cursor = db.execute( - 'INSERT INTO groups (tenant_id, aliasname, account_id, state) VALUES (?, ?, ?, ?)', - (tenant_id, aliasname, account_id, state) + 'INSERT INTO groups (tenant_id, aliasname, state) VALUES (?, ?, ?)', + (tenant_id, aliasname, state) ) db.commit() return cursor.lastrowid @@ -42,7 +70,7 @@ class GroupModel: @staticmethod def update(group_id, tenant_id, **kwargs): db = get_db() - allowed = ['aliasname', 'state', 'account_id', 'last_lat', 'last_lon', 'last_pos_at'] + allowed = ['aliasname', 'state', 'last_lat', 'last_lon', 'last_pos_at'] updates = [] values = [] for k, v in kwargs.items(): @@ -59,5 +87,9 @@ class GroupModel: @staticmethod def delete(group_id, tenant_id): db = get_db() + db.execute( + 'DELETE FROM group_accounts WHERE group_id = ? AND tenant_id = ?', + (group_id, tenant_id) + ) db.execute('DELETE FROM groups WHERE id = ? AND tenant_id = ?', (group_id, tenant_id)) db.commit() diff --git a/CMBNet/cmbnet/services/groups_service.py b/CMBNet/cmbnet/services/groups_service.py index 8d18250..fd910e0 100644 --- a/CMBNet/cmbnet/services/groups_service.py +++ b/CMBNet/cmbnet/services/groups_service.py @@ -15,9 +15,11 @@ class GroupsService: def load_from_db(cls, tenant_id): """Lädt alle Gruppen eines Mandanten aus der Datenbank in den Cache""" groups = GroupModel.get_all_by_tenant(tenant_id) - if tenant_id not in cls._cache: - cls._cache[tenant_id] = {} - + memberships = GroupModel.get_account_ids_by_group(tenant_id) + # Vollständig neu aufbauen, damit gelöschte Gruppen nicht im Cache + # zurückbleiben. + cls._cache[tenant_id] = {} + for group in groups: cls._cache[tenant_id][group['id']] = { 'id': group['id'], @@ -27,7 +29,7 @@ class GroupsService: 'last_lat': group['last_lat'], 'last_lon': group['last_lon'], 'last_pos_at': group['last_pos_at'], - 'account_id': group['account_id'], + 'account_ids': memberships.get(group['id'], []), 'created_at': group['created_at'], 'updated_at': group['updated_at'] } @@ -43,7 +45,7 @@ class GroupsService: @classmethod def get_by_id(cls, tenant_id, group_id): """Gibt eine spezifische Gruppe aus dem Cache zurück""" - if tenant_id not in cls._cache: + if tenant_id not in cls._cache or not cls._cache[tenant_id]: cls.load_from_db(tenant_id) return cls._cache.get(tenant_id, {}).get(group_id) @@ -64,16 +66,19 @@ class GroupsService: group = cls.get_by_id(tenant_id, group_id) if not group: return False - return group.get('account_id') == account_id - + account_ids = {int(value) for value in group.get('account_ids', [])} + return int(account_id) in account_ids + @classmethod def get_accounts_for_group(cls, group_id, tenant_id): """Gibt alle mit einer Gruppe verknüpften Accounts zurück""" - group = cls.get_by_id(tenant_id, group_id) - if not group or not group.get('account_id'): - return [] - account = AccountModel.get_by_id(group['account_id'], tenant_id) - return [account] if account else [] + account_ids = GroupModel.get_account_ids_for_group(group_id, tenant_id) + accounts = [] + for account_id in account_ids: + account = AccountModel.get_by_id(account_id, tenant_id) + if account: + accounts.append(account) + return accounts @classmethod def get_streets_for_group(cls, group_id, tenant_id): diff --git a/CMBNet/cmbnet/utils/helpers.py b/CMBNet/cmbnet/utils/helpers.py index e649a55..9f1d535 100644 --- a/CMBNet/cmbnet/utils/helpers.py +++ b/CMBNet/cmbnet/utils/helpers.py @@ -1,7 +1,7 @@ """ Hilfsfunktionen für CMBNet """ -from flask import g +from flask import current_app, g import json @@ -15,6 +15,33 @@ def get_current_account(): return getattr(g, 'current_account', None) +def notify_reload(text, tenant_id=None, sender_id=None): + """Sendet eine interne Code-99-Nachricht an alle Clients eines Mandanten.""" + from cmbnet.ws import broker + from cmbnet.ws.protocol import WSMessage + + tenant_id = tenant_id if tenant_id is not None else get_tenant_id() + account = get_current_account() + if sender_id is None and account: + sender_id = account['id'] + + if not tenant_id or not sender_id: + return False + + try: + broker.route_message( + tenant_id, + WSMessage(sender_id=sender_id, code=99, msg=str(text)) + ) + return True + except Exception as exc: + try: + current_app.logger.warning('Code-99-Nachricht konnte nicht gesendet werden: %s', exc) + except Exception: + pass + return False + + def log_transaction(action, entity_type, entity_id, details=None): """ Schreibt einen Eintrag ins Transaktionslog diff --git a/CMBNet/cmbnet/views/main.py b/CMBNet/cmbnet/views/main.py index 7f49537..7baedb9 100644 --- a/CMBNet/cmbnet/views/main.py +++ b/CMBNet/cmbnet/views/main.py @@ -3,7 +3,7 @@ Haupt-Views """ from flask import ( Blueprint, render_template, g, redirect, url_for, request, jsonify, - make_response, session + make_response, session, current_app ) from cmbnet.auth import login_required, role_required @@ -65,28 +65,23 @@ def manifest(tenant=None, **kwargs): """Liefert das Web-App-Manifest für die mobilen Views.""" account = getattr(g, 'current_account', None) role = account['role'] if account else session.get('role') + title = current_app.config.get('DISPLAY_TITLE', '20*C+M+B+27') if role == 'Dispatcher': start_url = url_for('views.dispatcher_mobil', tenant=tenant) - name = 'CMBNet Dispatcher' - short_name = 'CMB Dispo' elif role == 'Gruppe': start_url = url_for('views.gruppen', tenant=tenant) - name = 'CMBNet Gruppe' - short_name = 'CMB Gruppe' else: start_url = url_for('views.index', tenant=tenant) - name = 'CMBNet' - short_name = 'CMBNet' icon_192 = url_for('static', filename='img/icon-192.png') icon_512 = url_for('static', filename='img/icon-512.png') payload = { 'id': start_url, - 'name': name, - 'short_name': short_name, - 'description': 'CMBNet – mobile Einsatzansicht', + 'name': title, + 'short_name': title, + 'description': f'{title} – mobile Einsatzansicht', 'lang': 'de', 'start_url': start_url, 'scope': url_for('views.index', tenant=tenant), diff --git a/CMBNet/cmbnet/ws/broker.py b/CMBNet/cmbnet/ws/broker.py index 8f34845..c2d73b8 100644 --- a/CMBNet/cmbnet/ws/broker.py +++ b/CMBNet/cmbnet/ws/broker.py @@ -7,6 +7,8 @@ die Nachricht zu. Wichtige Regeln aus der Spezifikation: - Code < 100: rein interne Nachrichten (z. B. Authentifizierung, Heartbeat). + Code 99 ist eine serverinterne Aufforderung an alle Clients, die Seite + wegen geänderter Daten neu zu laden. - Code 100/200/300: State- bzw. Positionsänderungen an Dispatcher, Beobachter und die jeweils betroffene Gruppe. - Code 1000/1100/2000: Chat-/Broadcast-Nachrichten. Diese werden persistiert, @@ -57,10 +59,13 @@ class WebSocketBroker: role = account['role'] # Für Gruppen-Accounts die zugehörige Gruppe ermitteln. Ein Account der - # Rolle "Gruppe" ist genau einer Gruppe zugeordnet. + # Rolle "Gruppe" ist höchstens einer Gruppe zugeordnet. if group_id is None and role == 'Gruppe': group = db.execute( - 'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?', + '''SELECT g.id FROM groups g + JOIN group_accounts ga + ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id + WHERE ga.account_id = ? AND g.tenant_id = ?''', (account_id, tenant_id) ).fetchone() group_id = group['id'] if group else None @@ -226,7 +231,10 @@ class WebSocketBroker: return True if role == 'Gruppe': group = db.execute( - 'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?', + '''SELECT g.id FROM groups g + JOIN group_accounts ga + ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id + WHERE ga.account_id = ? AND g.tenant_id = ?''', (account_id, tenant_id) ).fetchone() return bool(group and msg_row['receiver_id'] == group['id']) @@ -238,7 +246,10 @@ class WebSocketBroker: return True if role == 'Gruppe': group = db.execute( - 'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?', + '''SELECT g.id FROM groups g + JOIN group_accounts ga + ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id + WHERE ga.account_id = ? AND g.tenant_id = ?''', (account_id, tenant_id) ).fetchone() payload = self._payload(msg_row) @@ -293,6 +304,14 @@ class WebSocketBroker: self._deliver(tenant_id, message, sender) return + # Code 99 ist eine serverinterne Aufforderung zum Neuladen. Clients + # dürfen diesen Code nicht selbst auslösen. + if code == 99: + if apply_business: + return + self._deliver(tenant_id, message, sender) + return + # Sonstige interne Codes (< 100) werden nicht an die Oberfläche gegeben. if code < 100: return @@ -444,8 +463,14 @@ class WebSocketBroker: return False # Ein Gruppen-Account darf nur den Zustand seiner eigenen Gruppe ändern. - if sender['role'] == 'Gruppe' and group['account_id'] != sender['id']: - return False + if sender['role'] == 'Gruppe': + linked = db.execute( + '''SELECT 1 FROM group_accounts + WHERE tenant_id = ? AND group_id = ? AND account_id = ?''', + (tenant_id, group_id, sender['id']) + ).fetchone() + if not linked: + return False new_state = payload.get('state') if new_state not in ('offen', 'unterwegs', 'online', 'pausierend', 'fertig'): @@ -495,8 +520,14 @@ class WebSocketBroker: if not group: return False - if sender['role'] == 'Gruppe' and group['account_id'] != sender['id']: - return False + if sender['role'] == 'Gruppe': + linked = db.execute( + '''SELECT 1 FROM group_accounts + WHERE tenant_id = ? AND group_id = ? AND account_id = ?''', + (tenant_id, group_id, sender['id']) + ).fetchone() + if not linked: + return False try: lat = float(payload.get('lat')) @@ -583,7 +614,10 @@ class WebSocketBroker: } if sender and sender['role'] == 'Gruppe': group = db.execute( - 'SELECT id, aliasname FROM groups WHERE account_id = ? AND tenant_id = ?', + '''SELECT g.id, g.aliasname FROM groups g + JOIN group_accounts ga + ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id + WHERE ga.account_id = ? AND g.tenant_id = ?''', (sender['id'], tenant_id) ).fetchone() if group: @@ -723,14 +757,18 @@ class WebSocketBroker: def add_group_account(group_id): if not group_id: return - group = db.execute( - 'SELECT account_id FROM groups WHERE id = ? AND tenant_id = ?', + rows = db.execute( + '''SELECT account_id FROM group_accounts + WHERE group_id = ? AND tenant_id = ?''', (group_id, tenant_id) - ).fetchone() - if group and group['account_id']: - recipients.add(group['account_id']) + ).fetchall() + recipients.update(row['account_id'] for row in rows) - if code == 100: + if code == 99: + # Alle verbundenen Clients des Mandanten müssen die Seite neu laden. + add_accounts(('Gast', 'Beobachter', 'Gruppe', 'Dispatcher', 'Administrator')) + + elif code == 100: # Dispatcher, Gast, Beobachter + die mit der Straße verknüpfte # Gruppe. Bei einem Gruppenwechsel werden sowohl die alte als auch # die neue Gruppe benachrichtigt. @@ -836,7 +874,10 @@ class WebSocketBroker: if group_id is None and sender is not None and message.code in (200, 300, 2000): # Bei Gruppen-Nachrichten ist der Absender die Gruppe selbst. group = get_db().execute( - 'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?', + '''SELECT g.id FROM groups g + JOIN group_accounts ga + ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id + WHERE ga.account_id = ? AND g.tenant_id = ?''', (sender['id'], tenant_id) ).fetchone() group_id = group['id'] if group else None diff --git a/CMBNet/config.py b/CMBNet/config.py index 6321744..e8bff70 100644 --- a/CMBNet/config.py +++ b/CMBNet/config.py @@ -8,6 +8,10 @@ class Config: DATABASE_PATH = os.environ.get('CMBNET_DATABASE', str(BASE_DIR / 'instance' / 'cmbnet.sqlite3')) TENANTS = ['BV', 'RV', 'SV'] DEFAULT_TENANT = 'RV' + + # Intern heißt das Projekt weiterhin CMBNet. In den Web-Views wird + # stattdessen dieser Titel angezeigt. + DISPLAY_TITLE = '20*C+M+B+27' WS_HEARTBEAT_INTERVAL = int(os.environ.get('CMBNET_WS_HEARTBEAT_INTERVAL', '60')) WS_HEARTBEAT_TIMEOUT = 15 diff --git a/CMBNet/migrations/schema.sql b/CMBNet/migrations/schema.sql index 921f0a0..137b726 100644 --- a/CMBNet/migrations/schema.sql +++ b/CMBNet/migrations/schema.sql @@ -31,10 +31,22 @@ CREATE TABLE IF NOT EXISTS groups ( last_lat REAL, last_lon REAL, last_pos_at TIMESTAMP, - account_id INTEGER UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (tenant_id) REFERENCES tenants(id) +); + +-- Zuordnung von Gruppen-Accounts zu Gruppen (1:n: eine Gruppe, viele Accounts). +-- Ein Account der Rolle "Gruppe" darf höchstens einer Gruppe zugeordnet sein. +CREATE TABLE IF NOT EXISTS group_accounts ( + tenant_id INTEGER NOT NULL, + group_id INTEGER NOT NULL, + account_id INTEGER NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (tenant_id, group_id, account_id), + UNIQUE (tenant_id, account_id), FOREIGN KEY (tenant_id) REFERENCES tenants(id), + FOREIGN KEY (group_id) REFERENCES groups(id), FOREIGN KEY (account_id) REFERENCES accounts(id) ); @@ -145,6 +157,8 @@ CREATE TABLE IF NOT EXISTS transaction_log ( -- Indizes für Performance CREATE INDEX IF NOT EXISTS idx_accounts_tenant ON accounts(tenant_id); CREATE INDEX IF NOT EXISTS idx_groups_tenant ON groups(tenant_id); +CREATE INDEX IF NOT EXISTS idx_group_accounts_group + ON group_accounts(tenant_id, group_id); CREATE INDEX IF NOT EXISTS idx_streets_tenant ON streets(tenant_id); CREATE INDEX IF NOT EXISTS idx_street_house_numbers_lookup ON street_house_numbers(tenant_id, street_name, house_number); diff --git a/CMBNet/static/css/dispatcher.css b/CMBNet/static/css/dispatcher.css index ef42435..c2a36cd 100644 --- a/CMBNet/static/css/dispatcher.css +++ b/CMBNet/static/css/dispatcher.css @@ -103,11 +103,6 @@ body.dispatcher-page main.container { flex: 1 1 0; } -.clock-row > #speakerButton { - flex: 0 0 auto; - margin: 0 0.25rem; -} - .clock-date { display: flex; align-items: baseline; @@ -254,6 +249,9 @@ body.dispatcher-page main.container { } .icon-button { + --background-color: var(--primary); + --border-color: var(--primary); + --color: var(--primary-inverse); display: inline-flex; align-items: center; justify-content: center; @@ -262,22 +260,28 @@ body.dispatcher-page main.container { height: 2.5rem; margin: 0; padding: 0; + border: var(--border-width) solid var(--border-color); border-radius: 0.55rem; + background-color: var(--background-color); + color: var(--color); font-size: 1.2rem; line-height: 1; text-decoration: none; } -a.icon-button { - border: 1px solid var(--dispatcher-border-strong); - background: var(--form-element-background-color, #fff); - color: inherit; +a.icon-button:is(:hover, :focus-visible) { + --background-color: var(--primary-hover); + --border-color: var(--primary-hover); +} + +a.icon-button:focus-visible { + box-shadow: 0 0 0 var(--outline-width) var(--primary-focus); } .icon-button.active { - background: #2f6fdb; - border-color: #2f6fdb; - color: #fff; + --background-color: var(--primary-hover); + --border-color: var(--primary-hover); + --color: var(--primary-inverse); } .connection-status { @@ -294,6 +298,41 @@ a.icon-button { color: #b42318; } +.header-status-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 0.75rem; + margin-top: 0.45rem; +} + +.header-status-row .connection-status { + flex: 1 1 auto; + margin-top: 0; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.header-action-buttons { + display: flex; + flex: 0 0 auto; + align-items: center; + gap: 0.5rem; +} + +.header-action-buttons .icon-button { + width: 2.25rem; + height: 2.25rem; +} + +.group-assignment-button svg { + display: block; + width: 1.8rem; + height: 1.35rem; +} + /* ---------- Accordion ---------- */ .group-accordion { @@ -311,7 +350,8 @@ a.icon-button { } .group-item { - margin: 0 0 0.55rem; + --group-control-size: 2rem; + margin: 0 0 0.45rem; border: 1px solid var(--dispatcher-border); border-radius: 0.65rem; background: var(--card-background-color, #fff); @@ -321,8 +361,8 @@ a.icon-button { .group-item > summary { display: flex; align-items: center; - gap: 0.55rem; - padding: 0.65rem 0.75rem; + gap: 0.45rem; + padding: 0.5rem 0.65rem; cursor: pointer; list-style: none; user-select: none; @@ -371,67 +411,93 @@ a.icon-button { } .group-details { - padding: 0 0.75rem 0.75rem; + padding: 0 0.65rem 0.55rem; display: flex; flex-direction: column; - gap: 0.6rem; + gap: 0.4rem; } -.group-position-row { +.group-controls { display: flex; align-items: center; - gap: 0.5rem; + gap: 0.25rem; } -.group-position-row .icon-button { - width: 2.25rem; - height: 2.25rem; - font-size: 1.05rem; +.group-controls .icon-button { + width: var(--group-control-size); + height: var(--group-control-size); + font-size: 1rem; } -.group-position-row progress { - flex: 1 1 auto; - width: auto; - height: 0.75rem; - margin: 0; +/* Circular freshness indicator: a full circle is 100 % / Live. */ +.group-progress-circle { + --progress: 0; + --progress-color: #2f6fdb; + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + width: var(--group-control-size); + height: var(--group-control-size); + border-radius: 50%; + background: conic-gradient( + var(--progress-color) calc(var(--progress) * 1%), + var(--dispatcher-subtle-bg) 0 + ); } -.group-position-meta { - font-size: 0.72rem; +.group-progress-circle.is-live { + --progress-color: #2e9e4f; +} + +.group-progress-text { + display: flex; + align-items: center; + justify-content: center; + width: calc(100% - 0.4rem); + height: calc(100% - 0.4rem); + border-radius: 50%; + background: var(--card-background-color, #fff); color: var(--muted-color, #5b6771); + font-size: 0.5rem; + font-weight: 700; + line-height: 1; + font-variant-numeric: tabular-nums; + white-space: nowrap; } -.group-actions { - display: flex; - align-items: center; - gap: 0.5rem; +.group-progress-circle.is-live .group-progress-text { + color: #18794e; } .group-crosshair, .group-streets, .group-alias { - width: 2.35rem; - height: 2.35rem; + width: var(--group-control-size); + height: var(--group-control-size); margin: 0; padding: 0; - font-size: 1.1rem; + font-size: 1rem; } -.group-state-select { +.group-controls select.group-state-select { flex: 1 1 auto; width: auto; min-width: 0; - height: 2.35rem; + height: var(--group-control-size); margin: 0; - padding: 0.25rem 1.8rem 0.25rem 0.55rem; - font-size: 0.78rem; + padding: 0.15rem 1.35rem 0.15rem 0.4rem; + font-size: 0.7rem; } .group-message { + height: 1.9rem; margin: 0; + padding: 0.2rem 0.5rem; cursor: pointer; background: var(--dispatcher-subtle-bg); - font-size: 0.82rem; + font-size: 0.78rem; } .group-message:focus { @@ -527,6 +593,142 @@ dialog article > .dialog-body { overscroll-behavior: contain; } +/* Gruppen-Accounts den Gruppen zuordnen */ +dialog.group-assignment-dialog article { + width: min(72rem, 94vw); + max-width: 94vw; +} + +.group-assignment-hint { + margin: 0 0 0.65rem; + font-size: 0.8rem; + color: var(--muted-color, #5b6771); +} + +.group-assignment-scroll { + max-width: 100%; + max-height: min(58dvh, 34rem); + overflow: auto; + overscroll-behavior: contain; + border: 1px solid var(--dispatcher-border); + border-radius: 0.55rem; +} + +.group-assignment-table { + --assignment-choice-column-width: 4.8rem; + width: 100%; + margin: 0; + border-collapse: separate; + border-spacing: 0; + font-size: 0.78rem; +} + +.group-assignment-table th, +.group-assignment-table td { + padding: 0.38rem 0.55rem; + border-bottom: 1px solid var(--dispatcher-border); + text-align: center; + vertical-align: middle; +} + +.group-assignment-table tbody tr:last-child th, +.group-assignment-table tbody tr:last-child td { + border-bottom: 0; +} + +.group-assignment-table .assignment-account-header, +.group-assignment-table .assignment-account-name { + position: sticky; + left: 0; + z-index: 2; + min-width: 4.5rem; + max-width: 16rem; + background: var(--card-background-color, #fff); + text-align: right; + white-space: nowrap; +} + +.group-assignment-table .assignment-account-header { + z-index: 3; + vertical-align: bottom; +} + +.group-assignment-table .assignment-account-name { + font-weight: 600; +} + +.group-assignment-table .assignment-spacer-header, +.group-assignment-table .assignment-spacer-cell { + width: 100%; + min-width: var(--assignment-right-space, 2rem); + padding: 0; + border: 0; + background: transparent; +} + +.group-assignment-table .not-participating-header, +.group-assignment-table .not-participating-cell { + background: rgba(214, 40, 40, 0.12); + border-right: 2px solid rgba(214, 40, 40, 0.45); + border-left: 2px solid rgba(214, 40, 40, 0.45); +} + +.group-assignment-table .not-participating-header { + color: #b42318; + font-weight: 700; +} + +.group-assignment-table .group-column-header, +.group-assignment-table .not-participating-header { + position: relative; + width: var(--assignment-choice-column-width); + min-width: var(--assignment-choice-column-width); + height: var(--group-header-height, 6.2rem); + padding: 0 0.2rem 0.4rem; + vertical-align: bottom; + overflow: visible; +} + +.group-assignment-table .group-column-header { + border-left: 1px solid var(--dispatcher-border); +} + +.group-assignment-table .not-participating-header .group-column-label { + font-weight: 700; +} + +.group-assignment-table .group-column-label { + position: absolute; + left: 0.7rem; + bottom: 0.55rem; + display: block; + transform: rotate(-45deg); + transform-origin: left bottom; + white-space: nowrap; + font-size: 0.68rem; + font-weight: 600; + line-height: 1; +} + +.group-assignment-table .group-assignment-cell, +.group-assignment-table .not-participating-cell { + width: var(--assignment-choice-column-width); + min-width: var(--assignment-choice-column-width); +} + +.group-assignment-table input[type="radio"] { + margin: 0; +} + +.group-assignment-empty { + margin: 0; + padding: 1rem; + border-radius: 0.5rem; + background: var(--dispatcher-subtle-bg); + color: var(--muted-color, #5b6771); + text-align: center; +} + /* Nicht-modaler Straßendialog: bleibt neben der Karte bedienbar. */ dialog.group-streets-dialog { position: fixed; @@ -851,11 +1053,6 @@ dialog.group-streets-dialog.is-dragging article header { height: 2.25rem; } - .clock-row > #speakerButton { - width: 2.25rem; - height: 2.25rem; - } - .clock-time { font-size: 1.55rem; } @@ -894,6 +1091,34 @@ html[data-theme="dark"] .connection-status.disconnected { color: #ff8b8b; } +html[data-theme="dark"] .group-assignment-table .assignment-account-header, +html[data-theme="dark"] .group-assignment-table .assignment-account-name { + background: var(--card-background-color, #111827); +} + +html[data-theme="dark"] .group-assignment-table .not-participating-header, +html[data-theme="dark"] .group-assignment-table .not-participating-cell { + background: rgba(255, 99, 99, 0.17); + border-right-color: rgba(255, 139, 139, 0.5); + border-left-color: rgba(255, 139, 139, 0.5); +} + +html[data-theme="dark"] .group-assignment-table .not-participating-header { + color: #ffb4b4; +} + +html[data-theme="dark"] .group-progress-circle { + --progress-color: #58a6ff; +} + +html[data-theme="dark"] .group-progress-circle.is-live { + --progress-color: #5bd6a2; +} + +html[data-theme="dark"] .group-progress-circle.is-live .group-progress-text { + color: #5bd6a2; +} + html[data-theme="dark"] .street-search-status.error { color: #ff8b8b; } diff --git a/CMBNet/static/css/style.css b/CMBNet/static/css/style.css index 8b532c3..d16a518 100644 --- a/CMBNet/static/css/style.css +++ b/CMBNet/static/css/style.css @@ -140,3 +140,62 @@ html[data-theme="dark"] article.success { border-color: #23633f; color: #9be7b5; } + +/* Code-99-Reload-Hinweis: bewusst auffällig, rot mit weißer Schrift. */ +dialog.reload-notice-dialog { + max-width: 94vw; +} + +dialog.reload-notice-dialog article { + width: min(36rem, 94vw); + max-width: 94vw; + background: #b42318; + border: 2px solid #f4b4b0; + color: #ffffff; +} + +dialog.reload-notice-dialog article > header, +dialog.reload-notice-dialog article > footer { + background: transparent; +} + +dialog.reload-notice-dialog article > header { + border-bottom: 1px solid rgba(255, 255, 255, 0.35); +} + +dialog.reload-notice-dialog h3 { + margin: 0; + color: #ffffff; +} + +.reload-notice-body { + padding: 0.35rem 0 0.75rem; +} + +.reload-notice-body p { + margin: 0; + color: #ffffff; +} + +.reload-notice-body p + p { + margin-top: 0.75rem; +} + +.reload-notice-hint { + font-weight: 700; +} + +dialog.reload-notice-dialog article > footer { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 0.5rem; + border-top: 1px solid rgba(255, 255, 255, 0.35); + padding-top: 0.75rem; +} + +dialog.reload-notice-dialog article > footer button { + width: auto; + margin: 0; + flex: 0 0 auto; +} diff --git a/CMBNet/static/js/reload_notice.js b/CMBNet/static/js/reload_notice.js new file mode 100644 index 0000000..229c546 --- /dev/null +++ b/CMBNet/static/js/reload_notice.js @@ -0,0 +1,174 @@ +/* + * Gemeinsamer Hinweis für Code 99: Daten wurden geändert, Seite neu laden. + * + * Dispatcher- und Mobil-Views rufen window.showReloadNotice(text) aus ihrer + * bestehenden WebSocket-Verbindung auf. Admin-Seiten erhalten über den + * optionalen Watcher eine eigene Verbindung, damit auch dort Änderungen + * anderer Administratoren sichtbar werden. + */ +(function () { + 'use strict'; + + const HINT = 'Die Webseite muss neu geladen werden, damit die Änderungen sichtbar werden.'; + let dialog = null; + let adminSocket = null; + let adminRetryTimer = null; + let adminStopped = false; + + function ensureDialog() { + if (dialog) return dialog; + + dialog = document.createElement('dialog'); + dialog.id = 'reloadNoticeModal'; + dialog.className = 'reload-notice-dialog'; + dialog.setAttribute('aria-labelledby', 'reloadNoticeTitle'); + + const article = document.createElement('article'); + + const header = document.createElement('header'); + const title = document.createElement('h3'); + title.id = 'reloadNoticeTitle'; + title.textContent = 'Daten geändert'; + header.appendChild(title); + + const body = document.createElement('div'); + body.className = 'reload-notice-body'; + const text = document.createElement('p'); + text.id = 'reloadNoticeText'; + text.textContent = 'Die Daten wurden geändert.'; + const hint = document.createElement('p'); + hint.className = 'reload-notice-hint'; + hint.textContent = HINT; + body.append(text, hint); + + const footer = document.createElement('footer'); + + const laterButton = document.createElement('button'); + laterButton.type = 'button'; + laterButton.className = 'secondary'; + laterButton.textContent = 'Später'; + laterButton.addEventListener('click', closeReloadNotice); + + const restartButton = document.createElement('button'); + restartButton.type = 'button'; + restartButton.textContent = 'Neustarten'; + restartButton.addEventListener('click', () => window.location.reload()); + + footer.append(laterButton, restartButton); + article.append(header, body, footer); + dialog.appendChild(article); + document.body.appendChild(dialog); + + // Escape entspricht "Später": Dialog schließen, keine weitere Aktion. + dialog.addEventListener('cancel', event => { + event.preventDefault(); + closeReloadNotice(); + }); + + return dialog; + } + + function closeReloadNotice() { + if (dialog && dialog.open) dialog.close(); + } + + function showReloadNotice(text) { + const currentDialog = ensureDialog(); + const textElement = currentDialog.querySelector('#reloadNoticeText'); + if (textElement) { + textElement.textContent = text && String(text).trim() + ? String(text).trim() + : 'Die Daten wurden geändert.'; + } + if (!currentDialog.open) { + if (typeof currentDialog.showModal === 'function') { + currentDialog.showModal(); + } else { + currentDialog.setAttribute('open', ''); + } + } + } + + function appUrl(path) { + if (typeof window.CMBNET_APP_URL === 'function') { + return window.CMBNET_APP_URL(path); + } + const base = (window.CMBNET_BASE_URL || '').replace(/\/+$/, ''); + const clean = String(path == null ? '' : path).replace(/^\/+/, ''); + return clean ? `${base}/${clean}` : (base || '/'); + } + + function scheduleAdminReconnect() { + if (adminStopped || adminRetryTimer) return; + adminRetryTimer = setTimeout(() => { + adminRetryTimer = null; + connectAdminWatcher(); + }, 3000); + } + + async function connectAdminWatcher() { + if (adminStopped) return; + const tenant = window.CMBNET_TENANT || ''; + if (!tenant) return; + + try { + const response = await fetch(appUrl(`${tenant}/api/auth/ws-token`), { + credentials: 'same-origin' + }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const data = await response.json(); + if (!data.token) throw new Error('Kein WebSocket-Token'); + + const wsUrl = `${window.location.protocol === 'https:' ? 'wss' : 'ws'}://` + + `${window.location.host}${appUrl(`${tenant}/ws`)}`; + const ws = new WebSocket(wsUrl); + adminSocket = ws; + + ws.addEventListener('open', () => { + ws.send(JSON.stringify({code: 0, msg: data.token})); + }); + + ws.addEventListener('message', event => { + let message; + try { + message = JSON.parse(event.data); + } catch (error) { + return; + } + if (Number(message.code) !== 99) return; + const text = typeof message.msg === 'string' + ? message.msg + : ''; + showReloadNotice(text); + }); + + ws.addEventListener('close', () => { + if (adminSocket === ws) adminSocket = null; + scheduleAdminReconnect(); + }); + + ws.addEventListener('error', () => { + if (adminSocket === ws) adminSocket = null; + scheduleAdminReconnect(); + }); + } catch (error) { + scheduleAdminReconnect(); + } + } + + window.showReloadNotice = showReloadNotice; + window.closeReloadNotice = closeReloadNotice; + + document.addEventListener('DOMContentLoaded', () => { + ensureDialog(); + if (window.CMBNET_ADMIN_RELOAD_WATCH) { + connectAdminWatcher(); + } + }); + + window.addEventListener('beforeunload', () => { + adminStopped = true; + if (adminRetryTimer) clearTimeout(adminRetryTimer); + if (adminSocket) adminSocket.close(); + }); +})(); diff --git a/CMBNet/static/js/sw.js b/CMBNet/static/js/sw.js index 39524bc..14355d6 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-v1'; +const VERSION = 'cmbnet-pwa-v4'; const BASE = new URL('./', self.location).href; const SHELL_CACHE = `${VERSION}-shell`; const TILE_CACHE = `${VERSION}-tiles`; @@ -19,6 +19,7 @@ const PRECACHE_PATHS = [ 'static/css/mobile.css', 'static/js/leaflet.js', 'static/js/str2pl.js', + 'static/js/reload_notice.js', 'static/js/views/mobile.js', 'static/img/logo.png', 'static/img/icon-192.png', @@ -208,7 +209,7 @@ function offlineHtml() { -CMBNet – offline +20*C+M+B+27 – offline