""" Admin API Endpunkte """ from flask import Blueprint, request, jsonify, g, session from cmbnet.auth import role_required from cmbnet.db import get_db from cmbnet.auth import hash_password from cmbnet.models.accounts import AccountModel 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, 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 import json admin_api_bp = Blueprint('admin_api', __name__) # === ACCOUNTS === @admin_api_bp.route('/accounts', methods=['POST']) @role_required('Administrator') def create_account(**kwargs): data = request.get_json() name = data.get('name', '').strip() password = data.get('password', '') role = data.get('role', 'Gast') if not name or not password: return jsonify({'error': 'Name und Passwort erforderlich'}), 400 existing = AccountModel.get_by_name_and_tenant(name, g.tenant_id) if existing: return jsonify({'error': 'Account existiert bereits'}), 400 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}) @admin_api_bp.route('/accounts//role', methods=['POST']) @role_required('Administrator') 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}) @admin_api_bp.route('/accounts//password', methods=['POST']) @role_required('Administrator') def reset_password(account_id, **kwargs): data = request.get_json() password = data.get('password', '') 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}) # === GRUPPEN === @admin_api_bp.route('/gruppen', methods=['POST']) @role_required('Administrator') def create_group(**kwargs): data = request.get_json() or {} aliasname = str(data.get('aliasname') or '').strip() db = get_db() 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}) 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}) @admin_api_bp.route('/gruppen/', methods=['POST']) @role_required('Administrator') def update_group(group_id, **kwargs): data = request.get_json() or {} db = get_db() old = GroupModel.get_by_id(group_id, g.tenant_id) if not old: return jsonify({'error': 'Gruppe nicht gefunden'}), 404 updates = {} if 'aliasname' in data: updates['aliasname'] = data['aliasname'] allowed_states = {'offen', 'unterwegs', 'online', 'pausierend', 'fertig'} state_changed = False if 'state' in data: new_state = data['state'] if new_state not in allowed_states: return jsonify({'error': 'Ungültiger State'}), 400 if new_state != old['state']: updates['state'] = new_state state_changed = True if not updates: return jsonify({'success': True}) GroupModel.update(group_id, g.tenant_id, **updates) if state_changed: db.execute( 'INSERT INTO group_state_history (tenant_id, group_id, from_state, to_state, actor_account_id) VALUES (?, ?, ?, ?, ?)', (g.tenant_id, group_id, old['state'], updates['state'], session['account_id']) ) db.commit() msg = WSMessage(sender_id=session['account_id'], code=200, msg=json.dumps({'group_id': group_id, 'state': updates['state'], 'actor': session['account_id']})) try: broker.route_message(g.tenant_id, msg) except Exception as e: print(f'Broker error: {e}') 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}) @admin_api_bp.route('/gruppen//history') @role_required('Administrator') def group_history(group_id, **kwargs): db = get_db() history = db.execute( 'SELECT h.*, a.name as actor_name FROM group_state_history h LEFT JOIN accounts a ON h.actor_account_id = a.id WHERE h.group_id = ? AND h.tenant_id = ? ORDER BY h.created_at DESC', (group_id, g.tenant_id) ).fetchall() return jsonify([dict(row) for row in history]) @admin_api_bp.route('/gruppen//history//revert', methods=['POST']) @role_required('Administrator') 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}) @admin_api_bp.route('/gruppen//position/history/', methods=['POST']) @role_required('Administrator') def set_group_position_from_history(group_id, hist_id, **kwargs): success, msg = HistoryService.set_group_position_from_history( g.tenant_id, group_id, hist_id, session['account_id'] ) if not success: return jsonify({'error': msg}), 400 notify_reload('Administration: Gruppenposition wurde aus der Historie gesetzt.') return jsonify({'success': True, 'message': msg}) @admin_api_bp.route('/gruppen//position', methods=['DELETE']) @role_required('Administrator') def clear_group_position(group_id, **kwargs): success, msg = HistoryService.clear_group_position( g.tenant_id, group_id, session['account_id'] ) if not success: return jsonify({'error': msg}), 400 notify_reload('Administration: Gruppenposition wurde gelöscht.') return jsonify({'success': True, 'message': msg}) # === STRASSEN === @admin_api_bp.route('/strassen', methods=['POST']) @role_required('Administrator') def create_street(**kwargs): data = request.get_json() name = data.get('name', '').strip() if not name: return jsonify({'error': 'Name erforderlich'}), 400 street_id = StreetModel.create(g.tenant_id, name, hn_min=data.get('hn_min'), hn_max=data.get('hn_max'), bbox=data.get('bbox'), state='unbearbeitet', group_id=None) db = get_db() db.execute( 'INSERT INTO street_state_history (tenant_id, street_id, from_state, to_state, group_id, actor_account_id) VALUES (?, ?, ?, ?, ?, ?)', (g.tenant_id, street_id, None, 'unbearbeitet', None, session['account_id']) ) 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}) @admin_api_bp.route('/strassen/', methods=['POST']) @role_required('Administrator') def update_street(street_id, **kwargs): data = request.get_json() db = get_db() old = StreetModel.get_by_id(street_id, g.tenant_id) if not old: return jsonify({'error': 'Straße nicht gefunden'}), 404 changes = {} for key in ['name', 'hn_min', 'hn_max', 'bbox', 'group_id']: if key in data: if key == 'group_id' and (data[key] == '' or data[key] is None): changes[key] = None elif key in ['hn_min', 'hn_max'] and data[key] != '' and data[key] is not None: try: changes[key] = int(data[key]) except: changes[key] = data[key] else: changes[key] = data[key] if 'state' in data and data['state'] != old['state']: changes['state'] = data['state'] if data['state'] == 'unbearbeitet': changes['group_id'] = None db.execute( 'INSERT INTO street_state_history (tenant_id, street_id, from_state, to_state, group_id, actor_account_id) VALUES (?, ?, ?, ?, ?, ?)', (g.tenant_id, street_id, old['state'], data['state'], changes.get('group_id', old['group_id']), session['account_id']) ) # Code 100 msg = WSMessage(sender_id=session['account_id'], code=100, msg=json.dumps({'name': old['name'], 'state': data['state'], 'actor': session['account_id'], 'street_id': street_id, 'group_id': changes.get('group_id', old['group_id'])})) try: broker.route_message(g.tenant_id, msg) except: pass 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}) @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}) @admin_api_bp.route('/strassen//history') @role_required('Administrator') def street_history(street_id, **kwargs): db = get_db() history = db.execute( 'SELECT h.*, a.name as actor_name FROM street_state_history h LEFT JOIN accounts a ON h.actor_account_id = a.id WHERE h.street_id = ? AND h.tenant_id = ? ORDER BY h.created_at DESC', (street_id, g.tenant_id) ).fetchall() return jsonify([dict(row) for row in history]) @admin_api_bp.route('/strassen//history//revert', methods=['POST']) @role_required('Administrator') 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}) @admin_api_bp.route('/strassen/import', methods=['POST']) @role_required('Administrator') def import_streets(**kwargs): if 'file' not in request.files: return jsonify({'error': 'Keine Datei'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'error': 'Keine Datei ausgewählt'}), 400 content = file.read() if len(content) > 5_000_000: return jsonify({'error': 'Datei zu groß'}), 400 streets_data = parse_streets_csv(content) if not streets_data: return jsonify({ 'error': 'Keine gültigen Straßen in der CSV gefunden. ' 'Erwartete Spalten: Name;Hausnummer minimal;Hausnummer maximal;Bounding Box' }), 400 db = get_db() count = 0 for s in streets_data: street_id = StreetModel.create(g.tenant_id, s['name'], s['hn_min'], s['hn_max'], s['bbox'], 'unbearbeitet', None) db.execute( 'INSERT INTO street_state_history (tenant_id, street_id, from_state, to_state, group_id, actor_account_id) VALUES (?, ?, ?, ?, ?, ?)', (g.tenant_id, street_id, None, 'unbearbeitet', None, session['account_id']) ) log_transaction('street.import', 'street', street_id, {'name': s['name']}) count += 1 db.commit() notify_reload(f'Administration: {count} Straßen wurden importiert.') return jsonify({'success': True, 'count': count}) @admin_api_bp.route('/broker/status') @role_required('Administrator') def broker_status(**kwargs): """Status aktiver WebSocket-Verbindungen aller Worker. Die Verbindungsliste liegt in der gemeinsamen Tabelle ``ws_clients``. Dadurch zeigt das Dashboard auch Clients, die an einem anderen WSGI-Worker hängen. """ connections = broker.describe_connections(g.tenant_id) result = [] for conn in connections: result.append({ 'client_id': conn['client_id'], 'account_id': conn['account_id'], 'account_name': conn['account_name'], 'role': conn['role'], 'authenticated': bool(conn['authenticated']), 'group_id': conn['group_id'], 'group_alias': conn['group_alias'] }) return jsonify({'connections': result}) @admin_api_bp.route('/hausnummern/import', methods=['POST']) @role_required('Administrator') def import_house_numbers(**kwargs): if 'file' not in request.files: return jsonify({'error': 'Keine Datei'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'error': 'Keine Datei ausgewählt'}), 400 content = file.read() if len(content) > 5_000_000: return jsonify({'error': 'Datei zu groß'}), 400 house_numbers = parse_house_numbers_csv(content) if not house_numbers: return jsonify({ 'error': 'Keine gültigen Hausnummern in der CSV gefunden. ' 'Erwartete Spalten: Straßenname;Hausnummer;Longitude;Latitude' }), 400 db = get_db() for entry in house_numbers: db.execute( '''INSERT INTO street_house_numbers (tenant_id, street_name, house_number, longitude, latitude) VALUES (?, ?, ?, ?, ?) ON CONFLICT(tenant_id, street_name, house_number) DO UPDATE SET longitude = excluded.longitude, latitude = excluded.latitude''', ( g.tenant_id, entry['street_name'], entry['house_number'], entry['longitude'], entry['latitude'] ) ) db.commit() log_transaction( 'house_number.import', 'street_house_number', None, {'count': len(house_numbers)} ) notify_reload(f'Administration: {len(house_numbers)} Hausnummern wurden importiert.') return jsonify({'success': True, 'count': len(house_numbers)})