"""Dashboard-Statistiken.""" from fastapi import APIRouter, Depends from auth import get_current_admin from database import db_dependency import aiosqlite router = APIRouter(prefix="/api/dashboard", tags=["dashboard"]) @router.get("/stats") async def get_stats( admin: dict = Depends(get_current_admin), db: aiosqlite.Connection = Depends(db_dependency), ): """Gesamtstatistiken fuer das Dashboard.""" cursor = await db.execute("SELECT COUNT(*) as cnt FROM organizations") org_count = (await cursor.fetchone())["cnt"] cursor = await db.execute("SELECT COUNT(*) as cnt FROM organizations WHERE is_active = 1") active_orgs = (await cursor.fetchone())["cnt"] cursor = await db.execute("SELECT COUNT(*) as cnt FROM users WHERE is_active = 1") active_users = (await cursor.fetchone())["cnt"] cursor = await db.execute("SELECT COUNT(*) as cnt FROM users") total_users = (await cursor.fetchone())["cnt"] cursor = await db.execute("SELECT COUNT(*) as cnt FROM licenses WHERE status = 'active'") active_licenses = (await cursor.fetchone())["cnt"] cursor = await db.execute("SELECT COUNT(*) as cnt FROM incidents") total_incidents = (await cursor.fetchone())["cnt"] cursor = await db.execute("SELECT COUNT(*) as cnt FROM incidents WHERE status = 'active'") active_incidents = (await cursor.fetchone())["cnt"] # Bald ablaufende Lizenzen (30 Tage) cursor = await db.execute( """SELECT l.id, l.organization_id, l.license_type, l.valid_until, l.max_users, o.name as org_name FROM licenses l JOIN organizations o ON o.id = l.organization_id WHERE l.status = 'active' AND l.valid_until IS NOT NULL AND l.valid_until < datetime('now', '+30 days') ORDER BY l.valid_until""" ) expiring = [dict(row) for row in await cursor.fetchall()] # Letzte Aktivitaeten (neue Orgs, neue Nutzer) cursor = await db.execute( "SELECT 'org' as type, name as label, created_at FROM organizations ORDER BY created_at DESC LIMIT 5" ) recent_orgs = [dict(row) for row in await cursor.fetchall()] cursor = await db.execute( """SELECT 'user' as type, u.username || ' (' || o.name || ')' as label, u.created_at FROM users u JOIN organizations o ON o.id = u.organization_id ORDER BY u.created_at DESC LIMIT 5""" ) recent_users = [dict(row) for row in await cursor.fetchall()] return { "organizations": {"total": org_count, "active": active_orgs}, "users": {"total": total_users, "active": active_users}, "licenses": {"active": active_licenses}, "incidents": {"total": total_incidents, "active": active_incidents}, "expiring_licenses": expiring, "recent_activity": sorted(recent_orgs + recent_users, key=lambda x: x["created_at"], reverse=True)[:10], }