Files
Sternsinger/CMBNet/cmbnet/api/groups.py
T

136 lines
4.9 KiB
Python

"""
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, notify_reload
api_groups_bp = Blueprint('api_groups', __name__)
@api_groups_bp.route('/groups/me')
@role_required(['Gruppe'])
def get_my_group(**kwargs):
from cmbnet.services.groups_service import GroupsService
groups = GroupsService.get_all(g.tenant_id)
account_id = int(g.current_account['id'])
for group in groups.values():
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
@api_groups_bp.route('/groups/<int:group_id>/alias', methods=['POST'])
@role_required(['Dispatcher', 'Administrator'])
def update_group_alias(group_id, **kwargs):
"""Ändert den Aliasnamen einer Gruppe aus dem Dispatcher-View."""
data = request.get_json(silent=True) or {}
aliasname = str(data.get('aliasname') or '').strip()
if len(aliasname) > 120:
return jsonify({'error': 'Aliasname ist zu lang (maximal 120 Zeichen)'}), 400
group = GroupModel.get_by_id(group_id, g.tenant_id)
if not group:
return jsonify({'error': 'Gruppe nicht gefunden'}), 404
if group['aliasname'] != aliasname:
GroupModel.update(group_id, g.tenant_id, aliasname=aliasname)
log_transaction(
'group.alias_update', 'group', group_id,
{'from': group['aliasname'], 'to': aliasname}
)
GroupsService.invalidate(g.tenant_id)
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)})