opencode ergebnis V0.1
This commit is contained in:
1 parent
61d86a3d83
commit
7e498ebc3f
71 files changed
+28982
-46
No files matched your search
@@ -0,0 +1,31 @@
|
||||
# CMBNet
|
||||
|
||||
Webanwendung für die Verwaltung von Straßen und Gruppen mit Kartendarstellung.
|
||||
|
||||
## Setup
|
||||
|
||||
```bash
|
||||
cd CMBNet
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
mkdir -p instance logs data migrations
|
||||
flask --app cmbnet init-db
|
||||
flask --app cmbnet run --debug --host 127.0.0.1 --port 5000
|
||||
```
|
||||
|
||||
## Zugriff
|
||||
|
||||
Öffne http://127.0.0.1:5000 und wähle einen Mandanten (BV, RV, SV).
|
||||
|
||||
## Erste Einrichtung
|
||||
|
||||
Nach der Initialisierung der Datenbank müssen noch Mandanten und ein Admin-Account angelegt werden.
|
||||
|
||||
```bash
|
||||
sqlite3 instance/cmbnet.sqlite3
|
||||
INSERT INTO tenants (code, name) VALUES ('BV', 'Bezirk BV'), ('RV', 'Bezirk RV'), ('SV', 'Bezirk SV');
|
||||
INSERT INTO accounts (tenant_id, name, password_hash, role) VALUES (2, 'admin', '...', 'Administrator');
|
||||
```
|
||||
|
||||
Für den Passwort-Hash kann `python3 -c "from werkzeug.security import generate_password_hash; print(generate_password_hash('admin'))"` verwendet werden.
|
||||
@@ -0,0 +1,6 @@
|
||||
from cmbnet import create_app
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
@@ -0,0 +1,79 @@
|
||||
import os
|
||||
from flask import Flask, g, session
|
||||
from config import config
|
||||
from cmbnet.extensions import sock
|
||||
|
||||
|
||||
def create_app(config_name=None):
|
||||
if config_name is None:
|
||||
config_name = os.environ.get('FLASK_ENV', 'development')
|
||||
|
||||
app = Flask(__name__,
|
||||
template_folder='../templates',
|
||||
static_folder='../static')
|
||||
app.config.from_object(config[config_name])
|
||||
|
||||
# Stelle sicher, dass instance Verzeichnis existiert
|
||||
os.makedirs(app.instance_path, exist_ok=True)
|
||||
os.makedirs(app.config['LOG_DIR'], exist_ok=True)
|
||||
|
||||
# Sock initialisieren
|
||||
sock.init_app(app)
|
||||
|
||||
# Datenbank-Setup
|
||||
from cmbnet.db import close_db, init_db_command
|
||||
app.teardown_appcontext(close_db)
|
||||
app.cli.add_command(init_db_command)
|
||||
|
||||
# Tenant und Account für Requests laden
|
||||
@app.before_request
|
||||
def load_current_account():
|
||||
if 'account_id' in session:
|
||||
from cmbnet.db import get_db
|
||||
db = get_db()
|
||||
account = db.execute('SELECT a.*, t.code as tenant_code FROM accounts a JOIN tenants t ON a.tenant_id = t.id WHERE a.id = ?', (session['account_id'],)).fetchone()
|
||||
if account:
|
||||
g.current_account = account
|
||||
g.tenant_id = account['tenant_id']
|
||||
g.tenant_code = account['tenant_code']
|
||||
else:
|
||||
session.clear()
|
||||
|
||||
# Blueprints registrieren
|
||||
from cmbnet.views import auth_bp, views_bp
|
||||
from cmbnet.admin.accounts import admin_accounts_bp
|
||||
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.api.init import api_init_bp
|
||||
from cmbnet.api.auth import api_auth_bp
|
||||
|
||||
app.register_blueprint(auth_bp, url_prefix='/<tenant>')
|
||||
app.register_blueprint(views_bp, url_prefix='/<tenant>')
|
||||
# Admin-Views immer unter /<tenant>/admin/..., damit sie nicht mit den
|
||||
# rollenspezifischen Views (z. B. views.gruppen unter /<tenant>/gruppen)
|
||||
# kollidieren.
|
||||
app.register_blueprint(admin_accounts_bp, url_prefix='/<tenant>/admin')
|
||||
app.register_blueprint(admin_gruppen_bp, url_prefix='/<tenant>/admin')
|
||||
app.register_blueprint(admin_strassen_bp, url_prefix='/<tenant>/admin')
|
||||
app.register_blueprint(admin_api_bp, url_prefix='/<tenant>/admin/api')
|
||||
app.register_blueprint(api_init_bp, url_prefix='/<tenant>/api')
|
||||
app.register_blueprint(api_auth_bp, url_prefix='/<tenant>/api')
|
||||
|
||||
# WebSocket Routes laden
|
||||
from cmbnet.ws import routes
|
||||
|
||||
# Heartbeat starten (Code 1 jede Minute, Aufräumen alter Nachrichten)
|
||||
from cmbnet.ws.heartbeat import heartbeat_manager
|
||||
heartbeat_manager.start(
|
||||
app,
|
||||
interval=app.config.get('WS_HEARTBEAT_INTERVAL', 60)
|
||||
)
|
||||
|
||||
# Root redirect
|
||||
@app.route('/')
|
||||
def index():
|
||||
from flask import redirect, url_for
|
||||
return redirect(url_for('auth.login_select'))
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,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
|
||||
|
||||
admin_bp = admin_accounts_bp
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
Accountverwaltung
|
||||
"""
|
||||
from flask import Blueprint, render_template, g
|
||||
from cmbnet.auth import role_required
|
||||
from cmbnet.db import get_db
|
||||
|
||||
admin_accounts_bp = Blueprint('admin', __name__)
|
||||
|
||||
|
||||
@admin_accounts_bp.route('/accounts')
|
||||
@role_required('Administrator')
|
||||
def accounts(**kwargs):
|
||||
"""Accountverwaltung"""
|
||||
db = get_db()
|
||||
accounts = db.execute(
|
||||
'SELECT a.*, t.code as tenant_code FROM accounts a JOIN tenants t ON a.tenant_id = t.id WHERE a.tenant_id = ? ORDER BY a.id',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
return render_template('admin/accounts.html', accounts=accounts)
|
||||
@@ -0,0 +1,365 @@
|
||||
"""
|
||||
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
|
||||
from cmbnet.utils.csv_utils import parse_streets_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})
|
||||
|
||||
return jsonify({'success': True, 'id': account_id})
|
||||
|
||||
|
||||
@admin_api_bp.route('/accounts/<int:account_id>/role', methods=['POST'])
|
||||
@role_required('Administrator')
|
||||
def update_account_role(account_id, **kwargs):
|
||||
data = request.get_json()
|
||||
role = data.get('role')
|
||||
AccountModel.update_role(account_id, g.tenant_id, role)
|
||||
log_transaction('account.role_change', 'account', account_id, {'role': role})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/accounts/<int:account_id>/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)
|
||||
AccountModel.set_password(account_id, g.tenant_id, password_hash)
|
||||
log_transaction('account.password_reset', 'account', account_id, {})
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/accounts/<int:account_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_account(account_id, **kwargs):
|
||||
AccountModel.delete(account_id, g.tenant_id)
|
||||
log_transaction('account.delete', 'account', account_id, {})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
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()
|
||||
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')
|
||||
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})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
GroupsService.load_from_db(g.tenant_id)
|
||||
return jsonify({'success': True, 'id': group_id})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>', 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']
|
||||
|
||||
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:
|
||||
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)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_group(group_id, **kwargs):
|
||||
GroupModel.delete(group_id, g.tenant_id)
|
||||
log_transaction('group.delete', 'group', group_id, {})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>/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/<int:group_id>/history/<int:hist_id>/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
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>/position/history/<int:hist_id>', 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
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>/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
|
||||
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})
|
||||
return jsonify({'success': True, 'id': street_id})
|
||||
|
||||
|
||||
@admin_api_bp.route('/strassen/<int:street_id>', 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)
|
||||
|
||||
db.commit()
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/strassen/<int:street_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_street(street_id, **kwargs):
|
||||
StreetModel.delete(street_id, g.tenant_id)
|
||||
log_transaction('street.delete', 'street', street_id, {})
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/strassen/<int:street_id>/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/<int:street_id>/history/<int:hist_id>/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
|
||||
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)
|
||||
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()
|
||||
return jsonify({'success': True, 'count': count})
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
Gruppenverwaltung
|
||||
"""
|
||||
from flask import Blueprint, render_template, g
|
||||
from cmbnet.auth import role_required
|
||||
from cmbnet.db import get_db
|
||||
|
||||
admin_gruppen_bp = Blueprint('admin_gruppen', __name__)
|
||||
|
||||
|
||||
@admin_gruppen_bp.route('/gruppen')
|
||||
@role_required('Administrator')
|
||||
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',
|
||||
(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)
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
Straßenverwaltung
|
||||
"""
|
||||
from flask import Blueprint, render_template, g
|
||||
from cmbnet.auth import role_required
|
||||
from cmbnet.db import get_db
|
||||
|
||||
admin_strassen_bp = Blueprint('admin_strassen', __name__)
|
||||
|
||||
|
||||
@admin_strassen_bp.route('/strassen')
|
||||
@role_required('Administrator')
|
||||
def strassen(**kwargs):
|
||||
"""Straßenverwaltung"""
|
||||
db = get_db()
|
||||
strassen = db.execute(
|
||||
'SELECT s.*, g.aliasname as group_name FROM streets s LEFT JOIN groups g ON s.group_id = g.id WHERE s.tenant_id = ? ORDER BY s.name',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
gruppen = db.execute(
|
||||
'SELECT * FROM groups WHERE tenant_id = ? ORDER BY id',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
return render_template('admin/strassen.html', strassen=strassen, gruppen=gruppen)
|
||||
@@ -0,0 +1,4 @@
|
||||
from .init import api_init_bp
|
||||
from .auth import api_auth_bp
|
||||
|
||||
api_bp = api_init_bp
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
API Auth Endpunkte
|
||||
"""
|
||||
from flask import Blueprint, jsonify, g, session
|
||||
from cmbnet.auth import login_required
|
||||
from cmbnet.db import get_db
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
api_auth_bp = Blueprint('api_auth', __name__)
|
||||
|
||||
|
||||
@api_auth_bp.route('/auth/ws-token', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def ws_token(**kwargs):
|
||||
"""Erzeugt ein Zugriffstoken für WebSocket-Authentifizierung"""
|
||||
db = get_db()
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = datetime.now() + timedelta(hours=1)
|
||||
|
||||
db.execute(
|
||||
'INSERT INTO ws_tokens (tenant_id, account_id, token, expires_at) VALUES (?, ?, ?, ?)',
|
||||
(g.tenant_id, session['account_id'], token, expires_at)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
return jsonify({'token': token})
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
API Endpunkte für Initialdaten
|
||||
"""
|
||||
from flask import Blueprint, jsonify, g
|
||||
from cmbnet.auth import login_required
|
||||
from cmbnet.services.streets_service import StreetsService
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
|
||||
api_init_bp = Blueprint('api_init', __name__)
|
||||
|
||||
|
||||
@api_init_bp.route('/init/streets')
|
||||
@login_required
|
||||
def init_streets(**kwargs):
|
||||
"""Liefert alle Straßen für den Initialload"""
|
||||
streets = StreetsService.get_all_for_init(g.tenant_id)
|
||||
return jsonify(streets)
|
||||
|
||||
|
||||
@api_init_bp.route('/init/groups')
|
||||
@login_required
|
||||
def init_groups(**kwargs):
|
||||
"""Liefert alle Gruppen für den Initialload (aus Cache)"""
|
||||
groups_dict = GroupsService.get_all(g.tenant_id)
|
||||
groups_list = list(groups_dict.values())
|
||||
return jsonify(groups_list)
|
||||
@@ -0,0 +1,2 @@
|
||||
from .decorators import login_required, role_required, tenant_required
|
||||
from .utils import verify_password, hash_password
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
Authentifizierungs-Decoratoren
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import session, redirect, url_for, request, g, abort, flash
|
||||
|
||||
|
||||
def _get_tenant_for_redirect():
|
||||
"""Hilfsfunktion um Tenant für Redirect zu ermitteln"""
|
||||
if hasattr(g, 'tenant_code') and g.tenant_code:
|
||||
return g.tenant_code
|
||||
if 'tenant_code' in session:
|
||||
return session['tenant_code']
|
||||
# Versuche aus URL
|
||||
tenant = request.view_args.get('tenant') if request.view_args else None
|
||||
if tenant:
|
||||
return tenant
|
||||
return 'RV'
|
||||
|
||||
|
||||
def login_required(f):
|
||||
"""Decorator für routes die einen eingeloggten Account erfordern"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if 'account_id' not in session:
|
||||
return redirect(url_for('auth.login', tenant=_get_tenant_for_redirect()))
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
|
||||
def role_required(roles):
|
||||
"""Decorator für routes die bestimmte Rollen erfordern"""
|
||||
if isinstance(roles, str):
|
||||
roles = [roles]
|
||||
|
||||
def decorator(f):
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
if 'account_id' not in session:
|
||||
return redirect(url_for('auth.login', tenant=_get_tenant_for_redirect()))
|
||||
|
||||
account_role = session.get('role')
|
||||
if account_role not in roles:
|
||||
abort(403)
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
return decorator
|
||||
|
||||
|
||||
def tenant_required(f):
|
||||
"""Decorator für tenant-spezifische Routes"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# Tenant wird bereits in der Route über URL extrahiert
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
@@ -0,0 +1,14 @@
|
||||
"""
|
||||
Authentifizierungs-Hilfsfunktionen
|
||||
"""
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
"""Erstellt einen Passwort-Hash"""
|
||||
return generate_password_hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash, password):
|
||||
"""Überprüft ein Passwort gegen den Hash"""
|
||||
return check_password_hash(password_hash, password)
|
||||
Whitespace-only changes.
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
Transaktionslogging für CMBNet
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def write_transaction_log(tenant_id, actor_id, actor_name, action, entity_type, entity_id, details=None):
|
||||
"""
|
||||
Schreibt einen lesbaren Eintrag ins tägliche Logfile
|
||||
"""
|
||||
log_dir = Path(current_app.config['LOG_DIR'])
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
date_str = datetime.now().strftime('%Y-%m-%d')
|
||||
log_file = log_dir / f'cmbnet-{date_str}.log'
|
||||
|
||||
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
|
||||
actor_str = f"{actor_id}({actor_name})" if actor_id and actor_name else "SYSTEM"
|
||||
|
||||
if isinstance(details, dict):
|
||||
details_str = str(details)
|
||||
elif details is None:
|
||||
details_str = "{}"
|
||||
else:
|
||||
details_str = str(details)
|
||||
|
||||
log_line = f"{timestamp} [TENANT:{get_tenant_code(tenant_id)}] [ACTOR:{actor_str}] ACTION:{action} ENTITY:{entity_type}:{entity_id} DETAILS:{details_str}\n"
|
||||
|
||||
with open(log_file, 'a', encoding='utf-8') as f:
|
||||
f.write(log_line)
|
||||
|
||||
|
||||
def get_tenant_code(tenant_id):
|
||||
"""Holt den Tenant-Code für die Logausgabe"""
|
||||
from cmbnet.db import get_db
|
||||
db = get_db()
|
||||
tenant = db.execute('SELECT code FROM tenants WHERE id = ?', (tenant_id,)).fetchone()
|
||||
return tenant['code'] if tenant else str(tenant_id)
|
||||
@@ -0,0 +1 @@
|
||||
from .database import get_db, close_db, init_db_command
|
||||
@@ -0,0 +1,39 @@
|
||||
import sqlite3
|
||||
import os
|
||||
from pathlib import Path
|
||||
from flask import current_app, g
|
||||
import click
|
||||
|
||||
|
||||
def get_db():
|
||||
"""Stellt eine Datenbankverbindung für den aktuellen Request bereit"""
|
||||
if 'db' not in g:
|
||||
db_path = current_app.config['DATABASE_PATH']
|
||||
# Stelle sicher, dass das instance Verzeichnis existiert
|
||||
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
g.db = sqlite3.connect(db_path)
|
||||
g.db.row_factory = sqlite3.Row
|
||||
return g.db
|
||||
|
||||
|
||||
def close_db(e=None):
|
||||
"""Schließt die Datenbankverbindung am Ende des Requests"""
|
||||
db = g.pop('db', None)
|
||||
if db is not None:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Initialisiert die Datenbank mit dem Schema"""
|
||||
db = get_db()
|
||||
schema_path = Path(current_app.root_path).parent / 'migrations' / 'schema.sql'
|
||||
with open(schema_path, 'r', encoding='utf-8') as f:
|
||||
db.executescript(f.read())
|
||||
db.commit()
|
||||
|
||||
|
||||
@click.command('init-db')
|
||||
def init_db_command():
|
||||
"""CLI-Befehl zum Initialisieren der Datenbank"""
|
||||
init_db()
|
||||
click.echo('Datenbank wurde initialisiert.')
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
Erweiterungen für die CMBNet Anwendung
|
||||
|
||||
Hier liegen gemeinsame Instanzen, die von mehreren Modulen benötigt werden.
|
||||
Wichtig ist eine einzige Sock-Instanz: Routen werden auf diesem Objekt
|
||||
registriert und es muss anschließend mit der Flask-App initialisiert werden.
|
||||
"""
|
||||
from flask_sock import Sock
|
||||
|
||||
sock = Sock()
|
||||
@@ -0,0 +1,3 @@
|
||||
from .accounts import AccountModel
|
||||
from .groups import GroupModel
|
||||
from .streets import StreetModel
|
||||
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
Account Model - Abstraktionsschicht für Datenbankzugriffe
|
||||
"""
|
||||
from cmbnet.db import get_db
|
||||
|
||||
|
||||
class AccountModel:
|
||||
@staticmethod
|
||||
def get_all_by_tenant(tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM accounts WHERE tenant_id = ? ORDER BY id',
|
||||
(tenant_id,)
|
||||
).fetchall()
|
||||
|
||||
@staticmethod
|
||||
def get_by_id(account_id, tenant_id=None):
|
||||
db = get_db()
|
||||
if tenant_id:
|
||||
return db.execute(
|
||||
'SELECT * FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
return db.execute('SELECT * FROM accounts WHERE id = ?', (account_id,)).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def get_by_name_and_tenant(name, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM accounts WHERE name = ? AND tenant_id = ?',
|
||||
(name, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def create(tenant_id, name, password_hash, role):
|
||||
db = get_db()
|
||||
cursor = db.execute(
|
||||
'INSERT INTO accounts (tenant_id, name, password_hash, role) VALUES (?, ?, ?, ?)',
|
||||
(tenant_id, name, password_hash, role)
|
||||
)
|
||||
db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
@staticmethod
|
||||
def update_role(account_id, tenant_id, role):
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'UPDATE accounts SET role = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?',
|
||||
(role, account_id, tenant_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def set_password(account_id, tenant_id, password_hash):
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'UPDATE accounts SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?',
|
||||
(password_hash, account_id, tenant_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def delete(account_id, tenant_id):
|
||||
db = get_db()
|
||||
db.execute('DELETE FROM accounts WHERE id = ? AND tenant_id = ?', (account_id, tenant_id))
|
||||
db.commit()
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Group Model - Abstraktionsschicht für Datenbankzugriffe
|
||||
"""
|
||||
from cmbnet.db import get_db
|
||||
|
||||
|
||||
class GroupModel:
|
||||
@staticmethod
|
||||
def get_all_by_tenant(tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM groups WHERE tenant_id = ? ORDER BY id',
|
||||
(tenant_id,)
|
||||
).fetchall()
|
||||
|
||||
@staticmethod
|
||||
def get_by_id(group_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def get_by_account_id(account_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def create(tenant_id, aliasname, account_id=None, state='offen'):
|
||||
db = get_db()
|
||||
cursor = db.execute(
|
||||
'INSERT INTO groups (tenant_id, aliasname, account_id, state) VALUES (?, ?, ?, ?)',
|
||||
(tenant_id, aliasname, account_id, state)
|
||||
)
|
||||
db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
@staticmethod
|
||||
def update(group_id, tenant_id, **kwargs):
|
||||
db = get_db()
|
||||
allowed = ['aliasname', 'state', 'account_id', 'last_lat', 'last_lon', 'last_pos_at']
|
||||
updates = []
|
||||
values = []
|
||||
for k, v in kwargs.items():
|
||||
if k in allowed:
|
||||
updates.append(f'{k} = ?')
|
||||
values.append(v)
|
||||
if not updates:
|
||||
return
|
||||
updates.append('updated_at = CURRENT_TIMESTAMP')
|
||||
values.extend([group_id, tenant_id])
|
||||
db.execute(f'UPDATE groups SET {", ".join(updates)} WHERE id = ? AND tenant_id = ?', values)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def delete(group_id, tenant_id):
|
||||
db = get_db()
|
||||
db.execute('DELETE FROM groups WHERE id = ? AND tenant_id = ?', (group_id, tenant_id))
|
||||
db.commit()
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Street Model - Abstraktionsschicht für Datenbankzugriffe
|
||||
"""
|
||||
from cmbnet.db import get_db
|
||||
|
||||
|
||||
class StreetModel:
|
||||
@staticmethod
|
||||
def get_all_by_tenant(tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM streets WHERE tenant_id = ? ORDER BY name',
|
||||
(tenant_id,)
|
||||
).fetchall()
|
||||
|
||||
@staticmethod
|
||||
def get_by_id(street_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM streets WHERE id = ? AND tenant_id = ?',
|
||||
(street_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
@staticmethod
|
||||
def get_by_group_id(group_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM streets WHERE group_id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchall()
|
||||
|
||||
@staticmethod
|
||||
def create(tenant_id, name, hn_min=None, hn_max=None, bbox=None, state='unbearbeitet', group_id=None):
|
||||
db = get_db()
|
||||
cursor = db.execute(
|
||||
'INSERT INTO streets (tenant_id, name, hn_min, hn_max, bbox, state, group_id) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
(tenant_id, name, hn_min, hn_max, bbox, state, group_id)
|
||||
)
|
||||
db.commit()
|
||||
return cursor.lastrowid
|
||||
|
||||
@staticmethod
|
||||
def update(street_id, tenant_id, **kwargs):
|
||||
db = get_db()
|
||||
allowed = ['name', 'state', 'group_id', 'hn_min', 'hn_max', 'bbox']
|
||||
updates = []
|
||||
values = []
|
||||
for k, v in kwargs.items():
|
||||
if k in allowed:
|
||||
updates.append(f'{k} = ?')
|
||||
values.append(v)
|
||||
if not updates:
|
||||
return
|
||||
updates.append('updated_at = CURRENT_TIMESTAMP')
|
||||
values.extend([street_id, tenant_id])
|
||||
db.execute(f'UPDATE streets SET {", ".join(updates)} WHERE id = ? AND tenant_id = ?', values)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
def delete(street_id, tenant_id):
|
||||
db = get_db()
|
||||
db.execute('DELETE FROM streets WHERE id = ? AND tenant_id = ?', (street_id, tenant_id))
|
||||
db.commit()
|
||||
@@ -0,0 +1,3 @@
|
||||
from .groups_service import GroupsService
|
||||
from .streets_service import StreetsService
|
||||
from .accounts_service import AccountsService
|
||||
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
Accounts Service - Geschäftslogik für Accounts
|
||||
"""
|
||||
from cmbnet.models.accounts import AccountModel
|
||||
from cmbnet.auth import verify_password, hash_password
|
||||
|
||||
|
||||
class AccountsService:
|
||||
@staticmethod
|
||||
def verify_account_password(account, password):
|
||||
"""Überprüft Passwort gegen Account"""
|
||||
if not account:
|
||||
return False
|
||||
return verify_password(account['password_hash'], password)
|
||||
|
||||
@staticmethod
|
||||
def has_role(account, roles):
|
||||
"""Prüft, ob Account eine der angegebenen Rollen hat"""
|
||||
if isinstance(roles, str):
|
||||
roles = [roles]
|
||||
if not account:
|
||||
return False
|
||||
return account['role'] in roles
|
||||
|
||||
@staticmethod
|
||||
def create_account(tenant_id, name, password, role):
|
||||
"""Erstellt einen neuen Account"""
|
||||
password_hash = hash_password(password)
|
||||
return AccountModel.create(tenant_id, name, password_hash, role)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
Groups Service - Geschäftslogik für Gruppen mit In-Memory-Caching
|
||||
"""
|
||||
from cmbnet.models.groups import GroupModel
|
||||
from cmbnet.models.streets import StreetModel
|
||||
from cmbnet.models.accounts import AccountModel
|
||||
from cmbnet.db import get_db
|
||||
|
||||
|
||||
class GroupsService:
|
||||
# In-Memory Cache: groups_cache[tenant_id][group_id] = group_dict
|
||||
_cache = {}
|
||||
|
||||
@classmethod
|
||||
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] = {}
|
||||
|
||||
for group in groups:
|
||||
cls._cache[tenant_id][group['id']] = {
|
||||
'id': group['id'],
|
||||
'tenant_id': group['tenant_id'],
|
||||
'aliasname': group['aliasname'],
|
||||
'state': group['state'],
|
||||
'last_lat': group['last_lat'],
|
||||
'last_lon': group['last_lon'],
|
||||
'last_pos_at': group['last_pos_at'],
|
||||
'account_id': group['account_id'],
|
||||
'created_at': group['created_at'],
|
||||
'updated_at': group['updated_at']
|
||||
}
|
||||
return cls._cache[tenant_id]
|
||||
|
||||
@classmethod
|
||||
def get_all(cls, tenant_id, force_reload=False):
|
||||
"""Gibt alle Gruppen für einen Mandanten zurück (aus Cache)"""
|
||||
if force_reload or tenant_id not in cls._cache or not cls._cache[tenant_id]:
|
||||
cls.load_from_db(tenant_id)
|
||||
return cls._cache.get(tenant_id, {})
|
||||
|
||||
@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:
|
||||
cls.load_from_db(tenant_id)
|
||||
return cls._cache.get(tenant_id, {}).get(group_id)
|
||||
|
||||
@classmethod
|
||||
def invalidate(cls, tenant_id):
|
||||
"""Invalidiert den Cache für einen Mandanten (erzwingt Neuladen)"""
|
||||
if tenant_id in cls._cache:
|
||||
cls._cache[tenant_id] = {}
|
||||
|
||||
@classmethod
|
||||
def invalidate_all(cls):
|
||||
"""Invalidiert den gesamten Cache"""
|
||||
cls._cache = {}
|
||||
|
||||
@classmethod
|
||||
def is_account_linked(cls, account_id, group_id, tenant_id):
|
||||
"""Prüft, ob ein Account mit einer Gruppe verknüpft ist"""
|
||||
group = cls.get_by_id(tenant_id, group_id)
|
||||
if not group:
|
||||
return False
|
||||
return group.get('account_id') == account_id
|
||||
|
||||
@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 []
|
||||
|
||||
@classmethod
|
||||
def get_streets_for_group(cls, group_id, tenant_id):
|
||||
"""Gibt alle mit einer Gruppe verknüpften Straßen zurück"""
|
||||
return StreetModel.get_by_group_id(group_id, tenant_id)
|
||||
|
||||
@classmethod
|
||||
def update_cache_entry(cls, tenant_id, group_id, data):
|
||||
"""Aktualisiert einen Eintrag im Cache.
|
||||
|
||||
Der Cache wird vor dem Aktualisieren vollständig geladen, damit ein
|
||||
gezieltes Update (z. B. nach Code 200/300) keinen Teil-Cache erzeugt,
|
||||
der anschließend beim Initialload unvollständige Gruppendaten liefert.
|
||||
"""
|
||||
if tenant_id not in cls._cache or not cls._cache[tenant_id]:
|
||||
cls.load_from_db(tenant_id)
|
||||
if group_id not in cls._cache[tenant_id]:
|
||||
cls._cache[tenant_id][group_id] = {}
|
||||
cls._cache[tenant_id][group_id].update(data)
|
||||
@@ -0,0 +1,276 @@
|
||||
"""
|
||||
History Service für Revert von States
|
||||
"""
|
||||
import json
|
||||
from datetime import datetime
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.models.streets import StreetModel
|
||||
from cmbnet.models.groups import GroupModel
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.utils.helpers import log_transaction
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
class HistoryService:
|
||||
@staticmethod
|
||||
def revert_street(tenant_id, street_id, hist_id, actor_account_id):
|
||||
db = get_db()
|
||||
history = db.execute(
|
||||
'SELECT * FROM street_state_history WHERE id = ? AND tenant_id = ? AND street_id = ?',
|
||||
(hist_id, tenant_id, street_id)
|
||||
).fetchone()
|
||||
if not history:
|
||||
return False, 'Historieneintrag nicht gefunden'
|
||||
|
||||
street = StreetModel.get_by_id(street_id, tenant_id)
|
||||
if not street:
|
||||
return False, 'Straße nicht gefunden'
|
||||
|
||||
old_state = street['state']
|
||||
target_state = history['to_state']
|
||||
target_group_id = history['group_id']
|
||||
|
||||
if target_state == 'unbearbeitet':
|
||||
target_group_id = None
|
||||
|
||||
# Update Straße
|
||||
StreetModel.update(street_id, tenant_id, state=target_state, group_id=target_group_id)
|
||||
|
||||
# Neuen History-Eintrag für den Revert
|
||||
db.execute(
|
||||
'''INSERT INTO street_state_history
|
||||
(tenant_id, street_id, from_state, to_state, group_id, actor_account_id, reason)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, street_id, old_state, target_state, target_group_id, actor_account_id, f'revert_from_hist_{hist_id}')
|
||||
)
|
||||
db.commit()
|
||||
|
||||
log_transaction('street.revert', 'street', street_id, {
|
||||
'from': old_state,
|
||||
'to': target_state,
|
||||
'group_id': target_group_id,
|
||||
'hist_id': hist_id
|
||||
})
|
||||
|
||||
# Code 100 verschicken
|
||||
msg = WSMessage(
|
||||
sender_id=actor_account_id,
|
||||
code=100,
|
||||
msg=json.dumps({
|
||||
'name': street['name'],
|
||||
'state': target_state,
|
||||
'actor': actor_account_id,
|
||||
'street_id': street_id,
|
||||
'group_id': target_group_id
|
||||
})
|
||||
)
|
||||
try:
|
||||
broker.route_message(tenant_id, msg)
|
||||
except Exception as e:
|
||||
print(f'Broker error: {e}')
|
||||
|
||||
return True, 'Zustand wiederhergestellt'
|
||||
|
||||
@staticmethod
|
||||
def revert_group(tenant_id, group_id, hist_id, actor_account_id):
|
||||
db = get_db()
|
||||
history = db.execute(
|
||||
'SELECT * FROM group_state_history WHERE id = ? AND tenant_id = ? AND group_id = ?',
|
||||
(hist_id, tenant_id, group_id)
|
||||
).fetchone()
|
||||
if not history:
|
||||
return False, 'Historieneintrag nicht gefunden'
|
||||
|
||||
group = GroupModel.get_by_id(group_id, tenant_id)
|
||||
if not group:
|
||||
return False, 'Gruppe nicht gefunden'
|
||||
|
||||
old_state = group['state']
|
||||
target_state = history['to_state']
|
||||
target_lat = history['last_lat']
|
||||
target_lon = history['last_lon']
|
||||
target_pos_at = history['last_pos_at']
|
||||
|
||||
GroupModel.update(group_id, tenant_id,
|
||||
state=target_state,
|
||||
last_lat=target_lat,
|
||||
last_lon=target_lon,
|
||||
last_pos_at=target_pos_at)
|
||||
|
||||
# Neuen History-Eintrag
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon, last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, old_state, target_state, target_lat, target_lon, target_pos_at, actor_account_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Cache aktualisieren
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {
|
||||
'state': target_state,
|
||||
'last_lat': target_lat,
|
||||
'last_lon': target_lon,
|
||||
'last_pos_at': target_pos_at
|
||||
})
|
||||
|
||||
log_transaction('group.revert', 'group', group_id, {
|
||||
'from': old_state,
|
||||
'to': target_state,
|
||||
'hist_id': hist_id
|
||||
})
|
||||
|
||||
# Code 200
|
||||
msg200 = WSMessage(
|
||||
sender_id=actor_account_id,
|
||||
code=200,
|
||||
msg=json.dumps({
|
||||
'group_id': group_id,
|
||||
'state': target_state,
|
||||
'actor': actor_account_id
|
||||
})
|
||||
)
|
||||
try:
|
||||
broker.route_message(tenant_id, msg200)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Code 300 wenn Position vorhanden
|
||||
if target_lat is not None and target_lon is not None:
|
||||
msg300 = WSMessage(
|
||||
sender_id=actor_account_id,
|
||||
code=300,
|
||||
msg=json.dumps({
|
||||
'group_id': group_id,
|
||||
'lat': target_lat,
|
||||
'lon': target_lon,
|
||||
'ts': target_pos_at,
|
||||
'actor': actor_account_id
|
||||
})
|
||||
)
|
||||
try:
|
||||
broker.route_message(tenant_id, msg300)
|
||||
except:
|
||||
pass
|
||||
|
||||
return True, 'Gruppe wiederhergestellt'
|
||||
|
||||
@staticmethod
|
||||
def _send_group_position(tenant_id, group_id, lat, lon, pos_at, actor_account_id):
|
||||
"""Meldet eine Positionsänderung an die berechtigten Clients (Code 300)."""
|
||||
msg = WSMessage(
|
||||
sender_id=actor_account_id,
|
||||
code=300,
|
||||
msg=json.dumps({
|
||||
'group_id': group_id,
|
||||
'lat': lat,
|
||||
'lon': lon,
|
||||
'ts': pos_at,
|
||||
'actor': actor_account_id
|
||||
})
|
||||
)
|
||||
try:
|
||||
broker.route_message(tenant_id, msg)
|
||||
except Exception as e:
|
||||
print(f'Broker error: {e}')
|
||||
|
||||
@staticmethod
|
||||
def set_group_position_from_history(tenant_id, group_id, hist_id, actor_account_id):
|
||||
"""Übernimmt ausschließlich die Position eines Historieneintrags.
|
||||
|
||||
Der State der Gruppe bleibt unverändert; die Übernahme wird selbst als
|
||||
neuer Historieneintrag festgehalten.
|
||||
"""
|
||||
db = get_db()
|
||||
history = db.execute(
|
||||
'SELECT * FROM group_state_history WHERE id = ? AND tenant_id = ? AND group_id = ?',
|
||||
(hist_id, tenant_id, group_id)
|
||||
).fetchone()
|
||||
if not history:
|
||||
return False, 'Historieneintrag nicht gefunden'
|
||||
|
||||
target_lat = history['last_lat']
|
||||
target_lon = history['last_lon']
|
||||
if target_lat is None or target_lon is None:
|
||||
return False, 'Historieneintrag enthält keine Position'
|
||||
|
||||
group = GroupModel.get_by_id(group_id, tenant_id)
|
||||
if not group:
|
||||
return False, 'Gruppe nicht gefunden'
|
||||
|
||||
target_pos_at = history['last_pos_at']
|
||||
GroupModel.update(
|
||||
group_id, tenant_id,
|
||||
last_lat=target_lat,
|
||||
last_lon=target_lon,
|
||||
last_pos_at=target_pos_at
|
||||
)
|
||||
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon, last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, group['state'], group['state'],
|
||||
target_lat, target_lon, target_pos_at, actor_account_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {
|
||||
'last_lat': target_lat,
|
||||
'last_lon': target_lon,
|
||||
'last_pos_at': target_pos_at
|
||||
})
|
||||
|
||||
log_transaction('group.position_from_history', 'group', group_id, {
|
||||
'hist_id': hist_id,
|
||||
'lat': target_lat,
|
||||
'lon': target_lon
|
||||
})
|
||||
HistoryService._send_group_position(
|
||||
tenant_id, group_id, target_lat, target_lon, target_pos_at, actor_account_id
|
||||
)
|
||||
|
||||
return True, 'Position übernommen'
|
||||
|
||||
@staticmethod
|
||||
def clear_group_position(tenant_id, group_id, actor_account_id):
|
||||
"""Löscht die aktuelle Position einer Gruppe."""
|
||||
group = GroupModel.get_by_id(group_id, tenant_id)
|
||||
if not group:
|
||||
return False, 'Gruppe nicht gefunden'
|
||||
|
||||
if group['last_lat'] is None and group['last_lon'] is None:
|
||||
return True, 'Position ist bereits unbekannt'
|
||||
|
||||
GroupModel.update(
|
||||
group_id, tenant_id,
|
||||
last_lat=None,
|
||||
last_lon=None,
|
||||
last_pos_at=None
|
||||
)
|
||||
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon, last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, group['state'], group['state'],
|
||||
None, None, None, actor_account_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {
|
||||
'last_lat': None,
|
||||
'last_lon': None,
|
||||
'last_pos_at': None
|
||||
})
|
||||
|
||||
log_transaction('group.position_clear', 'group', group_id, {})
|
||||
|
||||
# Null-Koordinaten signalisieren den Clients, die Markierung zu entfernen.
|
||||
HistoryService._send_group_position(
|
||||
tenant_id, group_id, None, None, None, actor_account_id
|
||||
)
|
||||
|
||||
return True, 'Position gelöscht'
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
Streets Service - Geschäftslogik für Straßen
|
||||
"""
|
||||
from cmbnet.models.streets import StreetModel
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.utils.helpers import log_transaction
|
||||
import json
|
||||
|
||||
|
||||
class StreetsService:
|
||||
@staticmethod
|
||||
def get_all_for_init(tenant_id):
|
||||
"""Gibt alle Straßen für den AJAX-Initialload zurück"""
|
||||
streets = StreetModel.get_all_by_tenant(tenant_id)
|
||||
result = []
|
||||
for street in streets:
|
||||
result.append({
|
||||
'id': street['id'],
|
||||
'name': street['name'],
|
||||
'state': street['state'],
|
||||
'group_id': street['group_id'],
|
||||
'hn_min': street['hn_min'],
|
||||
'hn_max': street['hn_max'],
|
||||
'bbox': json.loads(street['bbox']) if street['bbox'] else None
|
||||
})
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def update_street(street_id, tenant_id, changes, actor_account_id=None):
|
||||
"""Aktualisiert eine Straße und schreibt History/Log"""
|
||||
db = get_db()
|
||||
old_street = StreetModel.get_by_id(street_id, tenant_id)
|
||||
if not old_street:
|
||||
return False
|
||||
|
||||
StreetModel.update(street_id, tenant_id, **changes)
|
||||
|
||||
# History bei State-Wechsel
|
||||
if 'state' in changes and changes['state'] != old_street['state']:
|
||||
db.execute(
|
||||
'''INSERT INTO street_state_history
|
||||
(tenant_id, street_id, from_state, to_state, group_id, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, street_id, old_street['state'], changes['state'],
|
||||
changes.get('group_id', old_street['group_id']), actor_account_id)
|
||||
)
|
||||
db.commit()
|
||||
log_transaction('street.state_change', 'street', street_id,
|
||||
{'from': old_street['state'], 'to': changes['state']})
|
||||
else:
|
||||
log_transaction('street.update', 'street', street_id, changes)
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
CSV Import Utils für Straßen
|
||||
"""
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
|
||||
|
||||
def parse_streets_csv(file_content):
|
||||
"""
|
||||
Parst CSV mit Delimiter ';'
|
||||
Erwartete Spalten: Name, Hausnummer minimal, Hausnummer maximal, Bounding Box
|
||||
"""
|
||||
streets = []
|
||||
# Versuche mit verschiedenen Encodings
|
||||
try:
|
||||
text = file_content.decode('utf-8')
|
||||
except:
|
||||
try:
|
||||
text = file_content.decode('latin-1')
|
||||
except:
|
||||
text = file_content.decode('cp1252')
|
||||
|
||||
f = io.StringIO(text)
|
||||
reader = csv.DictReader(f, delimiter=';')
|
||||
|
||||
for row in reader:
|
||||
name = row.get('Name') or row.get('name') or row.get('Strasse') or row.get('Straße')
|
||||
hn_min = row.get('Hausnummer minimal') or row.get('hn_min') or row.get('Hausnummer_minimal')
|
||||
hn_max = row.get('Hausnummer maximal') or row.get('hn_max') or row.get('Hausnummer_maximal')
|
||||
bbox = row.get('Bounding Box') or row.get('bbox') or row.get('BoundingBox')
|
||||
|
||||
if not name:
|
||||
continue
|
||||
|
||||
try:
|
||||
hn_min_int = int(hn_min) if hn_min and hn_min.strip() else None
|
||||
except:
|
||||
hn_min_int = None
|
||||
|
||||
try:
|
||||
hn_max_int = int(hn_max) if hn_max and hn_max.strip() else None
|
||||
except:
|
||||
hn_max_int = None
|
||||
|
||||
streets.append({
|
||||
'name': name.strip(),
|
||||
'hn_min': hn_min_int,
|
||||
'hn_max': hn_max_int,
|
||||
'bbox': bbox.strip() if bbox else None
|
||||
})
|
||||
|
||||
return streets
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
Hilfsfunktionen für CMBNet
|
||||
"""
|
||||
from flask import g
|
||||
import json
|
||||
|
||||
|
||||
def get_tenant_id():
|
||||
"""Gibt die aktuelle Tenant-ID aus dem Request-Kontext zurück"""
|
||||
return getattr(g, 'tenant_id', None)
|
||||
|
||||
|
||||
def get_current_account():
|
||||
"""Gibt den aktuellen Account aus dem Request-Kontext zurück"""
|
||||
return getattr(g, 'current_account', None)
|
||||
|
||||
|
||||
def log_transaction(action, entity_type, entity_id, details=None):
|
||||
"""
|
||||
Schreibt einen Eintrag ins Transaktionslog
|
||||
"""
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.core.logging import write_transaction_log
|
||||
|
||||
db = get_db()
|
||||
tenant_id = get_tenant_id()
|
||||
account = get_current_account()
|
||||
actor_id = account['id'] if account else None
|
||||
|
||||
details_json = json.dumps(details) if details else None
|
||||
|
||||
db.execute(
|
||||
'INSERT INTO transaction_log (tenant_id, actor_account_id, action, entity_type, entity_id, details) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(tenant_id, actor_id, action, entity_type, entity_id, details_json)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# Auch ins Logfile schreiben
|
||||
write_transaction_log(tenant_id, actor_id, account['name'] if account else None, action, entity_type, entity_id, details)
|
||||
@@ -0,0 +1,2 @@
|
||||
from .auth import auth_bp
|
||||
from .main import views_bp
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
Authentifizierungs-Views
|
||||
"""
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, session, flash, g
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.auth import verify_password
|
||||
|
||||
auth_bp = Blueprint('auth', __name__)
|
||||
|
||||
|
||||
@auth_bp.before_request
|
||||
def load_tenant():
|
||||
"""Lädt Tenant aus URL"""
|
||||
tenant_code = request.view_args.get('tenant')
|
||||
if tenant_code:
|
||||
db = get_db()
|
||||
tenant = db.execute('SELECT * FROM tenants WHERE code = ?', (tenant_code,)).fetchone()
|
||||
if not tenant:
|
||||
flash('Ungültiger Mandant', 'error')
|
||||
return redirect(url_for('auth.login_select'))
|
||||
g.tenant_id = tenant['id']
|
||||
g.tenant_code = tenant['code']
|
||||
|
||||
|
||||
@auth_bp.route('/login', methods=['GET', 'POST'])
|
||||
def login(**kwargs):
|
||||
"""Login-View"""
|
||||
tenant_code = g.tenant_code
|
||||
next_url = request.args.get('next')
|
||||
|
||||
if request.method == 'POST':
|
||||
username = request.form.get('username', '').strip()
|
||||
password = request.form.get('password', '')
|
||||
tenant_selected = request.form.get('tenant', tenant_code)
|
||||
|
||||
db = get_db()
|
||||
# Überprüfe Account für den Tenant
|
||||
account = db.execute(
|
||||
'SELECT a.*, t.code as tenant_code FROM accounts a JOIN tenants t ON a.tenant_id = t.id WHERE a.name = ? AND t.code = ?',
|
||||
(username, tenant_selected)
|
||||
).fetchone()
|
||||
|
||||
if account and verify_password(account['password_hash'], password):
|
||||
# Login erfolgreich
|
||||
session['account_id'] = account['id']
|
||||
session['tenant_id'] = account['tenant_id']
|
||||
session['tenant_code'] = account['tenant_code']
|
||||
session['role'] = account['role']
|
||||
session['username'] = account['name']
|
||||
|
||||
# Weiterleitung
|
||||
if next_url:
|
||||
return redirect(next_url)
|
||||
|
||||
# Rollenbasierte Weiterleitung
|
||||
role = account['role']
|
||||
if role == 'Administrator':
|
||||
return redirect(url_for('admin.accounts', tenant=tenant_selected))
|
||||
elif role == 'Dispatcher':
|
||||
return redirect(url_for('views.dispatcher', tenant=tenant_selected))
|
||||
elif role == 'Beobachter':
|
||||
return redirect(url_for('views.praesentation', tenant=tenant_selected))
|
||||
elif role == 'Gruppe':
|
||||
return redirect(url_for('views.gruppen', tenant=tenant_selected))
|
||||
else:
|
||||
return redirect(url_for('views.oeffentlich', tenant=tenant_selected))
|
||||
else:
|
||||
flash('Ungültiger Benutzername oder Passwort', 'error')
|
||||
|
||||
return render_template('login.html', tenant_code=tenant_code)
|
||||
|
||||
|
||||
@auth_bp.route('/login/select')
|
||||
def login_select(**kwargs):
|
||||
"""Mandantenauswahl für Login"""
|
||||
return render_template('login_select.html')
|
||||
|
||||
|
||||
@auth_bp.route('/logout')
|
||||
def logout(**kwargs):
|
||||
"""Logout"""
|
||||
session.clear()
|
||||
tenant_code = g.get('tenant_code') or request.args.get('tenant') or 'RV'
|
||||
return redirect(url_for('auth.login', tenant=tenant_code))
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
Haupt-Views
|
||||
"""
|
||||
from flask import Blueprint, render_template, g, redirect, url_for
|
||||
from cmbnet.auth import login_required
|
||||
|
||||
views_bp = Blueprint('views', __name__)
|
||||
|
||||
|
||||
@views_bp.route('/')
|
||||
@login_required
|
||||
def index(**kwargs):
|
||||
"""Startseite - Weiterleitung je nach Rolle"""
|
||||
role = g.current_account['role'] if hasattr(g, 'current_account') else None
|
||||
tenant = g.tenant_code
|
||||
|
||||
if role == 'Administrator':
|
||||
return redirect(url_for('admin.accounts', tenant=tenant))
|
||||
elif role == 'Dispatcher':
|
||||
return redirect(url_for('views.dispatcher', tenant=tenant))
|
||||
elif role == 'Beobachter':
|
||||
return redirect(url_for('views.praesentation', tenant=tenant))
|
||||
elif role == 'Gruppe':
|
||||
return redirect(url_for('views.gruppen', tenant=tenant))
|
||||
else:
|
||||
return redirect(url_for('views.oeffentlich', tenant=tenant))
|
||||
|
||||
|
||||
@views_bp.route('/dispatcher')
|
||||
@login_required
|
||||
def dispatcher(**kwargs):
|
||||
"""Dispatcher-View"""
|
||||
return render_template('dispatcher.html')
|
||||
|
||||
|
||||
@views_bp.route('/dispatcher_mobil')
|
||||
@login_required
|
||||
def dispatcher_mobil(**kwargs):
|
||||
"""Dispatcher-Mobil-View"""
|
||||
return render_template('dispatcher_mobil.html')
|
||||
|
||||
|
||||
@views_bp.route('/gruppen')
|
||||
@login_required
|
||||
def gruppen(**kwargs):
|
||||
"""Gruppen-View"""
|
||||
return render_template('gruppen.html')
|
||||
|
||||
|
||||
@views_bp.route('/praesentation')
|
||||
@login_required
|
||||
def praesentation(**kwargs):
|
||||
"""Präsentations-View"""
|
||||
return render_template('praesentation.html')
|
||||
|
||||
|
||||
@views_bp.route('/oeffentlich')
|
||||
def oeffentlich(**kwargs):
|
||||
"""Öffentlicher-View"""
|
||||
return render_template('oeffentlich.html')
|
||||
@@ -0,0 +1,4 @@
|
||||
from .broker import WebSocketBroker
|
||||
from .protocol import WSMessage
|
||||
|
||||
broker = WebSocketBroker()
|
||||
@@ -0,0 +1,754 @@
|
||||
"""
|
||||
WebSocket Broker - Kernkomponente für Realtime-Kommunikation
|
||||
|
||||
Der Broker nimmt Nachrichten aus WebSocket-Verbindungen (und aus HTTP-Handlern)
|
||||
entgegen, wertet den Code aus, bestimmt den erlaubten Empfängerkreis und stellt
|
||||
die Nachricht zu.
|
||||
|
||||
Wichtige Regeln aus der Spezifikation:
|
||||
- Code < 100: rein interne Nachrichten (z. B. Authentifizierung, Heartbeat).
|
||||
- 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,
|
||||
damit sie bei einer späteren Anmeldung als "Late Entry" nachgeliefert werden
|
||||
können. Nachrichten, die älter als LATE_ENTRY_MAX_AGE_HOURS (Default 8h) sind,
|
||||
werden gelöscht.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from flask import current_app
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
class WebSocketBroker:
|
||||
def __init__(self):
|
||||
# connections[tenant_id][account_id] = {
|
||||
# 'ws': <WebSocket-Objekt>,
|
||||
# 'role': <Rolle des Accounts>,
|
||||
# 'group_id': <verknüpfte Gruppe oder None>,
|
||||
# }
|
||||
self.connections = {}
|
||||
# authenticated[tenant_id][account_id] = True
|
||||
# Erst nach erfolgreichem Code-0-Handshake darf ein Client Nachrichten
|
||||
# über die Verbindung senden.
|
||||
self.authenticated = {}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Verbindungen und Authentifizierung
|
||||
# ------------------------------------------------------------------
|
||||
def register_connection(self, tenant_id, account_id, ws, role=None, group_id=None):
|
||||
"""Registriert eine neue, noch nicht authentifizierte Verbindung.
|
||||
|
||||
Rolle und Gruppenzuordnung werden direkt mitgespeichert. Sie werden
|
||||
später für die Empfängerermittlung und für das Cleanup benötigt.
|
||||
"""
|
||||
db = get_db()
|
||||
account = db.execute(
|
||||
'SELECT role FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
if not account:
|
||||
return False
|
||||
|
||||
if role is None:
|
||||
role = account['role']
|
||||
|
||||
# Für Gruppen-Accounts die zugehörige Gruppe ermitteln. Ein Account der
|
||||
# Rolle "Gruppe" ist genau einer Gruppe zugeordnet.
|
||||
if group_id is None and role == 'Gruppe':
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
group_id = group['id'] if group else None
|
||||
|
||||
if tenant_id not in self.connections:
|
||||
self.connections[tenant_id] = {}
|
||||
|
||||
# Eine neue Verbindung muss den Token-Handshake erneut durchlaufen.
|
||||
# Ein eventuell noch gesetzter Auth-Status einer älteren Verbindung
|
||||
# desselben Accounts darf nicht übernommen werden.
|
||||
authenticated = self.authenticated.get(tenant_id)
|
||||
if authenticated:
|
||||
authenticated.pop(account_id, None)
|
||||
|
||||
self.connections[tenant_id][account_id] = {
|
||||
'ws': ws,
|
||||
'role': role,
|
||||
'group_id': group_id,
|
||||
'last_ping': datetime.now()
|
||||
}
|
||||
return True
|
||||
|
||||
def is_authenticated(self, tenant_id, account_id):
|
||||
"""Prüft, ob eine Verbindung den Code-0-Handshake erfolgreich absolviert hat."""
|
||||
return self.authenticated.get(tenant_id, {}).get(account_id, False)
|
||||
|
||||
def authenticate(self, tenant_id, account_id, token):
|
||||
"""Authentifiziert eine Verbindung anhand des Einmal-Tokens (Code 0)."""
|
||||
db = get_db()
|
||||
token_row = db.execute(
|
||||
'SELECT * FROM ws_tokens WHERE token = ? AND tenant_id = ? '
|
||||
'AND account_id = ? AND used = 0',
|
||||
(token, tenant_id, account_id)
|
||||
).fetchone()
|
||||
|
||||
if not token_row:
|
||||
return False
|
||||
|
||||
# Ablaufzeit prüfen (Tokens sind nur kurzzeitig gültig).
|
||||
if token_row['expires_at']:
|
||||
try:
|
||||
expires = datetime.fromisoformat(token_row['expires_at'].replace('Z', '+00:00'))
|
||||
# SQLite liefert naive Zeitstempel; ein Vergleich mit einer
|
||||
# zeitzonenbehafteten Zeit wäre nicht möglich.
|
||||
if expires.tzinfo is not None:
|
||||
expires = expires.astimezone().replace(tzinfo=None)
|
||||
if expires < datetime.now():
|
||||
return False
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
# Token darf nur einmal verwendet werden.
|
||||
db.execute('UPDATE ws_tokens SET used = 1 WHERE id = ?', (token_row['id'],))
|
||||
db.commit()
|
||||
|
||||
if tenant_id not in self.authenticated:
|
||||
self.authenticated[tenant_id] = {}
|
||||
self.authenticated[tenant_id][account_id] = True
|
||||
|
||||
# Nach erfolgreicher Authentifizierung dürfen die gespeicherten
|
||||
# Nachrichten der letzten 8 Stunden nachgeliefert werden.
|
||||
self.send_late_entries(tenant_id, account_id)
|
||||
return True
|
||||
|
||||
def remove_connection(self, tenant_id, account_id, ws=None):
|
||||
"""Entfernt eine Verbindung.
|
||||
|
||||
Wenn ein Account mehrere Tabs/Verbindungen öffnet, wird nur die
|
||||
tatsächlich beendete Verbindung entfernt (ws-Vergleich), nicht die
|
||||
zuletzt registrierte.
|
||||
"""
|
||||
connections = self.connections.get(tenant_id)
|
||||
if connections and account_id in connections:
|
||||
if ws is None or connections[account_id].get('ws') is ws:
|
||||
del connections[account_id]
|
||||
# Nur wenn die tatsächlich beendete Verbindung die aktuelle
|
||||
# war, darf auch der Authentifizierungsstatus entfernt werden.
|
||||
authenticated = self.authenticated.get(tenant_id)
|
||||
if authenticated and account_id in authenticated:
|
||||
del authenticated[account_id]
|
||||
|
||||
def _get_connection(self, tenant_id, account_id):
|
||||
return self.connections.get(tenant_id, {}).get(account_id)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Late Entry
|
||||
# ------------------------------------------------------------------
|
||||
def send_late_entries(self, tenant_id, account_id):
|
||||
"""Sendet gespeicherte Nachrichten (Code >= 1000) der letzten 8 Stunden.
|
||||
|
||||
Es werden ausschließlich Nachrichten zugestellt, für die der Account
|
||||
laut Protokoll berechtigt ist. Die Zustellung erfolgt chronologisch.
|
||||
Anschließend werden abgelaufene Nachrichten gelöscht.
|
||||
"""
|
||||
db = get_db()
|
||||
cutoff = self._late_entry_cutoff()
|
||||
|
||||
messages = db.execute(
|
||||
'SELECT * FROM ws_messages_store WHERE tenant_id = ? AND ts >= ? '
|
||||
'ORDER BY ts ASC, id ASC',
|
||||
(tenant_id, cutoff)
|
||||
).fetchall()
|
||||
|
||||
conn = self._get_connection(tenant_id, account_id)
|
||||
if not conn:
|
||||
return
|
||||
|
||||
for msg_row in messages:
|
||||
if not self._is_allowed_for_client(tenant_id, account_id, msg_row):
|
||||
continue
|
||||
|
||||
msg = WSMessage(
|
||||
sender_id=msg_row['sender_id'],
|
||||
receiver_id=msg_row['receiver_id'],
|
||||
code=msg_row['code'],
|
||||
msg=msg_row['msg'],
|
||||
ts=msg_row['ts']
|
||||
)
|
||||
self._send(tenant_id, account_id, msg)
|
||||
|
||||
# Abgelaufene Nachrichten werden bei jeder Anmeldung aufgeräumt.
|
||||
self.cleanup_old_messages(tenant_id)
|
||||
|
||||
def _late_entry_cutoff(self):
|
||||
"""Zeitstempel (ms), ab dem gespeicherte Nachrichten noch zustellbar sind."""
|
||||
max_age_hours = current_app.config.get('LATE_ENTRY_MAX_AGE_HOURS', 8)
|
||||
return int((datetime.now() - timedelta(hours=max_age_hours)).timestamp() * 1000)
|
||||
|
||||
def cleanup_old_messages(self, tenant_id=None):
|
||||
"""Löscht persistierte Nachrichten, die älter als die Late-Entry-Frist sind."""
|
||||
db = get_db()
|
||||
cutoff = self._late_entry_cutoff()
|
||||
|
||||
if tenant_id is None:
|
||||
db.execute('DELETE FROM ws_messages_store WHERE ts < ?', (cutoff,))
|
||||
else:
|
||||
db.execute(
|
||||
'DELETE FROM ws_messages_store WHERE tenant_id = ? AND ts < ?',
|
||||
(tenant_id, cutoff)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
def _is_allowed_for_client(self, tenant_id, account_id, msg_row):
|
||||
"""Prüft, ob eine persistierte Nachricht für diesen Client bestimmt ist."""
|
||||
db = get_db()
|
||||
account = db.execute(
|
||||
'SELECT * FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
if not account:
|
||||
return False
|
||||
|
||||
role = account['role']
|
||||
code = msg_row['code']
|
||||
|
||||
# Code 1000: Broadcast an Dispatcher, Beobachter und alle Gruppen.
|
||||
if code == 1000:
|
||||
return role in ('Dispatcher', 'Beobachter', 'Gruppe')
|
||||
|
||||
# Code 1100: Dispatcher, Beobachter und die angesprochene Gruppe.
|
||||
if code == 1100:
|
||||
if role in ('Dispatcher', 'Beobachter'):
|
||||
return True
|
||||
if role == 'Gruppe':
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
return bool(group and msg_row['receiver_id'] == group['id'])
|
||||
return False
|
||||
|
||||
# Code 2000: nur Dispatcher und Beobachter.
|
||||
if code == 2000:
|
||||
return role in ('Dispatcher', 'Beobachter')
|
||||
|
||||
return False
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Nachrichtenverarbeitung
|
||||
# ------------------------------------------------------------------
|
||||
def route_message(self, tenant_id, message, apply_business=False):
|
||||
"""Wertet den Code aus, persistiert ggf. und stellt die Nachricht zu.
|
||||
|
||||
``apply_business`` wird nur für Nachrichten verwendet, die direkt über
|
||||
die WebSocket-Route eingehen. Serverintern erzeugte Nachrichten (z. B.
|
||||
aus der Admin-API) haben die Datenbank bereits aktualisiert und dürfen
|
||||
deshalb nicht ein zweites Mal angewendet werden.
|
||||
"""
|
||||
db = get_db()
|
||||
|
||||
# Absender muss zum Mandanten gehören. Die Absender-ID wird in der
|
||||
# WebSocket-Route aus der Session gesetzt und kann nicht gefälscht
|
||||
# werden.
|
||||
sender = db.execute(
|
||||
'SELECT * FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(message.sender_id, tenant_id)
|
||||
).fetchone()
|
||||
if not sender:
|
||||
return
|
||||
|
||||
code = message.code
|
||||
|
||||
# Code 0 wird ausschließlich in der WebSocket-Route (Handshake)
|
||||
# verarbeitet und niemals weitergeleitet.
|
||||
if code <= 0:
|
||||
return
|
||||
|
||||
# Code 1 sendet ausschließlich der Server (Heartbeat-Routine).
|
||||
# Nachrichten dieses Typs von Clients werden ignoriert.
|
||||
if code == 1:
|
||||
return
|
||||
|
||||
# Code 2 ist die Antwort eines Clients auf den Heartbeat. Sie wird nur
|
||||
# an Dispatcher-Views weitergeleitet und nicht gespeichert.
|
||||
if code == 2:
|
||||
self._deliver(tenant_id, message, sender)
|
||||
return
|
||||
|
||||
# Sonstige interne Codes (< 100) werden nicht an die Oberfläche gegeben.
|
||||
if code < 100:
|
||||
return
|
||||
|
||||
# Ab hier: fachliche Nachrichten (>= 100).
|
||||
# Zustandsänderungen, die ein Client per WebSocket meldet, werden vor
|
||||
# der Zustellung in der Datenbank persistiert. So sind sie auch nach
|
||||
# einem Neuladen der Seite wieder sichtbar.
|
||||
if apply_business and code in (100, 200, 300):
|
||||
if not self._apply_business_change(tenant_id, message, sender):
|
||||
return
|
||||
|
||||
message = self._prepare_message(tenant_id, message, sender)
|
||||
|
||||
# Ab Code 1000 werden Nachrichten für die Late-Entry-Funktion
|
||||
# gespeichert. Gespeichert wird die bereits aufbereitete Nachricht
|
||||
# (bei Code 1100 inklusive Aliasname-Präfix).
|
||||
if code >= 1000:
|
||||
self._persist_message(tenant_id, message)
|
||||
|
||||
self._deliver(tenant_id, message, sender)
|
||||
|
||||
def _apply_business_change(self, tenant_id, message, sender):
|
||||
"""Persistiert Code 100/200/300 aus einer WebSocket-Nachricht.
|
||||
|
||||
Gibt ``False`` zurück, wenn die Nachricht ungültig oder für den
|
||||
Absender nicht erlaubt ist. In diesem Fall wird sie nicht zugestellt.
|
||||
"""
|
||||
payload = self._payload(message)
|
||||
if not isinstance(payload, dict):
|
||||
return False
|
||||
|
||||
if message.code == 100:
|
||||
return self._apply_street_change(tenant_id, message, sender, payload)
|
||||
if message.code == 200:
|
||||
return self._apply_group_state_change(tenant_id, message, sender, payload)
|
||||
if message.code == 300:
|
||||
return self._apply_group_position_change(tenant_id, message, sender, payload)
|
||||
return False
|
||||
|
||||
def _apply_street_change(self, tenant_id, message, sender, payload):
|
||||
"""Wendet einen Straßen-State-Wechsel aus einer Code-100-Nachricht an."""
|
||||
if sender['role'] not in ('Dispatcher', 'Administrator'):
|
||||
return False
|
||||
|
||||
db = get_db()
|
||||
street = None
|
||||
street_id = payload.get('street_id')
|
||||
if street_id is not None:
|
||||
try:
|
||||
street_id = int(street_id)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
street = db.execute(
|
||||
'SELECT * FROM streets WHERE id = ? AND tenant_id = ?',
|
||||
(street_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
if not street and payload.get('name'):
|
||||
street = db.execute(
|
||||
'SELECT * FROM streets WHERE name = ? AND tenant_id = ?',
|
||||
(str(payload['name']), tenant_id)
|
||||
).fetchone()
|
||||
|
||||
if not street:
|
||||
return False
|
||||
|
||||
new_state = payload.get('state')
|
||||
if new_state not in ('unbearbeitet', 'zugewiesen', 'erledigt'):
|
||||
return False
|
||||
|
||||
if 'group_id' in payload:
|
||||
group_id = payload['group_id']
|
||||
if group_id in ('', None):
|
||||
group_id = None
|
||||
else:
|
||||
try:
|
||||
group_id = int(group_id)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
else:
|
||||
group_id = street['group_id']
|
||||
|
||||
# Unbearbeitet bedeutet immer "keine Gruppe". Für "zugewiesen" ist
|
||||
# dagegen eine gültige Gruppe erforderlich.
|
||||
if new_state == 'unbearbeitet':
|
||||
group_id = None
|
||||
elif new_state == 'zugewiesen' and group_id is None:
|
||||
return False
|
||||
|
||||
if group_id is not None:
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if not group:
|
||||
return False
|
||||
|
||||
old_state = street['state']
|
||||
old_group_id = street['group_id']
|
||||
changed = old_state != new_state or old_group_id != group_id
|
||||
|
||||
if changed:
|
||||
db.execute(
|
||||
'UPDATE streets SET state = ?, group_id = ?, updated_at = CURRENT_TIMESTAMP '
|
||||
'WHERE id = ? AND tenant_id = ?',
|
||||
(new_state, group_id, street['id'], tenant_id)
|
||||
)
|
||||
db.execute(
|
||||
'''INSERT INTO street_state_history
|
||||
(tenant_id, street_id, from_state, to_state, group_id, actor_account_id, reason)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, street['id'], old_state, new_state,
|
||||
group_id, sender['id'], 'ws_code_100')
|
||||
)
|
||||
db.commit()
|
||||
self._log_business(tenant_id, sender['id'], 'street.state_change', 'street',
|
||||
street['id'], {'from': old_state, 'to': new_state,
|
||||
'group_id': group_id})
|
||||
|
||||
# Für die Empfängerermittlung muss die alte Gruppe bekannt bleiben:
|
||||
# Bei einem Gruppenwechsel erhält sowohl die alte als auch die neue
|
||||
# Gruppe die Code-100-Nachricht.
|
||||
message._old_group_id = old_group_id
|
||||
message.msg = json.dumps({
|
||||
'name': street['name'],
|
||||
'state': new_state,
|
||||
'actor': sender['id'],
|
||||
'street_id': street['id'],
|
||||
'group_id': group_id
|
||||
}, ensure_ascii=False)
|
||||
return True
|
||||
|
||||
def _apply_group_state_change(self, tenant_id, message, sender, payload):
|
||||
"""Wendet einen Gruppen-State-Wechsel aus einer Code-200-Nachricht an."""
|
||||
if sender['role'] not in ('Dispatcher', 'Administrator', 'Gruppe'):
|
||||
return False
|
||||
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
if not group_id:
|
||||
return False
|
||||
|
||||
db = get_db()
|
||||
group = db.execute(
|
||||
'SELECT * FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if not group:
|
||||
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
|
||||
|
||||
new_state = payload.get('state')
|
||||
if new_state not in ('offen', 'unterwegs', 'online', 'pausierend', 'fertig'):
|
||||
return False
|
||||
|
||||
if new_state != group['state']:
|
||||
db.execute(
|
||||
'UPDATE groups SET state = ?, updated_at = CURRENT_TIMESTAMP '
|
||||
'WHERE id = ? AND tenant_id = ?',
|
||||
(new_state, group_id, tenant_id)
|
||||
)
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon,
|
||||
last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, group['state'], new_state,
|
||||
group['last_lat'], group['last_lon'], group['last_pos_at'], sender['id'])
|
||||
)
|
||||
db.commit()
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {'state': new_state})
|
||||
self._log_business(tenant_id, sender['id'], 'group.state_change', 'group',
|
||||
group_id, {'from': group['state'], 'to': new_state})
|
||||
|
||||
message.receiver_id = group_id
|
||||
message.msg = json.dumps({
|
||||
'group_id': group_id,
|
||||
'state': new_state,
|
||||
'actor': sender['id']
|
||||
}, ensure_ascii=False)
|
||||
return True
|
||||
|
||||
def _apply_group_position_change(self, tenant_id, message, sender, payload):
|
||||
"""Wendet eine Positionsänderung aus einer Code-300-Nachricht an."""
|
||||
if sender['role'] not in ('Dispatcher', 'Administrator', 'Gruppe'):
|
||||
return False
|
||||
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
if not group_id:
|
||||
return False
|
||||
|
||||
db = get_db()
|
||||
group = db.execute(
|
||||
'SELECT * FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if not group:
|
||||
return False
|
||||
|
||||
if sender['role'] == 'Gruppe' and group['account_id'] != sender['id']:
|
||||
return False
|
||||
|
||||
try:
|
||||
lat = float(payload.get('lat'))
|
||||
lon = float(payload.get('lon'))
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
||||
return False
|
||||
|
||||
# Der Server setzt den Zeitstempel, damit die Progressbar nicht durch
|
||||
# manipulierbare Client-Zeitangaben verfälscht wird.
|
||||
pos_at = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
|
||||
ts_ms = int(time.time() * 1000)
|
||||
|
||||
db.execute(
|
||||
'UPDATE groups SET last_lat = ?, last_lon = ?, last_pos_at = ?, '
|
||||
'updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?',
|
||||
(lat, lon, pos_at, group_id, tenant_id)
|
||||
)
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon,
|
||||
last_pos_at, actor_account_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)''',
|
||||
(tenant_id, group_id, group['state'], group['state'],
|
||||
lat, lon, pos_at, sender['id'])
|
||||
)
|
||||
db.commit()
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {
|
||||
'last_lat': lat,
|
||||
'last_lon': lon,
|
||||
'last_pos_at': pos_at
|
||||
})
|
||||
self._log_business(tenant_id, sender['id'], 'group.position_change', 'group',
|
||||
group_id, {'lat': lat, 'lon': lon})
|
||||
|
||||
message.receiver_id = group_id
|
||||
# Auch der Nachrichten-Zeitstempel wird serverseitig gesetzt, damit
|
||||
# die Progressbar nicht von einer manipulierten Client-Uhr abhängt.
|
||||
message.ts = ts_ms
|
||||
message.msg = json.dumps({
|
||||
'group_id': group_id,
|
||||
'lat': lat,
|
||||
'lon': lon,
|
||||
'ts': ts_ms,
|
||||
'actor': sender['id']
|
||||
}, ensure_ascii=False)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _log_business(tenant_id, actor_id, action, entity_type, entity_id, details):
|
||||
"""Schreibt eine per WebSocket ausgelöste Änderung ins Transaktionslog."""
|
||||
try:
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'INSERT INTO transaction_log '
|
||||
'(tenant_id, actor_account_id, action, entity_type, entity_id, details) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(tenant_id, actor_id, action, entity_type, entity_id,
|
||||
json.dumps(details, ensure_ascii=False))
|
||||
)
|
||||
db.commit()
|
||||
|
||||
from cmbnet.core.logging import write_transaction_log
|
||||
actor = db.execute(
|
||||
'SELECT name FROM accounts WHERE id = ? AND tenant_id = ?',
|
||||
(actor_id, tenant_id)
|
||||
).fetchone()
|
||||
write_transaction_log(tenant_id, actor_id, actor['name'] if actor else None,
|
||||
action, entity_type, entity_id, details)
|
||||
except Exception as exc:
|
||||
print(f'Transaction log error: {exc}')
|
||||
|
||||
def _prepare_message(self, tenant_id, message, sender):
|
||||
"""Ergänzt Nachrichten um serverseitig abgeleitete Informationen."""
|
||||
db = get_db()
|
||||
payload = self._payload(message)
|
||||
|
||||
if message.code == 1100:
|
||||
# Empfänger ist eine spezielle Gruppe. Die Gruppen-ID wird aus dem
|
||||
# Payload oder dem receiver_id-Feld gelesen.
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
group = self._fetch_group(tenant_id, group_id)
|
||||
message.receiver_id = group_id
|
||||
|
||||
# Spezifikation: Dem Freitext wird der Aliasname der Gruppe
|
||||
# vorangestellt. Ein bereits vorhandenes Präfix wird nicht doppelt
|
||||
# gesetzt.
|
||||
if group:
|
||||
alias = group['aliasname'] or str(group['id'])
|
||||
prefix = f'{alias}: '
|
||||
text = message.msg if isinstance(message.msg, str) else json.dumps(message.msg)
|
||||
if not text.startswith(prefix):
|
||||
message.msg = prefix + text
|
||||
|
||||
elif message.code == 2000:
|
||||
# Spezifikation: Inhalt ist JSON mit Gruppen-ID und Freitext.
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
message.receiver_id = group_id
|
||||
if isinstance(payload, dict):
|
||||
if group_id and not payload.get('group_id'):
|
||||
payload['group_id'] = group_id
|
||||
message.msg = json.dumps(payload, ensure_ascii=False)
|
||||
elif group_id:
|
||||
message.msg = json.dumps(
|
||||
{'group_id': group_id, 'text': message.msg},
|
||||
ensure_ascii=False
|
||||
)
|
||||
|
||||
return message
|
||||
|
||||
def _deliver(self, tenant_id, message, sender):
|
||||
"""Stellt eine Nachricht an alle berechtigten, verbundenen Clients zu."""
|
||||
for recipient_id in self._get_recipients(tenant_id, message, sender):
|
||||
self._send(tenant_id, recipient_id, message)
|
||||
|
||||
def _send(self, tenant_id, account_id, message):
|
||||
"""Sendet eine Nachricht, falls für den Account eine Verbindung besteht."""
|
||||
# Erst nach erfolgreicher Token-Authentifizierung dürfen Nachrichten
|
||||
# an einen Client zugestellt werden.
|
||||
if not self.is_authenticated(tenant_id, account_id):
|
||||
return
|
||||
conn = self._get_connection(tenant_id, account_id)
|
||||
if not conn:
|
||||
return
|
||||
try:
|
||||
conn['ws'].send(message.to_json())
|
||||
except Exception:
|
||||
# Eine fehlerhafte Verbindung darf den Versand an andere Clients
|
||||
# nicht verhindern. Das Aufräumen übernimmt die Route beim
|
||||
# Schließen der Verbindung.
|
||||
pass
|
||||
|
||||
def _get_recipients(self, tenant_id, message, sender):
|
||||
"""Bestimmt den Empfängerkreis abhängig vom Nachrichtencode."""
|
||||
db = get_db()
|
||||
recipients = set()
|
||||
code = message.code
|
||||
payload = self._payload(message)
|
||||
|
||||
def add_accounts(roles):
|
||||
placeholders = ','.join('?' for _ in roles)
|
||||
rows = db.execute(
|
||||
f'SELECT id FROM accounts WHERE tenant_id = ? AND role IN ({placeholders})',
|
||||
(tenant_id, *roles)
|
||||
).fetchall()
|
||||
recipients.update(row['id'] for row in rows)
|
||||
|
||||
def add_group_account(group_id):
|
||||
if not group_id:
|
||||
return
|
||||
group = db.execute(
|
||||
'SELECT account_id FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if group and group['account_id']:
|
||||
recipients.add(group['account_id'])
|
||||
|
||||
if 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.
|
||||
add_accounts(('Dispatcher', 'Beobachter', 'Gast'))
|
||||
|
||||
group_ids = set()
|
||||
group_id = payload.get('group_id') if isinstance(payload, dict) else None
|
||||
if group_id not in (None, ''):
|
||||
group_ids.add(group_id)
|
||||
old_group_id = getattr(message, '_old_group_id', None)
|
||||
if old_group_id is not None:
|
||||
group_ids.add(old_group_id)
|
||||
|
||||
street_id = payload.get('street_id') if isinstance(payload, dict) else None
|
||||
# Das Payload stammt aus dem vertrauenswürdigen Server-Code. Nur
|
||||
# wenn keine Gruppen-ID enthalten ist, wird die Straße aus der
|
||||
# Datenbank gelesen.
|
||||
if street_id and not (isinstance(payload, dict) and 'group_id' in payload):
|
||||
street = db.execute(
|
||||
'SELECT group_id FROM streets WHERE id = ? AND tenant_id = ?',
|
||||
(street_id, tenant_id)
|
||||
).fetchone()
|
||||
if street and street['group_id'] is not None:
|
||||
group_ids.add(street['group_id'])
|
||||
|
||||
for group_id in group_ids:
|
||||
add_group_account(group_id)
|
||||
|
||||
elif code in (200, 300):
|
||||
# Dispatcher, Beobachter + die betroffene Gruppe.
|
||||
add_accounts(('Dispatcher', 'Beobachter'))
|
||||
group_id = self._resolve_group_id(tenant_id, message, sender, payload)
|
||||
add_group_account(group_id)
|
||||
|
||||
elif code == 1000:
|
||||
# Broadcast an Dispatcher, Beobachter und alle Gruppen.
|
||||
add_accounts(('Dispatcher', 'Beobachter', 'Gruppe'))
|
||||
|
||||
elif code == 1100:
|
||||
# Dispatcher, Beobachter + die spezielle Gruppe.
|
||||
add_accounts(('Dispatcher', 'Beobachter'))
|
||||
add_group_account(message.receiver_id)
|
||||
|
||||
elif code == 2000:
|
||||
# Eine Gruppe sendet an Dispatcher und Beobachter.
|
||||
add_accounts(('Dispatcher', 'Beobachter'))
|
||||
|
||||
elif code == 2:
|
||||
# Heartbeat-Antworten werden nur an Dispatcher-Views weitergegeben.
|
||||
add_accounts(('Dispatcher',))
|
||||
|
||||
return recipients
|
||||
|
||||
def _persist_message(self, tenant_id, message):
|
||||
"""Speichert Nachrichten mit Code >= 1000 für die Late-Entry-Funktion."""
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'INSERT INTO ws_messages_store '
|
||||
'(tenant_id, sender_id, receiver_id, code, ts, msg) '
|
||||
'VALUES (?, ?, ?, ?, ?, ?)',
|
||||
(tenant_id, message.sender_id, message.receiver_id,
|
||||
message.code, message.ts, message.msg)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Hilfsfunktionen
|
||||
# ------------------------------------------------------------------
|
||||
@staticmethod
|
||||
def _payload(message):
|
||||
"""Liefert den JSON-Payload einer Nachricht oder None."""
|
||||
if isinstance(message.msg, dict):
|
||||
return message.msg
|
||||
if not isinstance(message.msg, str):
|
||||
return None
|
||||
try:
|
||||
data = json.loads(message.msg)
|
||||
return data if isinstance(data, dict) else None
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
def _resolve_group_id(self, tenant_id, message, sender, payload):
|
||||
"""Ermittelt die betroffene Gruppen-ID aus Payload, receiver_id oder Absender."""
|
||||
group_id = payload.get('group_id') if isinstance(payload, dict) else None
|
||||
if group_id is None:
|
||||
group_id = message.receiver_id
|
||||
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 = ?',
|
||||
(sender['id'], tenant_id)
|
||||
).fetchone()
|
||||
group_id = group['id'] if group else None
|
||||
if group_id is not None:
|
||||
try:
|
||||
group_id = int(group_id)
|
||||
except (TypeError, ValueError):
|
||||
group_id = None
|
||||
return group_id
|
||||
|
||||
@staticmethod
|
||||
def _fetch_group(tenant_id, group_id):
|
||||
"""Lädt eine Gruppe mandantenspezifisch."""
|
||||
if not group_id:
|
||||
return None
|
||||
return get_db().execute(
|
||||
'SELECT id, aliasname FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
Heartbeat-Routine für WebSocket-Verbindungen
|
||||
|
||||
Der Server sendet jede Minute eine Nachricht mit Code 1 an alle
|
||||
authentifizierten Clients. Die Clients antworten mit Code 2; diese Antwort
|
||||
wird vom Broker ausschließlich an Dispatcher-Views weitergeleitet.
|
||||
|
||||
Zusätzlich räumt die Routine abgelaufene Late-Entry-Nachrichten auf, damit die
|
||||
Tabelle ws_messages_store nicht unbegrenzt wächst.
|
||||
"""
|
||||
from threading import Timer
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
class HeartbeatManager:
|
||||
def __init__(self, interval=60):
|
||||
self.interval = interval
|
||||
self.running = False
|
||||
self.app = None
|
||||
self._timer = None
|
||||
|
||||
def start(self, app=None, interval=None):
|
||||
"""Startet die zyklische Heartbeat-Routine."""
|
||||
# Die App-Referenz wird benötigt, um im Hintergrund-Thread einen
|
||||
# Flask-App-Kontext für Datenbankzugriffe öffnen zu können.
|
||||
if app is not None:
|
||||
self.app = app
|
||||
if interval is not None:
|
||||
self.interval = interval
|
||||
|
||||
if self.running:
|
||||
return
|
||||
self.running = True
|
||||
self._send_heartbeat()
|
||||
|
||||
def stop(self):
|
||||
"""Stoppt die Heartbeat-Routine."""
|
||||
self.running = False
|
||||
if self._timer is not None:
|
||||
self._timer.cancel()
|
||||
self._timer = None
|
||||
|
||||
def _send_heartbeat(self):
|
||||
if not self.running:
|
||||
return
|
||||
|
||||
msg = WSMessage(sender_id=0, code=1, msg='ping')
|
||||
|
||||
# Nur authentifizierte Verbindungen erhalten einen Heartbeat.
|
||||
for tenant_id, connections in list(broker.connections.items()):
|
||||
for account_id, conn_info in list(connections.items()):
|
||||
if not broker.is_authenticated(tenant_id, account_id):
|
||||
continue
|
||||
try:
|
||||
conn_info['ws'].send(msg.to_json())
|
||||
except Exception:
|
||||
# Defekte Verbindungen werden beim Schließen durch die
|
||||
# WebSocket-Route entfernt.
|
||||
pass
|
||||
|
||||
# Abgelaufene persistierte Nachrichten löschen.
|
||||
if self.app is not None:
|
||||
try:
|
||||
with self.app.app_context():
|
||||
broker.cleanup_old_messages()
|
||||
except Exception as exc:
|
||||
print(f'Heartbeat cleanup error: {exc}')
|
||||
|
||||
# Nächsten Heartbeat planen. Der Timer läuft als Daemon, damit er den
|
||||
# Prozess beim Beenden nicht blockiert.
|
||||
self._timer = Timer(self.interval, self._send_heartbeat)
|
||||
self._timer.daemon = True
|
||||
self._timer.start()
|
||||
|
||||
|
||||
heartbeat_manager = HeartbeatManager()
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
WebSocket Protokoll Definition
|
||||
"""
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class WSMessage:
|
||||
def __init__(self, sender_id=None, receiver_id=None, code=0, msg="", ts=None):
|
||||
self.sender_id = sender_id
|
||||
self.receiver_id = receiver_id
|
||||
self.code = code
|
||||
self.msg = msg
|
||||
self.ts = ts or int(datetime.now().timestamp() * 1000)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'sender_id': self.sender_id,
|
||||
'receiver_id': self.receiver_id,
|
||||
'code': self.code,
|
||||
'ts': self.ts,
|
||||
'msg': self.msg
|
||||
}
|
||||
|
||||
def to_json(self):
|
||||
return json.dumps(self.to_dict())
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data):
|
||||
return cls(
|
||||
sender_id=data.get('sender_id'),
|
||||
receiver_id=data.get('receiver_id'),
|
||||
code=data.get('code', 0),
|
||||
msg=data.get('msg', ''),
|
||||
ts=data.get('ts')
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_json(cls, json_str):
|
||||
try:
|
||||
data = json.loads(json_str)
|
||||
return cls.from_dict(data)
|
||||
except:
|
||||
return None
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
WebSocket Routes
|
||||
|
||||
Ablauf einer Verbindung:
|
||||
1. Client verbindet sich mit /<tenant>/ws.
|
||||
2. Client sendet Code 0 mit dem zuvor über die API geholten Einmal-Token.
|
||||
3. Erst nach erfolgreicher Prüfung dürfen fachliche Nachrichten gesendet
|
||||
werden. Vorher wird die Verbindung geschlossen.
|
||||
"""
|
||||
from flask import session
|
||||
from cmbnet.extensions import sock
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
@sock.route('/<tenant>/ws')
|
||||
def ws(ws, tenant):
|
||||
"""WebSocket Endpoint"""
|
||||
from cmbnet.db import get_db
|
||||
|
||||
db = get_db()
|
||||
tenant_row = db.execute('SELECT * FROM tenants WHERE code = ?', (tenant,)).fetchone()
|
||||
if not tenant_row:
|
||||
ws.close()
|
||||
return
|
||||
|
||||
tenant_id = tenant_row['id']
|
||||
account_id = session.get('account_id')
|
||||
if not account_id:
|
||||
ws.close()
|
||||
return
|
||||
|
||||
# Verbindung registrieren, aber noch nicht als authentifiziert markieren.
|
||||
if not broker.register_connection(tenant_id, account_id, ws):
|
||||
ws.close()
|
||||
return
|
||||
|
||||
try:
|
||||
while True:
|
||||
data = ws.receive()
|
||||
if data is None:
|
||||
break
|
||||
|
||||
msg = WSMessage.from_json(data)
|
||||
if not msg:
|
||||
continue
|
||||
|
||||
# Die Absender-ID stammt immer aus der Session und kann vom Client
|
||||
# nicht gefälscht werden.
|
||||
msg.sender_id = account_id
|
||||
|
||||
# Code 0: Authentifizierung über den Einmal-Token.
|
||||
if msg.code == 0:
|
||||
if not broker.authenticate(tenant_id, account_id, msg.msg):
|
||||
ws.close()
|
||||
break
|
||||
continue
|
||||
|
||||
# Fachliche Nachrichten sind erst nach erfolgreicher
|
||||
# Authentifizierung erlaubt.
|
||||
if not broker.is_authenticated(tenant_id, account_id):
|
||||
ws.close()
|
||||
break
|
||||
|
||||
broker.route_message(tenant_id, msg, apply_business=True)
|
||||
|
||||
except Exception as exc:
|
||||
print(f'WebSocket error: {exc}')
|
||||
finally:
|
||||
broker.remove_connection(tenant_id, account_id, ws)
|
||||
@@ -0,0 +1,38 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).parent
|
||||
|
||||
class Config:
|
||||
SECRET_KEY = os.environ.get('CMBNET_SECRET_KEY', 'dev-secret-key-change-in-production')
|
||||
DATABASE_PATH = os.environ.get('CMBNET_DATABASE', str(BASE_DIR / 'instance' / 'cmbnet.sqlite3'))
|
||||
TENANTS = ['BV', 'RV', 'SV']
|
||||
DEFAULT_TENANT = 'RV'
|
||||
|
||||
WS_HEARTBEAT_INTERVAL = int(os.environ.get('CMBNET_WS_HEARTBEAT_INTERVAL', '60'))
|
||||
WS_HEARTBEAT_TIMEOUT = 15
|
||||
LATE_ENTRY_MAX_AGE_HOURS = int(os.environ.get('CMBNET_LATE_ENTRY_MAX_AGE_HOURS', '8'))
|
||||
|
||||
LOG_DIR = BASE_DIR / 'logs'
|
||||
|
||||
MAX_CSV_SIZE_BYTES = 5_000_000
|
||||
|
||||
SESSION_COOKIE_HTTPONLY = True
|
||||
SESSION_COOKIE_SAMESITE = 'Lax'
|
||||
SESSION_COOKIE_SECURE = False # Set to True in production with HTTPS
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SESSION_COOKIE_SECURE = True
|
||||
|
||||
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig
|
||||
}
|
||||
Executable
+116
@@ -0,0 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
import sqlite3
|
||||
import getpass
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
# Versuche werkzeug zu importieren
|
||||
try:
|
||||
from werkzeug.security import generate_password_hash
|
||||
except ImportError:
|
||||
print("Fehler: werkzeug nicht gefunden. Installiere es mit: pip install werkzeug")
|
||||
exit(1)
|
||||
|
||||
def main():
|
||||
print("=== CMBNet Admin-Account erstellen ===\n")
|
||||
|
||||
# Datenbankpfad
|
||||
db_path = Path(__file__).parent / 'instance' / 'cmbnet.sqlite3'
|
||||
|
||||
if not db_path.exists():
|
||||
print(f"Fehler: Datenbank nicht gefunden: {db_path}")
|
||||
print("Führe zuerst aus: flask --app cmbnet init-db")
|
||||
exit(1)
|
||||
|
||||
conn = sqlite3.connect(db_path)
|
||||
conn.row_factory = sqlite3.Row
|
||||
cur = conn.cursor()
|
||||
|
||||
# Mandanten anzeigen
|
||||
cur.execute("SELECT id, code, name FROM tenants ORDER BY code")
|
||||
tenants = cur.fetchall()
|
||||
|
||||
if not tenants:
|
||||
print("Keine Mandanten gefunden. Erstelle sie...")
|
||||
cur.execute("INSERT OR IGNORE INTO tenants (code, name) VALUES ('BV', 'Bezirk BV')")
|
||||
cur.execute("INSERT OR IGNORE INTO tenants (code, name) VALUES ('RV', 'Bezirk RV')")
|
||||
cur.execute("INSERT OR IGNORE INTO tenants (code, name) VALUES ('SV', 'Bezirk SV')")
|
||||
conn.commit()
|
||||
cur.execute("SELECT id, code, name FROM tenants ORDER BY code")
|
||||
tenants = cur.fetchall()
|
||||
|
||||
print("Verfügbare Mandanten:")
|
||||
for t in tenants:
|
||||
print(f" {t['code']} - {t['name']}")
|
||||
print()
|
||||
|
||||
# Auswahl
|
||||
tenant_code = input("Mandant (BV/RV/SV): ").strip().upper()
|
||||
while tenant_code not in [t['code'] for t in tenants]:
|
||||
print("Ungültiger Mandant!")
|
||||
tenant_code = input("Mandant (BV/RV/SV): ").strip().upper()
|
||||
|
||||
cur.execute("SELECT id FROM tenants WHERE code = ?", (tenant_code,))
|
||||
tenant_id = cur.fetchone()['id']
|
||||
|
||||
# Account-Daten
|
||||
username = input("Benutzername: ").strip()
|
||||
while not username:
|
||||
print("Benutzername darf nicht leer sein!")
|
||||
username = input("Benutzername: ").strip()
|
||||
|
||||
# Prüfe ob Account bereits existiert
|
||||
cur.execute("SELECT id FROM accounts WHERE tenant_id = ? AND name = ?", (tenant_id, username))
|
||||
if cur.fetchone():
|
||||
print(f"Fehler: Account '{username}' existiert bereits für Mandant {tenant_code}!")
|
||||
conn.close()
|
||||
exit(1)
|
||||
|
||||
password = getpass.getpass("Passwort: ")
|
||||
password_confirm = getpass.getpass("Passwort wiederholen: ")
|
||||
|
||||
while password != password_confirm:
|
||||
print("Passwörter stimmen nicht überein!")
|
||||
password = getpass.getpass("Passwort: ")
|
||||
password_confirm = getpass.getpass("Passwort wiederholen: ")
|
||||
|
||||
while not password:
|
||||
print("Passwort darf nicht leer sein!")
|
||||
password = getpass.getpass("Passwort: ")
|
||||
password_confirm = getpass.getpass("Passwort wiederholen: ")
|
||||
while password != password_confirm:
|
||||
print("Passwörter stimmen nicht überein!")
|
||||
password = getpass.getpass("Passwort: ")
|
||||
password_confirm = getpass.getpass("Passwort wiederholen: ")
|
||||
|
||||
# Rolle
|
||||
print("\nRollen: Gast, Beobachter, Gruppe, Dispatcher, Administrator")
|
||||
role = input("Rolle [Administrator]: ").strip()
|
||||
if not role:
|
||||
role = 'Administrator'
|
||||
|
||||
valid_roles = ['Gast', 'Beobachter', 'Gruppe', 'Dispatcher', 'Administrator']
|
||||
while role not in valid_roles:
|
||||
print("Ungültige Rolle!")
|
||||
role = input("Rolle [Administrator]: ").strip()
|
||||
if not role:
|
||||
role = 'Administrator'
|
||||
|
||||
# Hash erstellen und Account anlegen
|
||||
password_hash = generate_password_hash(password)
|
||||
|
||||
cur.execute(
|
||||
"INSERT INTO accounts (tenant_id, name, password_hash, role) VALUES (?, ?, ?, ?)",
|
||||
(tenant_id, username, password_hash, role)
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
print(f"\n✅ Account erfolgreich erstellt!")
|
||||
print(f" Mandant: {tenant_code}")
|
||||
print(f" Benutzername: {username}")
|
||||
print(f" Rolle: {role}")
|
||||
|
||||
conn.close()
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
2026-10-22 22:52:47.774 [TENANT:RV] [ACTOR:1(admin)] ACTION:account.create ENTITY:account:2 DETAILS:{'name': 'thomas', 'role': 'Dispatcher'}
|
||||
2026-10-22 23:21:51.655 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.create ENTITY:group:1 DETAILS:{'aliasname': 'Alpha', 'account_id': 2}
|
||||
2026-10-22 23:21:51.658 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_from_history ENTITY:group:1 DETAILS:{'hist_id': 2, 'lat': 50.123, 'lon': 8.456}
|
||||
2026-10-22 23:21:51.661 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_clear ENTITY:group:1 DETAILS:{}
|
||||
2026-10-22 23:21:51.664 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'state': 'unterwegs'}
|
||||
2026-10-22 23:21:51.665 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'aliasname': 'Alpha neu'}
|
||||
2026-10-22 23:21:51.666 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'account_id': 3}
|
||||
2026-10-22 23:21:51.668 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.create ENTITY:group:2 DETAILS:{'aliasname': 'Beta', 'account_id': 2}
|
||||
2026-10-22 23:22:45.650 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_from_history ENTITY:group:1 DETAILS:{'hist_id': 1, 'lat': 50.1, 'lon': 8.2}
|
||||
2026-10-22 23:22:54.817 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_from_history ENTITY:group:1 DETAILS:{'hist_id': 1, 'lat': 50.1, 'lon': 8.2}
|
||||
2026-10-22 23:22:54.820 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_clear ENTITY:group:1 DETAILS:{}
|
||||
2026-10-22 23:24:01.082 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.create ENTITY:group:1 DETAILS:{'aliasname': 'Alpha', 'account_id': 2}
|
||||
2026-10-22 23:24:01.086 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_from_history ENTITY:group:1 DETAILS:{'hist_id': 2, 'lat': 50.123, 'lon': 8.456}
|
||||
2026-10-22 23:24:01.089 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_clear ENTITY:group:1 DETAILS:{}
|
||||
2026-10-22 23:24:01.091 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'state': 'unterwegs'}
|
||||
2026-10-22 23:24:01.092 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'aliasname': 'Alpha neu'}
|
||||
2026-10-22 23:24:01.094 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'account_id': 3}
|
||||
2026-10-22 23:24:01.095 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.create ENTITY:group:2 DETAILS:{'aliasname': 'Beta', 'account_id': 2}
|
||||
2026-10-22 23:24:01.168 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_from_history ENTITY:group:1 DETAILS:{'hist_id': 1, 'lat': 50.1, 'lon': 8.2}
|
||||
2026-10-22 23:24:01.171 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_clear ENTITY:group:1 DETAILS:{}
|
||||
2026-10-22 23:25:35.444 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.create ENTITY:group:1 DETAILS:{'aliasname': 'Test1', 'account_id': None}
|
||||
2026-10-22 23:26:13.833 [TENANT:RV] [ACTOR:1(admin)] ACTION:account.create ENTITY:account:3 DETAILS:{'name': 'Test1', 'role': 'Gruppe'}
|
||||
2026-10-22 23:26:25.636 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'account_id': 3}
|
||||
2026-10-22 23:40:32.313 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:40:32.314 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:40:32.315 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'unbearbeitet', 'group_id': None}
|
||||
2026-10-22 23:40:32.316 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'erledigt', 'group_id': 1}
|
||||
2026-10-22 23:40:32.317 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.12, 'lon': 8.34}
|
||||
2026-10-22 23:40:32.318 [TENANT:RV] [ACTOR:3(Gruppe 1 Account)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.22, 'lon': 8.44}
|
||||
2026-10-22 23:40:32.319 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
2026-10-22 23:40:43.752 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:40:43.753 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:40:43.754 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'unbearbeitet', 'group_id': None}
|
||||
2026-10-22 23:40:43.755 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'erledigt', 'group_id': 1}
|
||||
2026-10-22 23:40:43.756 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.12, 'lon': 8.34}
|
||||
2026-10-22 23:40:43.757 [TENANT:RV] [ACTOR:3(Gruppe 1 Account)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.22, 'lon': 8.44}
|
||||
2026-10-22 23:40:43.758 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
2026-10-22 23:42:41.855 [TENANT:RV] [ACTOR:1(disp)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:42:42.561 [TENANT:RV] [ACTOR:1(disp)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:42:42.564 [TENANT:RV] [ACTOR:1(disp)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.33, 'lon': 8.55}
|
||||
2026-10-22 23:42:43.272 [TENANT:RV] [ACTOR:1(disp)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
2026-10-22 23:42:50.051 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.create ENTITY:group:1 DETAILS:{'aliasname': 'Alpha', 'account_id': 2}
|
||||
2026-10-22 23:42:50.053 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_from_history ENTITY:group:1 DETAILS:{'hist_id': 2, 'lat': 50.123, 'lon': 8.456}
|
||||
2026-10-22 23:42:50.056 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_clear ENTITY:group:1 DETAILS:{}
|
||||
2026-10-22 23:42:50.058 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'state': 'unterwegs'}
|
||||
2026-10-22 23:42:50.060 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'aliasname': 'Alpha neu'}
|
||||
2026-10-22 23:42:50.061 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.update ENTITY:group:1 DETAILS:{'account_id': 3}
|
||||
2026-10-22 23:42:50.063 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.create ENTITY:group:2 DETAILS:{'aliasname': 'Beta', 'account_id': 2}
|
||||
2026-10-22 23:42:50.676 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_from_history ENTITY:group:1 DETAILS:{'hist_id': 1, 'lat': 50.1, 'lon': 8.2}
|
||||
2026-10-22 23:42:50.679 [TENANT:RV] [ACTOR:1(admin)] ACTION:group.position_clear ENTITY:group:1 DETAILS:{}
|
||||
2026-10-22 23:47:10.037 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:47:10.038 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:47:10.039 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'unbearbeitet', 'group_id': None}
|
||||
2026-10-22 23:47:10.040 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'erledigt', 'group_id': 1}
|
||||
2026-10-22 23:47:10.042 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.12, 'lon': 8.34}
|
||||
2026-10-22 23:47:10.043 [TENANT:RV] [ACTOR:3(Gruppe 1 Account)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.22, 'lon': 8.44}
|
||||
2026-10-22 23:47:10.043 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
2026-10-22 23:47:13.193 [TENANT:RV] [ACTOR:1(disp)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:47:13.904 [TENANT:RV] [ACTOR:1(disp)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:47:13.908 [TENANT:RV] [ACTOR:1(disp)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.33, 'lon': 8.55}
|
||||
2026-10-22 23:47:14.617 [TENANT:RV] [ACTOR:1(disp)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
2026-10-22 23:49:15.249 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:49:15.251 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:49:15.251 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'unbearbeitet', 'group_id': None}
|
||||
2026-10-22 23:49:15.253 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'erledigt', 'group_id': 1}
|
||||
2026-10-22 23:49:15.254 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.12, 'lon': 8.34}
|
||||
2026-10-22 23:49:15.255 [TENANT:RV] [ACTOR:3(Gruppe 1 Account)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.22, 'lon': 8.44}
|
||||
2026-10-22 23:49:15.255 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
2026-10-22 23:50:54.449 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:50:54.451 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:50:54.452 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'unbearbeitet', 'group_id': None}
|
||||
2026-10-22 23:50:54.453 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'erledigt', 'group_id': 1}
|
||||
2026-10-22 23:50:54.454 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.12, 'lon': 8.34}
|
||||
2026-10-22 23:50:54.455 [TENANT:RV] [ACTOR:3(Gruppe 1 Account)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.22, 'lon': 8.44}
|
||||
2026-10-22 23:50:54.456 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
2026-10-22 23:50:58.311 [TENANT:RV] [ACTOR:1(disp)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:50:59.016 [TENANT:RV] [ACTOR:1(disp)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:50:59.019 [TENANT:RV] [ACTOR:1(disp)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.33, 'lon': 8.55}
|
||||
2026-10-22 23:50:59.725 [TENANT:RV] [ACTOR:1(disp)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
2026-10-22 23:57:38.054 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'unbearbeitet', 'to': 'zugewiesen', 'group_id': 1}
|
||||
2026-10-22 23:57:38.056 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'zugewiesen', 'group_id': 2}
|
||||
2026-10-22 23:57:38.057 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'unbearbeitet', 'group_id': None}
|
||||
2026-10-22 23:57:38.058 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:street.state_change ENTITY:street:1 DETAILS:{'from': 'zugewiesen', 'to': 'erledigt', 'group_id': 1}
|
||||
2026-10-22 23:57:38.059 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.12, 'lon': 8.34}
|
||||
2026-10-22 23:57:38.060 [TENANT:RV] [ACTOR:3(Gruppe 1 Account)] ACTION:group.position_change ENTITY:group:1 DETAILS:{'lat': 50.22, 'lon': 8.44}
|
||||
2026-10-22 23:57:38.061 [TENANT:RV] [ACTOR:1(Leitstelle)] ACTION:group.state_change ENTITY:group:1 DETAILS:{'from': 'offen', 'to': 'unterwegs'}
|
||||
@@ -0,0 +1,137 @@
|
||||
-- CMBNet Datenbankschema
|
||||
-- Mandantenfähigkeit: Jede Tabelle hat tenant_id
|
||||
|
||||
-- Mandanten
|
||||
CREATE TABLE IF NOT EXISTS tenants (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
code TEXT UNIQUE NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Accounts
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
role TEXT NOT NULL CHECK(role IN ('Gast', 'Beobachter', 'Gruppe', 'Dispatcher', 'Administrator')),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
UNIQUE(tenant_id, name)
|
||||
);
|
||||
|
||||
-- Gruppen
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
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,
|
||||
account_id INTEGER UNIQUE,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
-- Straßen
|
||||
CREATE TABLE IF NOT EXISTS streets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
state TEXT NOT NULL DEFAULT 'unbearbeitet' CHECK(state IN ('unbearbeitet', 'zugewiesen', 'erledigt')),
|
||||
group_id INTEGER,
|
||||
hn_min INTEGER,
|
||||
hn_max INTEGER,
|
||||
bbox TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (group_id) REFERENCES groups(id)
|
||||
);
|
||||
|
||||
-- Historie Straßen
|
||||
CREATE TABLE IF NOT EXISTS street_state_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
street_id INTEGER NOT NULL,
|
||||
from_state TEXT,
|
||||
to_state TEXT NOT NULL,
|
||||
group_id INTEGER,
|
||||
actor_account_id INTEGER,
|
||||
reason TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (street_id) REFERENCES streets(id),
|
||||
FOREIGN KEY (actor_account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
-- Historie Gruppen
|
||||
CREATE TABLE IF NOT EXISTS group_state_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
group_id INTEGER NOT NULL,
|
||||
from_state TEXT,
|
||||
to_state TEXT NOT NULL,
|
||||
last_lat REAL,
|
||||
last_lon REAL,
|
||||
last_pos_at TIMESTAMP,
|
||||
actor_account_id INTEGER,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (group_id) REFERENCES groups(id),
|
||||
FOREIGN KEY (actor_account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
-- WebSocket Tokens
|
||||
CREATE TABLE IF NOT EXISTS ws_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
token TEXT UNIQUE NOT NULL,
|
||||
session_id TEXT,
|
||||
expires_at TIMESTAMP,
|
||||
used BOOLEAN DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
-- Persistierte WebSocket Nachrichten für Code >= 1000
|
||||
CREATE TABLE IF NOT EXISTS ws_messages_store (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
sender_id INTEGER,
|
||||
receiver_id INTEGER,
|
||||
code INTEGER NOT NULL,
|
||||
ts INTEGER NOT NULL,
|
||||
msg TEXT,
|
||||
delivered_to TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id)
|
||||
);
|
||||
|
||||
-- Transaktionslog
|
||||
CREATE TABLE IF NOT EXISTS transaction_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
actor_account_id INTEGER,
|
||||
action TEXT NOT NULL,
|
||||
entity_type TEXT NOT NULL,
|
||||
entity_id INTEGER,
|
||||
details TEXT,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (actor_account_id) REFERENCES accounts(id)
|
||||
);
|
||||
|
||||
-- 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_streets_tenant ON streets(tenant_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_tokens_token ON ws_tokens(token);
|
||||
CREATE INDEX IF NOT EXISTS idx_ws_messages_ts ON ws_messages_store(ts);
|
||||
@@ -0,0 +1,5 @@
|
||||
Flask>=3.0.0
|
||||
Werkzeug>=3.0.0
|
||||
flask-sock>=0.7.0
|
||||
simple-websocket>=1.0.0
|
||||
python-dateutil>=2.9.0
|
||||
@@ -0,0 +1,427 @@
|
||||
/* Dispatcher-View: Karte 2/3 links, Kontrollansicht 1/3 rechts */
|
||||
|
||||
body.dispatcher-page {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
background: #eef1f4;
|
||||
}
|
||||
|
||||
body.dispatcher-page main.container {
|
||||
width: 100vw;
|
||||
max-width: none;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.dispatcher-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 2fr) minmax(320px, 1fr);
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.map-pane {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
background: #dce3e8;
|
||||
}
|
||||
|
||||
#map {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
/* Fadenkreuz-Modus der Karte */
|
||||
.leaflet-container.crosshair,
|
||||
.leaflet-container.crosshair .leaflet-interactive {
|
||||
cursor: crosshair !important;
|
||||
}
|
||||
|
||||
.control-pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
background: var(--card-background-color, #fff);
|
||||
border-left: 1px solid rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
/* ---------- Header ---------- */
|
||||
|
||||
.control-header {
|
||||
flex: 0 0 auto;
|
||||
padding: 0.85rem 1rem 0.6rem;
|
||||
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.clock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.05rem;
|
||||
margin-bottom: 0.55rem;
|
||||
}
|
||||
|
||||
.clock-date {
|
||||
font-size: 0.78rem;
|
||||
color: var(--muted-color, #5b6771);
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.clock-time {
|
||||
font-size: clamp(1.8rem, 4vw, 2.7rem);
|
||||
line-height: 1.05;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.header-controls {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.map-layer-label {
|
||||
flex: 1 1 auto;
|
||||
margin: 0 !important;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.map-layer-label > span {
|
||||
display: block;
|
||||
margin-bottom: 0.15rem;
|
||||
color: var(--muted-color, #5b6771);
|
||||
}
|
||||
|
||||
.map-layer-label select {
|
||||
margin: 0;
|
||||
height: 2.35rem;
|
||||
padding-top: 0.25rem;
|
||||
padding-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.icon-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border-radius: 0.55rem;
|
||||
font-size: 1.2rem;
|
||||
line-height: 1;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
a.icon-button {
|
||||
border: 1px solid rgba(0, 0, 0, 0.18);
|
||||
background: var(--form-element-background-color, #fff);
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.icon-button.active {
|
||||
background: #2f6fdb;
|
||||
border-color: #2f6fdb;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.connection-status {
|
||||
margin-top: 0.45rem;
|
||||
font-size: 0.72rem;
|
||||
color: var(--muted-color, #5b6771);
|
||||
}
|
||||
|
||||
.connection-status.connected {
|
||||
color: #18794e;
|
||||
}
|
||||
|
||||
.connection-status.disconnected {
|
||||
color: #b42318;
|
||||
}
|
||||
|
||||
/* ---------- Accordion ---------- */
|
||||
|
||||
.group-accordion {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 0.7rem;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
.group-empty {
|
||||
padding: 1rem;
|
||||
color: var(--muted-color, #5b6771);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.group-item {
|
||||
margin: 0 0 0.55rem;
|
||||
border: 1px solid rgba(0, 0, 0, 0.12);
|
||||
border-radius: 0.65rem;
|
||||
background: var(--card-background-color, #fff);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.group-item > summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
padding: 0.65rem 0.75rem;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.group-item > summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.group-item > summary::after {
|
||||
content: "▾";
|
||||
margin-left: auto;
|
||||
font-size: 0.8rem;
|
||||
color: var(--muted-color, #5b6771);
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
|
||||
.group-item[open] > summary::after {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.group-dot {
|
||||
flex: 0 0 auto;
|
||||
width: 0.8rem;
|
||||
height: 0.8rem;
|
||||
border-radius: 50%;
|
||||
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.9), 0 0 0 3px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.group-name {
|
||||
min-width: 0;
|
||||
font-weight: 650;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-state {
|
||||
flex: 0 0 auto;
|
||||
margin-left: 0.35rem;
|
||||
padding: 0.1rem 0.45rem;
|
||||
border-radius: 999px;
|
||||
background: rgba(0, 0, 0, 0.07);
|
||||
font-size: 0.7rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.group-details {
|
||||
padding: 0 0.75rem 0.75rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.group-position-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.group-position-row .icon-button {
|
||||
width: 2.25rem;
|
||||
height: 2.25rem;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.group-position-row progress {
|
||||
flex: 1 1 auto;
|
||||
width: auto;
|
||||
height: 0.75rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group-position-meta {
|
||||
font-size: 0.72rem;
|
||||
color: var(--muted-color, #5b6771);
|
||||
}
|
||||
|
||||
.group-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.group-crosshair {
|
||||
width: 2.35rem;
|
||||
height: 2.35rem;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.group-message {
|
||||
margin: 0;
|
||||
cursor: pointer;
|
||||
background: rgba(0, 0, 0, 0.035);
|
||||
font-size: 0.82rem;
|
||||
}
|
||||
|
||||
.group-message:focus {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* ---------- Footer ---------- */
|
||||
|
||||
.control-footer {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
padding: 0.7rem 1rem 0.85rem;
|
||||
border-top: 1px solid rgba(0, 0, 0, 0.1);
|
||||
background: var(--card-background-color, #fff);
|
||||
}
|
||||
|
||||
.slider-control {
|
||||
margin: 0 !important;
|
||||
font-size: 0.74rem;
|
||||
}
|
||||
|
||||
.slider-control > span {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
color: var(--muted-color, #5b6771);
|
||||
}
|
||||
|
||||
.slider-control input[type="range"] {
|
||||
margin: 0.25rem 0 0;
|
||||
height: 1.15rem;
|
||||
}
|
||||
|
||||
.footer-buttons {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.1rem;
|
||||
}
|
||||
|
||||
/* ---------- Dialoge ---------- */
|
||||
|
||||
dialog article {
|
||||
max-height: 90dvh;
|
||||
}
|
||||
|
||||
#chatModal article,
|
||||
.chat-dialog {
|
||||
width: min(44rem, 94vw);
|
||||
max-width: 94vw;
|
||||
}
|
||||
|
||||
.chat-messages {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
max-height: 58dvh;
|
||||
overflow-y: auto;
|
||||
padding: 0.15rem;
|
||||
}
|
||||
|
||||
.chat-empty {
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
color: var(--muted-color, #5b6771);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.chat-message {
|
||||
padding: 0.5rem 0.65rem;
|
||||
border-radius: 0.55rem;
|
||||
background: rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.chat-message.own {
|
||||
background: rgba(47, 111, 219, 0.12);
|
||||
}
|
||||
|
||||
.chat-message-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 0.7rem;
|
||||
margin-bottom: 0.18rem;
|
||||
font-size: 0.7rem;
|
||||
color: var(--muted-color, #5b6771);
|
||||
}
|
||||
|
||||
.chat-message-text {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
/* ---------- Leaflet-Marker ---------- */
|
||||
|
||||
.group-marker-icon {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.group-marker-icon span {
|
||||
display: block;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
background: var(--marker-color, #2f6fdb);
|
||||
border: 2px solid #fff;
|
||||
box-shadow: 0 0 0 2px rgba(0, 0, 0, 0.38), 0 1px 3px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.dispatcher-layout {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: minmax(0, 55vh) minmax(0, 45vh);
|
||||
grid-template-rows: minmax(0, 55dvh) minmax(0, 45dvh);
|
||||
}
|
||||
|
||||
.control-pane {
|
||||
border-left: 0;
|
||||
border-top: 1px solid rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.control-header {
|
||||
padding-top: 0.55rem;
|
||||
padding-bottom: 0.45rem;
|
||||
}
|
||||
|
||||
.clock {
|
||||
flex-direction: row;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.clock-time {
|
||||
font-size: 1.55rem;
|
||||
}
|
||||
|
||||
.group-accordion {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
|
||||
.control-footer {
|
||||
padding: 0.5rem 0.75rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/* CMBNet Custom Styles */
|
||||
article.error {
|
||||
background-color: #f8d7da;
|
||||
border-color: #f5c6cb;
|
||||
color: #721c24;
|
||||
}
|
||||
|
||||
article.success {
|
||||
background-color: #d4edda;
|
||||
border-color: #c3e6cb;
|
||||
color: #155724;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,78 @@
|
||||
const tenant = window.location.pathname.split('/')[1];
|
||||
const apiBase = `/${tenant}/admin/api`;
|
||||
|
||||
function changeRole(accountId, role) {
|
||||
fetch(`${apiBase}/accounts/${accountId}/role`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({role: role})
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) alert('Rolle geändert');
|
||||
});
|
||||
}
|
||||
|
||||
function openPasswordModal(accountId) {
|
||||
document.getElementById('pwdAccountId').value = accountId;
|
||||
document.getElementById('passwordModal').showModal();
|
||||
}
|
||||
|
||||
function closePasswordModal() {
|
||||
document.getElementById('passwordModal').close();
|
||||
document.getElementById('newPassword').value = '';
|
||||
}
|
||||
|
||||
function resetPassword() {
|
||||
const accountId = document.getElementById('pwdAccountId').value;
|
||||
const password = document.getElementById('newPassword').value;
|
||||
fetch(`${apiBase}/accounts/${accountId}/password`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({password: password})
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
alert('Passwort zurückgesetzt');
|
||||
closePasswordModal();
|
||||
} else {
|
||||
alert(data.error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function deleteAccount(accountId) {
|
||||
if (!confirm('Account wirklich löschen?')) return;
|
||||
fetch(`${apiBase}/accounts/${accountId}`, {
|
||||
method: 'DELETE'
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function openCreateAccountModal() {
|
||||
document.getElementById('createAccountModal').showModal();
|
||||
}
|
||||
|
||||
function closeCreateAccountModal() {
|
||||
document.getElementById('createAccountModal').close();
|
||||
document.getElementById('newAccountName').value = '';
|
||||
document.getElementById('newAccountPassword').value = '';
|
||||
}
|
||||
|
||||
function createAccount() {
|
||||
const name = document.getElementById('newAccountName').value;
|
||||
const password = document.getElementById('newAccountPassword').value;
|
||||
const role = document.getElementById('newAccountRole').value;
|
||||
fetch(`${apiBase}/accounts`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({name, password, role})
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
alert('Account angelegt');
|
||||
location.reload();
|
||||
} else {
|
||||
alert(data.error);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
const tenant = window.location.pathname.split('/')[1];
|
||||
const apiBase = `/${tenant}/admin/api`;
|
||||
const GROUP_STATES = ['offen', 'unterwegs', 'online', 'pausierend', 'fertig'];
|
||||
let currentGroupId = null;
|
||||
|
||||
function hasPosition(lat, lon) {
|
||||
return lat !== null && lat !== undefined && lon !== null && lon !== undefined;
|
||||
}
|
||||
|
||||
function formatPosition(lat, lon) {
|
||||
return hasPosition(lat, lon) ? `${lat}, ${lon}` : 'unbekannt';
|
||||
}
|
||||
|
||||
function showError(data) {
|
||||
alert(data && data.error ? data.error : 'Aktion fehlgeschlagen');
|
||||
}
|
||||
|
||||
function makeButton(label, className, handler) {
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.textContent = label;
|
||||
if (className) button.className = className;
|
||||
button.addEventListener('click', handler);
|
||||
return button;
|
||||
}
|
||||
|
||||
function updateGruppe(groupId, data) {
|
||||
fetch(`${apiBase}/gruppen/${groupId}`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(data)
|
||||
}).then(r => r.json()).then(result => {
|
||||
if (!result.success) showError(result);
|
||||
}).catch(() => alert('Server nicht erreichbar'));
|
||||
}
|
||||
|
||||
function deleteGruppe(groupId) {
|
||||
if (!confirm('Gruppe wirklich löschen?')) return;
|
||||
fetch(`${apiBase}/gruppen/${groupId}`, {
|
||||
method: 'DELETE'
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
location.reload();
|
||||
} else {
|
||||
showError(data);
|
||||
}
|
||||
}).catch(() => alert('Server nicht erreichbar'));
|
||||
}
|
||||
|
||||
// === Neue Gruppe ===
|
||||
|
||||
function openCreateGruppeModal() {
|
||||
document.getElementById('gruppeAlias').value = '';
|
||||
document.getElementById('gruppeAccount').value = '';
|
||||
document.getElementById('createGruppeModal').showModal();
|
||||
}
|
||||
|
||||
function closeCreateGruppeModal() {
|
||||
document.getElementById('createGruppeModal').close();
|
||||
document.getElementById('gruppeAlias').value = '';
|
||||
document.getElementById('gruppeAccount').value = '';
|
||||
}
|
||||
|
||||
function buildStateSelect(state) {
|
||||
const select = document.createElement('select');
|
||||
GROUP_STATES.forEach(value => {
|
||||
const option = document.createElement('option');
|
||||
option.value = value;
|
||||
option.textContent = value;
|
||||
option.selected = value === state;
|
||||
select.appendChild(option);
|
||||
});
|
||||
return select;
|
||||
}
|
||||
|
||||
function buildAccountSelect(accountId) {
|
||||
const select = document.createElement('select');
|
||||
const source = document.getElementById('gruppeAccount');
|
||||
Array.from(source.options).forEach(option => {
|
||||
const copy = document.createElement('option');
|
||||
copy.value = option.value;
|
||||
copy.textContent = option.textContent;
|
||||
copy.selected = String(option.value) === String(accountId ?? '');
|
||||
select.appendChild(copy);
|
||||
});
|
||||
return select;
|
||||
}
|
||||
|
||||
function addGruppeRow(gruppe) {
|
||||
const tbody = document.querySelector('#gruppenTable tbody');
|
||||
const row = document.createElement('tr');
|
||||
row.dataset.id = gruppe.id;
|
||||
|
||||
const idCell = document.createElement('td');
|
||||
idCell.textContent = gruppe.id;
|
||||
row.appendChild(idCell);
|
||||
|
||||
const aliasCell = document.createElement('td');
|
||||
const aliasInput = document.createElement('input');
|
||||
aliasInput.type = 'text';
|
||||
aliasInput.value = gruppe.aliasname || '';
|
||||
aliasInput.addEventListener('change',
|
||||
() => updateGruppe(gruppe.id, {aliasname: aliasInput.value}));
|
||||
aliasCell.appendChild(aliasInput);
|
||||
row.appendChild(aliasCell);
|
||||
|
||||
const stateCell = document.createElement('td');
|
||||
const stateSelect = buildStateSelect(gruppe.state);
|
||||
stateSelect.addEventListener('change',
|
||||
() => updateGruppe(gruppe.id, {state: stateSelect.value}));
|
||||
stateCell.appendChild(stateSelect);
|
||||
row.appendChild(stateCell);
|
||||
|
||||
const accountCell = document.createElement('td');
|
||||
const accountSelect = buildAccountSelect(gruppe.account_id);
|
||||
accountSelect.addEventListener('change',
|
||||
() => updateGruppe(gruppe.id, {account_id: accountSelect.value}));
|
||||
accountCell.appendChild(accountSelect);
|
||||
row.appendChild(accountCell);
|
||||
|
||||
const positionCell = document.createElement('td');
|
||||
positionCell.className = 'group-position';
|
||||
positionCell.textContent = formatPosition(gruppe.last_lat, gruppe.last_lon);
|
||||
row.appendChild(positionCell);
|
||||
|
||||
const actionsCell = document.createElement('td');
|
||||
actionsCell.appendChild(makeButton('Historie', '', () => showHistory(gruppe.id)));
|
||||
|
||||
const clearPositionButton = makeButton('Position löschen', 'secondary delete-position',
|
||||
() => deleteGroupPosition(gruppe.id));
|
||||
clearPositionButton.disabled = !hasPosition(gruppe.last_lat, gruppe.last_lon);
|
||||
actionsCell.appendChild(clearPositionButton);
|
||||
|
||||
actionsCell.appendChild(makeButton('Löschen', 'secondary', () => deleteGruppe(gruppe.id)));
|
||||
row.appendChild(actionsCell);
|
||||
|
||||
tbody.appendChild(row);
|
||||
row.scrollIntoView({block: 'nearest'});
|
||||
}
|
||||
|
||||
function createGruppe() {
|
||||
const aliasname = document.getElementById('gruppeAlias').value;
|
||||
const accountId = document.getElementById('gruppeAccount').value;
|
||||
|
||||
fetch(`${apiBase}/gruppen`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({aliasname, account_id: accountId})
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (!data.success) {
|
||||
showError(data);
|
||||
return;
|
||||
}
|
||||
addGruppeRow({
|
||||
id: data.id,
|
||||
aliasname: aliasname,
|
||||
account_id: accountId || null,
|
||||
state: 'offen',
|
||||
last_lat: null,
|
||||
last_lon: null
|
||||
});
|
||||
closeCreateGruppeModal();
|
||||
}).catch(() => alert('Server nicht erreichbar'));
|
||||
}
|
||||
|
||||
// === Historie / Position ===
|
||||
|
||||
function setPositionCell(groupId, lat, lon) {
|
||||
const row = document.querySelector(`#gruppenTable tr[data-id="${groupId}"]`);
|
||||
if (!row) return;
|
||||
|
||||
const positionCell = row.querySelector('.group-position');
|
||||
if (positionCell) positionCell.textContent = formatPosition(lat, lon);
|
||||
|
||||
const clearButton = row.querySelector('.delete-position');
|
||||
if (clearButton) clearButton.disabled = !hasPosition(lat, lon);
|
||||
}
|
||||
|
||||
function showHistory(groupId) {
|
||||
currentGroupId = groupId;
|
||||
fetch(`${apiBase}/gruppen/${groupId}/history`)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const tbody = document.getElementById('historyBody');
|
||||
tbody.innerHTML = '';
|
||||
data.forEach(entry => {
|
||||
const row = document.createElement('tr');
|
||||
|
||||
[entry.created_at, entry.from_state || '-', entry.to_state,
|
||||
formatPosition(entry.last_lat, entry.last_lon)].forEach(value => {
|
||||
const cell = document.createElement('td');
|
||||
cell.textContent = value;
|
||||
row.appendChild(cell);
|
||||
});
|
||||
|
||||
const actionCell = document.createElement('td');
|
||||
actionCell.appendChild(makeButton('Zustand wiederherstellen', '',
|
||||
() => revertGroup(entry.id)));
|
||||
if (hasPosition(entry.last_lat, entry.last_lon)) {
|
||||
actionCell.appendChild(makeButton('Position setzen', 'secondary',
|
||||
() => setPositionFromHistory(entry.id, entry.last_lat, entry.last_lon)));
|
||||
}
|
||||
row.appendChild(actionCell);
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
document.getElementById('historyModal').showModal();
|
||||
})
|
||||
.catch(() => alert('Historie konnte nicht geladen werden'));
|
||||
}
|
||||
|
||||
function setPositionFromHistory(histId, lat, lon) {
|
||||
if (!confirm('Position aus diesem Historieneintrag übernehmen?')) return;
|
||||
fetch(`${apiBase}/gruppen/${currentGroupId}/position/history/${histId}`, {
|
||||
method: 'POST'
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (!data.success) {
|
||||
showError(data);
|
||||
return;
|
||||
}
|
||||
setPositionCell(currentGroupId, lat, lon);
|
||||
closeHistoryModal();
|
||||
}).catch(() => alert('Server nicht erreichbar'));
|
||||
}
|
||||
|
||||
function deleteGroupPosition(groupId) {
|
||||
if (!confirm('Position dieser Gruppe wirklich löschen?')) return;
|
||||
fetch(`${apiBase}/gruppen/${groupId}/position`, {
|
||||
method: 'DELETE'
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (!data.success) {
|
||||
showError(data);
|
||||
return;
|
||||
}
|
||||
setPositionCell(groupId, null, null);
|
||||
}).catch(() => alert('Server nicht erreichbar'));
|
||||
}
|
||||
|
||||
function revertGroup(histId) {
|
||||
if (!confirm('Zustand wirklich wiederherstellen?')) return;
|
||||
fetch(`${apiBase}/gruppen/${currentGroupId}/history/${histId}/revert`, {
|
||||
method: 'POST'
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
location.reload();
|
||||
} else {
|
||||
showError(data);
|
||||
}
|
||||
}).catch(() => alert('Server nicht erreichbar'));
|
||||
}
|
||||
|
||||
function closeHistoryModal() {
|
||||
document.getElementById('historyModal').close();
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
const tenant = window.location.pathname.split('/')[1];
|
||||
const apiBase = `/${tenant}/admin/api`;
|
||||
let currentStreetId = null;
|
||||
let editMode = false;
|
||||
|
||||
function updateStrasse(streetId, data) {
|
||||
fetch(`${apiBase}/strassen/${streetId}`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(data)
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function deleteStrasse(streetId) {
|
||||
if (!confirm('Straße wirklich löschen?')) return;
|
||||
fetch(`${apiBase}/strassen/${streetId}`, {
|
||||
method: 'DELETE'
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) location.reload();
|
||||
});
|
||||
}
|
||||
|
||||
function openCreateStrasseModal() {
|
||||
editMode = false;
|
||||
document.getElementById('strasseModalTitle').innerText = 'Neue Straße';
|
||||
document.getElementById('strasseId').value = '';
|
||||
document.getElementById('strasseName').value = '';
|
||||
document.getElementById('strasseHnMin').value = '';
|
||||
document.getElementById('strasseHnMax').value = '';
|
||||
document.getElementById('strasseBbox').value = '';
|
||||
document.getElementById('strasseState').value = 'unbearbeitet';
|
||||
document.getElementById('strasseState').disabled = true;
|
||||
document.getElementById('strasseGroup').value = '';
|
||||
document.getElementById('strasseGroup').disabled = true;
|
||||
document.getElementById('strasseModal').showModal();
|
||||
}
|
||||
|
||||
function editStrasse(streetId) {
|
||||
editMode = true;
|
||||
const row = document.querySelector(`tr[data-id="${streetId}"]`);
|
||||
document.getElementById('strasseModalTitle').innerText = 'Straße bearbeiten';
|
||||
document.getElementById('strasseId').value = streetId;
|
||||
document.getElementById('strasseName').value = row.cells[1].innerText;
|
||||
document.getElementById('strasseHnMin').value = row.cells[4].innerText === '-' ? '' : row.cells[4].innerText;
|
||||
document.getElementById('strasseHnMax').value = row.cells[5].innerText === '-' ? '' : row.cells[5].innerText;
|
||||
document.getElementById('strasseBbox').value = row.cells[6].innerText === '-' ? '' : row.cells[6].innerText;
|
||||
document.getElementById('strasseState').value = row.cells[2].querySelector('select').value;
|
||||
document.getElementById('strasseState').disabled = false;
|
||||
document.getElementById('strasseGroup').value = row.cells[3].querySelector('select').value;
|
||||
document.getElementById('strasseGroup').disabled = false;
|
||||
document.getElementById('strasseModal').showModal();
|
||||
}
|
||||
|
||||
function closeStrasseModal() {
|
||||
document.getElementById('strasseModal').close();
|
||||
}
|
||||
|
||||
function saveStrasse() {
|
||||
const id = document.getElementById('strasseId').value;
|
||||
const data = {
|
||||
name: document.getElementById('strasseName').value,
|
||||
hn_min: document.getElementById('strasseHnMin').value || null,
|
||||
hn_max: document.getElementById('strasseHnMax').value || null,
|
||||
bbox: document.getElementById('strasseBbox').value || null,
|
||||
state: document.getElementById('strasseState').value,
|
||||
group_id: document.getElementById('strasseGroup').value || null
|
||||
};
|
||||
|
||||
if (!editMode) {
|
||||
fetch(`${apiBase}/strassen`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(data)
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
alert('Straße angelegt');
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
fetch(`${apiBase}/strassen/${id}`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify(data)
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
alert('Gespeichert');
|
||||
location.reload();
|
||||
}
|
||||
});
|
||||
}
|
||||
closeStrasseModal();
|
||||
}
|
||||
|
||||
function importCSV(input) {
|
||||
const file = input.files[0];
|
||||
if (!file) return;
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
fetch(`${apiBase}/strassen/import`, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
alert(`${data.count} Straßen importiert`);
|
||||
location.reload();
|
||||
} else {
|
||||
alert(data.error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function showStreetHistory(streetId) {
|
||||
currentStreetId = streetId;
|
||||
fetch(`${apiBase}/strassen/${streetId}/history`)
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
const tbody = document.getElementById('streetHistoryBody');
|
||||
tbody.innerHTML = '';
|
||||
data.forEach(h => {
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = `
|
||||
<td>${h.created_at}</td>
|
||||
<td>${h.from_state || '-'}</td>
|
||||
<td>${h.to_state}</td>
|
||||
<td>${h.group_id || '-'}</td>
|
||||
<td><button onclick="revertStreet(${h.id})">Wiederherstellen</button></td>
|
||||
`;
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
document.getElementById('streetHistoryModal').showModal();
|
||||
});
|
||||
}
|
||||
|
||||
function revertStreet(histId) {
|
||||
if (!confirm('Zustand wirklich wiederherstellen?')) return;
|
||||
fetch(`${apiBase}/strassen/${currentStreetId}/history/${histId}/revert`, {
|
||||
method: 'POST'
|
||||
}).then(r => r.json()).then(data => {
|
||||
if (data.success) {
|
||||
alert('Wiederhergestellt');
|
||||
location.reload();
|
||||
} else {
|
||||
alert(data.error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function closeStreetHistoryModal() {
|
||||
document.getElementById('streetHistoryModal').close();
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,100 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Accountverwaltung - CMBNet{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Accountverwaltung</h1>
|
||||
<p><a href="{{ url_for('views.dispatcher', tenant=session.tenant_code) }}">← Zurück</a> | <a href="{{ url_for('auth.logout', tenant=session.tenant_code) }}">Abmelden</a></p>
|
||||
|
||||
<table id="accountsTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Name</th>
|
||||
<th>Rolle</th>
|
||||
<th>Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for account in accounts %}
|
||||
<tr data-id="{{ account.id }}">
|
||||
<td>{{ account.id }}</td>
|
||||
<td>{{ account.name }}</td>
|
||||
<td>
|
||||
<select onchange="changeRole({{ account.id }}, this.value)">
|
||||
<option value="Gast" {% if account.role == 'Gast' %}selected{% endif %}>Gast</option>
|
||||
<option value="Beobachter" {% if account.role == 'Beobachter' %}selected{% endif %}>Beobachter</option>
|
||||
<option value="Gruppe" {% if account.role == 'Gruppe' %}selected{% endif %}>Gruppe</option>
|
||||
<option value="Dispatcher" {% if account.role == 'Dispatcher' %}selected{% endif %}>Dispatcher</option>
|
||||
<option value="Administrator" {% if account.role == 'Administrator' %}selected{% endif %}>Administrator</option>
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<button onclick="openPasswordModal({{ account.id }})">Passwort zurücksetzen</button>
|
||||
<button class="secondary" onclick="deleteAccount({{ account.id }})">Löschen</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<button onclick="openCreateAccountModal()">Neuer Account</button>
|
||||
|
||||
<nav>
|
||||
<ul>
|
||||
<li><a href="{{ url_for('admin_gruppen.gruppen', tenant=session.tenant_code) }}">Gruppenverwaltung</a></li>
|
||||
<li><a href="{{ url_for('admin_strassen.strassen', tenant=session.tenant_code) }}">Straßenverwaltung</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<!-- Passwort Modal -->
|
||||
<dialog id="passwordModal">
|
||||
<article>
|
||||
<header>
|
||||
<a href="#close" aria-label="Close" class="close" onclick="closePasswordModal()"></a>
|
||||
<h3>Passwort zurücksetzen</h3>
|
||||
</header>
|
||||
<input type="hidden" id="pwdAccountId">
|
||||
<label>Neues Passwort
|
||||
<input type="password" id="newPassword">
|
||||
</label>
|
||||
<footer>
|
||||
<button onclick="closePasswordModal()">Abbrechen</button>
|
||||
<button onclick="resetPassword()">Zurücksetzen</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<!-- Create Account Modal -->
|
||||
<dialog id="createAccountModal">
|
||||
<article>
|
||||
<header>
|
||||
<a href="#close" aria-label="Close" class="close" onclick="closeCreateAccountModal()"></a>
|
||||
<h3>Neuer Account</h3>
|
||||
</header>
|
||||
<label>Name
|
||||
<input type="text" id="newAccountName">
|
||||
</label>
|
||||
<label>Passwort
|
||||
<input type="password" id="newAccountPassword">
|
||||
</label>
|
||||
<label>Rolle
|
||||
<select id="newAccountRole">
|
||||
<option value="Gast">Gast</option>
|
||||
<option value="Beobachter">Beobachter</option>
|
||||
<option value="Gruppe">Gruppe</option>
|
||||
<option value="Dispatcher">Dispatcher</option>
|
||||
<option value="Administrator">Administrator</option>
|
||||
</select>
|
||||
</label>
|
||||
<footer>
|
||||
<button onclick="closeCreateAccountModal()">Abbrechen</button>
|
||||
<button onclick="createAccount()">Anlegen</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/views/admin_accounts.js') }}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,109 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Gruppenverwaltung - CMBNet{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Gruppenverwaltung</h1>
|
||||
<p><a href="{{ url_for('admin.accounts', tenant=session.tenant_code) }}">← Zurück zur Accountverwaltung</a></p>
|
||||
|
||||
<table id="gruppenTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Aliasname</th>
|
||||
<th>State</th>
|
||||
<th>Account</th>
|
||||
<th>Position</th>
|
||||
<th>Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for gruppe in gruppen %}
|
||||
<tr data-id="{{ gruppe.id }}">
|
||||
<td>{{ gruppe.id }}</td>
|
||||
<td><input type="text" value="{{ gruppe.aliasname or '' }}" onchange="updateGruppe({{ gruppe.id }}, {aliasname: this.value})"></td>
|
||||
<td>
|
||||
<select onchange="updateGruppe({{ gruppe.id }}, {state: this.value})">
|
||||
<option value="offen" {% if gruppe.state == 'offen' %}selected{% endif %}>offen</option>
|
||||
<option value="unterwegs" {% if gruppe.state == 'unterwegs' %}selected{% endif %}>unterwegs</option>
|
||||
<option value="online" {% if gruppe.state == 'online' %}selected{% endif %}>online</option>
|
||||
<option value="pausierend" {% if gruppe.state == 'pausierend' %}selected{% endif %}>pausierend</option>
|
||||
<option value="fertig" {% if gruppe.state == 'fertig' %}selected{% endif %}>fertig</option>
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<select onchange="updateGruppe({{ gruppe.id }}, {account_id: this.value})">
|
||||
<option value="">-</option>
|
||||
{% for acc in accounts %}
|
||||
<option value="{{ acc.id }}" {% if gruppe.account_id == acc.id %}selected{% endif %}>{{ acc.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</td>
|
||||
<td class="group-position">{% if gruppe.last_lat is not none and gruppe.last_lon is not none %}{{ gruppe.last_lat }}, {{ gruppe.last_lon }}{% else %}unbekannt{% endif %}</td>
|
||||
<td>
|
||||
<button onclick="showHistory({{ gruppe.id }})">Historie</button>
|
||||
<button class="secondary delete-position" onclick="deleteGroupPosition({{ gruppe.id }})" {% if gruppe.last_lat is none or gruppe.last_lon is none %}disabled{% endif %}>Position löschen</button>
|
||||
<button class="secondary" onclick="deleteGruppe({{ gruppe.id }})">Löschen</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<button onclick="openCreateGruppeModal()">Neue Gruppe</button>
|
||||
|
||||
<!-- Create Gruppe Modal -->
|
||||
<dialog id="createGruppeModal">
|
||||
<article>
|
||||
<header>
|
||||
<a href="#close" aria-label="Close" class="close" onclick="closeCreateGruppeModal()"></a>
|
||||
<h3>Neue Gruppe</h3>
|
||||
</header>
|
||||
<label>Aliasname
|
||||
<input type="text" id="gruppeAlias">
|
||||
</label>
|
||||
<label>Account (Rolle Gruppe)
|
||||
<select id="gruppeAccount">
|
||||
<option value="">-</option>
|
||||
{% for acc in accounts %}
|
||||
<option value="{{ acc.id }}">{{ acc.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<footer>
|
||||
<button onclick="closeCreateGruppeModal()">Abbrechen</button>
|
||||
<button onclick="createGruppe()">Anlegen</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<!-- History Modal -->
|
||||
<dialog id="historyModal">
|
||||
<article style="max-width: 800px;">
|
||||
<header>
|
||||
<a href="#close" aria-label="Close" class="close" onclick="closeHistoryModal()"></a>
|
||||
<h3>Gruppen-Historie</h3>
|
||||
</header>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Datum</th>
|
||||
<th>Von</th>
|
||||
<th>Nach</th>
|
||||
<th>Position</th>
|
||||
<th>Aktion</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="historyBody">
|
||||
</tbody>
|
||||
</table>
|
||||
<footer>
|
||||
<button onclick="closeHistoryModal()">Schließen</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/views/admin_gruppen.js') }}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,130 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Straßenverwaltung - CMBNet{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Straßenverwaltung</h1>
|
||||
<p><a href="{{ url_for('admin.accounts', tenant=session.tenant_code) }}">← Zurück zur Accountverwaltung</a></p>
|
||||
|
||||
<table id="strassenTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Name</th>
|
||||
<th>State</th>
|
||||
<th>Gruppe</th>
|
||||
<th>HN Min</th>
|
||||
<th>HN Max</th>
|
||||
<th>BBox</th>
|
||||
<th>Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for strasse in strassen %}
|
||||
<tr data-id="{{ strasse.id }}">
|
||||
<td>{{ strasse.id }}</td>
|
||||
<td>{{ strasse.name }}</td>
|
||||
<td>
|
||||
<select onchange="updateStrasse({{ strasse.id }}, {state: this.value})">
|
||||
<option value="unbearbeitet" {% if strasse.state == 'unbearbeitet' %}selected{% endif %}>unbearbeitet</option>
|
||||
<option value="zugewiesen" {% if strasse.state == 'zugewiesen' %}selected{% endif %}>zugewiesen</option>
|
||||
<option value="erledigt" {% if strasse.state == 'erledigt' %}selected{% endif %}>erledigt</option>
|
||||
</select>
|
||||
</td>
|
||||
<td>
|
||||
<select onchange="updateStrasse({{ strasse.id }}, {group_id: this.value})">
|
||||
<option value="">-</option>
|
||||
{% for gruppe in gruppen %}
|
||||
<option value="{{ gruppe.id }}" {% if strasse.group_id == gruppe.id %}selected{% endif %}>{{ gruppe.aliasname or gruppe.id }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</td>
|
||||
<td>{{ strasse.hn_min or '-' }}</td>
|
||||
<td>{{ strasse.hn_max or '-' }}</td>
|
||||
<td>{{ strasse.bbox[:20] if strasse.bbox else '-' }}</td>
|
||||
<td>
|
||||
<button onclick="editStrasse({{ strasse.id }})">✎</button>
|
||||
<button onclick="showStreetHistory({{ strasse.id }})">Historie</button>
|
||||
<button class="secondary" onclick="deleteStrasse({{ strasse.id }})">🗑</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<button onclick="openCreateStrasseModal()">Neue Straße</button>
|
||||
<button onclick="document.getElementById('csvFile').click()">Import CSV</button>
|
||||
<input type="file" id="csvFile" accept=".csv" style="display:none" onchange="importCSV(this)">
|
||||
|
||||
<!-- Create/Edit Strasse Modal -->
|
||||
<dialog id="strasseModal">
|
||||
<article>
|
||||
<header>
|
||||
<a href="#close" aria-label="Close" class="close" onclick="closeStrasseModal()"></a>
|
||||
<h3 id="strasseModalTitle">Straße</h3>
|
||||
</header>
|
||||
<input type="hidden" id="strasseId">
|
||||
<label>Name
|
||||
<input type="text" id="strasseName">
|
||||
</label>
|
||||
<label>Hausnummer minimal
|
||||
<input type="number" id="strasseHnMin">
|
||||
</label>
|
||||
<label>Hausnummer maximal
|
||||
<input type="number" id="strasseHnMax">
|
||||
</label>
|
||||
<label>Bounding Box (JSON Array)
|
||||
<textarea id="strasseBbox"></textarea>
|
||||
</label>
|
||||
<label>State
|
||||
<select id="strasseState">
|
||||
<option value="unbearbeitet">unbearbeitet</option>
|
||||
<option value="zugewiesen">zugewiesen</option>
|
||||
<option value="erledigt">erledigt</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>Gruppe
|
||||
<select id="strasseGroup">
|
||||
<option value="">-</option>
|
||||
{% for gruppe in gruppen %}
|
||||
<option value="{{ gruppe.id }}">{{ gruppe.aliasname or gruppe.id }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<footer>
|
||||
<button onclick="closeStrasseModal()">Abbrechen</button>
|
||||
<button onclick="saveStrasse()">Speichern</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<!-- History Modal -->
|
||||
<dialog id="streetHistoryModal">
|
||||
<article style="max-width: 800px;">
|
||||
<header>
|
||||
<a href="#close" aria-label="Close" class="close" onclick="closeStreetHistoryModal()"></a>
|
||||
<h3>Straßen-Historie</h3>
|
||||
</header>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Datum</th>
|
||||
<th>Von</th>
|
||||
<th>Nach</th>
|
||||
<th>Gruppe</th>
|
||||
<th>Aktion</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="streetHistoryBody">
|
||||
</tbody>
|
||||
</table>
|
||||
<footer>
|
||||
<button onclick="closeStreetHistoryModal()">Schließen</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="{{ url_for('static', filename='js/views/admin_strassen.js') }}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,26 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de" data-theme="light">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>{% block title %}CMBNet{% endblock %}</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@1/css/pico.min.css">
|
||||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
|
||||
{% block head %}{% endblock %}
|
||||
</head>
|
||||
<body class="{% block body_class %}{% endblock %}">
|
||||
<main class="container">
|
||||
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||
{% if messages %}
|
||||
{% for category, message in messages %}
|
||||
<article class="{{ category }}">{{ message }}</article>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endwith %}
|
||||
{% block content %}{% endblock %}
|
||||
</main>
|
||||
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,123 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Dispatcher - {{ session.tenant_code }} - CMBNet{% endblock %}
|
||||
|
||||
{% block body_class %}dispatcher-page{% endblock %}
|
||||
|
||||
{% block head %}
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='css/dispatcher.css') }}">
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="dispatcher-layout">
|
||||
<section class="map-pane" aria-label="Kartenansicht">
|
||||
<div id="map"></div>
|
||||
</section>
|
||||
|
||||
<aside class="control-pane" aria-label="Kontrollansicht">
|
||||
<header class="control-header">
|
||||
<div class="clock" aria-live="off">
|
||||
<div class="clock-date" id="clockDate"></div>
|
||||
<div class="clock-time" id="clockTime">--:--:--</div>
|
||||
</div>
|
||||
|
||||
<div class="header-controls">
|
||||
<label class="map-layer-label">
|
||||
<span>Hintergrundkarte</span>
|
||||
<select id="baseLayerSelect">
|
||||
<option value="osm">OpenStreetMap</option>
|
||||
<option value="aerial">Luftbild</option>
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" id="speakerButton" class="icon-button"
|
||||
title="Nachricht an alle senden" aria-label="Nachricht an alle senden">📢</button>
|
||||
</div>
|
||||
<div class="connection-status" id="connectionStatus">Verbinde …</div>
|
||||
</header>
|
||||
|
||||
<div class="group-accordion" id="groupAccordion"></div>
|
||||
|
||||
<footer class="control-footer">
|
||||
<label class="slider-control" for="opacitySlider">
|
||||
<span>Opazität <output id="opacityValue">0.70</output></span>
|
||||
<input id="opacitySlider" type="range" min="0" max="1" step="0.05" value="0.7">
|
||||
</label>
|
||||
<label class="slider-control" for="weightSlider">
|
||||
<span>Markerbreite <output id="weightValue">20</output></span>
|
||||
<input id="weightSlider" type="range" min="1" max="100" step="1" value="20">
|
||||
</label>
|
||||
<div class="footer-buttons">
|
||||
<button type="button" id="fitBoundsButton" class="icon-button"
|
||||
title="Gesamten Straßenbereich anzeigen" aria-label="Gesamten Straßenbereich anzeigen">🌍</button>
|
||||
<a id="logoutButton" class="icon-button" href="{{ url_for('auth.logout', tenant=session.tenant_code) }}"
|
||||
title="Session beenden" aria-label="Session beenden">⏻</a>
|
||||
</div>
|
||||
</footer>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<!-- Freitext an alle senden -->
|
||||
<dialog id="speakerModal">
|
||||
<article>
|
||||
<header>
|
||||
<button class="close" type="button" aria-label="Schließen" onclick="closeSpeakerModal()"></button>
|
||||
<h3>Nachricht an alle</h3>
|
||||
</header>
|
||||
<label>Freitext
|
||||
<textarea id="speakerText" rows="4" placeholder="Nachricht eingeben …"></textarea>
|
||||
</label>
|
||||
<footer>
|
||||
<button type="button" class="secondary" onclick="closeSpeakerModal()">Abbrechen</button>
|
||||
<button type="button" onclick="sendSpeakerMessage()">Senden</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<!-- Straßen-State ändern -->
|
||||
<dialog id="streetModal">
|
||||
<article>
|
||||
<header>
|
||||
<button class="close" type="button" aria-label="Schließen" onclick="closeStreetModal()"></button>
|
||||
<h3 id="streetModalTitle">Straße</h3>
|
||||
</header>
|
||||
<label>State
|
||||
<select id="streetStateSelect">
|
||||
<option value="unbearbeitet">unbearbeitet</option>
|
||||
<option value="zugewiesen">zugewiesen</option>
|
||||
<option value="erledigt">erledigt</option>
|
||||
</select>
|
||||
</label>
|
||||
<label id="streetGroupLabel">Gruppe
|
||||
<select id="streetGroupSelect"></select>
|
||||
</label>
|
||||
<footer>
|
||||
<button type="button" class="secondary" onclick="closeStreetModal()">Abbrechen</button>
|
||||
<button type="button" onclick="saveStreetState()">Speichern</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
|
||||
<!-- Chatverlauf einer Gruppe -->
|
||||
<dialog id="chatModal">
|
||||
<article class="chat-dialog">
|
||||
<header>
|
||||
<button class="close" type="button" aria-label="Schließen" onclick="closeChatModal()"></button>
|
||||
<h3 id="chatTitle">Chat</h3>
|
||||
</header>
|
||||
<div class="chat-messages" id="chatMessages"></div>
|
||||
<footer>
|
||||
<button type="button" onclick="closeChatModal()">Schließen</button>
|
||||
</footer>
|
||||
</article>
|
||||
</dialog>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
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 }};
|
||||
</script>
|
||||
<script src="{{ url_for('static', filename='js/str2pl.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/views/dispatcher.js') }}"></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,8 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Dispatcher Mobil - CMBNet{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Dispatcher Mobil View</h1>
|
||||
<p>Wird später implementiert</p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,9 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Gruppen View - CMBNet{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Gruppen View</h1>
|
||||
<p>Willkommen, {{ session.username }}</p>
|
||||
<p><a href="{{ url_for('auth.logout', tenant=session.tenant_code) }}">Abmelden</a></p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,27 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Login - CMBNet ({{ tenant_code }}){% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<article>
|
||||
<header>
|
||||
<h1>CMBNet Login</h1>
|
||||
<p>Mandant: <strong>{{ tenant_code }}</strong></p>
|
||||
</header>
|
||||
<form method="post">
|
||||
<input type="hidden" name="tenant" value="{{ tenant_code }}">
|
||||
<label for="username">
|
||||
Benutzername
|
||||
<input type="text" id="username" name="username" required autofocus>
|
||||
</label>
|
||||
<label for="password">
|
||||
Passwort
|
||||
<input type="password" id="password" name="password" required>
|
||||
</label>
|
||||
<button type="submit">Anmelden</button>
|
||||
</form>
|
||||
<footer>
|
||||
<a href="{{ url_for('auth.login_select', tenant=tenant_code) }}">← Zurück zur Mandantenauswahl</a>
|
||||
</footer>
|
||||
</article>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,17 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Mandantenauswahl - CMBNet{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<article>
|
||||
<header>
|
||||
<h1>CMBNet - Mandantenauswahl</h1>
|
||||
</header>
|
||||
<p>Bitte wählen Sie Ihren Mandanten aus:</p>
|
||||
<div class="grid">
|
||||
<a href="{{ url_for('auth.login', tenant='BV') }}" role="button">BV</a>
|
||||
<a href="{{ url_for('auth.login', tenant='RV') }}" role="button" class="secondary">RV</a>
|
||||
<a href="{{ url_for('auth.login', tenant='SV') }}" role="button" class="contrast">SV</a>
|
||||
</div>
|
||||
</article>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,8 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Öffentlicher View - CMBNet{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Öffentlicher View</h1>
|
||||
<p><a href="{{ url_for('auth.login_select', tenant='RV') }}">Login</a></p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,9 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Präsentations View - CMBNet{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Präsentations View</h1>
|
||||
<p>Willkommen, {{ session.username }}</p>
|
||||
<p><a href="{{ url_for('auth.logout', tenant=session.tenant_code) }}">Abmelden</a></p>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,3 @@
|
||||
from cmbnet import create_app
|
||||
|
||||
app = create_app()
|
||||
Reference in new issue
Block a user