Neue Verwaltung der Gruppenzuordnung 1:n
This commit is contained in:
1 parent
fa02a7ade0
commit
02c017d53d
34 files changed
+1306
-251
No files matched your search
@@ -91,6 +91,11 @@ def create_app(config_name=None):
|
||||
template_folder='../templates',
|
||||
static_folder='../static')
|
||||
app.config.from_object(config[config_name])
|
||||
|
||||
# Anzeigetitel für alle Web-Views. Der interne Projektname bleibt CMBNet.
|
||||
app.jinja_env.globals['APP_TITLE'] = app.config.get(
|
||||
'DISPLAY_TITLE', '20*C+M+B+27'
|
||||
)
|
||||
|
||||
# Middleware registrieren
|
||||
app.wsgi_app = PrefixMiddleware(app.wsgi_app)
|
||||
@@ -104,8 +109,13 @@ def create_app(config_name=None):
|
||||
|
||||
# Datenbank-Setup
|
||||
from cmbnet.db import close_db, init_db_command
|
||||
from cmbnet.db.database import ensure_schema
|
||||
app.teardown_appcontext(close_db)
|
||||
app.cli.add_command(init_db_command)
|
||||
|
||||
# Bestehende Installationen idempotent auf das aktuelle Schema heben.
|
||||
with app.app_context():
|
||||
ensure_schema()
|
||||
|
||||
# Tenant und Account für Requests laden
|
||||
@app.before_request
|
||||
|
||||
+37
-50
@@ -10,7 +10,7 @@ from cmbnet.models.groups import GroupModel
|
||||
from cmbnet.models.streets import StreetModel
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.services.history_service import HistoryService
|
||||
from cmbnet.utils.helpers import log_transaction
|
||||
from cmbnet.utils.helpers import log_transaction, notify_reload
|
||||
from cmbnet.utils.csv_utils import parse_streets_csv, parse_house_numbers_csv
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
@@ -38,7 +38,8 @@ def create_account(**kwargs):
|
||||
password_hash = hash_password(password)
|
||||
account_id = AccountModel.create(g.tenant_id, name, password_hash, role)
|
||||
log_transaction('account.create', 'account', account_id, {'name': name, 'role': role})
|
||||
|
||||
notify_reload(f'Administration: Account „{name}“ wurde erstellt.')
|
||||
|
||||
return jsonify({'success': True, 'id': account_id})
|
||||
|
||||
|
||||
@@ -47,9 +48,12 @@ def create_account(**kwargs):
|
||||
def update_account_role(account_id, **kwargs):
|
||||
data = request.get_json()
|
||||
role = data.get('role')
|
||||
account = AccountModel.get_by_id(account_id, g.tenant_id)
|
||||
AccountModel.update_role(account_id, g.tenant_id, role)
|
||||
log_transaction('account.role_change', 'account', account_id, {'role': role})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
name = account['name'] if account else f'#{account_id}'
|
||||
notify_reload(f'Administration: Rolle von Account „{name}“ wurde geändert.')
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@@ -61,17 +65,23 @@ def reset_password(account_id, **kwargs):
|
||||
if not password:
|
||||
return jsonify({'error': 'Passwort erforderlich'}), 400
|
||||
password_hash = hash_password(password)
|
||||
account = AccountModel.get_by_id(account_id, g.tenant_id)
|
||||
AccountModel.set_password(account_id, g.tenant_id, password_hash)
|
||||
log_transaction('account.password_reset', 'account', account_id, {})
|
||||
name = account['name'] if account else f'#{account_id}'
|
||||
notify_reload(f'Administration: Passwort für Account „{name}“ wurde zurückgesetzt.')
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/accounts/<int:account_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_account(account_id, **kwargs):
|
||||
account = AccountModel.get_by_id(account_id, g.tenant_id)
|
||||
AccountModel.delete(account_id, g.tenant_id)
|
||||
log_transaction('account.delete', 'account', account_id, {})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
name = account['name'] if account else f'#{account_id}'
|
||||
notify_reload(f'Administration: Account „{name}“ wurde gelöscht.')
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@@ -81,37 +91,18 @@ def delete_account(account_id, **kwargs):
|
||||
def create_group(**kwargs):
|
||||
data = request.get_json() or {}
|
||||
aliasname = str(data.get('aliasname') or '').strip()
|
||||
account_id = data.get('account_id')
|
||||
db = get_db()
|
||||
|
||||
if account_id == '' or account_id is None:
|
||||
account_id = None
|
||||
else:
|
||||
try:
|
||||
account_id = int(account_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'Ungültiger Account'}), 400
|
||||
|
||||
account = AccountModel.get_by_id(account_id, g.tenant_id)
|
||||
if not account or account['role'] != 'Gruppe':
|
||||
return jsonify({'error': 'Account muss die Rolle "Gruppe" haben'}), 400
|
||||
|
||||
linked = db.execute(
|
||||
'SELECT id FROM groups WHERE tenant_id = ? AND account_id = ?',
|
||||
(g.tenant_id, account_id)
|
||||
).fetchone()
|
||||
if linked:
|
||||
return jsonify({'error': 'Dieser Account ist bereits mit einer Gruppe verknüpft'}), 400
|
||||
|
||||
group_id = GroupModel.create(g.tenant_id, aliasname, account_id, 'offen')
|
||||
group_id = GroupModel.create(g.tenant_id, aliasname, 'offen')
|
||||
db.execute(
|
||||
'INSERT INTO group_state_history (tenant_id, group_id, from_state, to_state, actor_account_id) VALUES (?, ?, ?, ?, ?)',
|
||||
(g.tenant_id, group_id, None, 'offen', session['account_id'])
|
||||
)
|
||||
db.commit()
|
||||
log_transaction('group.create', 'group', group_id, {'aliasname': aliasname, 'account_id': account_id})
|
||||
log_transaction('group.create', 'group', group_id, {'aliasname': aliasname})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
GroupsService.load_from_db(g.tenant_id)
|
||||
notify_reload(f'Administration: Gruppe „{aliasname or group_id}“ wurde erstellt.')
|
||||
return jsonify({'success': True, 'id': group_id})
|
||||
|
||||
|
||||
@@ -128,30 +119,6 @@ def update_group(group_id, **kwargs):
|
||||
if 'aliasname' in data:
|
||||
updates['aliasname'] = data['aliasname']
|
||||
|
||||
if 'account_id' in data:
|
||||
account_id = data['account_id']
|
||||
if account_id in ('', None):
|
||||
account_id = None
|
||||
else:
|
||||
try:
|
||||
account_id = int(account_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'Ungültiger Account'}), 400
|
||||
|
||||
account = AccountModel.get_by_id(account_id, g.tenant_id)
|
||||
if not account or account['role'] != 'Gruppe':
|
||||
return jsonify({'error': 'Account muss die Rolle "Gruppe" haben'}), 400
|
||||
|
||||
linked = db.execute(
|
||||
'SELECT id FROM groups WHERE tenant_id = ? AND account_id = ? AND id != ?',
|
||||
(g.tenant_id, account_id, group_id)
|
||||
).fetchone()
|
||||
if linked:
|
||||
return jsonify({'error': 'Dieser Account ist bereits mit einer Gruppe verknüpft'}), 400
|
||||
|
||||
if account_id != old['account_id']:
|
||||
updates['account_id'] = account_id
|
||||
|
||||
allowed_states = {'offen', 'unterwegs', 'online', 'pausierend', 'fertig'}
|
||||
state_changed = False
|
||||
if 'state' in data:
|
||||
@@ -183,15 +150,20 @@ def update_group(group_id, **kwargs):
|
||||
log_transaction('group.update', 'group', group_id, updates)
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
GroupsService.load_from_db(g.tenant_id)
|
||||
display_name = updates.get('aliasname', old['aliasname']) or group_id
|
||||
notify_reload(f'Administration: Gruppe „{display_name}“ wurde geändert.')
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@admin_api_bp.route('/gruppen/<int:group_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_group(group_id, **kwargs):
|
||||
group = GroupModel.get_by_id(group_id, g.tenant_id)
|
||||
GroupModel.delete(group_id, g.tenant_id)
|
||||
log_transaction('group.delete', 'group', group_id, {})
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
display_name = (group['aliasname'] if group and group['aliasname'] else group_id)
|
||||
notify_reload(f'Administration: Gruppe „{display_name}“ wurde gelöscht.')
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@@ -212,6 +184,7 @@ def revert_group_hist(group_id, hist_id, **kwargs):
|
||||
success, msg = HistoryService.revert_group(g.tenant_id, group_id, hist_id, session['account_id'])
|
||||
if not success:
|
||||
return jsonify({'error': msg}), 400
|
||||
notify_reload('Administration: Gruppenhistorie wurde wiederhergestellt.')
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@@ -223,6 +196,7 @@ def set_group_position_from_history(group_id, hist_id, **kwargs):
|
||||
)
|
||||
if not success:
|
||||
return jsonify({'error': msg}), 400
|
||||
notify_reload('Administration: Gruppenposition wurde aus der Historie gesetzt.')
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@@ -234,6 +208,7 @@ def clear_group_position(group_id, **kwargs):
|
||||
)
|
||||
if not success:
|
||||
return jsonify({'error': msg}), 400
|
||||
notify_reload('Administration: Gruppenposition wurde gelöscht.')
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@@ -258,6 +233,7 @@ def create_street(**kwargs):
|
||||
)
|
||||
db.commit()
|
||||
log_transaction('street.create', 'street', street_id, {'name': name})
|
||||
notify_reload(f'Administration: Straße „{name}“ wurde erstellt.')
|
||||
return jsonify({'success': True, 'id': street_id})
|
||||
|
||||
|
||||
@@ -303,7 +279,9 @@ def update_street(street_id, **kwargs):
|
||||
if changes:
|
||||
StreetModel.update(street_id, g.tenant_id, **changes)
|
||||
log_transaction('street.update', 'street', street_id, changes)
|
||||
|
||||
display_name = changes.get('name', old['name'])
|
||||
notify_reload(f'Administration: Straße „{display_name}“ wurde geändert.')
|
||||
|
||||
db.commit()
|
||||
return jsonify({'success': True})
|
||||
|
||||
@@ -311,8 +289,11 @@ def update_street(street_id, **kwargs):
|
||||
@admin_api_bp.route('/strassen/<int:street_id>', methods=['DELETE'])
|
||||
@role_required('Administrator')
|
||||
def delete_street(street_id, **kwargs):
|
||||
street = StreetModel.get_by_id(street_id, g.tenant_id)
|
||||
StreetModel.delete(street_id, g.tenant_id)
|
||||
log_transaction('street.delete', 'street', street_id, {})
|
||||
name = street['name'] if street else f'#{street_id}'
|
||||
notify_reload(f'Administration: Straße „{name}“ wurde gelöscht.')
|
||||
return jsonify({'success': True})
|
||||
|
||||
|
||||
@@ -333,6 +314,7 @@ def revert_street_hist(street_id, hist_id, **kwargs):
|
||||
success, msg = HistoryService.revert_street(g.tenant_id, street_id, hist_id, session['account_id'])
|
||||
if not success:
|
||||
return jsonify({'error': msg}), 400
|
||||
notify_reload('Administration: Straßenhistorie wurde wiederhergestellt.')
|
||||
return jsonify({'success': True, 'message': msg})
|
||||
|
||||
|
||||
@@ -367,6 +349,7 @@ def import_streets(**kwargs):
|
||||
count += 1
|
||||
|
||||
db.commit()
|
||||
notify_reload(f'Administration: {count} Straßen wurden importiert.')
|
||||
return jsonify({'success': True, 'count': count})
|
||||
|
||||
|
||||
@@ -392,7 +375,10 @@ def broker_status(**kwargs):
|
||||
}
|
||||
if account['role'] == 'Gruppe':
|
||||
group = get_db().execute(
|
||||
'SELECT id, aliasname FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
'''SELECT g.id, g.aliasname FROM groups g
|
||||
JOIN group_accounts ga
|
||||
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
||||
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
||||
(account['id'], g.tenant_id)
|
||||
).fetchone()
|
||||
if group:
|
||||
@@ -447,4 +433,5 @@ def import_house_numbers(**kwargs):
|
||||
None,
|
||||
{'count': len(house_numbers)}
|
||||
)
|
||||
notify_reload(f'Administration: {len(house_numbers)} Hausnummern wurden importiert.')
|
||||
return jsonify({'success': True, 'count': len(house_numbers)})
|
||||
@@ -14,11 +14,7 @@ def gruppen(**kwargs):
|
||||
"""Gruppenverwaltung"""
|
||||
db = get_db()
|
||||
gruppen = db.execute(
|
||||
'SELECT g.*, a.name as account_name FROM groups g LEFT JOIN accounts a ON g.account_id = a.id WHERE g.tenant_id = ? ORDER BY g.id',
|
||||
'SELECT * FROM groups WHERE tenant_id = ? ORDER BY id',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
accounts = db.execute(
|
||||
"SELECT * FROM accounts WHERE tenant_id = ? AND role = 'Gruppe'",
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
return render_template('admin/gruppen.html', gruppen=gruppen, accounts=accounts)
|
||||
return render_template('admin/gruppen.html', gruppen=gruppen)
|
||||
@@ -4,9 +4,10 @@ API-Endpunkte für Gruppen im Dispatcher-View.
|
||||
from flask import Blueprint, jsonify, g, request
|
||||
|
||||
from cmbnet.auth import role_required
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.models.groups import GroupModel
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.utils.helpers import log_transaction
|
||||
from cmbnet.utils.helpers import log_transaction, notify_reload
|
||||
|
||||
api_groups_bp = Blueprint('api_groups', __name__)
|
||||
|
||||
@@ -16,9 +17,10 @@ api_groups_bp = Blueprint('api_groups', __name__)
|
||||
def get_my_group(**kwargs):
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
groups = GroupsService.get_all(g.tenant_id)
|
||||
account_id = g.current_account['id']
|
||||
account_id = int(g.current_account['id'])
|
||||
for group in groups.values():
|
||||
if group.get('account_id') == account_id:
|
||||
account_ids = {int(value) for value in group.get('account_ids', [])}
|
||||
if account_id in account_ids:
|
||||
return jsonify(group)
|
||||
return jsonify({'error': 'Gruppe nicht gefunden'}), 404
|
||||
|
||||
@@ -47,3 +49,87 @@ def update_group_alias(group_id, **kwargs):
|
||||
GroupsService.load_from_db(g.tenant_id)
|
||||
|
||||
return jsonify({'success': True, 'aliasname': aliasname})
|
||||
|
||||
|
||||
@api_groups_bp.route('/groups/assignments', methods=['POST'])
|
||||
@role_required(['Dispatcher', 'Administrator'])
|
||||
def update_group_assignments(**kwargs):
|
||||
'''Speichert die Zuordnung von Gruppen-Accounts zu Gruppen.
|
||||
|
||||
Die Tabelle ``group_accounts`` erzwingt über ``UNIQUE(tenant_id,
|
||||
account_id)``, dass ein Gruppen-Account höchstens einer Gruppe zugeordnet
|
||||
ist. Ein ``null``-Wert in ``assignments`` bedeutet "Nicht dabei".
|
||||
'''
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_assignments = data.get('assignments')
|
||||
if not isinstance(raw_assignments, dict):
|
||||
return jsonify({'error': 'Ungültige Zuordnungen'}), 400
|
||||
|
||||
db = get_db()
|
||||
account_rows = db.execute(
|
||||
"SELECT id FROM accounts WHERE tenant_id = ? AND role = 'Gruppe'",
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
allowed_accounts = {int(row['id']) for row in account_rows}
|
||||
|
||||
group_rows = db.execute(
|
||||
'SELECT id FROM groups WHERE tenant_id = ?',
|
||||
(g.tenant_id,)
|
||||
).fetchall()
|
||||
allowed_groups = {int(row['id']) for row in group_rows}
|
||||
|
||||
normalized = {}
|
||||
for raw_account_id, raw_group_id in raw_assignments.items():
|
||||
try:
|
||||
account_id = int(raw_account_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'Ungültiger Account'}), 400
|
||||
if account_id not in allowed_accounts:
|
||||
return jsonify({'error': 'Account muss die Rolle "Gruppe" haben'}), 400
|
||||
|
||||
if raw_group_id in (None, '', 'none'):
|
||||
group_id = None
|
||||
else:
|
||||
try:
|
||||
group_id = int(raw_group_id)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'Ungültige Gruppe'}), 400
|
||||
if group_id not in allowed_groups:
|
||||
return jsonify({'error': 'Gruppe nicht gefunden'}), 400
|
||||
|
||||
normalized[account_id] = group_id
|
||||
|
||||
changes = []
|
||||
for account_id, group_id in normalized.items():
|
||||
current = db.execute(
|
||||
'''SELECT group_id FROM group_accounts
|
||||
WHERE tenant_id = ? AND account_id = ?''',
|
||||
(g.tenant_id, account_id)
|
||||
).fetchone()
|
||||
current_group_id = current['group_id'] if current else None
|
||||
if current_group_id == group_id:
|
||||
continue
|
||||
|
||||
db.execute(
|
||||
'DELETE FROM group_accounts WHERE tenant_id = ? AND account_id = ?',
|
||||
(g.tenant_id, account_id)
|
||||
)
|
||||
if group_id is not None:
|
||||
db.execute(
|
||||
'''INSERT INTO group_accounts (tenant_id, group_id, account_id)
|
||||
VALUES (?, ?, ?)''',
|
||||
(g.tenant_id, group_id, account_id)
|
||||
)
|
||||
changes.append({'account_id': account_id, 'group_id': group_id})
|
||||
|
||||
if changes:
|
||||
db.commit()
|
||||
log_transaction(
|
||||
'group.assignment_update', 'group', None,
|
||||
{'changes': changes}
|
||||
)
|
||||
GroupsService.invalidate(g.tenant_id)
|
||||
GroupsService.load_from_db(g.tenant_id)
|
||||
|
||||
notify_reload('Gruppenzuordnungen wurden geändert.')
|
||||
return jsonify({'success': True, 'changes': len(changes)})
|
||||
@@ -23,6 +23,104 @@ def close_db(e=None):
|
||||
db.close()
|
||||
|
||||
|
||||
def ensure_schema():
|
||||
"""Ergänzt bestehende Datenbanken um das Gruppen-Account-Zuordnungsmodell.
|
||||
|
||||
Neue Installationen erhalten das Schema über ``migrations/schema.sql``.
|
||||
Für bestehende Datenbanken wird die frühere 1:1-Verknüpfung
|
||||
``groups.account_id`` in die neue Tabelle ``group_accounts`` übernommen
|
||||
und die alte Spalte durch einen Tabellen-Neubau entfernt.
|
||||
"""
|
||||
db = get_db()
|
||||
groups_table = db.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'groups'"
|
||||
).fetchone()
|
||||
if not groups_table:
|
||||
return
|
||||
|
||||
db.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS group_accounts (
|
||||
tenant_id INTEGER NOT NULL,
|
||||
group_id INTEGER NOT NULL,
|
||||
account_id INTEGER NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (tenant_id, group_id, account_id),
|
||||
UNIQUE (tenant_id, account_id),
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id),
|
||||
FOREIGN KEY (group_id) REFERENCES groups(id),
|
||||
FOREIGN KEY (account_id) REFERENCES accounts(id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_group_accounts_group
|
||||
ON group_accounts(tenant_id, group_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_groups_tenant ON groups(tenant_id);
|
||||
''')
|
||||
db.commit()
|
||||
|
||||
columns = {
|
||||
row['name'] for row in db.execute('PRAGMA table_info(groups)').fetchall()
|
||||
}
|
||||
if 'account_id' not in columns:
|
||||
return
|
||||
|
||||
db.execute(
|
||||
'''INSERT OR IGNORE INTO group_accounts (tenant_id, group_id, account_id)
|
||||
SELECT g.tenant_id, g.id, g.account_id
|
||||
FROM groups g
|
||||
JOIN accounts a
|
||||
ON a.id = g.account_id AND a.tenant_id = g.tenant_id
|
||||
WHERE g.account_id IS NOT NULL AND a.role = 'Gruppe' '''
|
||||
)
|
||||
db.commit()
|
||||
|
||||
# SQLite kann eine UNIQUE-Spalte nicht per ALTER TABLE DROP COLUMN
|
||||
# entfernen. Deshalb wird die Tabelle ohne die alte Spalte neu aufgebaut.
|
||||
# Die bereits kopierten Zuordnungen bleiben dabei erhalten.
|
||||
fk_enabled = db.execute('PRAGMA foreign_keys').fetchone()[0]
|
||||
db.execute('PRAGMA foreign_keys = OFF')
|
||||
try:
|
||||
db.execute('DROP TABLE IF EXISTS groups_new')
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
db.execute('''
|
||||
CREATE TABLE groups_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tenant_id INTEGER NOT NULL,
|
||||
aliasname TEXT,
|
||||
state TEXT NOT NULL DEFAULT 'offen'
|
||||
CHECK(state IN ('offen', 'unterwegs', 'online', 'pausierend', 'fertig')),
|
||||
last_lat REAL,
|
||||
last_lon REAL,
|
||||
last_pos_at TIMESTAMP,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (tenant_id) REFERENCES tenants(id)
|
||||
)
|
||||
''')
|
||||
db.execute('''
|
||||
INSERT INTO groups_new
|
||||
(id, tenant_id, aliasname, state, last_lat, last_lon,
|
||||
last_pos_at, created_at, updated_at)
|
||||
SELECT id, tenant_id, aliasname, state, last_lat, last_lon,
|
||||
last_pos_at, created_at, updated_at
|
||||
FROM groups
|
||||
''')
|
||||
db.execute('DROP TABLE groups')
|
||||
db.execute('ALTER TABLE groups_new RENAME TO groups')
|
||||
db.execute('CREATE INDEX IF NOT EXISTS idx_groups_tenant ON groups(tenant_id)')
|
||||
db.commit()
|
||||
except sqlite3.DatabaseError as exc:
|
||||
db.rollback()
|
||||
try:
|
||||
db.execute('DROP TABLE IF EXISTS groups_new')
|
||||
db.commit()
|
||||
except sqlite3.DatabaseError:
|
||||
pass
|
||||
current_app.logger.warning(
|
||||
'groups.account_id konnte nicht entfernt werden: %s', exc
|
||||
)
|
||||
finally:
|
||||
db.execute('PRAGMA foreign_keys = ON' if fk_enabled else 'PRAGMA foreign_keys = OFF')
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Initialisiert die Datenbank mit dem Schema"""
|
||||
db = get_db()
|
||||
@@ -30,6 +128,7 @@ def init_db():
|
||||
with open(schema_path, 'r', encoding='utf-8') as f:
|
||||
db.executescript(f.read())
|
||||
db.commit()
|
||||
ensure_schema()
|
||||
|
||||
|
||||
@click.command('init-db')
|
||||
|
||||
@@ -48,6 +48,13 @@ class AccountModel:
|
||||
'UPDATE accounts SET role = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND tenant_id = ?',
|
||||
(role, account_id, tenant_id)
|
||||
)
|
||||
# Ein Account, der nicht mehr die Rolle "Gruppe" hat, darf keine
|
||||
# Gruppenzuordnung behalten.
|
||||
if role != 'Gruppe':
|
||||
db.execute(
|
||||
'DELETE FROM group_accounts WHERE tenant_id = ? AND account_id = ?',
|
||||
(tenant_id, account_id)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
@staticmethod
|
||||
@@ -62,5 +69,9 @@ class AccountModel:
|
||||
@staticmethod
|
||||
def delete(account_id, tenant_id):
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'DELETE FROM group_accounts WHERE tenant_id = ? AND account_id = ?',
|
||||
(tenant_id, account_id)
|
||||
)
|
||||
db.execute('DELETE FROM accounts WHERE id = ? AND tenant_id = ?', (account_id, tenant_id))
|
||||
db.commit()
|
||||
@@ -25,16 +25,44 @@ class GroupModel:
|
||||
def get_by_account_id(account_id, tenant_id):
|
||||
db = get_db()
|
||||
return db.execute(
|
||||
'SELECT * FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
'''SELECT g.* FROM groups g
|
||||
JOIN group_accounts ga
|
||||
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
||||
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
|
||||
|
||||
@staticmethod
|
||||
def create(tenant_id, aliasname, account_id=None, state='offen'):
|
||||
def get_account_ids_for_group(group_id, tenant_id):
|
||||
db = get_db()
|
||||
rows = db.execute(
|
||||
'''SELECT account_id FROM group_accounts
|
||||
WHERE group_id = ? AND tenant_id = ?
|
||||
ORDER BY account_id''',
|
||||
(group_id, tenant_id)
|
||||
).fetchall()
|
||||
return [row['account_id'] for row in rows]
|
||||
|
||||
@staticmethod
|
||||
def get_account_ids_by_group(tenant_id):
|
||||
db = get_db()
|
||||
rows = db.execute(
|
||||
'''SELECT group_id, account_id FROM group_accounts
|
||||
WHERE tenant_id = ?
|
||||
ORDER BY group_id, account_id''',
|
||||
(tenant_id,)
|
||||
).fetchall()
|
||||
result = {}
|
||||
for row in rows:
|
||||
result.setdefault(row['group_id'], []).append(row['account_id'])
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def create(tenant_id, aliasname, state='offen'):
|
||||
db = get_db()
|
||||
cursor = db.execute(
|
||||
'INSERT INTO groups (tenant_id, aliasname, account_id, state) VALUES (?, ?, ?, ?)',
|
||||
(tenant_id, aliasname, account_id, state)
|
||||
'INSERT INTO groups (tenant_id, aliasname, state) VALUES (?, ?, ?)',
|
||||
(tenant_id, aliasname, state)
|
||||
)
|
||||
db.commit()
|
||||
return cursor.lastrowid
|
||||
@@ -42,7 +70,7 @@ class GroupModel:
|
||||
@staticmethod
|
||||
def update(group_id, tenant_id, **kwargs):
|
||||
db = get_db()
|
||||
allowed = ['aliasname', 'state', 'account_id', 'last_lat', 'last_lon', 'last_pos_at']
|
||||
allowed = ['aliasname', 'state', 'last_lat', 'last_lon', 'last_pos_at']
|
||||
updates = []
|
||||
values = []
|
||||
for k, v in kwargs.items():
|
||||
@@ -59,5 +87,9 @@ class GroupModel:
|
||||
@staticmethod
|
||||
def delete(group_id, tenant_id):
|
||||
db = get_db()
|
||||
db.execute(
|
||||
'DELETE FROM group_accounts WHERE group_id = ? AND tenant_id = ?',
|
||||
(group_id, tenant_id)
|
||||
)
|
||||
db.execute('DELETE FROM groups WHERE id = ? AND tenant_id = ?', (group_id, tenant_id))
|
||||
db.commit()
|
||||
@@ -15,9 +15,11 @@ class GroupsService:
|
||||
def load_from_db(cls, tenant_id):
|
||||
"""Lädt alle Gruppen eines Mandanten aus der Datenbank in den Cache"""
|
||||
groups = GroupModel.get_all_by_tenant(tenant_id)
|
||||
if tenant_id not in cls._cache:
|
||||
cls._cache[tenant_id] = {}
|
||||
|
||||
memberships = GroupModel.get_account_ids_by_group(tenant_id)
|
||||
# Vollständig neu aufbauen, damit gelöschte Gruppen nicht im Cache
|
||||
# zurückbleiben.
|
||||
cls._cache[tenant_id] = {}
|
||||
|
||||
for group in groups:
|
||||
cls._cache[tenant_id][group['id']] = {
|
||||
'id': group['id'],
|
||||
@@ -27,7 +29,7 @@ class GroupsService:
|
||||
'last_lat': group['last_lat'],
|
||||
'last_lon': group['last_lon'],
|
||||
'last_pos_at': group['last_pos_at'],
|
||||
'account_id': group['account_id'],
|
||||
'account_ids': memberships.get(group['id'], []),
|
||||
'created_at': group['created_at'],
|
||||
'updated_at': group['updated_at']
|
||||
}
|
||||
@@ -43,7 +45,7 @@ class GroupsService:
|
||||
@classmethod
|
||||
def get_by_id(cls, tenant_id, group_id):
|
||||
"""Gibt eine spezifische Gruppe aus dem Cache zurück"""
|
||||
if tenant_id not in cls._cache:
|
||||
if tenant_id not in cls._cache or not cls._cache[tenant_id]:
|
||||
cls.load_from_db(tenant_id)
|
||||
return cls._cache.get(tenant_id, {}).get(group_id)
|
||||
|
||||
@@ -64,16 +66,19 @@ class GroupsService:
|
||||
group = cls.get_by_id(tenant_id, group_id)
|
||||
if not group:
|
||||
return False
|
||||
return group.get('account_id') == account_id
|
||||
|
||||
account_ids = {int(value) for value in group.get('account_ids', [])}
|
||||
return int(account_id) in account_ids
|
||||
|
||||
@classmethod
|
||||
def get_accounts_for_group(cls, group_id, tenant_id):
|
||||
"""Gibt alle mit einer Gruppe verknüpften Accounts zurück"""
|
||||
group = cls.get_by_id(tenant_id, group_id)
|
||||
if not group or not group.get('account_id'):
|
||||
return []
|
||||
account = AccountModel.get_by_id(group['account_id'], tenant_id)
|
||||
return [account] if account else []
|
||||
account_ids = GroupModel.get_account_ids_for_group(group_id, tenant_id)
|
||||
accounts = []
|
||||
for account_id in account_ids:
|
||||
account = AccountModel.get_by_id(account_id, tenant_id)
|
||||
if account:
|
||||
accounts.append(account)
|
||||
return accounts
|
||||
|
||||
@classmethod
|
||||
def get_streets_for_group(cls, group_id, tenant_id):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
Hilfsfunktionen für CMBNet
|
||||
"""
|
||||
from flask import g
|
||||
from flask import current_app, g
|
||||
import json
|
||||
|
||||
|
||||
@@ -15,6 +15,33 @@ def get_current_account():
|
||||
return getattr(g, 'current_account', None)
|
||||
|
||||
|
||||
def notify_reload(text, tenant_id=None, sender_id=None):
|
||||
"""Sendet eine interne Code-99-Nachricht an alle Clients eines Mandanten."""
|
||||
from cmbnet.ws import broker
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
tenant_id = tenant_id if tenant_id is not None else get_tenant_id()
|
||||
account = get_current_account()
|
||||
if sender_id is None and account:
|
||||
sender_id = account['id']
|
||||
|
||||
if not tenant_id or not sender_id:
|
||||
return False
|
||||
|
||||
try:
|
||||
broker.route_message(
|
||||
tenant_id,
|
||||
WSMessage(sender_id=sender_id, code=99, msg=str(text))
|
||||
)
|
||||
return True
|
||||
except Exception as exc:
|
||||
try:
|
||||
current_app.logger.warning('Code-99-Nachricht konnte nicht gesendet werden: %s', exc)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def log_transaction(action, entity_type, entity_id, details=None):
|
||||
"""
|
||||
Schreibt einen Eintrag ins Transaktionslog
|
||||
|
||||
@@ -3,7 +3,7 @@ Haupt-Views
|
||||
"""
|
||||
from flask import (
|
||||
Blueprint, render_template, g, redirect, url_for, request, jsonify,
|
||||
make_response, session
|
||||
make_response, session, current_app
|
||||
)
|
||||
from cmbnet.auth import login_required, role_required
|
||||
|
||||
@@ -65,28 +65,23 @@ def manifest(tenant=None, **kwargs):
|
||||
"""Liefert das Web-App-Manifest für die mobilen Views."""
|
||||
account = getattr(g, 'current_account', None)
|
||||
role = account['role'] if account else session.get('role')
|
||||
title = current_app.config.get('DISPLAY_TITLE', '20*C+M+B+27')
|
||||
|
||||
if role == 'Dispatcher':
|
||||
start_url = url_for('views.dispatcher_mobil', tenant=tenant)
|
||||
name = 'CMBNet Dispatcher'
|
||||
short_name = 'CMB Dispo'
|
||||
elif role == 'Gruppe':
|
||||
start_url = url_for('views.gruppen', tenant=tenant)
|
||||
name = 'CMBNet Gruppe'
|
||||
short_name = 'CMB Gruppe'
|
||||
else:
|
||||
start_url = url_for('views.index', tenant=tenant)
|
||||
name = 'CMBNet'
|
||||
short_name = 'CMBNet'
|
||||
|
||||
icon_192 = url_for('static', filename='img/icon-192.png')
|
||||
icon_512 = url_for('static', filename='img/icon-512.png')
|
||||
|
||||
payload = {
|
||||
'id': start_url,
|
||||
'name': name,
|
||||
'short_name': short_name,
|
||||
'description': 'CMBNet – mobile Einsatzansicht',
|
||||
'name': title,
|
||||
'short_name': title,
|
||||
'description': f'{title} – mobile Einsatzansicht',
|
||||
'lang': 'de',
|
||||
'start_url': start_url,
|
||||
'scope': url_for('views.index', tenant=tenant),
|
||||
|
||||
+57
-16
@@ -7,6 +7,8 @@ die Nachricht zu.
|
||||
|
||||
Wichtige Regeln aus der Spezifikation:
|
||||
- Code < 100: rein interne Nachrichten (z. B. Authentifizierung, Heartbeat).
|
||||
Code 99 ist eine serverinterne Aufforderung an alle Clients, die Seite
|
||||
wegen geänderter Daten neu zu laden.
|
||||
- Code 100/200/300: State- bzw. Positionsänderungen an Dispatcher, Beobachter
|
||||
und die jeweils betroffene Gruppe.
|
||||
- Code 1000/1100/2000: Chat-/Broadcast-Nachrichten. Diese werden persistiert,
|
||||
@@ -57,10 +59,13 @@ class WebSocketBroker:
|
||||
role = account['role']
|
||||
|
||||
# Für Gruppen-Accounts die zugehörige Gruppe ermitteln. Ein Account der
|
||||
# Rolle "Gruppe" ist genau einer Gruppe zugeordnet.
|
||||
# Rolle "Gruppe" ist höchstens einer Gruppe zugeordnet.
|
||||
if group_id is None and role == 'Gruppe':
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
'''SELECT g.id FROM groups g
|
||||
JOIN group_accounts ga
|
||||
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
||||
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
group_id = group['id'] if group else None
|
||||
@@ -226,7 +231,10 @@ class WebSocketBroker:
|
||||
return True
|
||||
if role == 'Gruppe':
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
'''SELECT g.id FROM groups g
|
||||
JOIN group_accounts ga
|
||||
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
||||
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
return bool(group and msg_row['receiver_id'] == group['id'])
|
||||
@@ -238,7 +246,10 @@ class WebSocketBroker:
|
||||
return True
|
||||
if role == 'Gruppe':
|
||||
group = db.execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
'''SELECT g.id FROM groups g
|
||||
JOIN group_accounts ga
|
||||
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
||||
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
||||
(account_id, tenant_id)
|
||||
).fetchone()
|
||||
payload = self._payload(msg_row)
|
||||
@@ -293,6 +304,14 @@ class WebSocketBroker:
|
||||
self._deliver(tenant_id, message, sender)
|
||||
return
|
||||
|
||||
# Code 99 ist eine serverinterne Aufforderung zum Neuladen. Clients
|
||||
# dürfen diesen Code nicht selbst auslösen.
|
||||
if code == 99:
|
||||
if apply_business:
|
||||
return
|
||||
self._deliver(tenant_id, message, sender)
|
||||
return
|
||||
|
||||
# Sonstige interne Codes (< 100) werden nicht an die Oberfläche gegeben.
|
||||
if code < 100:
|
||||
return
|
||||
@@ -444,8 +463,14 @@ class WebSocketBroker:
|
||||
return False
|
||||
|
||||
# Ein Gruppen-Account darf nur den Zustand seiner eigenen Gruppe ändern.
|
||||
if sender['role'] == 'Gruppe' and group['account_id'] != sender['id']:
|
||||
return False
|
||||
if sender['role'] == 'Gruppe':
|
||||
linked = db.execute(
|
||||
'''SELECT 1 FROM group_accounts
|
||||
WHERE tenant_id = ? AND group_id = ? AND account_id = ?''',
|
||||
(tenant_id, group_id, sender['id'])
|
||||
).fetchone()
|
||||
if not linked:
|
||||
return False
|
||||
|
||||
new_state = payload.get('state')
|
||||
if new_state not in ('offen', 'unterwegs', 'online', 'pausierend', 'fertig'):
|
||||
@@ -495,8 +520,14 @@ class WebSocketBroker:
|
||||
if not group:
|
||||
return False
|
||||
|
||||
if sender['role'] == 'Gruppe' and group['account_id'] != sender['id']:
|
||||
return False
|
||||
if sender['role'] == 'Gruppe':
|
||||
linked = db.execute(
|
||||
'''SELECT 1 FROM group_accounts
|
||||
WHERE tenant_id = ? AND group_id = ? AND account_id = ?''',
|
||||
(tenant_id, group_id, sender['id'])
|
||||
).fetchone()
|
||||
if not linked:
|
||||
return False
|
||||
|
||||
try:
|
||||
lat = float(payload.get('lat'))
|
||||
@@ -583,7 +614,10 @@ class WebSocketBroker:
|
||||
}
|
||||
if sender and sender['role'] == 'Gruppe':
|
||||
group = db.execute(
|
||||
'SELECT id, aliasname FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
'''SELECT g.id, g.aliasname FROM groups g
|
||||
JOIN group_accounts ga
|
||||
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
||||
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
||||
(sender['id'], tenant_id)
|
||||
).fetchone()
|
||||
if group:
|
||||
@@ -723,14 +757,18 @@ class WebSocketBroker:
|
||||
def add_group_account(group_id):
|
||||
if not group_id:
|
||||
return
|
||||
group = db.execute(
|
||||
'SELECT account_id FROM groups WHERE id = ? AND tenant_id = ?',
|
||||
rows = db.execute(
|
||||
'''SELECT account_id FROM group_accounts
|
||||
WHERE group_id = ? AND tenant_id = ?''',
|
||||
(group_id, tenant_id)
|
||||
).fetchone()
|
||||
if group and group['account_id']:
|
||||
recipients.add(group['account_id'])
|
||||
).fetchall()
|
||||
recipients.update(row['account_id'] for row in rows)
|
||||
|
||||
if code == 100:
|
||||
if code == 99:
|
||||
# Alle verbundenen Clients des Mandanten müssen die Seite neu laden.
|
||||
add_accounts(('Gast', 'Beobachter', 'Gruppe', 'Dispatcher', 'Administrator'))
|
||||
|
||||
elif code == 100:
|
||||
# Dispatcher, Gast, Beobachter + die mit der Straße verknüpfte
|
||||
# Gruppe. Bei einem Gruppenwechsel werden sowohl die alte als auch
|
||||
# die neue Gruppe benachrichtigt.
|
||||
@@ -836,7 +874,10 @@ class WebSocketBroker:
|
||||
if group_id is None and sender is not None and message.code in (200, 300, 2000):
|
||||
# Bei Gruppen-Nachrichten ist der Absender die Gruppe selbst.
|
||||
group = get_db().execute(
|
||||
'SELECT id FROM groups WHERE account_id = ? AND tenant_id = ?',
|
||||
'''SELECT g.id FROM groups g
|
||||
JOIN group_accounts ga
|
||||
ON ga.group_id = g.id AND ga.tenant_id = g.tenant_id
|
||||
WHERE ga.account_id = ? AND g.tenant_id = ?''',
|
||||
(sender['id'], tenant_id)
|
||||
).fetchone()
|
||||
group_id = group['id'] if group else None
|
||||
|
||||
Reference in new issue
Block a user