🎉 Improved database structure with new files 'myp.db-shm' and 'myp.db-wal', updated documentation to 'STECKDOSENSCHALTZEITEN.md'. Also, refactored logs for better organization. 📝🔍📈

This commit is contained in:
Till Tomczak 2025-06-02 14:47:37 +02:00
parent 7ee6ce5cae
commit 7bea427bd6
47 changed files with 3194 additions and 598 deletions

View File

@ -8369,12 +8369,12 @@ def refresh_dashboard():
# ===== STECKDOSEN-MONITORING API-ROUTEN ===== # ===== STECKDOSEN-MONITORING API-ROUTEN =====
@app.route("/api/admin/plug-monitoring/logs", methods=['GET']) @app.route("/api/admin/plug-schedules/logs", methods=['GET'])
@login_required @login_required
@admin_required @admin_required
def api_admin_plug_monitoring_logs(): def api_admin_plug_schedules_logs():
""" """
API-Endpoint für Steckdosen-Monitoring-Logs. API-Endpoint für Steckdosenschaltzeiten-Logs.
Unterstützt Filterung nach Drucker, Zeitraum und Status. Unterstützt Filterung nach Drucker, Zeitraum und Status.
""" """
try: try:
@ -8459,12 +8459,12 @@ def api_admin_plug_monitoring_logs():
"details": str(e) if current_user.is_admin else None "details": str(e) if current_user.is_admin else None
}), 500 }), 500
@app.route("/api/admin/plug-monitoring/statistics", methods=['GET']) @app.route("/api/admin/plug-schedules/statistics", methods=['GET'])
@login_required @login_required
@admin_required @admin_required
def api_admin_plug_monitoring_statistics(): def api_admin_plug_schedules_statistics():
""" """
API-Endpoint für Steckdosen-Monitoring-Statistiken. API-Endpoint für Steckdosenschaltzeiten-Statistiken.
""" """
try: try:
hours = request.args.get('hours', default=24, type=int) hours = request.args.get('hours', default=24, type=int)
@ -8511,12 +8511,12 @@ def api_admin_plug_monitoring_statistics():
"details": str(e) if current_user.is_admin else None "details": str(e) if current_user.is_admin else None
}), 500 }), 500
@app.route("/api/admin/plug-monitoring/cleanup", methods=['POST']) @app.route("/api/admin/plug-schedules/cleanup", methods=['POST'])
@login_required @login_required
@admin_required @admin_required
def api_admin_plug_monitoring_cleanup(): def api_admin_plug_schedules_cleanup():
""" """
API-Endpoint zum Bereinigen alter Steckdosen-Logs. API-Endpoint zum Bereinigen alter Steckdosenschaltzeiten-Logs.
""" """
try: try:
data = request.get_json() or {} data = request.get_json() or {}
@ -8530,7 +8530,7 @@ def api_admin_plug_monitoring_cleanup():
SystemLog.log_system_event( SystemLog.log_system_event(
level="INFO", level="INFO",
message=f"Steckdosen-Logs bereinigt: {deleted_count} Einträge gelöscht (älter als {days} Tage)", message=f"Steckdosen-Logs bereinigt: {deleted_count} Einträge gelöscht (älter als {days} Tage)",
module="admin_plug_monitoring", module="admin_plug_schedules",
user_id=current_user.id user_id=current_user.id
) )
@ -8551,6 +8551,98 @@ def api_admin_plug_monitoring_cleanup():
"details": str(e) if current_user.is_admin else None "details": str(e) if current_user.is_admin else None
}), 500 }), 500
@app.route("/api/admin/plug-schedules/calendar", methods=['GET'])
@login_required
@admin_required
def api_admin_plug_schedules_calendar():
"""
API-Endpoint für Kalender-Daten der Steckdosenschaltzeiten.
Liefert Events für FullCalendar im JSON-Format.
"""
try:
# Parameter aus Request
start_date = request.args.get('start')
end_date = request.args.get('end')
printer_id = request.args.get('printer_id', type=int)
if not start_date or not end_date:
return jsonify([]) # Leere Events bei fehlenden Daten
# Datum-Strings zu datetime konvertieren
start_dt = datetime.fromisoformat(start_date.replace('Z', '+00:00'))
end_dt = datetime.fromisoformat(end_date.replace('Z', '+00:00'))
db_session = get_db_session()
try:
# Query für Logs im Zeitraum
query = db_session.query(PlugStatusLog)\
.filter(PlugStatusLog.timestamp >= start_dt)\
.filter(PlugStatusLog.timestamp <= end_dt)\
.join(Printer)
# Drucker-Filter
if printer_id:
query = query.filter(PlugStatusLog.printer_id == printer_id)
# Logs abrufen und nach Drucker gruppieren
logs = query.order_by(PlugStatusLog.timestamp.asc()).all()
# Events für FullCalendar formatieren
events = []
for log in logs:
# Farbe und Titel basierend auf Status
if log.status == 'on':
color = '#10b981' # Grün
title = f"🟢 {log.printer.name}: EIN"
elif log.status == 'off':
color = '#f59e0b' # Orange
title = f"🔴 {log.printer.name}: AUS"
elif log.status == 'connected':
color = '#3b82f6' # Blau
title = f"🔌 {log.printer.name}: Verbunden"
elif log.status == 'disconnected':
color = '#ef4444' # Rot
title = f"{log.printer.name}: Getrennt"
else:
color = '#6b7280' # Grau
title = f"{log.printer.name}: {log.status}"
# Event-Objekt für FullCalendar
event = {
'id': f"plug_{log.id}",
'title': title,
'start': log.timestamp.isoformat(),
'backgroundColor': color,
'borderColor': color,
'textColor': '#ffffff',
'allDay': False,
'extendedProps': {
'printer_id': log.printer_id,
'printer_name': log.printer.name,
'status': log.status,
'source': log.source,
'user_id': log.user_id,
'user_name': log.user.name if log.user else None,
'notes': log.notes,
'response_time_ms': log.response_time_ms,
'error_message': log.error_message,
'power_consumption': log.power_consumption,
'voltage': log.voltage,
'current': log.current
}
}
events.append(event)
return jsonify(events)
finally:
db_session.close()
except Exception as e:
app_logger.error(f"Fehler beim Abrufen der Kalender-Daten: {str(e)}")
return jsonify([]), 500
def get_relative_time(timestamp): def get_relative_time(timestamp):
""" """
Hilfsfunktion für relative Zeitangaben. Hilfsfunktion für relative Zeitangaben.

BIN
backend/database/myp.db-shm Normal file

Binary file not shown.

BIN
backend/database/myp.db-wal Normal file

Binary file not shown.

View File

@ -111,3 +111,4 @@
2025-06-02 14:28:19 - [analytics] analytics - [INFO] INFO - 📈 Analytics Engine initialisiert 2025-06-02 14:28:19 - [analytics] analytics - [INFO] INFO - 📈 Analytics Engine initialisiert
2025-06-02 14:30:43 - [analytics] analytics - [INFO] INFO - 📈 Analytics Engine initialisiert 2025-06-02 14:30:43 - [analytics] analytics - [INFO] INFO - 📈 Analytics Engine initialisiert
2025-06-02 14:34:09 - [analytics] analytics - [INFO] INFO - 📈 Analytics Engine initialisiert 2025-06-02 14:34:09 - [analytics] analytics - [INFO] INFO - 📈 Analytics Engine initialisiert
2025-06-02 14:43:36 - [analytics] analytics - [INFO] INFO - 📈 Analytics Engine initialisiert

View File

@ -2902,3 +2902,26 @@ WHERE jobs.status = ?) AS anon_1]
2025-06-02 14:34:18 - [app] app - [ERROR] ERROR - Datenbank-Transaktion fehlgeschlagen: name 'func' is not defined 2025-06-02 14:34:18 - [app] app - [ERROR] ERROR - Datenbank-Transaktion fehlgeschlagen: name 'func' is not defined
2025-06-02 14:34:18 - [app] app - [ERROR] ERROR - Fehler beim Erstellen der Steckdosen-Statistiken: name 'func' is not defined 2025-06-02 14:34:18 - [app] app - [ERROR] ERROR - Fehler beim Erstellen der Steckdosen-Statistiken: name 'func' is not defined
2025-06-02 14:34:20 - [app] app - [INFO] INFO - Admin-Check für Funktion api_admin_plug_monitoring_logs: User authenticated: True, User ID: 1, Is Admin: True 2025-06-02 14:34:20 - [app] app - [INFO] INFO - Admin-Check für Funktion api_admin_plug_monitoring_logs: User authenticated: True, User ID: 1, Is Admin: True
2025-06-02 14:43:36 - [app] app - [INFO] INFO - Optimierte SQLite-Engine erstellt: C:\Users\TTOMCZA.EMEA\Dev\Projektarbeit-MYP\backend\database\myp.db
2025-06-02 14:43:37 - [app] app - [INFO] INFO - SQLite für Raspberry Pi optimiert (reduzierte Cache-Größe, SD-Karten I/O)
2025-06-02 14:43:37 - [app] app - [INFO] INFO - ✅ Timeout Force-Quit Manager geladen
2025-06-02 14:43:37 - [app] app - [INFO] INFO - ✅ Zentraler Shutdown-Manager initialisiert
2025-06-02 14:43:37 - [app] app - [INFO] INFO - 🔄 Starte Datenbank-Setup und Migrationen...
2025-06-02 14:43:37 - [app] app - [INFO] INFO - Datenbank mit Optimierungen initialisiert
2025-06-02 14:43:37 - [app] app - [INFO] INFO - ✅ JobOrder-Tabelle bereits vorhanden
2025-06-02 14:43:37 - [app] app - [INFO] INFO - Admin-Benutzer admin (admin@mercedes-benz.com) existiert bereits. Passwort wurde zurückgesetzt.
2025-06-02 14:43:37 - [app] app - [INFO] INFO - ✅ Datenbank-Setup und Migrationen erfolgreich abgeschlossen
2025-06-02 14:43:37 - [app] app - [INFO] INFO - 🖨️ Starte automatische Steckdosen-Initialisierung...
2025-06-02 14:43:40 - [app] app - [INFO] INFO - Steckdosen-Status geloggt: Drucker 4, Status: disconnected, Quelle: system
2025-06-02 14:43:42 - [app] app - [INFO] INFO - Steckdosen-Status geloggt: Drucker 5, Status: disconnected, Quelle: system
2025-06-02 14:43:42 - [app] app - [INFO] INFO - ✅ Steckdosen-Initialisierung: 0/2 Drucker erfolgreich
2025-06-02 14:43:42 - [app] app - [WARNING] WARNING - ⚠️ 2 Drucker konnten nicht initialisiert werden
2025-06-02 14:43:42 - [app] app - [INFO] INFO - 🔄 Debug-Modus: Queue Manager deaktiviert für Entwicklung
2025-06-02 14:43:42 - [app] app - [INFO] INFO - Job-Scheduler gestartet
2025-06-02 14:43:42 - [app] app - [INFO] INFO - Starte Debug-Server auf 0.0.0.0:5000 (HTTP)
2025-06-02 14:43:42 - [app] app - [INFO] INFO - Windows-Debug-Modus: Auto-Reload deaktiviert
2025-06-02 14:43:49 - [app] app - [INFO] INFO - Admin-Check für Funktion admin_plug_schedules: User authenticated: True, User ID: 1, Is Admin: True
2025-06-02 14:43:49 - [app] app - [INFO] INFO - Admin Administrator (ID: 1) öffnet Steckdosenschaltzeiten
2025-06-02 14:43:49 - [app] app - [ERROR] ERROR - Datenbank-Transaktion fehlgeschlagen: name 'func' is not defined
2025-06-02 14:43:49 - [app] app - [ERROR] ERROR - Fehler beim Erstellen der Steckdosen-Statistiken: name 'func' is not defined
2025-06-02 14:43:51 - [app] app - [INFO] INFO - Admin-Check für Funktion api_admin_plug_schedules_calendar: User authenticated: True, User ID: 1, Is Admin: True

View File

@ -115,3 +115,4 @@
2025-06-02 14:28:19 - [backup] backup - [INFO] INFO - BackupManager initialisiert (minimal implementation) 2025-06-02 14:28:19 - [backup] backup - [INFO] INFO - BackupManager initialisiert (minimal implementation)
2025-06-02 14:30:43 - [backup] backup - [INFO] INFO - BackupManager initialisiert (minimal implementation) 2025-06-02 14:30:43 - [backup] backup - [INFO] INFO - BackupManager initialisiert (minimal implementation)
2025-06-02 14:34:08 - [backup] backup - [INFO] INFO - BackupManager initialisiert (minimal implementation) 2025-06-02 14:34:08 - [backup] backup - [INFO] INFO - BackupManager initialisiert (minimal implementation)
2025-06-02 14:43:36 - [backup] backup - [INFO] INFO - BackupManager initialisiert (minimal implementation)

View File

@ -445,3 +445,7 @@
2025-06-02 14:34:09 - [dashboard] dashboard - [INFO] INFO - Dashboard-Background-Worker gestartet 2025-06-02 14:34:09 - [dashboard] dashboard - [INFO] INFO - Dashboard-Background-Worker gestartet
2025-06-02 14:34:09 - [dashboard] dashboard - [INFO] INFO - Dashboard WebSocket-Server wird mit threading initialisiert (eventlet-Fallback) 2025-06-02 14:34:09 - [dashboard] dashboard - [INFO] INFO - Dashboard WebSocket-Server wird mit threading initialisiert (eventlet-Fallback)
2025-06-02 14:34:09 - [dashboard] dashboard - [INFO] INFO - Dashboard WebSocket-Server initialisiert (async_mode: threading) 2025-06-02 14:34:09 - [dashboard] dashboard - [INFO] INFO - Dashboard WebSocket-Server initialisiert (async_mode: threading)
2025-06-02 14:43:37 - [dashboard] dashboard - [INFO] INFO - Dashboard-Background-Worker gestartet
2025-06-02 14:43:37 - [dashboard] dashboard - [INFO] INFO - Dashboard-Background-Worker gestartet
2025-06-02 14:43:37 - [dashboard] dashboard - [INFO] INFO - Dashboard WebSocket-Server wird mit threading initialisiert (eventlet-Fallback)
2025-06-02 14:43:37 - [dashboard] dashboard - [INFO] INFO - Dashboard WebSocket-Server initialisiert (async_mode: threading)

View File

@ -111,3 +111,4 @@
2025-06-02 14:28:19 - [database] database - [INFO] INFO - Datenbank-Wartungs-Scheduler gestartet 2025-06-02 14:28:19 - [database] database - [INFO] INFO - Datenbank-Wartungs-Scheduler gestartet
2025-06-02 14:30:43 - [database] database - [INFO] INFO - Datenbank-Wartungs-Scheduler gestartet 2025-06-02 14:30:43 - [database] database - [INFO] INFO - Datenbank-Wartungs-Scheduler gestartet
2025-06-02 14:34:08 - [database] database - [INFO] INFO - Datenbank-Wartungs-Scheduler gestartet 2025-06-02 14:34:08 - [database] database - [INFO] INFO - Datenbank-Wartungs-Scheduler gestartet
2025-06-02 14:43:36 - [database] database - [INFO] INFO - Datenbank-Wartungs-Scheduler gestartet

View File

@ -108,3 +108,4 @@
2025-06-02 14:28:20 - [email_notification] email_notification - [INFO] INFO - 📧 Offline-E-Mail-Benachrichtigung initialisiert (kein echter E-Mail-Versand) 2025-06-02 14:28:20 - [email_notification] email_notification - [INFO] INFO - 📧 Offline-E-Mail-Benachrichtigung initialisiert (kein echter E-Mail-Versand)
2025-06-02 14:30:44 - [email_notification] email_notification - [INFO] INFO - 📧 Offline-E-Mail-Benachrichtigung initialisiert (kein echter E-Mail-Versand) 2025-06-02 14:30:44 - [email_notification] email_notification - [INFO] INFO - 📧 Offline-E-Mail-Benachrichtigung initialisiert (kein echter E-Mail-Versand)
2025-06-02 14:34:09 - [email_notification] email_notification - [INFO] INFO - 📧 Offline-E-Mail-Benachrichtigung initialisiert (kein echter E-Mail-Versand) 2025-06-02 14:34:09 - [email_notification] email_notification - [INFO] INFO - 📧 Offline-E-Mail-Benachrichtigung initialisiert (kein echter E-Mail-Versand)
2025-06-02 14:43:37 - [email_notification] email_notification - [INFO] INFO - 📧 Offline-E-Mail-Benachrichtigung initialisiert (kein echter E-Mail-Versand)

View File

@ -222,3 +222,5 @@
2025-06-02 14:30:44 - [maintenance] maintenance - [INFO] INFO - Wartungs-Scheduler gestartet 2025-06-02 14:30:44 - [maintenance] maintenance - [INFO] INFO - Wartungs-Scheduler gestartet
2025-06-02 14:34:09 - [maintenance] maintenance - [INFO] INFO - Wartungs-Scheduler gestartet 2025-06-02 14:34:09 - [maintenance] maintenance - [INFO] INFO - Wartungs-Scheduler gestartet
2025-06-02 14:34:09 - [maintenance] maintenance - [INFO] INFO - Wartungs-Scheduler gestartet 2025-06-02 14:34:09 - [maintenance] maintenance - [INFO] INFO - Wartungs-Scheduler gestartet
2025-06-02 14:43:37 - [maintenance] maintenance - [INFO] INFO - Wartungs-Scheduler gestartet
2025-06-02 14:43:37 - [maintenance] maintenance - [INFO] INFO - Wartungs-Scheduler gestartet

View File

@ -220,3 +220,5 @@
2025-06-02 14:30:44 - [multi_location] multi_location - [INFO] INFO - Standard-Standort erstellt 2025-06-02 14:30:44 - [multi_location] multi_location - [INFO] INFO - Standard-Standort erstellt
2025-06-02 14:34:09 - [multi_location] multi_location - [INFO] INFO - Standard-Standort erstellt 2025-06-02 14:34:09 - [multi_location] multi_location - [INFO] INFO - Standard-Standort erstellt
2025-06-02 14:34:09 - [multi_location] multi_location - [INFO] INFO - Standard-Standort erstellt 2025-06-02 14:34:09 - [multi_location] multi_location - [INFO] INFO - Standard-Standort erstellt
2025-06-02 14:43:37 - [multi_location] multi_location - [INFO] INFO - Standard-Standort erstellt
2025-06-02 14:43:37 - [multi_location] multi_location - [INFO] INFO - Standard-Standort erstellt

View File

@ -110,3 +110,4 @@
2025-06-02 14:28:20 - [permissions] permissions - [INFO] INFO - 🔐 Permission Template Helpers registriert 2025-06-02 14:28:20 - [permissions] permissions - [INFO] INFO - 🔐 Permission Template Helpers registriert
2025-06-02 14:30:44 - [permissions] permissions - [INFO] INFO - 🔐 Permission Template Helpers registriert 2025-06-02 14:30:44 - [permissions] permissions - [INFO] INFO - 🔐 Permission Template Helpers registriert
2025-06-02 14:34:09 - [permissions] permissions - [INFO] INFO - 🔐 Permission Template Helpers registriert 2025-06-02 14:34:09 - [permissions] permissions - [INFO] INFO - 🔐 Permission Template Helpers registriert
2025-06-02 14:43:37 - [permissions] permissions - [INFO] INFO - 🔐 Permission Template Helpers registriert

View File

@ -3180,3 +3180,23 @@
2025-06-02 14:34:29 - [printer_monitor] printer_monitor - [WARNING] WARNING - 🔌 Tapo P110 (192.168.0.104): UNREACHABLE (Ping fehlgeschlagen) 2025-06-02 14:34:29 - [printer_monitor] printer_monitor - [WARNING] WARNING - 🔌 Tapo P110 (192.168.0.104): UNREACHABLE (Ping fehlgeschlagen)
2025-06-02 14:34:29 - [printer_monitor] printer_monitor - [WARNING] WARNING - 🔌 Tapo P110 (192.168.0.103): UNREACHABLE (Ping fehlgeschlagen) 2025-06-02 14:34:29 - [printer_monitor] printer_monitor - [WARNING] WARNING - 🔌 Tapo P110 (192.168.0.103): UNREACHABLE (Ping fehlgeschlagen)
2025-06-02 14:34:29 - [printer_monitor] printer_monitor - [INFO] INFO - ✅ Status-Update abgeschlossen für 2 Drucker 2025-06-02 14:34:29 - [printer_monitor] printer_monitor - [INFO] INFO - ✅ Status-Update abgeschlossen für 2 Drucker
2025-06-02 14:43:36 - [printer_monitor] printer_monitor - [INFO] INFO - 🖨️ Drucker-Monitor initialisiert
2025-06-02 14:43:36 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Automatische Tapo-Erkennung in separatem Thread gestartet
2025-06-02 14:43:37 - [printer_monitor] printer_monitor - [INFO] INFO - 🚀 Starte Steckdosen-Initialisierung beim Programmstart...
2025-06-02 14:43:38 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Starte automatische Tapo-Steckdosenerkennung...
2025-06-02 14:43:38 - [printer_monitor] printer_monitor - [INFO] INFO - 🔄 Teste 6 Standard-IPs aus der Konfiguration
2025-06-02 14:43:38 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Teste IP 1/6: 192.168.0.103
2025-06-02 14:43:40 - [printer_monitor] printer_monitor - [WARNING] WARNING - ❌ Tapo P110 (192.168.0.103): Steckdose konnte nicht ausgeschaltet werden
2025-06-02 14:43:42 - [printer_monitor] printer_monitor - [WARNING] WARNING - ❌ Tapo P110 (192.168.0.104): Steckdose konnte nicht ausgeschaltet werden
2025-06-02 14:43:42 - [printer_monitor] printer_monitor - [INFO] INFO - 🎯 Steckdosen-Initialisierung abgeschlossen: 0/2 erfolgreich
2025-06-02 14:43:44 - [printer_monitor] printer_monitor - [INFO] INFO - 🔄 Aktualisiere Live-Druckerstatus...
2025-06-02 14:43:44 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Prüfe Status von 2 aktiven Druckern...
2025-06-02 14:43:44 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Teste IP 2/6: 192.168.0.104
2025-06-02 14:43:50 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Teste IP 3/6: 192.168.0.100
2025-06-02 14:43:53 - [printer_monitor] printer_monitor - [WARNING] WARNING - 🔌 Tapo P110 (192.168.0.103): UNREACHABLE (Ping fehlgeschlagen)
2025-06-02 14:43:53 - [printer_monitor] printer_monitor - [WARNING] WARNING - 🔌 Tapo P110 (192.168.0.104): UNREACHABLE (Ping fehlgeschlagen)
2025-06-02 14:43:53 - [printer_monitor] printer_monitor - [INFO] INFO - ✅ Status-Update abgeschlossen für 2 Drucker
2025-06-02 14:43:56 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Teste IP 4/6: 192.168.0.101
2025-06-02 14:44:02 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Teste IP 5/6: 192.168.0.102
2025-06-02 14:44:08 - [printer_monitor] printer_monitor - [INFO] INFO - 🔍 Teste IP 6/6: 192.168.0.105
2025-06-02 14:44:14 - [printer_monitor] printer_monitor - [INFO] INFO - ✅ Steckdosen-Erkennung abgeschlossen: 0/6 Steckdosen gefunden in 36.0s

View File

@ -6598,3 +6598,9 @@
2025-06-02 14:34:20 - [printers] printers - [INFO] INFO - 🔄 Live-Status-Abfrage von Benutzer Administrator (ID: 1) 2025-06-02 14:34:20 - [printers] printers - [INFO] INFO - 🔄 Live-Status-Abfrage von Benutzer Administrator (ID: 1)
2025-06-02 14:34:29 - [printers] printers - [INFO] INFO - ✅ Live-Status-Abfrage erfolgreich: 2 Drucker 2025-06-02 14:34:29 - [printers] printers - [INFO] INFO - ✅ Live-Status-Abfrage erfolgreich: 2 Drucker
2025-06-02 14:34:29 - [printers] printers - [INFO] INFO - ✅ API-Live-Drucker-Status-Abfrage 'get_live_printer_status' erfolgreich in 9076.30ms 2025-06-02 14:34:29 - [printers] printers - [INFO] INFO - ✅ API-Live-Drucker-Status-Abfrage 'get_live_printer_status' erfolgreich in 9076.30ms
2025-06-02 14:43:44 - [printers] printers - [INFO] INFO - 🔄 Live-Status-Abfrage von Benutzer Administrator (ID: 1)
2025-06-02 14:43:53 - [printers] printers - [INFO] INFO - ✅ Live-Status-Abfrage erfolgreich: 2 Drucker
2025-06-02 14:43:53 - [printers] printers - [INFO] INFO - ✅ API-Live-Drucker-Status-Abfrage 'get_live_printer_status' erfolgreich in 9009.19ms
2025-06-02 14:43:53 - [printers] printers - [INFO] INFO - 🔄 Live-Status-Abfrage von Benutzer Administrator (ID: 1)
2025-06-02 14:43:53 - [printers] printers - [INFO] INFO - ✅ Live-Status-Abfrage erfolgreich: 2 Drucker
2025-06-02 14:43:53 - [printers] printers - [INFO] INFO - ✅ API-Live-Drucker-Status-Abfrage 'get_live_printer_status' erfolgreich in 0.52ms

View File

@ -110,3 +110,4 @@
2025-06-02 14:28:20 - [security] security - [INFO] INFO - 🔒 Security System initialisiert 2025-06-02 14:28:20 - [security] security - [INFO] INFO - 🔒 Security System initialisiert
2025-06-02 14:30:44 - [security] security - [INFO] INFO - 🔒 Security System initialisiert 2025-06-02 14:30:44 - [security] security - [INFO] INFO - 🔒 Security System initialisiert
2025-06-02 14:34:09 - [security] security - [INFO] INFO - 🔒 Security System initialisiert 2025-06-02 14:34:09 - [security] security - [INFO] INFO - 🔒 Security System initialisiert
2025-06-02 14:43:37 - [security] security - [INFO] INFO - 🔒 Security System initialisiert

View File

@ -196,3 +196,4 @@
2025-06-02 14:28:20 - [shutdown_manager] shutdown_manager - [INFO] INFO - 🔧 Shutdown-Manager initialisiert 2025-06-02 14:28:20 - [shutdown_manager] shutdown_manager - [INFO] INFO - 🔧 Shutdown-Manager initialisiert
2025-06-02 14:30:44 - [shutdown_manager] shutdown_manager - [INFO] INFO - 🔧 Shutdown-Manager initialisiert 2025-06-02 14:30:44 - [shutdown_manager] shutdown_manager - [INFO] INFO - 🔧 Shutdown-Manager initialisiert
2025-06-02 14:34:09 - [shutdown_manager] shutdown_manager - [INFO] INFO - 🔧 Shutdown-Manager initialisiert 2025-06-02 14:34:09 - [shutdown_manager] shutdown_manager - [INFO] INFO - 🔧 Shutdown-Manager initialisiert
2025-06-02 14:43:37 - [shutdown_manager] shutdown_manager - [INFO] INFO - 🔧 Shutdown-Manager initialisiert

View File

@ -998,3 +998,12 @@
2025-06-02 14:34:09 - [startup] startup - [INFO] INFO - 🪟 Windows-Modus: Aktiviert 2025-06-02 14:34:09 - [startup] startup - [INFO] INFO - 🪟 Windows-Modus: Aktiviert
2025-06-02 14:34:09 - [startup] startup - [INFO] INFO - 🔒 Windows-sichere Log-Rotation: Aktiviert 2025-06-02 14:34:09 - [startup] startup - [INFO] INFO - 🔒 Windows-sichere Log-Rotation: Aktiviert
2025-06-02 14:34:09 - [startup] startup - [INFO] INFO - ================================================== 2025-06-02 14:34:09 - [startup] startup - [INFO] INFO - ==================================================
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - ==================================================
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - 🚀 MYP Platform Backend wird gestartet...
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - 🐍 Python Version: 3.13.3 (tags/v3.13.3:6280bb5, Apr 8 2025, 14:47:33) [MSC v.1943 64 bit (AMD64)]
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - 💻 Betriebssystem: nt (win32)
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - 📁 Arbeitsverzeichnis: C:\Users\TTOMCZA.EMEA\Dev\Projektarbeit-MYP\backend
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - ⏰ Startzeit: 2025-06-02T14:43:37.546420
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - 🪟 Windows-Modus: Aktiviert
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - 🔒 Windows-sichere Log-Rotation: Aktiviert
2025-06-02 14:43:37 - [startup] startup - [INFO] INFO - ==================================================

View File

@ -475,3 +475,7 @@
2025-06-02 14:34:08 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Subprocess automatisch gepatcht für UTF-8 Encoding (run + Popen) 2025-06-02 14:34:08 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Subprocess automatisch gepatcht für UTF-8 Encoding (run + Popen)
2025-06-02 14:34:08 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Globaler subprocess-Patch angewendet 2025-06-02 14:34:08 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Globaler subprocess-Patch angewendet
2025-06-02 14:34:08 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Alle Windows-Fixes erfolgreich angewendet 2025-06-02 14:34:08 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Alle Windows-Fixes erfolgreich angewendet
2025-06-02 14:43:36 - [windows_fixes] windows_fixes - [INFO] INFO - 🔧 Wende Windows-spezifische Fixes an...
2025-06-02 14:43:36 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Subprocess automatisch gepatcht für UTF-8 Encoding (run + Popen)
2025-06-02 14:43:36 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Globaler subprocess-Patch angewendet
2025-06-02 14:43:36 - [windows_fixes] windows_fixes - [INFO] INFO - ✅ Alle Windows-Fixes erfolgreich angewendet

View File

@ -16,6 +16,22 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/@esbuild/win32-x64": {
"version": "0.25.4",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.4.tgz",
"integrity": "sha512-nOT2vZNw6hJ+z43oP1SPea/G/6AbN6X+bGNhNuq8NtRHy4wsMhw765IKLNmnjek7GvjWBYQ8Q5VBoYTFg9y1UQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@fortawesome/fontawesome-free": { "node_modules/@fortawesome/fontawesome-free": {
"version": "6.7.2", "version": "6.7.2",
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-6.7.2.tgz", "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-6.7.2.tgz",
@ -179,6 +195,29 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/@pkgjs/parseargs": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
"integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=14"
}
},
"node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.41.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.41.1.tgz",
"integrity": "sha512-Wq2zpapRYLfi4aKxf2Xff0tN+7slj2d4R87WEzqw7ZLsVvO5zwYCIuEGSZYiK41+GlwUo1HiR+GdkLEJnCKTCw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@tailwindcss/forms": { "node_modules/@tailwindcss/forms": {
"version": "0.5.10", "version": "0.5.10",
"resolved": "https://registry.npmjs.org/@tailwindcss/forms/-/forms-0.5.10.tgz", "resolved": "https://registry.npmjs.org/@tailwindcss/forms/-/forms-0.5.10.tgz",

3
backend/node_modules/@esbuild/win32-x64/README.md generated vendored Normal file
View File

@ -0,0 +1,3 @@
# esbuild
This is the Windows 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.

BIN
backend/node_modules/@esbuild/win32-x64/esbuild.exe generated vendored Normal file

Binary file not shown.

20
backend/node_modules/@esbuild/win32-x64/package.json generated vendored Normal file
View File

@ -0,0 +1,20 @@
{
"name": "@esbuild/win32-x64",
"version": "0.25.4",
"description": "The Windows 64-bit binary for esbuild, a JavaScript bundler.",
"repository": {
"type": "git",
"url": "git+https://github.com/evanw/esbuild.git"
},
"license": "MIT",
"preferUnplugged": true,
"engines": {
"node": ">=18"
},
"os": [
"win32"
],
"cpu": [
"x64"
]
}

14
backend/node_modules/@pkgjs/parseargs/.editorconfig generated vendored Normal file
View File

@ -0,0 +1,14 @@
# EditorConfig is awesome: http://EditorConfig.org
# top-most EditorConfig file
root = true
# Copied from Node.js to ease compatibility in PR.
[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
quote_type = single

147
backend/node_modules/@pkgjs/parseargs/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,147 @@
# Changelog
## [0.11.0](https://github.com/pkgjs/parseargs/compare/v0.10.0...v0.11.0) (2022-10-08)
### Features
* add `default` option parameter ([#142](https://github.com/pkgjs/parseargs/issues/142)) ([cd20847](https://github.com/pkgjs/parseargs/commit/cd20847a00b2f556aa9c085ac83b942c60868ec1))
## [0.10.0](https://github.com/pkgjs/parseargs/compare/v0.9.1...v0.10.0) (2022-07-21)
### Features
* add parsed meta-data to returned properties ([#129](https://github.com/pkgjs/parseargs/issues/129)) ([91bfb4d](https://github.com/pkgjs/parseargs/commit/91bfb4d3f7b6937efab1b27c91c45d1205f1497e))
## [0.9.1](https://github.com/pkgjs/parseargs/compare/v0.9.0...v0.9.1) (2022-06-20)
### Bug Fixes
* **runtime:** support node 14+ ([#135](https://github.com/pkgjs/parseargs/issues/135)) ([6a1c5a6](https://github.com/pkgjs/parseargs/commit/6a1c5a6f7cadf2f035e004027e2742e3c4ce554b))
## [0.9.0](https://github.com/pkgjs/parseargs/compare/v0.8.0...v0.9.0) (2022-05-23)
### ⚠ BREAKING CHANGES
* drop handling of electron arguments (#121)
### Code Refactoring
* drop handling of electron arguments ([#121](https://github.com/pkgjs/parseargs/issues/121)) ([a2ffd53](https://github.com/pkgjs/parseargs/commit/a2ffd537c244a062371522b955acb45a404fc9f2))
## [0.8.0](https://github.com/pkgjs/parseargs/compare/v0.7.1...v0.8.0) (2022-05-16)
### ⚠ BREAKING CHANGES
* switch type:string option arguments to greedy, but with error for suspect cases in strict mode (#88)
* positionals now opt-in when strict:true (#116)
* create result.values with null prototype (#111)
### Features
* create result.values with null prototype ([#111](https://github.com/pkgjs/parseargs/issues/111)) ([9d539c3](https://github.com/pkgjs/parseargs/commit/9d539c3d57f269c160e74e0656ad4fa84ff92ec2))
* positionals now opt-in when strict:true ([#116](https://github.com/pkgjs/parseargs/issues/116)) ([3643338](https://github.com/pkgjs/parseargs/commit/364333826b746e8a7dc5505b4b22fd19ac51df3b))
* switch type:string option arguments to greedy, but with error for suspect cases in strict mode ([#88](https://github.com/pkgjs/parseargs/issues/88)) ([c2b5e72](https://github.com/pkgjs/parseargs/commit/c2b5e72161991dfdc535909f1327cc9b970fe7e8))
### [0.7.1](https://github.com/pkgjs/parseargs/compare/v0.7.0...v0.7.1) (2022-04-15)
### Bug Fixes
* resist pollution ([#106](https://github.com/pkgjs/parseargs/issues/106)) ([ecf2dec](https://github.com/pkgjs/parseargs/commit/ecf2dece0a9f2a76d789384d5d71c68ffe64022a))
## [0.7.0](https://github.com/pkgjs/parseargs/compare/v0.6.0...v0.7.0) (2022-04-13)
### Features
* Add strict mode to parser ([#74](https://github.com/pkgjs/parseargs/issues/74)) ([8267d02](https://github.com/pkgjs/parseargs/commit/8267d02083a87b8b8a71fcce08348d1e031ea91c))
## [0.6.0](https://github.com/pkgjs/parseargs/compare/v0.5.0...v0.6.0) (2022-04-11)
### ⚠ BREAKING CHANGES
* rework results to remove redundant `flags` property and store value true for boolean options (#83)
* switch to existing ERR_INVALID_ARG_VALUE (#97)
### Code Refactoring
* rework results to remove redundant `flags` property and store value true for boolean options ([#83](https://github.com/pkgjs/parseargs/issues/83)) ([be153db](https://github.com/pkgjs/parseargs/commit/be153dbed1d488cb7b6e27df92f601ba7337713d))
* switch to existing ERR_INVALID_ARG_VALUE ([#97](https://github.com/pkgjs/parseargs/issues/97)) ([084a23f](https://github.com/pkgjs/parseargs/commit/084a23f9fde2da030b159edb1c2385f24579ce40))
## [0.5.0](https://github.com/pkgjs/parseargs/compare/v0.4.0...v0.5.0) (2022-04-10)
### ⚠ BREAKING CHANGES
* Require type to be specified for each supplied option (#95)
### Features
* Require type to be specified for each supplied option ([#95](https://github.com/pkgjs/parseargs/issues/95)) ([02cd018](https://github.com/pkgjs/parseargs/commit/02cd01885b8aaa59f2db8308f2d4479e64340068))
## [0.4.0](https://github.com/pkgjs/parseargs/compare/v0.3.0...v0.4.0) (2022-03-12)
### ⚠ BREAKING CHANGES
* parsing, revisit short option groups, add support for combined short and value (#75)
* restructure configuration to take options bag (#63)
### Code Refactoring
* parsing, revisit short option groups, add support for combined short and value ([#75](https://github.com/pkgjs/parseargs/issues/75)) ([a92600f](https://github.com/pkgjs/parseargs/commit/a92600fa6c214508ab1e016fa55879a314f541af))
* restructure configuration to take options bag ([#63](https://github.com/pkgjs/parseargs/issues/63)) ([b412095](https://github.com/pkgjs/parseargs/commit/b4120957d90e809ee8b607b06e747d3e6a6b213e))
## [0.3.0](https://github.com/pkgjs/parseargs/compare/v0.2.0...v0.3.0) (2022-02-06)
### Features
* **parser:** support short-option groups ([#59](https://github.com/pkgjs/parseargs/issues/59)) ([882067b](https://github.com/pkgjs/parseargs/commit/882067bc2d7cbc6b796f8e5a079a99bc99d4e6ba))
## [0.2.0](https://github.com/pkgjs/parseargs/compare/v0.1.1...v0.2.0) (2022-02-05)
### Features
* basic support for shorts ([#50](https://github.com/pkgjs/parseargs/issues/50)) ([a2f36d7](https://github.com/pkgjs/parseargs/commit/a2f36d7da4145af1c92f76806b7fe2baf6beeceb))
### Bug Fixes
* always store value for a=b ([#43](https://github.com/pkgjs/parseargs/issues/43)) ([a85e8dc](https://github.com/pkgjs/parseargs/commit/a85e8dc06379fd2696ee195cc625de8fac6aee42))
* support single dash as positional ([#49](https://github.com/pkgjs/parseargs/issues/49)) ([d795bf8](https://github.com/pkgjs/parseargs/commit/d795bf877d068fd67aec381f30b30b63f97109ad))
### [0.1.1](https://github.com/pkgjs/parseargs/compare/v0.1.0...v0.1.1) (2022-01-25)
### Bug Fixes
* only use arrays in results for multiples ([#42](https://github.com/pkgjs/parseargs/issues/42)) ([c357584](https://github.com/pkgjs/parseargs/commit/c357584847912506319ed34a0840080116f4fd65))
## 0.1.0 (2022-01-22)
### Features
* expand scenarios covered by default arguments for environments ([#20](https://github.com/pkgjs/parseargs/issues/20)) ([582ada7](https://github.com/pkgjs/parseargs/commit/582ada7be0eca3a73d6e0bd016e7ace43449fa4c))
* update readme and include contributing guidelines ([8edd6fc](https://github.com/pkgjs/parseargs/commit/8edd6fc863cd705f6fac732724159ebe8065a2b0))
### Bug Fixes
* do not strip excess leading dashes on long option names ([#21](https://github.com/pkgjs/parseargs/issues/21)) ([f848590](https://github.com/pkgjs/parseargs/commit/f848590ebf3249ed5979ff47e003fa6e1a8ec5c0))
* name & readme ([3f057c1](https://github.com/pkgjs/parseargs/commit/3f057c1b158a1bdbe878c64b57460c58e56e465f))
* package.json values ([9bac300](https://github.com/pkgjs/parseargs/commit/9bac300e00cd76c77076bf9e75e44f8929512da9))
* update readme name ([957d8d9](https://github.com/pkgjs/parseargs/commit/957d8d96e1dcb48297c0a14345d44c0123b2883e))
### Build System
* first release as minor ([421c6e2](https://github.com/pkgjs/parseargs/commit/421c6e2569a8668ad14fac5a5af5be60479a7571))

201
backend/node_modules/@pkgjs/parseargs/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

413
backend/node_modules/@pkgjs/parseargs/README.md generated vendored Normal file
View File

@ -0,0 +1,413 @@
<!-- omit in toc -->
# parseArgs
[![Coverage][coverage-image]][coverage-url]
Polyfill of `util.parseArgs()`
## `util.parseArgs([config])`
<!-- YAML
added: v18.3.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/43459
description: add support for returning detailed parse information
using `tokens` in input `config` and returned properties.
-->
> Stability: 1 - Experimental
* `config` {Object} Used to provide arguments for parsing and to configure
the parser. `config` supports the following properties:
* `args` {string\[]} array of argument strings. **Default:** `process.argv`
with `execPath` and `filename` removed.
* `options` {Object} Used to describe arguments known to the parser.
Keys of `options` are the long names of options and values are an
{Object} accepting the following properties:
* `type` {string} Type of argument, which must be either `boolean` or `string`.
* `multiple` {boolean} Whether this option can be provided multiple
times. If `true`, all values will be collected in an array. If
`false`, values for the option are last-wins. **Default:** `false`.
* `short` {string} A single character alias for the option.
* `default` {string | boolean | string\[] | boolean\[]} The default option
value when it is not set by args. It must be of the same type as the
the `type` property. When `multiple` is `true`, it must be an array.
* `strict` {boolean} Should an error be thrown when unknown arguments
are encountered, or when arguments are passed that do not match the
`type` configured in `options`.
**Default:** `true`.
* `allowPositionals` {boolean} Whether this command accepts positional
arguments.
**Default:** `false` if `strict` is `true`, otherwise `true`.
* `tokens` {boolean} Return the parsed tokens. This is useful for extending
the built-in behavior, from adding additional checks through to reprocessing
the tokens in different ways.
**Default:** `false`.
* Returns: {Object} The parsed command line arguments:
* `values` {Object} A mapping of parsed option names with their {string}
or {boolean} values.
* `positionals` {string\[]} Positional arguments.
* `tokens` {Object\[] | undefined} See [parseArgs tokens](#parseargs-tokens)
section. Only returned if `config` includes `tokens: true`.
Provides a higher level API for command-line argument parsing than interacting
with `process.argv` directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.
```mjs
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f'
},
bar: {
type: 'string'
}
};
const {
values,
positionals
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
```
```cjs
const { parseArgs } = require('node:util');
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f'
},
bar: {
type: 'string'
}
};
const {
values,
positionals
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []
```
`util.parseArgs` is experimental and behavior may change. Join the
conversation in [pkgjs/parseargs][] to contribute to the design.
### `parseArgs` `tokens`
Detailed parse information is available for adding custom behaviours by
specifying `tokens: true` in the configuration.
The returned tokens have properties describing:
* all tokens
* `kind` {string} One of 'option', 'positional', or 'option-terminator'.
* `index` {number} Index of element in `args` containing token. So the
source argument for a token is `args[token.index]`.
* option tokens
* `name` {string} Long name of option.
* `rawName` {string} How option used in args, like `-f` of `--foo`.
* `value` {string | undefined} Option value specified in args.
Undefined for boolean options.
* `inlineValue` {boolean | undefined} Whether option value specified inline,
like `--foo=bar`.
* positional tokens
* `value` {string} The value of the positional argument in args (i.e. `args[index]`).
* option-terminator token
The returned tokens are in the order encountered in the input args. Options
that appear more than once in args produce a token for each use. Short option
groups like `-xy` expand to a token for each option. So `-xxx` produces
three tokens.
For example to use the returned tokens to add support for a negated option
like `--no-color`, the tokens can be reprocessed to change the value stored
for the negated option.
```mjs
import { parseArgs } from 'node:util';
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
// Reprocess the option tokens and overwrite the returned values.
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
// Store foo:false for --no-foo
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
// Resave value so last one wins if both --foo and --no-foo.
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
```
```cjs
const { parseArgs } = require('node:util');
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
// Reprocess the option tokens and overwrite the returned values.
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
// Store foo:false for --no-foo
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
// Resave value so last one wins if both --foo and --no-foo.
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
```
Example usage showing negated options, and when an option is used
multiple ways then last one wins.
```console
$ node negate.js
{ logfile: 'default.log', color: undefined }
$ node negate.js --no-logfile --no-color
{ logfile: false, color: false }
$ node negate.js --logfile=test.log --color
{ logfile: 'test.log', color: true }
$ node negate.js --no-logfile --logfile=test.log --color --no-color
{ logfile: 'test.log', color: false }
```
-----
<!-- omit in toc -->
## Table of Contents
- [`util.parseArgs([config])`](#utilparseargsconfig)
- [Scope](#scope)
- [Version Matchups](#version-matchups)
- [🚀 Getting Started](#-getting-started)
- [🙌 Contributing](#-contributing)
- [💡 `process.mainArgs` Proposal](#-processmainargs-proposal)
- [Implementation:](#implementation)
- [📃 Examples](#-examples)
- [F.A.Qs](#faqs)
- [Links & Resources](#links--resources)
-----
## Scope
It is already possible to build great arg parsing modules on top of what Node.js provides; the prickly API is abstracted away by these modules. Thus, process.parseArgs() is not necessarily intended for library authors; it is intended for developers of simple CLI tools, ad-hoc scripts, deployed Node.js applications, and learning materials.
It is exceedingly difficult to provide an API which would both be friendly to these Node.js users while being extensible enough for libraries to build upon. We chose to prioritize these use cases because these are currently not well-served by Node.js' API.
----
## Version Matchups
| Node.js | @pkgjs/parseArgs |
| -- | -- |
| [v18.3.0](https://nodejs.org/docs/latest-v18.x/api/util.html#utilparseargsconfig) | [v0.9.1](https://github.com/pkgjs/parseargs/tree/v0.9.1#utilparseargsconfig) |
| [v16.17.0](https://nodejs.org/dist/latest-v16.x/docs/api/util.html#utilparseargsconfig), [v18.7.0](https://nodejs.org/docs/latest-v18.x/api/util.html#utilparseargsconfig) | [0.10.0](https://github.com/pkgjs/parseargs/tree/v0.10.0#utilparseargsconfig) |
----
## 🚀 Getting Started
1. **Install dependencies.**
```bash
npm install
```
2. **Open the index.js file and start editing!**
3. **Test your code by calling parseArgs through our test file**
```bash
npm test
```
----
## 🙌 Contributing
Any person who wants to contribute to the initiative is welcome! Please first read the [Contributing Guide](CONTRIBUTING.md)
Additionally, reading the [`Examples w/ Output`](#-examples-w-output) section of this document will be the best way to familiarize yourself with the target expected behavior for parseArgs() once it is fully implemented.
This package was implemented using [tape](https://www.npmjs.com/package/tape) as its test harness.
----
## 💡 `process.mainArgs` Proposal
> Note: This can be moved forward independently of the `util.parseArgs()` proposal/work.
### Implementation:
```javascript
process.mainArgs = process.argv.slice(process._exec ? 1 : 2)
```
----
## 📃 Examples
```js
const { parseArgs } = require('@pkgjs/parseargs');
```
```js
const { parseArgs } = require('@pkgjs/parseargs');
// specify the options that may be used
const options = {
foo: { type: 'string'},
bar: { type: 'boolean' },
};
const args = ['--foo=a', '--bar'];
const { values, positionals } = parseArgs({ args, options });
// values = { foo: 'a', bar: true }
// positionals = []
```
```js
const { parseArgs } = require('@pkgjs/parseargs');
// type:string & multiple
const options = {
foo: {
type: 'string',
multiple: true,
},
};
const args = ['--foo=a', '--foo', 'b'];
const { values, positionals } = parseArgs({ args, options });
// values = { foo: [ 'a', 'b' ] }
// positionals = []
```
```js
const { parseArgs } = require('@pkgjs/parseargs');
// shorts
const options = {
foo: {
short: 'f',
type: 'boolean'
},
};
const args = ['-f', 'b'];
const { values, positionals } = parseArgs({ args, options, allowPositionals: true });
// values = { foo: true }
// positionals = ['b']
```
```js
const { parseArgs } = require('@pkgjs/parseargs');
// unconfigured
const options = {};
const args = ['-f', '--foo=a', '--bar', 'b'];
const { values, positionals } = parseArgs({ strict: false, args, options, allowPositionals: true });
// values = { f: true, foo: 'a', bar: true }
// positionals = ['b']
```
----
## F.A.Qs
- Is `cmd --foo=bar baz` the same as `cmd baz --foo=bar`?
- yes
- Does the parser execute a function?
- no
- Does the parser execute one of several functions, depending on input?
- no
- Can subcommands take options that are distinct from the main command?
- no
- Does it output generated help when no options match?
- no
- Does it generated short usage? Like: `usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]`
- no (no usage/help at all)
- Does the user provide the long usage text? For each option? For the whole command?
- no
- Do subcommands (if implemented) have their own usage output?
- no
- Does usage print if the user runs `cmd --help`?
- no
- Does it set `process.exitCode`?
- no
- Does usage print to stderr or stdout?
- N/A
- Does it check types? (Say, specify that an option is a boolean, number, etc.)
- no
- Can an option have more than one type? (string or false, for example)
- no
- Can the user define a type? (Say, `type: path` to call `path.resolve()` on the argument.)
- no
- Does a `--foo=0o22` mean 0, 22, 18, or "0o22"?
- `"0o22"`
- Does it coerce types?
- no
- Does `--no-foo` coerce to `--foo=false`? For all options? Only boolean options?
- no, it sets `{values:{'no-foo': true}}`
- Is `--foo` the same as `--foo=true`? Only for known booleans? Only at the end?
- no, they are not the same. There is no special handling of `true` as a value so it is just another string.
- Does it read environment variables? Ie, is `FOO=1 cmd` the same as `cmd --foo=1`?
- no
- Do unknown arguments raise an error? Are they parsed? Are they treated as positional arguments?
- no, they are parsed, not treated as positionals
- Does `--` signal the end of options?
- yes
- Is `--` included as a positional?
- no
- Is `program -- foo` the same as `program foo`?
- yes, both store `{positionals:['foo']}`
- Does the API specify whether a `--` was present/relevant?
- no
- Is `-bar` the same as `--bar`?
- no, `-bar` is a short option or options, with expansion logic that follows the
[Utility Syntax Guidelines in POSIX.1-2017](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html). `-bar` expands to `-b`, `-a`, `-r`.
- Is `---foo` the same as `--foo`?
- no
- the first is a long option named `'-foo'`
- the second is a long option named `'foo'`
- Is `-` a positional? ie, `bash some-test.sh | tap -`
- yes
## Links & Resources
* [Initial Tooling Issue](https://github.com/nodejs/tooling/issues/19)
* [Initial Proposal](https://github.com/nodejs/node/pull/35015)
* [parseArgs Proposal](https://github.com/nodejs/node/pull/42675)
[coverage-image]: https://img.shields.io/nycrc/pkgjs/parseargs
[coverage-url]: https://github.com/pkgjs/parseargs/blob/main/.nycrc
[pkgjs/parseargs]: https://github.com/pkgjs/parseargs

View File

@ -0,0 +1,25 @@
'use strict';
// This example shows how to understand if a default value is used or not.
// 1. const { parseArgs } = require('node:util'); // from node
// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package
const { parseArgs } = require('..'); // in repo
const options = {
file: { short: 'f', type: 'string', default: 'FOO' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
const isFileDefault = !tokens.some((token) => token.kind === 'option' &&
token.name === 'file'
);
console.log(values);
console.log(`Is the file option [${values.file}] the default value? ${isFileDefault}`);
// Try the following:
// node is-default-value.js
// node is-default-value.js -f FILE
// node is-default-value.js --file FILE

View File

@ -0,0 +1,35 @@
'use strict';
// This is an example of using tokens to add a custom behaviour.
//
// Require the use of `=` for long options and values by blocking
// the use of space separated values.
// So allow `--foo=bar`, and not allow `--foo bar`.
//
// Note: this is not a common behaviour, most CLIs allow both forms.
// 1. const { parseArgs } = require('node:util'); // from node
// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package
const { parseArgs } = require('..'); // in repo
const options = {
file: { short: 'f', type: 'string' },
log: { type: 'string' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
const badToken = tokens.find((token) => token.kind === 'option' &&
token.value != null &&
token.rawName.startsWith('--') &&
!token.inlineValue
);
if (badToken) {
throw new Error(`Option value for '${badToken.rawName}' must be inline, like '${badToken.rawName}=VALUE'`);
}
console.log(values);
// Try the following:
// node limit-long-syntax.js -f FILE --log=LOG
// node limit-long-syntax.js --file FILE

View File

@ -0,0 +1,43 @@
'use strict';
// This example is used in the documentation.
// How might I add my own support for --no-foo?
// 1. const { parseArgs } = require('node:util'); // from node
// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package
const { parseArgs } = require('..'); // in repo
const options = {
'color': { type: 'boolean' },
'no-color': { type: 'boolean' },
'logfile': { type: 'string' },
'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
// Reprocess the option tokens and overwrite the returned values.
tokens
.filter((token) => token.kind === 'option')
.forEach((token) => {
if (token.name.startsWith('no-')) {
// Store foo:false for --no-foo
const positiveName = token.name.slice(3);
values[positiveName] = false;
delete values[token.name];
} else {
// Resave value so last one wins if both --foo and --no-foo.
values[token.name] = token.value ?? true;
}
});
const color = values.color;
const logfile = values.logfile ?? 'default.log';
console.log({ logfile, color });
// Try the following:
// node negate.js
// node negate.js --no-logfile --no-color
// negate.js --logfile=test.log --color
// node negate.js --no-logfile --logfile=test.log --color --no-color

View File

@ -0,0 +1,31 @@
'use strict';
// This is an example of using tokens to add a custom behaviour.
//
// Throw an error if an option is used more than once.
// 1. const { parseArgs } = require('node:util'); // from node
// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package
const { parseArgs } = require('..'); // in repo
const options = {
ding: { type: 'boolean', short: 'd' },
beep: { type: 'boolean', short: 'b' }
};
const { values, tokens } = parseArgs({ options, tokens: true });
const seenBefore = new Set();
tokens.forEach((token) => {
if (token.kind !== 'option') return;
if (seenBefore.has(token.name)) {
throw new Error(`option '${token.name}' used multiple times`);
}
seenBefore.add(token.name);
});
console.log(values);
// Try the following:
// node no-repeated-options --ding --beep
// node no-repeated-options --beep -b
// node no-repeated-options -ddd

View File

@ -0,0 +1,41 @@
// This is an example of using tokens to add a custom behaviour.
//
// This adds a option order check so that --some-unstable-option
// may only be used after --enable-experimental-options
//
// Note: this is not a common behaviour, the order of different options
// does not usually matter.
import { parseArgs } from '../index.js';
function findTokenIndex(tokens, target) {
return tokens.findIndex((token) => token.kind === 'option' &&
token.name === target
);
}
const experimentalName = 'enable-experimental-options';
const unstableName = 'some-unstable-option';
const options = {
[experimentalName]: { type: 'boolean' },
[unstableName]: { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });
const experimentalIndex = findTokenIndex(tokens, experimentalName);
const unstableIndex = findTokenIndex(tokens, unstableName);
if (unstableIndex !== -1 &&
((experimentalIndex === -1) || (unstableIndex < experimentalIndex))) {
throw new Error(`'--${experimentalName}' must be specified before '--${unstableName}'`);
}
console.log(values);
/* eslint-disable max-len */
// Try the following:
// node ordered-options.mjs
// node ordered-options.mjs --some-unstable-option
// node ordered-options.mjs --some-unstable-option --enable-experimental-options
// node ordered-options.mjs --enable-experimental-options --some-unstable-option

View File

@ -0,0 +1,26 @@
'use strict';
// This example is used in the documentation.
// 1. const { parseArgs } = require('node:util'); // from node
// 2. const { parseArgs } = require('@pkgjs/parseargs'); // from package
const { parseArgs } = require('..'); // in repo
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f'
},
bar: {
type: 'string'
}
};
const {
values,
positionals
} = parseArgs({ args, options });
console.log(values, positionals);
// Try the following:
// node simple-hard-coded.js

396
backend/node_modules/@pkgjs/parseargs/index.js generated vendored Normal file
View File

@ -0,0 +1,396 @@
'use strict';
const {
ArrayPrototypeForEach,
ArrayPrototypeIncludes,
ArrayPrototypeMap,
ArrayPrototypePush,
ArrayPrototypePushApply,
ArrayPrototypeShift,
ArrayPrototypeSlice,
ArrayPrototypeUnshiftApply,
ObjectEntries,
ObjectPrototypeHasOwnProperty: ObjectHasOwn,
StringPrototypeCharAt,
StringPrototypeIndexOf,
StringPrototypeSlice,
StringPrototypeStartsWith,
} = require('./internal/primordials');
const {
validateArray,
validateBoolean,
validateBooleanArray,
validateObject,
validateString,
validateStringArray,
validateUnion,
} = require('./internal/validators');
const {
kEmptyObject,
} = require('./internal/util');
const {
findLongOptionForShort,
isLoneLongOption,
isLoneShortOption,
isLongOptionAndValue,
isOptionValue,
isOptionLikeValue,
isShortOptionAndValue,
isShortOptionGroup,
useDefaultValueOption,
objectGetOwn,
optionsGetOwn,
} = require('./utils');
const {
codes: {
ERR_INVALID_ARG_VALUE,
ERR_PARSE_ARGS_INVALID_OPTION_VALUE,
ERR_PARSE_ARGS_UNKNOWN_OPTION,
ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL,
},
} = require('./internal/errors');
function getMainArgs() {
// Work out where to slice process.argv for user supplied arguments.
// Check node options for scenarios where user CLI args follow executable.
const execArgv = process.execArgv;
if (ArrayPrototypeIncludes(execArgv, '-e') ||
ArrayPrototypeIncludes(execArgv, '--eval') ||
ArrayPrototypeIncludes(execArgv, '-p') ||
ArrayPrototypeIncludes(execArgv, '--print')) {
return ArrayPrototypeSlice(process.argv, 1);
}
// Normally first two arguments are executable and script, then CLI arguments
return ArrayPrototypeSlice(process.argv, 2);
}
/**
* In strict mode, throw for possible usage errors like --foo --bar
*
* @param {object} token - from tokens as available from parseArgs
*/
function checkOptionLikeValue(token) {
if (!token.inlineValue && isOptionLikeValue(token.value)) {
// Only show short example if user used short option.
const example = StringPrototypeStartsWith(token.rawName, '--') ?
`'${token.rawName}=-XYZ'` :
`'--${token.name}=-XYZ' or '${token.rawName}-XYZ'`;
const errorMessage = `Option '${token.rawName}' argument is ambiguous.
Did you forget to specify the option argument for '${token.rawName}'?
To specify an option argument starting with a dash use ${example}.`;
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(errorMessage);
}
}
/**
* In strict mode, throw for usage errors.
*
* @param {object} config - from config passed to parseArgs
* @param {object} token - from tokens as available from parseArgs
*/
function checkOptionUsage(config, token) {
if (!ObjectHasOwn(config.options, token.name)) {
throw new ERR_PARSE_ARGS_UNKNOWN_OPTION(
token.rawName, config.allowPositionals);
}
const short = optionsGetOwn(config.options, token.name, 'short');
const shortAndLong = `${short ? `-${short}, ` : ''}--${token.name}`;
const type = optionsGetOwn(config.options, token.name, 'type');
if (type === 'string' && typeof token.value !== 'string') {
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong} <value>' argument missing`);
}
// (Idiomatic test for undefined||null, expecting undefined.)
if (type === 'boolean' && token.value != null) {
throw new ERR_PARSE_ARGS_INVALID_OPTION_VALUE(`Option '${shortAndLong}' does not take an argument`);
}
}
/**
* Store the option value in `values`.
*
* @param {string} longOption - long option name e.g. 'foo'
* @param {string|undefined} optionValue - value from user args
* @param {object} options - option configs, from parseArgs({ options })
* @param {object} values - option values returned in `values` by parseArgs
*/
function storeOption(longOption, optionValue, options, values) {
if (longOption === '__proto__') {
return; // No. Just no.
}
// We store based on the option value rather than option type,
// preserving the users intent for author to deal with.
const newValue = optionValue ?? true;
if (optionsGetOwn(options, longOption, 'multiple')) {
// Always store value in array, including for boolean.
// values[longOption] starts out not present,
// first value is added as new array [newValue],
// subsequent values are pushed to existing array.
// (note: values has null prototype, so simpler usage)
if (values[longOption]) {
ArrayPrototypePush(values[longOption], newValue);
} else {
values[longOption] = [newValue];
}
} else {
values[longOption] = newValue;
}
}
/**
* Store the default option value in `values`.
*
* @param {string} longOption - long option name e.g. 'foo'
* @param {string
* | boolean
* | string[]
* | boolean[]} optionValue - default value from option config
* @param {object} values - option values returned in `values` by parseArgs
*/
function storeDefaultOption(longOption, optionValue, values) {
if (longOption === '__proto__') {
return; // No. Just no.
}
values[longOption] = optionValue;
}
/**
* Process args and turn into identified tokens:
* - option (along with value, if any)
* - positional
* - option-terminator
*
* @param {string[]} args - from parseArgs({ args }) or mainArgs
* @param {object} options - option configs, from parseArgs({ options })
*/
function argsToTokens(args, options) {
const tokens = [];
let index = -1;
let groupCount = 0;
const remainingArgs = ArrayPrototypeSlice(args);
while (remainingArgs.length > 0) {
const arg = ArrayPrototypeShift(remainingArgs);
const nextArg = remainingArgs[0];
if (groupCount > 0)
groupCount--;
else
index++;
// Check if `arg` is an options terminator.
// Guideline 10 in https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html
if (arg === '--') {
// Everything after a bare '--' is considered a positional argument.
ArrayPrototypePush(tokens, { kind: 'option-terminator', index });
ArrayPrototypePushApply(
tokens, ArrayPrototypeMap(remainingArgs, (arg) => {
return { kind: 'positional', index: ++index, value: arg };
})
);
break; // Finished processing args, leave while loop.
}
if (isLoneShortOption(arg)) {
// e.g. '-f'
const shortOption = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(shortOption, options);
let value;
let inlineValue;
if (optionsGetOwn(options, longOption, 'type') === 'string' &&
isOptionValue(nextArg)) {
// e.g. '-f', 'bar'
value = ArrayPrototypeShift(remainingArgs);
inlineValue = false;
}
ArrayPrototypePush(
tokens,
{ kind: 'option', name: longOption, rawName: arg,
index, value, inlineValue });
if (value != null) ++index;
continue;
}
if (isShortOptionGroup(arg, options)) {
// Expand -fXzy to -f -X -z -y
const expanded = [];
for (let index = 1; index < arg.length; index++) {
const shortOption = StringPrototypeCharAt(arg, index);
const longOption = findLongOptionForShort(shortOption, options);
if (optionsGetOwn(options, longOption, 'type') !== 'string' ||
index === arg.length - 1) {
// Boolean option, or last short in group. Well formed.
ArrayPrototypePush(expanded, `-${shortOption}`);
} else {
// String option in middle. Yuck.
// Expand -abfFILE to -a -b -fFILE
ArrayPrototypePush(expanded, `-${StringPrototypeSlice(arg, index)}`);
break; // finished short group
}
}
ArrayPrototypeUnshiftApply(remainingArgs, expanded);
groupCount = expanded.length;
continue;
}
if (isShortOptionAndValue(arg, options)) {
// e.g. -fFILE
const shortOption = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(shortOption, options);
const value = StringPrototypeSlice(arg, 2);
ArrayPrototypePush(
tokens,
{ kind: 'option', name: longOption, rawName: `-${shortOption}`,
index, value, inlineValue: true });
continue;
}
if (isLoneLongOption(arg)) {
// e.g. '--foo'
const longOption = StringPrototypeSlice(arg, 2);
let value;
let inlineValue;
if (optionsGetOwn(options, longOption, 'type') === 'string' &&
isOptionValue(nextArg)) {
// e.g. '--foo', 'bar'
value = ArrayPrototypeShift(remainingArgs);
inlineValue = false;
}
ArrayPrototypePush(
tokens,
{ kind: 'option', name: longOption, rawName: arg,
index, value, inlineValue });
if (value != null) ++index;
continue;
}
if (isLongOptionAndValue(arg)) {
// e.g. --foo=bar
const equalIndex = StringPrototypeIndexOf(arg, '=');
const longOption = StringPrototypeSlice(arg, 2, equalIndex);
const value = StringPrototypeSlice(arg, equalIndex + 1);
ArrayPrototypePush(
tokens,
{ kind: 'option', name: longOption, rawName: `--${longOption}`,
index, value, inlineValue: true });
continue;
}
ArrayPrototypePush(tokens, { kind: 'positional', index, value: arg });
}
return tokens;
}
const parseArgs = (config = kEmptyObject) => {
const args = objectGetOwn(config, 'args') ?? getMainArgs();
const strict = objectGetOwn(config, 'strict') ?? true;
const allowPositionals = objectGetOwn(config, 'allowPositionals') ?? !strict;
const returnTokens = objectGetOwn(config, 'tokens') ?? false;
const options = objectGetOwn(config, 'options') ?? { __proto__: null };
// Bundle these up for passing to strict-mode checks.
const parseConfig = { args, strict, options, allowPositionals };
// Validate input configuration.
validateArray(args, 'args');
validateBoolean(strict, 'strict');
validateBoolean(allowPositionals, 'allowPositionals');
validateBoolean(returnTokens, 'tokens');
validateObject(options, 'options');
ArrayPrototypeForEach(
ObjectEntries(options),
({ 0: longOption, 1: optionConfig }) => {
validateObject(optionConfig, `options.${longOption}`);
// type is required
const optionType = objectGetOwn(optionConfig, 'type');
validateUnion(optionType, `options.${longOption}.type`, ['string', 'boolean']);
if (ObjectHasOwn(optionConfig, 'short')) {
const shortOption = optionConfig.short;
validateString(shortOption, `options.${longOption}.short`);
if (shortOption.length !== 1) {
throw new ERR_INVALID_ARG_VALUE(
`options.${longOption}.short`,
shortOption,
'must be a single character'
);
}
}
const multipleOption = objectGetOwn(optionConfig, 'multiple');
if (ObjectHasOwn(optionConfig, 'multiple')) {
validateBoolean(multipleOption, `options.${longOption}.multiple`);
}
const defaultValue = objectGetOwn(optionConfig, 'default');
if (defaultValue !== undefined) {
let validator;
switch (optionType) {
case 'string':
validator = multipleOption ? validateStringArray : validateString;
break;
case 'boolean':
validator = multipleOption ? validateBooleanArray : validateBoolean;
break;
}
validator(defaultValue, `options.${longOption}.default`);
}
}
);
// Phase 1: identify tokens
const tokens = argsToTokens(args, options);
// Phase 2: process tokens into parsed option values and positionals
const result = {
values: { __proto__: null },
positionals: [],
};
if (returnTokens) {
result.tokens = tokens;
}
ArrayPrototypeForEach(tokens, (token) => {
if (token.kind === 'option') {
if (strict) {
checkOptionUsage(parseConfig, token);
checkOptionLikeValue(token);
}
storeOption(token.name, token.value, options, result.values);
} else if (token.kind === 'positional') {
if (!allowPositionals) {
throw new ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL(token.value);
}
ArrayPrototypePush(result.positionals, token.value);
}
});
// Phase 3: fill in default values for missing args
ArrayPrototypeForEach(ObjectEntries(options), ({ 0: longOption,
1: optionConfig }) => {
const mustSetDefault = useDefaultValueOption(longOption,
optionConfig,
result.values);
if (mustSetDefault) {
storeDefaultOption(longOption,
objectGetOwn(optionConfig, 'default'),
result.values);
}
});
return result;
};
module.exports = {
parseArgs,
};

View File

@ -0,0 +1,47 @@
'use strict';
class ERR_INVALID_ARG_TYPE extends TypeError {
constructor(name, expected, actual) {
super(`${name} must be ${expected} got ${actual}`);
this.code = 'ERR_INVALID_ARG_TYPE';
}
}
class ERR_INVALID_ARG_VALUE extends TypeError {
constructor(arg1, arg2, expected) {
super(`The property ${arg1} ${expected}. Received '${arg2}'`);
this.code = 'ERR_INVALID_ARG_VALUE';
}
}
class ERR_PARSE_ARGS_INVALID_OPTION_VALUE extends Error {
constructor(message) {
super(message);
this.code = 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE';
}
}
class ERR_PARSE_ARGS_UNKNOWN_OPTION extends Error {
constructor(option, allowPositionals) {
const suggestDashDash = allowPositionals ? `. To specify a positional argument starting with a '-', place it at the end of the command after '--', as in '-- ${JSON.stringify(option)}` : '';
super(`Unknown option '${option}'${suggestDashDash}`);
this.code = 'ERR_PARSE_ARGS_UNKNOWN_OPTION';
}
}
class ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL extends Error {
constructor(positional) {
super(`Unexpected argument '${positional}'. This command does not take positional arguments`);
this.code = 'ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL';
}
}
module.exports = {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_PARSE_ARGS_INVALID_OPTION_VALUE,
ERR_PARSE_ARGS_UNKNOWN_OPTION,
ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL,
}
};

View File

@ -0,0 +1,393 @@
/*
This file is copied from https://github.com/nodejs/node/blob/v14.19.3/lib/internal/per_context/primordials.js
under the following license:
Copyright Node.js contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
'use strict';
/* eslint-disable node-core/prefer-primordials */
// This file subclasses and stores the JS builtins that come from the VM
// so that Node.js's builtin modules do not need to later look these up from
// the global proxy, which can be mutated by users.
// Use of primordials have sometimes a dramatic impact on performance, please
// benchmark all changes made in performance-sensitive areas of the codebase.
// See: https://github.com/nodejs/node/pull/38248
const primordials = {};
const {
defineProperty: ReflectDefineProperty,
getOwnPropertyDescriptor: ReflectGetOwnPropertyDescriptor,
ownKeys: ReflectOwnKeys,
} = Reflect;
// `uncurryThis` is equivalent to `func => Function.prototype.call.bind(func)`.
// It is using `bind.bind(call)` to avoid using `Function.prototype.bind`
// and `Function.prototype.call` after it may have been mutated by users.
const { apply, bind, call } = Function.prototype;
const uncurryThis = bind.bind(call);
primordials.uncurryThis = uncurryThis;
// `applyBind` is equivalent to `func => Function.prototype.apply.bind(func)`.
// It is using `bind.bind(apply)` to avoid using `Function.prototype.bind`
// and `Function.prototype.apply` after it may have been mutated by users.
const applyBind = bind.bind(apply);
primordials.applyBind = applyBind;
// Methods that accept a variable number of arguments, and thus it's useful to
// also create `${prefix}${key}Apply`, which uses `Function.prototype.apply`,
// instead of `Function.prototype.call`, and thus doesn't require iterator
// destructuring.
const varargsMethods = [
// 'ArrayPrototypeConcat' is omitted, because it performs the spread
// on its own for arrays and array-likes with a truthy
// @@isConcatSpreadable symbol property.
'ArrayOf',
'ArrayPrototypePush',
'ArrayPrototypeUnshift',
// 'FunctionPrototypeCall' is omitted, since there's 'ReflectApply'
// and 'FunctionPrototypeApply'.
'MathHypot',
'MathMax',
'MathMin',
'StringPrototypeConcat',
'TypedArrayOf',
];
function getNewKey(key) {
return typeof key === 'symbol' ?
`Symbol${key.description[7].toUpperCase()}${key.description.slice(8)}` :
`${key[0].toUpperCase()}${key.slice(1)}`;
}
function copyAccessor(dest, prefix, key, { enumerable, get, set }) {
ReflectDefineProperty(dest, `${prefix}Get${key}`, {
value: uncurryThis(get),
enumerable
});
if (set !== undefined) {
ReflectDefineProperty(dest, `${prefix}Set${key}`, {
value: uncurryThis(set),
enumerable
});
}
}
function copyPropsRenamed(src, dest, prefix) {
for (const key of ReflectOwnKeys(src)) {
const newKey = getNewKey(key);
const desc = ReflectGetOwnPropertyDescriptor(src, key);
if ('get' in desc) {
copyAccessor(dest, prefix, newKey, desc);
} else {
const name = `${prefix}${newKey}`;
ReflectDefineProperty(dest, name, desc);
if (varargsMethods.includes(name)) {
ReflectDefineProperty(dest, `${name}Apply`, {
// `src` is bound as the `this` so that the static `this` points
// to the object it was defined on,
// e.g.: `ArrayOfApply` gets a `this` of `Array`:
value: applyBind(desc.value, src),
});
}
}
}
}
function copyPropsRenamedBound(src, dest, prefix) {
for (const key of ReflectOwnKeys(src)) {
const newKey = getNewKey(key);
const desc = ReflectGetOwnPropertyDescriptor(src, key);
if ('get' in desc) {
copyAccessor(dest, prefix, newKey, desc);
} else {
const { value } = desc;
if (typeof value === 'function') {
desc.value = value.bind(src);
}
const name = `${prefix}${newKey}`;
ReflectDefineProperty(dest, name, desc);
if (varargsMethods.includes(name)) {
ReflectDefineProperty(dest, `${name}Apply`, {
value: applyBind(value, src),
});
}
}
}
}
function copyPrototype(src, dest, prefix) {
for (const key of ReflectOwnKeys(src)) {
const newKey = getNewKey(key);
const desc = ReflectGetOwnPropertyDescriptor(src, key);
if ('get' in desc) {
copyAccessor(dest, prefix, newKey, desc);
} else {
const { value } = desc;
if (typeof value === 'function') {
desc.value = uncurryThis(value);
}
const name = `${prefix}${newKey}`;
ReflectDefineProperty(dest, name, desc);
if (varargsMethods.includes(name)) {
ReflectDefineProperty(dest, `${name}Apply`, {
value: applyBind(value),
});
}
}
}
}
// Create copies of configurable value properties of the global object
[
'Proxy',
'globalThis',
].forEach((name) => {
// eslint-disable-next-line no-restricted-globals
primordials[name] = globalThis[name];
});
// Create copies of URI handling functions
[
decodeURI,
decodeURIComponent,
encodeURI,
encodeURIComponent,
].forEach((fn) => {
primordials[fn.name] = fn;
});
// Create copies of the namespace objects
[
'JSON',
'Math',
'Proxy',
'Reflect',
].forEach((name) => {
// eslint-disable-next-line no-restricted-globals
copyPropsRenamed(global[name], primordials, name);
});
// Create copies of intrinsic objects
[
'Array',
'ArrayBuffer',
'BigInt',
'BigInt64Array',
'BigUint64Array',
'Boolean',
'DataView',
'Date',
'Error',
'EvalError',
'Float32Array',
'Float64Array',
'Function',
'Int16Array',
'Int32Array',
'Int8Array',
'Map',
'Number',
'Object',
'RangeError',
'ReferenceError',
'RegExp',
'Set',
'String',
'Symbol',
'SyntaxError',
'TypeError',
'URIError',
'Uint16Array',
'Uint32Array',
'Uint8Array',
'Uint8ClampedArray',
'WeakMap',
'WeakSet',
].forEach((name) => {
// eslint-disable-next-line no-restricted-globals
const original = global[name];
primordials[name] = original;
copyPropsRenamed(original, primordials, name);
copyPrototype(original.prototype, primordials, `${name}Prototype`);
});
// Create copies of intrinsic objects that require a valid `this` to call
// static methods.
// Refs: https://www.ecma-international.org/ecma-262/#sec-promise.all
[
'Promise',
].forEach((name) => {
// eslint-disable-next-line no-restricted-globals
const original = global[name];
primordials[name] = original;
copyPropsRenamedBound(original, primordials, name);
copyPrototype(original.prototype, primordials, `${name}Prototype`);
});
// Create copies of abstract intrinsic objects that are not directly exposed
// on the global object.
// Refs: https://tc39.es/ecma262/#sec-%typedarray%-intrinsic-object
[
{ name: 'TypedArray', original: Reflect.getPrototypeOf(Uint8Array) },
{ name: 'ArrayIterator', original: {
prototype: Reflect.getPrototypeOf(Array.prototype[Symbol.iterator]()),
} },
{ name: 'StringIterator', original: {
prototype: Reflect.getPrototypeOf(String.prototype[Symbol.iterator]()),
} },
].forEach(({ name, original }) => {
primordials[name] = original;
// The static %TypedArray% methods require a valid `this`, but can't be bound,
// as they need a subclass constructor as the receiver:
copyPrototype(original, primordials, name);
copyPrototype(original.prototype, primordials, `${name}Prototype`);
});
/* eslint-enable node-core/prefer-primordials */
const {
ArrayPrototypeForEach,
FunctionPrototypeCall,
Map,
ObjectFreeze,
ObjectSetPrototypeOf,
Set,
SymbolIterator,
WeakMap,
WeakSet,
} = primordials;
// Because these functions are used by `makeSafe`, which is exposed
// on the `primordials` object, it's important to use const references
// to the primordials that they use:
const createSafeIterator = (factory, next) => {
class SafeIterator {
constructor(iterable) {
this._iterator = factory(iterable);
}
next() {
return next(this._iterator);
}
[SymbolIterator]() {
return this;
}
}
ObjectSetPrototypeOf(SafeIterator.prototype, null);
ObjectFreeze(SafeIterator.prototype);
ObjectFreeze(SafeIterator);
return SafeIterator;
};
primordials.SafeArrayIterator = createSafeIterator(
primordials.ArrayPrototypeSymbolIterator,
primordials.ArrayIteratorPrototypeNext
);
primordials.SafeStringIterator = createSafeIterator(
primordials.StringPrototypeSymbolIterator,
primordials.StringIteratorPrototypeNext
);
const copyProps = (src, dest) => {
ArrayPrototypeForEach(ReflectOwnKeys(src), (key) => {
if (!ReflectGetOwnPropertyDescriptor(dest, key)) {
ReflectDefineProperty(
dest,
key,
ReflectGetOwnPropertyDescriptor(src, key));
}
});
};
const makeSafe = (unsafe, safe) => {
if (SymbolIterator in unsafe.prototype) {
const dummy = new unsafe();
let next; // We can reuse the same `next` method.
ArrayPrototypeForEach(ReflectOwnKeys(unsafe.prototype), (key) => {
if (!ReflectGetOwnPropertyDescriptor(safe.prototype, key)) {
const desc = ReflectGetOwnPropertyDescriptor(unsafe.prototype, key);
if (
typeof desc.value === 'function' &&
desc.value.length === 0 &&
SymbolIterator in (FunctionPrototypeCall(desc.value, dummy) ?? {})
) {
const createIterator = uncurryThis(desc.value);
next = next ?? uncurryThis(createIterator(dummy).next);
const SafeIterator = createSafeIterator(createIterator, next);
desc.value = function() {
return new SafeIterator(this);
};
}
ReflectDefineProperty(safe.prototype, key, desc);
}
});
} else {
copyProps(unsafe.prototype, safe.prototype);
}
copyProps(unsafe, safe);
ObjectSetPrototypeOf(safe.prototype, null);
ObjectFreeze(safe.prototype);
ObjectFreeze(safe);
return safe;
};
primordials.makeSafe = makeSafe;
// Subclass the constructors because we need to use their prototype
// methods later.
// Defining the `constructor` is necessary here to avoid the default
// constructor which uses the user-mutable `%ArrayIteratorPrototype%.next`.
primordials.SafeMap = makeSafe(
Map,
class SafeMap extends Map {
constructor(i) { super(i); } // eslint-disable-line no-useless-constructor
}
);
primordials.SafeWeakMap = makeSafe(
WeakMap,
class SafeWeakMap extends WeakMap {
constructor(i) { super(i); } // eslint-disable-line no-useless-constructor
}
);
primordials.SafeSet = makeSafe(
Set,
class SafeSet extends Set {
constructor(i) { super(i); } // eslint-disable-line no-useless-constructor
}
);
primordials.SafeWeakSet = makeSafe(
WeakSet,
class SafeWeakSet extends WeakSet {
constructor(i) { super(i); } // eslint-disable-line no-useless-constructor
}
);
ObjectSetPrototypeOf(primordials, null);
ObjectFreeze(primordials);
module.exports = primordials;

14
backend/node_modules/@pkgjs/parseargs/internal/util.js generated vendored Normal file
View File

@ -0,0 +1,14 @@
'use strict';
// This is a placeholder for util.js in node.js land.
const {
ObjectCreate,
ObjectFreeze,
} = require('./primordials');
const kEmptyObject = ObjectFreeze(ObjectCreate(null));
module.exports = {
kEmptyObject,
};

View File

@ -0,0 +1,89 @@
'use strict';
// This file is a proxy of the original file located at:
// https://github.com/nodejs/node/blob/main/lib/internal/validators.js
// Every addition or modification to this file must be evaluated
// during the PR review.
const {
ArrayIsArray,
ArrayPrototypeIncludes,
ArrayPrototypeJoin,
} = require('./primordials');
const {
codes: {
ERR_INVALID_ARG_TYPE
}
} = require('./errors');
function validateString(value, name) {
if (typeof value !== 'string') {
throw new ERR_INVALID_ARG_TYPE(name, 'String', value);
}
}
function validateUnion(value, name, union) {
if (!ArrayPrototypeIncludes(union, value)) {
throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value);
}
}
function validateBoolean(value, name) {
if (typeof value !== 'boolean') {
throw new ERR_INVALID_ARG_TYPE(name, 'Boolean', value);
}
}
function validateArray(value, name) {
if (!ArrayIsArray(value)) {
throw new ERR_INVALID_ARG_TYPE(name, 'Array', value);
}
}
function validateStringArray(value, name) {
validateArray(value, name);
for (let i = 0; i < value.length; i++) {
validateString(value[i], `${name}[${i}]`);
}
}
function validateBooleanArray(value, name) {
validateArray(value, name);
for (let i = 0; i < value.length; i++) {
validateBoolean(value[i], `${name}[${i}]`);
}
}
/**
* @param {unknown} value
* @param {string} name
* @param {{
* allowArray?: boolean,
* allowFunction?: boolean,
* nullable?: boolean
* }} [options]
*/
function validateObject(value, name, options) {
const useDefaultOptions = options == null;
const allowArray = useDefaultOptions ? false : options.allowArray;
const allowFunction = useDefaultOptions ? false : options.allowFunction;
const nullable = useDefaultOptions ? false : options.nullable;
if ((!nullable && value === null) ||
(!allowArray && ArrayIsArray(value)) ||
(typeof value !== 'object' && (
!allowFunction || typeof value !== 'function'
))) {
throw new ERR_INVALID_ARG_TYPE(name, 'Object', value);
}
}
module.exports = {
validateArray,
validateObject,
validateString,
validateStringArray,
validateUnion,
validateBoolean,
validateBooleanArray,
};

36
backend/node_modules/@pkgjs/parseargs/package.json generated vendored Normal file
View File

@ -0,0 +1,36 @@
{
"name": "@pkgjs/parseargs",
"version": "0.11.0",
"description": "Polyfill of future proposal for `util.parseArgs()`",
"engines": {
"node": ">=14"
},
"main": "index.js",
"exports": {
".": "./index.js",
"./package.json": "./package.json"
},
"scripts": {
"coverage": "c8 --check-coverage tape 'test/*.js'",
"test": "c8 tape 'test/*.js'",
"posttest": "eslint .",
"fix": "npm run posttest -- --fix"
},
"repository": {
"type": "git",
"url": "git@github.com:pkgjs/parseargs.git"
},
"keywords": [],
"author": "",
"license": "MIT",
"bugs": {
"url": "https://github.com/pkgjs/parseargs/issues"
},
"homepage": "https://github.com/pkgjs/parseargs#readme",
"devDependencies": {
"c8": "^7.10.0",
"eslint": "^8.2.0",
"eslint-plugin-node-core": "iansu/eslint-plugin-node-core",
"tape": "^5.2.2"
}
}

198
backend/node_modules/@pkgjs/parseargs/utils.js generated vendored Normal file
View File

@ -0,0 +1,198 @@
'use strict';
const {
ArrayPrototypeFind,
ObjectEntries,
ObjectPrototypeHasOwnProperty: ObjectHasOwn,
StringPrototypeCharAt,
StringPrototypeIncludes,
StringPrototypeStartsWith,
} = require('./internal/primordials');
const {
validateObject,
} = require('./internal/validators');
// These are internal utilities to make the parsing logic easier to read, and
// add lots of detail for the curious. They are in a separate file to allow
// unit testing, although that is not essential (this could be rolled into
// main file and just tested implicitly via API).
//
// These routines are for internal use, not for export to client.
/**
* Return the named property, but only if it is an own property.
*/
function objectGetOwn(obj, prop) {
if (ObjectHasOwn(obj, prop))
return obj[prop];
}
/**
* Return the named options property, but only if it is an own property.
*/
function optionsGetOwn(options, longOption, prop) {
if (ObjectHasOwn(options, longOption))
return objectGetOwn(options[longOption], prop);
}
/**
* Determines if the argument may be used as an option value.
* @example
* isOptionValue('V') // returns true
* isOptionValue('-v') // returns true (greedy)
* isOptionValue('--foo') // returns true (greedy)
* isOptionValue(undefined) // returns false
*/
function isOptionValue(value) {
if (value == null) return false;
// Open Group Utility Conventions are that an option-argument
// is the argument after the option, and may start with a dash.
return true; // greedy!
}
/**
* Detect whether there is possible confusion and user may have omitted
* the option argument, like `--port --verbose` when `port` of type:string.
* In strict mode we throw errors if value is option-like.
*/
function isOptionLikeValue(value) {
if (value == null) return false;
return value.length > 1 && StringPrototypeCharAt(value, 0) === '-';
}
/**
* Determines if `arg` is just a short option.
* @example '-f'
*/
function isLoneShortOption(arg) {
return arg.length === 2 &&
StringPrototypeCharAt(arg, 0) === '-' &&
StringPrototypeCharAt(arg, 1) !== '-';
}
/**
* Determines if `arg` is a lone long option.
* @example
* isLoneLongOption('a') // returns false
* isLoneLongOption('-a') // returns false
* isLoneLongOption('--foo') // returns true
* isLoneLongOption('--foo=bar') // returns false
*/
function isLoneLongOption(arg) {
return arg.length > 2 &&
StringPrototypeStartsWith(arg, '--') &&
!StringPrototypeIncludes(arg, '=', 3);
}
/**
* Determines if `arg` is a long option and value in the same argument.
* @example
* isLongOptionAndValue('--foo') // returns false
* isLongOptionAndValue('--foo=bar') // returns true
*/
function isLongOptionAndValue(arg) {
return arg.length > 2 &&
StringPrototypeStartsWith(arg, '--') &&
StringPrototypeIncludes(arg, '=', 3);
}
/**
* Determines if `arg` is a short option group.
*
* See Guideline 5 of the [Open Group Utility Conventions](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html).
* One or more options without option-arguments, followed by at most one
* option that takes an option-argument, should be accepted when grouped
* behind one '-' delimiter.
* @example
* isShortOptionGroup('-a', {}) // returns false
* isShortOptionGroup('-ab', {}) // returns true
* // -fb is an option and a value, not a short option group
* isShortOptionGroup('-fb', {
* options: { f: { type: 'string' } }
* }) // returns false
* isShortOptionGroup('-bf', {
* options: { f: { type: 'string' } }
* }) // returns true
* // -bfb is an edge case, return true and caller sorts it out
* isShortOptionGroup('-bfb', {
* options: { f: { type: 'string' } }
* }) // returns true
*/
function isShortOptionGroup(arg, options) {
if (arg.length <= 2) return false;
if (StringPrototypeCharAt(arg, 0) !== '-') return false;
if (StringPrototypeCharAt(arg, 1) === '-') return false;
const firstShort = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(firstShort, options);
return optionsGetOwn(options, longOption, 'type') !== 'string';
}
/**
* Determine if arg is a short string option followed by its value.
* @example
* isShortOptionAndValue('-a', {}); // returns false
* isShortOptionAndValue('-ab', {}); // returns false
* isShortOptionAndValue('-fFILE', {
* options: { foo: { short: 'f', type: 'string' }}
* }) // returns true
*/
function isShortOptionAndValue(arg, options) {
validateObject(options, 'options');
if (arg.length <= 2) return false;
if (StringPrototypeCharAt(arg, 0) !== '-') return false;
if (StringPrototypeCharAt(arg, 1) === '-') return false;
const shortOption = StringPrototypeCharAt(arg, 1);
const longOption = findLongOptionForShort(shortOption, options);
return optionsGetOwn(options, longOption, 'type') === 'string';
}
/**
* Find the long option associated with a short option. Looks for a configured
* `short` and returns the short option itself if a long option is not found.
* @example
* findLongOptionForShort('a', {}) // returns 'a'
* findLongOptionForShort('b', {
* options: { bar: { short: 'b' } }
* }) // returns 'bar'
*/
function findLongOptionForShort(shortOption, options) {
validateObject(options, 'options');
const longOptionEntry = ArrayPrototypeFind(
ObjectEntries(options),
({ 1: optionConfig }) => objectGetOwn(optionConfig, 'short') === shortOption
);
return longOptionEntry?.[0] ?? shortOption;
}
/**
* Check if the given option includes a default value
* and that option has not been set by the input args.
*
* @param {string} longOption - long option name e.g. 'foo'
* @param {object} optionConfig - the option configuration properties
* @param {object} values - option values returned in `values` by parseArgs
*/
function useDefaultValueOption(longOption, optionConfig, values) {
return objectGetOwn(optionConfig, 'default') !== undefined &&
values[longOption] === undefined;
}
module.exports = {
findLongOptionForShort,
isLoneLongOption,
isLoneShortOption,
isLongOptionAndValue,
isOptionValue,
isOptionLikeValue,
isShortOptionAndValue,
isShortOptionGroup,
useDefaultValueOption,
objectGetOwn,
optionsGetOwn,
};

View File

@ -0,0 +1,3 @@
# `@rollup/rollup-win32-x64-msvc`
This is the **x86_64-pc-windows-msvc** binary for `rollup`

View File

@ -0,0 +1,19 @@
{
"name": "@rollup/rollup-win32-x64-msvc",
"version": "4.41.1",
"os": [
"win32"
],
"cpu": [
"x64"
],
"files": [
"rollup.win32-x64-msvc.node"
],
"description": "Native bindings for Rollup",
"author": "Lukas Taegert-Atkinson",
"homepage": "https://rollupjs.org/",
"license": "MIT",
"repository": "rollup/rollup",
"main": "./rollup.win32-x64-msvc.node"
}

Binary file not shown.

File diff suppressed because one or more lines are too long

View File

@ -1,585 +0,0 @@
{% extends "base.html" %}
{% block title %}{{ page_title }} - Mercedes-Benz MYP{% endblock %}
{% block content %}
<div class="min-h-screen">
<!-- Header mit Breadcrumb -->
<div>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="py-6">
<!-- Breadcrumb -->
<nav class="flex mb-4" aria-label="Breadcrumb">
<ol class="inline-flex items-center space-x-1 md:space-x-3">
{% for item in breadcrumb %}
<li class="inline-flex items-center">
{% if not loop.last %}
<a href="{{ item.url }}" class="inline-flex items-center text-sm font-medium text-gray-700 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400">
{{ item.name }}
</a>
{% if not loop.last %}
<svg class="w-6 h-6 text-gray-400 mx-1" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path>
</svg>
{% endif %}
{% else %}
<span class="ml-1 text-sm font-medium text-gray-500 dark:text-gray-400">{{ item.name }}</span>
{% endif %}
</li>
{% endfor %}
</ol>
</nav>
<!-- Titel und Beschreibung -->
<div class="flex justify-between items-start">
<div>
<h1 class="text-3xl font-bold text-gray-900 dark:text-white flex items-center">
<span class="mr-3">🔌</span>
{{ page_title }}
</h1>
<p class="mt-2 text-lg text-gray-600 dark:text-gray-300">
Übersicht aller Steckdosen-Statusänderungen und Smart Plug Monitoring-Daten
</p>
</div>
<div class="flex space-x-3">
<button id="refreshBtn"
class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium transition-colors duration-200 flex items-center">
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
</svg>
Aktualisieren
</button>
<button id="cleanupBtn"
class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg font-medium transition-colors duration-200 flex items-center">
<svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
</svg>
Alte Logs löschen
</button>
</div>
</div>
</div>
</div>
</div>
<!-- Hauptinhalt -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<!-- Statistik-Karten -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
<div class="flex items-center">
<div class="p-3 rounded-lg bg-blue-100 dark:bg-blue-900">
<svg class="w-6 h-6 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
</svg>
</div>
<div class="ml-4">
<p class="text-sm font-medium text-gray-600 dark:text-gray-400">Gesamt-Logs</p>
<p class="text-2xl font-bold text-gray-900 dark:text-white" id="totalLogs">{{ stats.total_logs or 0 }}</p>
</div>
</div>
</div>
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
<div class="flex items-center">
<div class="p-3 rounded-lg bg-green-100 dark:bg-green-900">
<svg class="w-6 h-6 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
</svg>
</div>
<div class="ml-4">
<p class="text-sm font-medium text-gray-600 dark:text-gray-400">Ø Antwortzeit</p>
<p class="text-2xl font-bold text-gray-900 dark:text-white" id="avgResponseTime">
{% if stats.average_response_time_ms %}
{{ "%.0f"|format(stats.average_response_time_ms) }}ms
{% else %}
--
{% endif %}
</p>
</div>
</div>
</div>
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
<div class="flex items-center">
<div class="p-3 rounded-lg bg-red-100 dark:bg-red-900">
<svg class="w-6 h-6 text-red-600 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
</svg>
</div>
<div class="ml-4">
<p class="text-sm font-medium text-gray-600 dark:text-gray-400">Fehlerrate</p>
<p class="text-2xl font-bold text-gray-900 dark:text-white" id="errorRate">{{ "%.1f"|format(stats.error_rate) }}%</p>
</div>
</div>
</div>
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6">
<div class="flex items-center">
<div class="p-3 rounded-lg bg-purple-100 dark:bg-purple-900">
<svg class="w-6 h-6 text-purple-600 dark:text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 4V2a1 1 0 011-1h8a1 1 0 011 1v2m-9 0h10m-10 0a1 1 0 00-1 1v14a1 1 0 001 1h10a1 1 0 001-1V5a1 1 0 00-1-1"></path>
</svg>
</div>
<div class="ml-4">
<p class="text-sm font-medium text-gray-600 dark:text-gray-400">Aktive Drucker</p>
<p class="text-2xl font-bold text-gray-900 dark:text-white" id="activePrinters">{{ printers|length }}</p>
</div>
</div>
</div>
</div>
<!-- Filter-Sektion -->
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6 mb-8">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Filter</h3>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div>
<label for="printerFilter" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Drucker</label>
<select id="printerFilter" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-blue-500 focus:border-blue-500">
<option value="">Alle Drucker</option>
{% for printer in printers %}
<option value="{{ printer.id }}">{{ printer.name }}</option>
{% endfor %}
</select>
</div>
<div>
<label for="statusFilter" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Status</label>
<select id="statusFilter" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-blue-500 focus:border-blue-500">
<option value="">Alle Status</option>
<option value="connected">🔌 Verbunden</option>
<option value="disconnected">❌ Getrennt</option>
<option value="on">🟢 Eingeschaltet</option>
<option value="off">🔴 Ausgeschaltet</option>
</select>
</div>
<div>
<label for="timeFilter" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Zeitraum</label>
<select id="timeFilter" class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-blue-500 focus:border-blue-500">
<option value="24">Letzte 24 Stunden</option>
<option value="48">Letzte 48 Stunden</option>
<option value="72">Letzte 3 Tage</option>
<option value="168">Letzte 7 Tage</option>
</select>
</div>
<div class="flex items-end">
<button id="applyFilters" class="w-full bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-medium transition-colors duration-200">
Filter anwenden
</button>
</div>
</div>
</div>
<!-- Status-Verteilung -->
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 p-6 mb-8">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Status-Verteilung (24h)</h3>
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
{% for status, count in stats.status_distribution.items() %}
<div class="text-center p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
<div class="text-2xl mb-2">
{% if status == 'connected' %}🔌
{% elif status == 'disconnected' %}❌
{% elif status == 'on' %}🟢
{% elif status == 'off' %}🔴
{% else %}❓{% endif %}
</div>
<div class="text-2xl font-bold text-gray-900 dark:text-white">{{ count }}</div>
<div class="text-sm text-gray-600 dark:text-gray-400 capitalize">{{ status }}</div>
</div>
{% endfor %}
</div>
</div>
<!-- Logs-Tabelle -->
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700">
<div class="p-6 border-b border-gray-200 dark:border-gray-700">
<div class="flex justify-between items-center">
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">Steckdosen-Logs</h3>
<div class="flex items-center space-x-2">
<span class="text-sm text-gray-600 dark:text-gray-400" id="logCount">Lade Daten...</span>
<button id="exportBtn" class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 font-medium text-sm">
Export
</button>
</div>
</div>
</div>
<!-- Loading-Indikator -->
<div id="loadingIndicator" class="p-8 text-center">
<div class="inline-flex items-center px-4 py-2 text-sm font-medium text-gray-600 dark:text-gray-400">
<svg class="w-4 h-4 mr-3 animate-spin" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
Lade Steckdosen-Logs...
</div>
</div>
<!-- Tabelle -->
<div id="logsTable" class="hidden">
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead class="bg-gray-50 dark:bg-gray-700">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Status</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Drucker</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Zeitstempel</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Quelle</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Details</th>
</tr>
</thead>
<tbody id="logsTableBody" class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
<!-- Wird dynamisch gefüllt -->
</tbody>
</table>
</div>
<!-- Paginierung -->
<div id="pagination" class="bg-white dark:bg-gray-800 px-4 py-3 flex items-center justify-between border-t border-gray-200 dark:border-gray-700 sm:px-6">
<!-- Wird dynamisch gefüllt -->
</div>
</div>
<!-- Keine Daten -->
<div id="noData" class="hidden p-8 text-center">
<div class="text-gray-500 dark:text-gray-400">
<svg class="w-12 h-12 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
</svg>
<p class="text-lg font-medium">Keine Logs gefunden</p>
<p class="text-sm">Für die ausgewählten Filter wurden keine Steckdosen-Logs gefunden.</p>
</div>
</div>
</div>
</div>
</div>
<!-- Cleanup-Modal -->
<div id="cleanupModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden z-50">
<div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<div class="inline-block align-bottom bg-white dark:bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
<div class="bg-white dark:bg-gray-800 px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div class="sm:flex sm:items-start">
<div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 dark:bg-red-900 sm:mx-0 sm:h-10 sm:w-10">
<svg class="h-6 w-6 text-red-600 dark:text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
</svg>
</div>
<div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
<h3 class="text-lg leading-6 font-medium text-gray-900 dark:text-white">Alte Logs löschen</h3>
<div class="mt-2">
<p class="text-sm text-gray-500 dark:text-gray-400">
Wie viele Tage alte Logs sollen gelöscht werden?
</p>
<div class="mt-4">
<label for="cleanupDays" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Tage</label>
<input type="number" id="cleanupDays" value="30" min="1" max="365"
class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-blue-500 focus:border-blue-500">
</div>
</div>
</div>
</div>
</div>
<div class="bg-gray-50 dark:bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<button type="button" id="confirmCleanup"
class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
Löschen
</button>
<button type="button" id="cancelCleanup"
class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-4 py-2 bg-white dark:bg-gray-800 text-base font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
Abbrechen
</button>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Globale Variablen
let currentPage = 1;
let currentFilters = {
printer_id: '',
status: '',
hours: 24
};
// DOM-Elemente
const loadingIndicator = document.getElementById('loadingIndicator');
const logsTable = document.getElementById('logsTable');
const noData = document.getElementById('noData');
const logsTableBody = document.getElementById('logsTableBody');
const pagination = document.getElementById('pagination');
const logCount = document.getElementById('logCount');
const refreshBtn = document.getElementById('refreshBtn');
const cleanupBtn = document.getElementById('cleanupBtn');
const applyFiltersBtn = document.getElementById('applyFilters');
const printerFilter = document.getElementById('printerFilter');
const statusFilter = document.getElementById('statusFilter');
const timeFilter = document.getElementById('timeFilter');
const cleanupModal = document.getElementById('cleanupModal');
const confirmCleanup = document.getElementById('confirmCleanup');
const cancelCleanup = document.getElementById('cancelCleanup');
const cleanupDays = document.getElementById('cleanupDays');
// Event-Listener
refreshBtn.addEventListener('click', loadLogs);
cleanupBtn.addEventListener('click', showCleanupModal);
applyFiltersBtn.addEventListener('click', applyFilters);
confirmCleanup.addEventListener('click', performCleanup);
cancelCleanup.addEventListener('click', hideCleanupModal);
// Initial laden
loadLogs();
function showLoading() {
loadingIndicator.classList.remove('hidden');
logsTable.classList.add('hidden');
noData.classList.add('hidden');
}
function hideLoading() {
loadingIndicator.classList.add('hidden');
}
function showTable() {
logsTable.classList.remove('hidden');
noData.classList.add('hidden');
}
function showNoData() {
noData.classList.remove('hidden');
logsTable.classList.add('hidden');
}
function applyFilters() {
currentFilters = {
printer_id: printerFilter.value,
status: statusFilter.value,
hours: parseInt(timeFilter.value)
};
currentPage = 1;
loadLogs();
}
function loadLogs() {
showLoading();
const params = new URLSearchParams({
page: currentPage,
per_page: 50,
...currentFilters
});
fetch(`/api/admin/plug-monitoring/logs?${params}`)
.then(response => response.json())
.then(data => {
hideLoading();
if (data.success && data.logs.length > 0) {
renderLogs(data.logs);
renderPagination(data.pagination);
updateLogCount(data.pagination.total);
showTable();
} else {
showNoData();
logCount.textContent = 'Keine Logs gefunden';
}
})
.catch(error => {
hideLoading();
console.error('Fehler beim Laden der Logs:', error);
showToast('Fehler beim Laden der Logs', 'error');
showNoData();
});
}
function renderLogs(logs) {
logsTableBody.innerHTML = '';
logs.forEach(log => {
const row = document.createElement('tr');
row.className = 'hover:bg-gray-50 dark:hover:bg-gray-700';
row.innerHTML = `
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<span class="text-lg mr-2">${log.status_icon}</span>
<span class="text-sm font-medium ${log.status_color} capitalize">${log.status}</span>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="text-sm font-medium text-gray-900 dark:text-white">${log.printer_name || 'Unbekannt'}</div>
<div class="text-sm text-gray-500 dark:text-gray-400">${log.ip_address || '--'}</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="text-sm text-gray-900 dark:text-white">${formatTimestamp(log.timestamp)}</div>
<div class="text-sm text-gray-500 dark:text-gray-400">${log.timestamp_relative}</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getSourceColor(log.source)}">
${log.source}
</span>
</td>
<td class="px-6 py-4">
<div class="text-sm text-gray-900 dark:text-white">
${log.response_time_ms ? `⏱️ ${log.response_time_ms}ms` : ''}
${log.power_consumption ? `⚡ ${log.power_consumption}W` : ''}
${log.error_message ? `❌ ${log.error_message}` : ''}
</div>
${log.notes ? `<div class="text-sm text-gray-500 dark:text-gray-400 mt-1">${log.notes}</div>` : ''}
</td>
`;
logsTableBody.appendChild(row);
});
}
function renderPagination(paginationData) {
if (paginationData.total_pages <= 1) {
pagination.innerHTML = '';
return;
}
const pages = [];
const startPage = Math.max(1, paginationData.page - 2);
const endPage = Math.min(paginationData.total_pages, paginationData.page + 2);
for (let i = startPage; i <= endPage; i++) {
pages.push(i);
}
pagination.innerHTML = `
<div class="flex-1 flex justify-between sm:hidden">
<button ${!paginationData.has_prev ? 'disabled' : ''}
onclick="changePage(${paginationData.page - 1})"
class="relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 text-sm font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 ${!paginationData.has_prev ? 'opacity-50 cursor-not-allowed' : ''}">
Zurück
</button>
<button ${!paginationData.has_next ? 'disabled' : ''}
onclick="changePage(${paginationData.page + 1})"
class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 text-sm font-medium rounded-md text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 ${!paginationData.has_next ? 'opacity-50 cursor-not-allowed' : ''}">
Weiter
</button>
</div>
<div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
<div>
<p class="text-sm text-gray-700 dark:text-gray-300">
Zeige <span class="font-medium">${(paginationData.page - 1) * paginationData.per_page + 1}</span> bis
<span class="font-medium">${Math.min(paginationData.page * paginationData.per_page, paginationData.total)}</span> von
<span class="font-medium">${paginationData.total}</span> Einträgen
</p>
</div>
<div>
<nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px">
<button ${!paginationData.has_prev ? 'disabled' : ''}
onclick="changePage(${paginationData.page - 1})"
class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 ${!paginationData.has_prev ? 'opacity-50 cursor-not-allowed' : ''}">
<svg class="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M12.707 5.293a1 1 0 010 1.414L9.414 10l3.293 3.293a1 1 0 01-1.414 1.414l-4-4a1 1 0 010-1.414l4-4a1 1 0 011.414 0z" clip-rule="evenodd"></path>
</svg>
</button>
${pages.map(page => `
<button onclick="changePage(${page})"
class="relative inline-flex items-center px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium ${page === paginationData.page
? 'text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900'
: 'text-gray-700 dark:text-gray-300'} hover:bg-gray-50 dark:hover:bg-gray-700">
${page}
</button>
`).join('')}
<button ${!paginationData.has_next ? 'disabled' : ''}
onclick="changePage(${paginationData.page + 1})"
class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-sm font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 ${!paginationData.has_next ? 'opacity-50 cursor-not-allowed' : ''}">
<svg class="h-5 w-5" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path>
</svg>
</button>
</nav>
</div>
</div>
`;
}
function updateLogCount(total) {
logCount.textContent = `${total} Logs gefunden`;
}
function formatTimestamp(timestamp) {
if (!timestamp) return '--';
const date = new Date(timestamp);
return date.toLocaleString('de-DE');
}
function getSourceColor(source) {
const colors = {
'system': 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200',
'manual': 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
'api': 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200',
'scheduler': 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200'
};
return colors[source] || 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
}
function showCleanupModal() {
cleanupModal.classList.remove('hidden');
}
function hideCleanupModal() {
cleanupModal.classList.add('hidden');
}
function performCleanup() {
const days = parseInt(cleanupDays.value);
if (days < 1 || days > 365) {
showToast('Ungültiger Wert für Tage (1-365)', 'error');
return;
}
fetch('/api/admin/plug-monitoring/cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token() }}'
},
body: JSON.stringify({ days: days })
})
.then(response => response.json())
.then(data => {
hideCleanupModal();
if (data.success) {
showToast(`${data.deleted_count} alte Logs wurden gelöscht`, 'success');
loadLogs(); // Tabelle aktualisieren
} else {
showToast('Fehler beim Löschen der Logs: ' + data.error, 'error');
}
})
.catch(error => {
hideCleanupModal();
console.error('Fehler beim Löschen der Logs:', error);
showToast('Fehler beim Löschen der Logs', 'error');
});
}
// Globale Funktionen für Pagination
window.changePage = function(page) {
currentPage = page;
loadLogs();
};
// Hilfsfunktion für Toast-Nachrichten
function showToast(message, type = 'info') {
if (typeof window.showToast === 'function') {
window.showToast(message, type);
} else {
alert(message);
}
}
});
</script>
{% endblock %}

View File

@ -0,0 +1,779 @@
{% extends "base.html" %}
{% block title %}Steckdosenschaltzeiten - Admin{% endblock %}
{% block head %}
<!-- FullCalendar CSS -->
<link href='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/main.min.css' rel='stylesheet' />
<link href='https://cdn.jsdelivr.net/npm/@fullcalendar/daygrid@6.1.10/main.min.css' rel='stylesheet' />
<link href='https://cdn.jsdelivr.net/npm/@fullcalendar/timegrid@6.1.10/main.min.css' rel='stylesheet' />
<!-- Chart.js für Statistiken -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
.calendar-container {
@apply bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 p-6 mb-6 transition-all duration-300;
}
.fc-event {
font-size: 11px;
border-radius: 6px;
padding: 2px 6px;
border: none !important;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.fc-event-title {
font-weight: 500;
}
/* FullCalendar Dark Mode */
.dark .fc-theme-standard td,
.dark .fc-theme-standard th {
border-color: #374151;
}
.dark .fc-theme-standard .fc-scrollgrid {
border-color: #374151;
}
.dark .fc-col-header-cell {
background: #1f2937;
color: #e5e7eb;
}
.dark .fc-daygrid-day {
background: #1f2937;
color: #e5e7eb;
}
.dark .fc-day-today {
background-color: #065f46 !important;
}
.dark .fc-button-primary {
background: #3b82f6;
border-color: #3b82f6;
}
.dark .fc-button-primary:hover {
background: #2563eb;
border-color: #2563eb;
}
.dark .fc-toolbar-title {
color: #e5e7eb;
}
.stats-card {
@apply bg-gradient-to-br from-blue-500 via-blue-600 to-indigo-700 dark:from-blue-600 dark:via-blue-700 dark:to-indigo-800 rounded-xl p-6 text-white shadow-lg border border-blue-200 dark:border-blue-800 transition-all duration-300 hover:shadow-xl hover:scale-105;
}
.stats-card-success {
@apply bg-gradient-to-br from-emerald-500 via-emerald-600 to-green-700 dark:from-emerald-600 dark:via-emerald-700 dark:to-green-800;
}
.stats-card-warning {
@apply bg-gradient-to-br from-amber-500 via-orange-500 to-orange-600 dark:from-amber-600 dark:via-orange-600 dark:to-orange-700;
}
.stats-card-danger {
@apply bg-gradient-to-br from-red-500 via-red-600 to-rose-700 dark:from-red-600 dark:via-red-700 dark:to-rose-800;
}
.control-panel {
@apply bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 p-6 mb-6 transition-all duration-300;
}
.filter-group {
@apply flex gap-4 items-center flex-wrap;
}
.btn-calendar {
@apply bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-600 text-white border-none px-4 py-2 rounded-lg cursor-pointer transition-all duration-200 font-medium shadow-md hover:shadow-lg;
}
.btn-calendar.active {
@apply bg-blue-800 dark:bg-blue-500 shadow-lg scale-105;
}
.btn-danger {
@apply bg-red-600 hover:bg-red-700 dark:bg-red-700 dark:hover:bg-red-600 text-white px-4 py-2 rounded-lg transition-all duration-200 font-medium shadow-md hover:shadow-lg;
}
.btn-primary {
@apply bg-blue-600 hover:bg-blue-700 dark:bg-blue-700 dark:hover:bg-blue-600 text-white px-4 py-2 rounded-lg transition-all duration-200 font-medium shadow-md hover:shadow-lg;
}
.legend {
@apply flex gap-6 flex-wrap mt-4 pt-4 border-t border-gray-200 dark:border-gray-600;
}
.legend-item {
@apply flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300;
}
.legend-color {
@apply w-4 h-4 rounded;
}
.select-custom {
@apply border border-gray-300 dark:border-gray-600 rounded-lg px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200;
}
.page-header {
@apply bg-gradient-to-r from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-gray-800 dark:to-gray-900 border-b border-gray-200 dark:border-gray-700;
}
.modal-overlay {
@apply fixed inset-0 bg-black bg-opacity-50 dark:bg-opacity-70 z-50 transition-opacity duration-300;
}
.modal-content {
@apply bg-white dark:bg-gray-800 rounded-xl max-w-2xl w-full p-6 shadow-2xl border border-gray-200 dark:border-gray-700 transition-all duration-300;
}
.modal-header {
@apply flex justify-between items-center mb-6 pb-4 border-b border-gray-200 dark:border-gray-600;
}
.modal-title {
@apply text-xl font-semibold text-gray-900 dark:text-gray-100;
}
.close-button {
@apply text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition-colors duration-200 text-xl;
}
.detail-grid {
@apply grid grid-cols-1 md:grid-cols-2 gap-4 text-sm;
}
.detail-item {
@apply space-y-1;
}
.detail-label {
@apply font-medium text-gray-600 dark:text-gray-400;
}
.detail-value {
@apply text-gray-900 dark:text-gray-100 bg-gray-50 dark:bg-gray-700 px-3 py-2 rounded-lg;
}
.error-message {
@apply bg-red-50 dark:bg-red-900/20 text-red-700 dark:text-red-400 p-3 rounded-lg border border-red-200 dark:border-red-800;
}
.notes-section {
@apply bg-blue-50 dark:bg-blue-900/20 text-blue-800 dark:text-blue-300 p-3 rounded-lg border border-blue-200 dark:border-blue-800;
}
</style>
{% endblock %}
{% block content %}
<div class="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors duration-300">
<!-- Header mit Breadcrumb -->
<div class="page-header">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="py-8">
<nav class="text-sm font-medium text-gray-600 dark:text-gray-400 mb-6">
<ol class="list-none p-0 inline-flex">
<li class="flex items-center">
<a href="{{ url_for('admin_page') }}" class="hover:text-blue-600 dark:hover:text-blue-400 transition-colors duration-200">
<i class="fas fa-tachometer-alt mr-2"></i>
Admin-Dashboard
</a>
<svg class="fill-current w-4 h-4 mx-3 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512">
<path d="M285.476 272.971c4.686 4.686 4.686 12.284 0 16.97l-133.952 133.954c-4.686 4.686-12.284 4.686-16.97 0l-133.952-133.954c-4.686-4.686-4.686-12.284 0-16.97 4.686-4.686 12.284-4.686 16.97 0l125.462 125.463 125.462-125.463c4.686-4.686 12.284-4.686 16.97 0z"/>
</svg>
</li>
<li class="text-gray-900 dark:text-gray-100 font-semibold">
<i class="fas fa-plug mr-2"></i>
Steckdosenschaltzeiten
</li>
</ol>
</nav>
<div class="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4">
<div>
<h1 class="text-4xl font-bold text-gray-900 dark:text-gray-100 mb-2">
<i class="fas fa-plug text-blue-600 dark:text-blue-400 mr-4"></i>
Steckdosenschaltzeiten
</h1>
<p class="text-lg text-gray-600 dark:text-gray-400">
Kalenderübersicht aller Drucker-Steckdosenschaltungen mit detaillierter Analyse
</p>
</div>
<div class="flex gap-3">
<button id="refreshData" class="btn-primary">
<i class="fas fa-sync-alt mr-2"></i>
Aktualisieren
</button>
<button id="cleanupLogs" class="btn-danger">
<i class="fas fa-trash mr-2"></i>
Alte Logs löschen
</button>
</div>
</div>
</div>
</div>
</div>
<!-- Haupt-Container -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<!-- Statistik-Karten -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
<div class="stats-card">
<div class="flex items-center justify-between">
<div>
<p class="text-sm opacity-90 mb-1">Schaltungen (24h)</p>
<p class="text-3xl font-bold" id="totalLogs">{{ stats.total_logs or 0 }}</p>
<p class="text-xs opacity-80 mt-1">Gesamt-Events</p>
</div>
<div class="p-3 bg-white/20 rounded-xl">
<i class="fas fa-chart-line text-2xl"></i>
</div>
</div>
</div>
<div class="stats-card stats-card-success">
<div class="flex items-center justify-between">
<div>
<p class="text-sm opacity-90 mb-1">Erfolgsrate</p>
<p class="text-3xl font-bold" id="successRate">{{ "%.1f"|format(100 - stats.error_rate) }}%</p>
<p class="text-xs opacity-80 mt-1">Erfolgreiche Schaltungen</p>
</div>
<div class="p-3 bg-white/20 rounded-xl">
<i class="fas fa-check-circle text-2xl"></i>
</div>
</div>
</div>
<div class="stats-card stats-card-warning">
<div class="flex items-center justify-between">
<div>
<p class="text-sm opacity-90 mb-1">Ø Antwortzeit</p>
<p class="text-3xl font-bold" id="avgResponseTime">
{% if stats.average_response_time_ms %}
{{ "%.0f"|format(stats.average_response_time_ms) }}ms
{% else %}
N/A
{% endif %}
</p>
<p class="text-xs opacity-80 mt-1">Durchschnittlich</p>
</div>
<div class="p-3 bg-white/20 rounded-xl">
<i class="fas fa-stopwatch text-2xl"></i>
</div>
</div>
</div>
<div class="stats-card stats-card-danger">
<div class="flex items-center justify-between">
<div>
<p class="text-sm opacity-90 mb-1">Fehlerzahl</p>
<p class="text-3xl font-bold" id="errorCount">{{ stats.error_count or 0 }}</p>
<p class="text-xs opacity-80 mt-1">Gescheiterte Versuche</p>
</div>
<div class="p-3 bg-white/20 rounded-xl">
<i class="fas fa-exclamation-triangle text-2xl"></i>
</div>
</div>
</div>
</div>
<!-- Filter und Steuerung -->
<div class="control-panel">
<div class="filter-group">
<div class="flex items-center gap-3">
<label for="printerFilter" class="font-medium text-gray-700 dark:text-gray-300">
<i class="fas fa-filter mr-2"></i>
Drucker filtern:
</label>
<select id="printerFilter" class="select-custom">
<option value="">Alle Drucker anzeigen</option>
{% for printer in printers %}
<option value="{{ printer.id }}">{{ printer.name }}</option>
{% endfor %}
</select>
</div>
<div class="flex items-center gap-3 border-l border-gray-300 dark:border-gray-600 pl-6 ml-6">
<label class="font-medium text-gray-700 dark:text-gray-300">
<i class="fas fa-eye mr-2"></i>
Ansicht:
</label>
<div class="flex gap-2">
<button id="monthView" class="btn-calendar active">
<i class="fas fa-calendar-alt mr-1"></i>
Monat
</button>
<button id="weekView" class="btn-calendar">
<i class="fas fa-calendar-week mr-1"></i>
Woche
</button>
<button id="dayView" class="btn-calendar">
<i class="fas fa-calendar-day mr-1"></i>
Tag
</button>
</div>
</div>
</div>
<!-- Legende -->
<div class="legend">
<h4 class="font-medium text-gray-700 dark:text-gray-300 w-full mb-2">
<i class="fas fa-info-circle mr-2"></i>
Status-Legende:
</h4>
<div class="legend-item">
<div class="legend-color bg-green-500"></div>
<span><i class="fas fa-toggle-on mr-1"></i>Steckdose EIN</span>
</div>
<div class="legend-item">
<div class="legend-color bg-orange-500"></div>
<span><i class="fas fa-toggle-off mr-1"></i>Steckdose AUS</span>
</div>
<div class="legend-item">
<div class="legend-color bg-blue-500"></div>
<span><i class="fas fa-plug mr-1"></i>Verbunden</span>
</div>
<div class="legend-item">
<div class="legend-color bg-red-500"></div>
<span><i class="fas fa-unlink mr-1"></i>Getrennt</span>
</div>
</div>
</div>
<!-- Kalender-Container -->
<div class="calendar-container">
<div id="calendar"></div>
</div>
<!-- Detailansicht Modal -->
<div id="eventDetailModal" class="modal-overlay hidden">
<div class="flex items-center justify-center min-h-screen p-4">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">
<i class="fas fa-info-circle mr-2 text-blue-600 dark:text-blue-400"></i>
Schaltung Details
</h3>
<button id="closeModal" class="close-button">
<i class="fas fa-times"></i>
</button>
</div>
<div id="modalContent">
<!-- Wird dynamisch gefüllt -->
</div>
<div class="mt-6 flex justify-end gap-3">
<button id="closeModalBtn" class="px-6 py-2 bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg hover:bg-gray-400 dark:hover:bg-gray-500 transition-all duration-200 font-medium">
<i class="fas fa-times mr-2"></i>
Schließen
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- FullCalendar JS -->
<script src='https://cdn.jsdelivr.net/npm/fullcalendar@6.1.10/index.global.min.js'></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
let calendar;
let currentPrinterFilter = '';
// Kalender initialisieren
function initCalendar() {
const calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
locale: 'de',
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay'
},
height: 'auto',
events: function(info, successCallback, failureCallback) {
loadCalendarEvents(info.start, info.end, currentPrinterFilter, successCallback, failureCallback);
},
eventClick: function(info) {
showEventDetails(info.event);
},
eventDidMount: function(info) {
// Tooltip hinzufügen
info.el.title = info.event.title + '\nKlicken für Details';
// Hover-Effekt
info.el.addEventListener('mouseenter', function() {
this.style.transform = 'scale(1.05)';
this.style.zIndex = '10';
});
info.el.addEventListener('mouseleave', function() {
this.style.transform = 'scale(1)';
this.style.zIndex = '1';
});
}
});
calendar.render();
}
// Events vom Server laden
function loadCalendarEvents(start, end, printerFilter, successCallback, failureCallback) {
const params = new URLSearchParams({
start: start.toISOString(),
end: end.toISOString()
});
if (printerFilter) {
params.append('printer_id', printerFilter);
}
fetch(`/api/admin/plug-schedules/calendar?${params}`)
.then(response => response.json())
.then(data => {
successCallback(data);
})
.catch(error => {
console.error('Fehler beim Laden der Kalender-Daten:', error);
failureCallback(error);
});
}
// Event-Details anzeigen
function showEventDetails(event) {
const props = event.extendedProps;
const modal = document.getElementById('eventDetailModal');
const content = document.getElementById('modalContent');
const startTime = new Date(event.start).toLocaleString('de-DE', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
let detailsHtml = `
<div class="space-y-6">
<div class="flex items-center p-4 bg-gray-50 dark:bg-gray-700 rounded-xl">
<span class="w-6 h-6 rounded-lg mr-4 shadow-md" style="background-color: ${event.backgroundColor}"></span>
<div>
<h4 class="font-semibold text-lg text-gray-900 dark:text-gray-100">${event.title}</h4>
<p class="text-sm text-gray-600 dark:text-gray-400">${startTime}</p>
</div>
</div>
<div class="detail-grid">
<div class="detail-item">
<div class="detail-label">
<i class="fas fa-printer mr-1"></i>
Drucker:
</div>
<div class="detail-value">${props.printer_name}</div>
</div>
<div class="detail-item">
<div class="detail-label">
<i class="fas fa-info-circle mr-1"></i>
Status:
</div>
<div class="detail-value capitalize">${props.status}</div>
</div>
<div class="detail-item">
<div class="detail-label">
<i class="fas fa-source mr-1"></i>
Quelle:
</div>
<div class="detail-value capitalize">${props.source}</div>
</div>
`;
if (props.user_name) {
detailsHtml += `
<div class="detail-item">
<div class="detail-label">
<i class="fas fa-user mr-1"></i>
Benutzer:
</div>
<div class="detail-value">${props.user_name}</div>
</div>
`;
}
if (props.response_time_ms) {
detailsHtml += `
<div class="detail-item">
<div class="detail-label">
<i class="fas fa-clock mr-1"></i>
Antwortzeit:
</div>
<div class="detail-value">${props.response_time_ms}ms</div>
</div>
`;
}
if (props.power_consumption) {
detailsHtml += `
<div class="detail-item">
<div class="detail-label">
<i class="fas fa-bolt mr-1"></i>
Verbrauch:
</div>
<div class="detail-value">${props.power_consumption}W</div>
</div>
`;
}
if (props.voltage) {
detailsHtml += `
<div class="detail-item">
<div class="detail-label">
<i class="fas fa-tachometer-alt mr-1"></i>
Spannung:
</div>
<div class="detail-value">${props.voltage}V</div>
</div>
`;
}
if (props.current) {
detailsHtml += `
<div class="detail-item">
<div class="detail-label">
<i class="fas fa-wave-square mr-1"></i>
Strom:
</div>
<div class="detail-value">${props.current}A</div>
</div>
`;
}
detailsHtml += `</div></div>`;
if (props.notes) {
detailsHtml += `
<div class="mt-6">
<div class="notes-section">
<div class="flex items-start gap-2">
<i class="fas fa-sticky-note mt-0.5"></i>
<div>
<span class="font-medium">Notizen:</span>
<p class="mt-1">${props.notes}</p>
</div>
</div>
</div>
</div>
`;
}
if (props.error_message) {
detailsHtml += `
<div class="mt-6">
<div class="error-message">
<div class="flex items-start gap-2">
<i class="fas fa-exclamation-triangle mt-0.5"></i>
<div>
<span class="font-medium">Fehlermeldung:</span>
<p class="mt-1">${props.error_message}</p>
</div>
</div>
</div>
</div>
`;
}
content.innerHTML = detailsHtml;
modal.classList.remove('hidden');
// Animation
setTimeout(() => {
modal.style.opacity = '1';
modal.querySelector('.modal-content').style.transform = 'scale(1)';
}, 10);
}
// Modal schließen
function closeModal() {
const modal = document.getElementById('eventDetailModal');
modal.style.opacity = '0';
modal.querySelector('.modal-content').style.transform = 'scale(0.95)';
setTimeout(() => {
modal.classList.add('hidden');
}, 300);
}
// Event-Listener
document.getElementById('closeModal').addEventListener('click', closeModal);
document.getElementById('closeModalBtn').addEventListener('click', closeModal);
// Modal schließen bei Klick außerhalb
document.getElementById('eventDetailModal').addEventListener('click', function(e) {
if (e.target === this) {
closeModal();
}
});
// Drucker-Filter
document.getElementById('printerFilter').addEventListener('change', function() {
currentPrinterFilter = this.value;
calendar.refetchEvents();
// Visual Feedback
this.style.transform = 'scale(1.02)';
setTimeout(() => {
this.style.transform = 'scale(1)';
}, 150);
});
// Ansicht-Buttons
document.getElementById('monthView').addEventListener('click', function() {
calendar.changeView('dayGridMonth');
updateActiveViewButton(this);
});
document.getElementById('weekView').addEventListener('click', function() {
calendar.changeView('timeGridWeek');
updateActiveViewButton(this);
});
document.getElementById('dayView').addEventListener('click', function() {
calendar.changeView('timeGridDay');
updateActiveViewButton(this);
});
function updateActiveViewButton(activeBtn) {
document.querySelectorAll('.btn-calendar').forEach(btn => {
btn.classList.remove('active');
});
activeBtn.classList.add('active');
}
// Aktualisieren-Button
document.getElementById('refreshData').addEventListener('click', function() {
// Loading-Animation
const originalContent = this.innerHTML;
this.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Lädt...';
this.disabled = true;
calendar.refetchEvents();
loadStatistics();
// Reset nach 2 Sekunden
setTimeout(() => {
this.innerHTML = originalContent;
this.disabled = false;
}, 2000);
});
// Cleanup-Button
document.getElementById('cleanupLogs').addEventListener('click', function() {
if (confirm('Möchten Sie wirklich alte Logs löschen? (älter als 30 Tage)\n\nDieser Vorgang kann nicht rückgängig gemacht werden.')) {
// Loading-Animation
const originalContent = this.innerHTML;
this.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Lösche...';
this.disabled = true;
fetch('/api/admin/plug-schedules/cleanup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token() }}'
},
body: JSON.stringify({ days: 30 })
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert(`✅ Erfolgreich ${data.deleted_count} alte Einträge gelöscht`);
calendar.refetchEvents();
loadStatistics();
} else {
alert('❌ Fehler beim Löschen: ' + data.error);
}
})
.catch(error => {
console.error('Fehler:', error);
alert('❌ Fehler beim Löschen der Logs');
})
.finally(() => {
this.innerHTML = originalContent;
this.disabled = false;
});
}
});
// Statistiken laden
function loadStatistics() {
fetch('/api/admin/plug-schedules/statistics')
.then(response => response.json())
.then(data => {
if (data.success) {
const stats = data.statistics;
// Animierte Zahlen-Updates
animateValue('totalLogs', stats.total_logs || 0);
animateValue('successRate', (100 - (stats.error_rate || 0)), '%');
animateValue('errorCount', stats.error_count || 0);
const avgTime = stats.average_response_time_ms;
document.getElementById('avgResponseTime').textContent =
avgTime ? Math.round(avgTime) + 'ms' : 'N/A';
}
})
.catch(error => {
console.error('Fehler beim Laden der Statistiken:', error);
});
}
// Animierte Werte-Updates
function animateValue(elementId, endValue, suffix = '') {
const element = document.getElementById(elementId);
const startValue = parseInt(element.textContent) || 0;
const difference = endValue - startValue;
const duration = 1000; // 1 Sekunde
const steps = 30;
const stepValue = difference / steps;
const stepDuration = duration / steps;
let currentValue = startValue;
let currentStep = 0;
const timer = setInterval(() => {
currentStep++;
currentValue += stepValue;
if (currentStep >= steps) {
currentValue = endValue;
clearInterval(timer);
}
element.textContent = Math.round(currentValue) + suffix;
}, stepDuration);
}
// Kalender initialisieren
initCalendar();
// Initiales Laden der Statistiken
loadStatistics();
});
</script>
{% endblock %}

View File

@ -716,10 +716,10 @@
</div> </div>
{% if current_user.is_authenticated and current_user.is_admin %} {% if current_user.is_authenticated and current_user.is_admin %}
<div class="pt-2 border-t border-slate-200 dark:border-slate-600"> <div class="pt-2 border-t border-slate-200 dark:border-slate-600">
<a href="{{ url_for('admin_plug_monitoring') }}" <a href="{{ url_for('admin_plug_schedules') }}"
class="flex items-center space-x-2 text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors duration-200"> class="flex items-center space-x-2 text-slate-600 dark:text-slate-400 hover:text-blue-600 dark:hover:text-blue-400 transition-colors duration-200">
<span class="text-sm">🔌</span> <span class="text-sm">🔌</span>
<span class="text-xs">Steckdosen-Monitoring</span> <span class="text-xs">Steckdosenschaltzeiten</span>
</a> </a>
</div> </div>
{% endif %} {% endif %}