Projektarbeit-MYP/backend/fix_public_stats.py

130 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""
Temporäres Skript zum Hinzufügen der fehlenden /api/statistics/public Route
"""
with open('app.py', 'r', encoding='utf-8') as f:
content = f.read()
# Die neue Route die hinzugefügt werden soll
new_route = '''
# ===== ÖFFENTLICHE STATISTIK-API =====
@app.route("/api/statistics/public", methods=['GET'])
def api_public_statistics():
"""
Öffentliche Statistiken ohne Authentifizierung.
Stellt grundlegende, nicht-sensible Systemstatistiken bereit,
die auf der Startseite angezeigt werden können.
Returns:
JSON: Öffentliche Statistiken
"""
try:
db_session = get_db_session()
# Grundlegende, nicht-sensible Statistiken
total_jobs = db_session.query(Job).count()
completed_jobs = db_session.query(Job).filter(Job.status == "finished").count()
total_printers = db_session.query(Printer).count()
active_printers = db_session.query(Printer).filter(
Printer.active == True,
Printer.status.in_(["online", "available", "idle"])
).count()
# Erfolgsrate berechnen
success_rate = round((completed_jobs / total_jobs * 100) if total_jobs > 0 else 0, 1)
# Anonymisierte Benutzerstatistiken
total_users = db_session.query(User).filter(User.active == True).count()
# Letzte 30 Tage Aktivität (anonymisiert)
thirty_days_ago = datetime.now() - timedelta(days=30)
recent_jobs = db_session.query(Job).filter(
Job.created_at >= thirty_days_ago
).count()
db_session.close()
public_stats = {
"system_info": {
"total_jobs": total_jobs,
"completed_jobs": completed_jobs,
"success_rate": success_rate,
"total_printers": total_printers,
"active_printers": active_printers,
"active_users": total_users,
"recent_activity": recent_jobs
},
"health_indicators": {
"system_status": "operational",
"printer_availability": round((active_printers / total_printers * 100) if total_printers > 0 else 0, 1),
"last_updated": datetime.now().isoformat()
},
"features": {
"multi_location_support": True,
"real_time_monitoring": True,
"automated_scheduling": True,
"advanced_reporting": True
}
}
return jsonify(public_stats)
except Exception as e:
app_logger.error(f"Fehler bei öffentlichen Statistiken: {str(e)}")
# Fallback-Statistiken bei Fehler
return jsonify({
"system_info": {
"total_jobs": 0,
"completed_jobs": 0,
"success_rate": 0,
"total_printers": 0,
"active_printers": 0,
"active_users": 0,
"recent_activity": 0
},
"health_indicators": {
"system_status": "maintenance",
"printer_availability": 0,
"last_updated": datetime.now().isoformat()
},
"features": {
"multi_location_support": True,
"real_time_monitoring": True,
"automated_scheduling": True,
"advanced_reporting": True
},
"error": "Statistiken temporär nicht verfügbar"
}), 200 # 200 statt 500 um Frontend nicht zu brechen
'''
# Füge die Route vor @app.route("/api/stats", methods=['GET']) hinzu
marker = '@app.route("/api/stats", methods=[\'GET\'])'
if marker in content:
parts = content.split(marker, 1)
new_content = parts[0] + new_route + marker + parts[1]
with open('app.py', 'w', encoding='utf-8') as f:
f.write(new_content)
print('✅ Öffentliche Statistik-API Route hinzugefügt')
else:
print('❌ Marker nicht gefunden - versuche alternativen Marker')
# Versuche alternativen Marker
alt_marker = '@app.route("/api/stats", methods=[\"GET\"])'
if alt_marker in content:
parts = content.split(alt_marker, 1)
new_content = parts[0] + new_route + alt_marker + parts[1]
with open('app.py', 'w', encoding='utf-8') as f:
f.write(new_content)
print('✅ Öffentliche Statistik-API Route mit alternativem Marker hinzugefügt')
else:
print('❌ Auch alternativer Marker nicht gefunden')
print('Suche verfügbare Marker...')
import re
stats_markers = re.findall(r'@app\.route\("/api/stats".*?\)', content)
print(f'Gefundene Stats-Marker: {stats_markers}')