6 Commits

Author SHA1 Message Date
e4b37d9261 Fehler in der API behoben 2025-08-02 18:37:17 +02:00
45cc02b4b0 Fehler in API behoben 2025-08-02 18:30:16 +02:00
05766d9a97 Version auf 1.4.7 erhöht - Dashboard mit Toggle-Funktionalität 2025-08-02 14:28:22 +02:00
e5fbc14a34 Dashboard erweitert: Toggle zwischen Wochen- und 24-Stunden-Verlauf für alle Charts 2025-08-02 14:25:07 +02:00
9e025bd4c7 Überarbeite Help Modal: Floating Schließen-Button und mehrsprachige Unterstützung
- Schließen-Button ist jetzt 'floating' mit position: fixed
- Button hat Hintergrund, Rahmen und Schatten für bessere Sichtbarkeit
- Alle Texte im Help Modal verwenden jetzt Übersetzungsfunktionen
- Vollständige mehrsprachige Unterstützung (Deutsch/Englisch)
- Bessere mobile Darstellung ohne Überschneidungen
2025-08-02 14:17:46 +02:00
f4ffd14624 Update CLOC 2025-08-02 11:38:28 +02:00
5 changed files with 315 additions and 108 deletions

View File

@@ -334,6 +334,7 @@ curl -X POST http://localhost:5000/api/plusminus \
``` ```
**Hinweis:** **Hinweis:**
- `"einheit"`: `"tage"`, `"wochen"` oder `"monate"` - `"einheit"`: `"tage"`, `"wochen"` oder `"monate"`
- `"richtung"`: `"add"` (plus) oder `"sub"` (minus) - `"richtung"`: `"add"` (plus) oder `"sub"` (minus)
- `"werktage"`: `true` für Werktage, sonst `false` (nur bei `"tage"` unterstützt) - `"werktage"`: `true` für Werktage, sonst `false` (nur bei `"tage"` unterstützt)
@@ -472,15 +473,15 @@ Damit ist die App für Menschen mit unterschiedlichen Einschränkungen (z.B. Seh
### Code Statistik ### Code Statistik
cloc|github.com/AlDanial/cloc v 2.06 T=0.08 s (301.6 files/s, 72354.1 lines/s) cloc|github.com/AlDanial/cloc v 2.06 T=0.17 s (146.7 files/s, 35235.5 lines/s)
--- | --- --- | ---
Language|files|blank|comment|code Language|files|blank|comment|code
:-------|-------:|-------:|-------:|-------: :-------|-------:|-------:|-------:|-------:
HTML|8|47|6|2086 HTML|8|48|6|2092
Python|2|59|68|690 Python|2|59|68|690
JavaScript|2|95|87|571 JavaScript|2|95|87|571
Markdown|3|176|0|492 Markdown|3|176|0|493
PO File|2|234|240|492 PO File|2|234|240|492
JSON|3|0|0|243 JSON|3|0|0|243
CSS|1|186|3|188 CSS|1|186|3|188
@@ -488,7 +489,7 @@ SVG|2|0|0|14
Dockerfile|1|5|6|8 Dockerfile|1|5|6|8
DOS Batch|1|0|0|1 DOS Batch|1|0|0|1
--------|--------|--------|--------|-------- --------|--------|--------|--------|--------
SUM:|25|802|410|4785 SUM:|25|803|410|4792
## Lizenz ## Lizenz

76
app.py
View File

@@ -20,7 +20,7 @@ app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'translations'
babel = Babel() babel = Babel()
# Version der App # Version der App
APP_VERSION = "1.4.6" APP_VERSION = "1.4.7"
# HTML-Template wird jetzt aus templates/index.html geladen # HTML-Template wird jetzt aus templates/index.html geladen
@@ -237,26 +237,63 @@ def index():
def parse_log_stats(log_path): def parse_log_stats(log_path):
pageviews = 0 pageviews = 0
func_counts = {} func_counts = {}
func_counts_hourly = {}
impressions_per_day = {} impressions_per_day = {}
impressions_per_hour = {}
api_counts = {} api_counts = {}
api_counts_hourly = {}
if os.path.exists(log_path): if os.path.exists(log_path):
with open(log_path, encoding='utf-8') as f: with open(log_path, encoding='utf-8') as f:
for line in f: for line in f:
if 'PAGEVIEW' in line: if 'PAGEVIEW' in line:
pageviews += 1 pageviews += 1
try: try:
date = line[:10] # Parse timestamp (format: YYYY-MM-DDTHH:MM:SS)
timestamp = line[:19] # First 19 chars for YYYY-MM-DDTHH:MM:SS
date = timestamp[:10] # YYYY-MM-DD
hour = timestamp[11:13] # HH
if len(date) == 10 and date[4] == '-' and date[7] == '-': if len(date) == 10 and date[4] == '-' and date[7] == '-':
impressions_per_day[date] = impressions_per_day.get(date, 0) + 1 impressions_per_day[date] = impressions_per_day.get(date, 0) + 1
if len(hour) == 2 and hour.isdigit():
hour_key = f"{date} {hour}:00"
impressions_per_hour[hour_key] = impressions_per_hour.get(hour_key, 0) + 1
except Exception: except Exception:
pass pass
elif 'FUNC:' in line: elif 'FUNC:' in line:
func = line.split('FUNC:')[1].strip() func = line.split('FUNC:')[1].strip()
func_counts[func] = func_counts.get(func, 0) + 1 func_counts[func] = func_counts.get(func, 0) + 1
# Stündliche Funktionsaufrufe
try:
timestamp = line[:19]
date = timestamp[:10]
hour = timestamp[11:13]
if len(hour) == 2 and hour.isdigit():
hour_key = f"{date} {hour}:00"
if hour_key not in func_counts_hourly:
func_counts_hourly[hour_key] = {}
func_counts_hourly[hour_key][func] = func_counts_hourly[hour_key].get(func, 0) + 1
except Exception:
pass
elif 'FUNC_API:' in line: elif 'FUNC_API:' in line:
api = line.split('FUNC_API:')[1].strip() api = line.split('FUNC_API:')[1].strip()
api_counts[api] = api_counts.get(api, 0) + 1 api_counts[api] = api_counts.get(api, 0) + 1
return pageviews, func_counts, impressions_per_day, api_counts
# Stündliche API-Aufrufe
try:
timestamp = line[:19]
date = timestamp[:10]
hour = timestamp[11:13]
if len(hour) == 2 and hour.isdigit():
hour_key = f"{date} {hour}:00"
if hour_key not in api_counts_hourly:
api_counts_hourly[hour_key] = {}
api_counts_hourly[hour_key][api] = api_counts_hourly[hour_key].get(api, 0) + 1
except Exception:
pass
return pageviews, func_counts, func_counts_hourly, impressions_per_day, impressions_per_hour, api_counts, api_counts_hourly
@app.route('/stats', methods=['GET', 'POST']) @app.route('/stats', methods=['GET', 'POST'])
def stats(): def stats():
@@ -270,8 +307,8 @@ def stats():
return render_template('stats_login.html', error='Falsches Passwort!') return render_template('stats_login.html', error='Falsches Passwort!')
return render_template('stats_login.html', error=None) return render_template('stats_login.html', error=None)
log_path = os.path.join('log', 'pageviews.log') log_path = os.path.join('log', 'pageviews.log')
pageviews, func_counts, impressions_per_day, api_counts = parse_log_stats(log_path) pageviews, func_counts, func_counts_hourly, impressions_per_day, impressions_per_hour, api_counts, api_counts_hourly = parse_log_stats(log_path)
return render_template('stats_dashboard.html', pageviews=pageviews, func_counts=func_counts, impressions_per_day=impressions_per_day, api_counts=api_counts) return render_template('stats_dashboard.html', pageviews=pageviews, func_counts=func_counts, func_counts_hourly=func_counts_hourly, impressions_per_day=impressions_per_day, impressions_per_hour=impressions_per_hour, api_counts=api_counts, api_counts_hourly=api_counts_hourly)
# --- REST API --- # --- REST API ---
def log_api_usage(api_name): def log_api_usage(api_name):
@@ -378,34 +415,22 @@ def api_plusminus():
if is_werktage: if is_werktage:
result = np.busday_offset(d.date(), anzahl_int, roll='forward') result = np.busday_offset(d.date(), anzahl_int, roll='forward')
result_dt = datetime.strptime(str(result), '%Y-%m-%d') result_dt = datetime.strptime(str(result), '%Y-%m-%d')
if locale == 'en': return jsonify({'result': result_dt.strftime('%Y-%m-%d')})
plusminus_result = f"Date {d.strftime('%m/%d/%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} workdays: {result_dt.strftime('%m/%d/%Y')}"
else:
plusminus_result = f"Datum {d.strftime('%d.%m.%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} Werktage: {result_dt.strftime('%d.%m.%Y')}"
else: else:
result = d + timedelta(days=anzahl_int) result = d + timedelta(days=anzahl_int)
if locale == 'en': return jsonify({'result': result.strftime('%Y-%m-%d')})
plusminus_result = f"Date {d.strftime('%m/%d/%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} days: {result.strftime('%m/%d/%Y')}"
else:
plusminus_result = f"Datum {d.strftime('%d.%m.%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} Tage: {result.strftime('%d.%m.%Y')}"
elif einheit == 'wochen': elif einheit == 'wochen':
if is_werktage: if is_werktage:
return jsonify({'error': 'Nicht unterstützt: Werktage + Wochen.'}), 400 return jsonify({'error': 'Nicht unterstützt: Werktage + Wochen.'}), 400
else: else:
result = d + timedelta(weeks=anzahl_int) result = d + timedelta(weeks=anzahl_int)
if locale == 'en': return jsonify({'result': result.strftime('%Y-%m-%d')})
plusminus_result = f"Date {d.strftime('%m/%d/%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} weeks: {result.strftime('%m/%d/%Y')}"
else:
plusminus_result = f"Datum {d.strftime('%d.%m.%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} Wochen: {result.strftime('%d.%m.%Y')}"
elif einheit == 'monate': elif einheit == 'monate':
if is_werktage: if is_werktage:
return jsonify({'error': 'Nicht unterstützt: Werktage + Monate.'}), 400 return jsonify({'error': 'Nicht unterstützt: Werktage + Monate.'}), 400
else: else:
result = d + relativedelta(months=anzahl_int) result = d + relativedelta(months=anzahl_int)
if locale == 'en': return jsonify({'result': result.strftime('%Y-%m-%d')})
plusminus_result = f"Date {d.strftime('%m/%d/%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} months: {result.strftime('%m/%d/%Y')}"
else:
plusminus_result = f"Datum {d.strftime('%d.%m.%Y')} {'plus' if anzahl_int>=0 else 'minus'} {abs(anzahl_int)} Monate: {result.strftime('%d.%m.%Y')}"
else: else:
return jsonify({'error': 'Ungültige Einheit'}), 400 return jsonify({'error': 'Ungültige Einheit'}), 400
except Exception as e: except Exception as e:
@@ -414,8 +439,13 @@ def api_plusminus():
@app.route('/api/stats', methods=['GET']) @app.route('/api/stats', methods=['GET'])
def api_stats(): def api_stats():
log_path = os.path.join('log', 'pageviews.log') log_path = os.path.join('log', 'pageviews.log')
pageviews, func_counts, impressions_per_day, api_counts = parse_log_stats(log_path) pageviews, func_counts, func_counts_hourly, impressions_per_day, impressions_per_hour, api_counts, api_counts_hourly = parse_log_stats(log_path)
return render_template('stats_dashboard.html', pageviews=pageviews, func_counts=func_counts, impressions_per_day=impressions_per_day, api_counts=api_counts) return jsonify({
"pageviews": pageviews,
"func_counts": func_counts,
"impressions_per_day": impressions_per_day,
"api_counts": api_counts
})
@app.route('/api/monitor', methods=['GET']) @app.route('/api/monitor', methods=['GET'])
def api_monitor(): def api_monitor():

View File

@@ -165,17 +165,17 @@ body {
box-sizing: border-box; box-sizing: border-box;
} }
.modal-close { .modal-close {
position: absolute; position: fixed;
top: 1em; top: 1em;
right: 1em; right: 1em;
background: none; background: rgba(255, 255, 255, 0.95);
border: none; border: 2px solid var(--border);
font-size: 1.5em; font-size: 1.5em;
cursor: pointer; cursor: pointer;
color: var(--text); color: var(--text);
padding: 0.5em; padding: 0.5em;
border-radius: 50%; border-radius: 50%;
transition: background 0.2s; transition: all 0.2s;
width: 2.5em; width: 2.5em;
height: 2.5em; height: 2.5em;
display: flex; display: flex;
@@ -183,6 +183,8 @@ body {
justify-content: center; justify-content: center;
min-width: 44px; min-width: 44px;
min-height: 44px; min-height: 44px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
z-index: 1001;
} }
.modal-close:hover { .modal-close:hover {
background: var(--border); background: var(--border);
@@ -516,6 +518,26 @@ button:focus, .accordion-header:focus {
overflow-y: auto; overflow-y: auto;
overflow-x: hidden; overflow-x: hidden;
} }
.modal-close {
top: 0.8em;
right: 0.8em;
font-size: 1.3em;
width: 2.2em;
height: 2.2em;
min-width: 48px;
min-height: 48px;
background: rgba(255, 255, 255, 0.98);
border: 2px solid var(--border);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.modal-content h1 {
margin-top: 0;
margin-bottom: 1em;
font-size: 1.2em;
line-height: 1.3;
}
} }
/* Sprachauswahl */ /* Sprachauswahl */
@@ -1011,7 +1033,7 @@ footer br + a {
<!-- Help Modal Overlay --> <!-- Help Modal Overlay -->
<div id="helpModal" class="modal-overlay" role="dialog" aria-labelledby="help-title" aria-describedby="help-content"> <div id="helpModal" class="modal-overlay" role="dialog" aria-labelledby="help-title" aria-describedby="help-content">
<div class="modal-content"> <div class="modal-content">
<button type="button" class="modal-close" onclick="hideHelp()" aria-label="Hilfe schließen">&times;</button> <button type="button" class="modal-close" onclick="hideHelp()" aria-label="{{ _('Hilfe schließen') }}">&times;</button>
<h1 id="help-title">{{ _('Was ist Elpatrons Datumsrechner?') }}</h1> <h1 id="help-title">{{ _('Was ist Elpatrons Datumsrechner?') }}</h1>
<p>{{ _('Der Datumsrechner kann verschiedene Datumsberechnungen durchführen:') }}</p> <p>{{ _('Der Datumsrechner kann verschiedene Datumsberechnungen durchführen:') }}</p>
@@ -1027,41 +1049,41 @@ footer br + a {
<li>{{ _('Start-/Enddatum einer Kalenderwoche eines Jahres') }}</li> <li>{{ _('Start-/Enddatum einer Kalenderwoche eines Jahres') }}</li>
</ul> </ul>
<h2>Online Datumsrechner gibt es bereits in einer Vielzahl, warum also noch einer?</h2> <h2>{{ _('Online Datumsrechner gibt es bereits in einer Vielzahl, warum also noch einer?') }}</h2>
<p>Aus zwei Gründen:</p> <p>{{ _('Aus zwei Gründen:') }}</p>
<ul> <ul>
<li>Finde mal einen Datumsrechner, der nicht vollkommen verseucht mit Werbung, Tracking und Cookies ist!</li> <li>{{ _('Finde mal einen Datumsrechner, der nicht vollkommen verseucht mit Werbung, Tracking und Cookies ist!') }}</li>
<li>Das hat mich so geärgert, dass ich meinen eigenen programmiert habe. <li>{{ _('Das hat mich so geärgert, dass ich meinen eigenen programmiert habe.') }}
<ul> <ul>
<li>Genau genommen nicht ich selbst. Diese App wurde zum überwiegenden Teil von KI nach meinen Anweisungen entwickelt (Vibe Coding).</li> <li>{{ _('Genau genommen nicht ich selbst. Diese App wurde zum überwiegenden Teil von KI nach meinen Anweisungen entwickelt (Vibe Coding).') }}</li>
</ul> </ul>
</li> </li>
</ul> </ul>
<h2>Was du noch wissen solltest</h2> <h2>{{ _('Was du noch wissen solltest') }}</h2>
<ul> <ul>
<li>Ich habe versucht, die App möglichst barrierefrei zu gestalten, um Menschen mit Einschränkungen die Benutzung zu erleichtern.</li> <li>{{ _('Ich habe versucht, die App möglichst barrierefrei zu gestalten, um Menschen mit Einschränkungen die Benutzung zu erleichtern.') }}</li>
<li>Diese App schnüffelt dir nicht hinterher, sammelt keine persönlichen Daten und geht dir auch sonst (hoffentlich!) in keiner Weise auf die Nerven.</li> <li>{{ _('Diese App schnüffelt dir nicht hinterher, sammelt keine persönlichen Daten und geht dir auch sonst (hoffentlich!) in keiner Weise auf die Nerven.') }}</li>
<li>Den Quellcode dieser App habe ich auf <a href="https://codeberg.org/elpatron/datecalc" target="_blank">Codeberg</a> veröffentlicht, du kannst ihn einsehen, verändern oder damit deinen eigenen kleinen Datumsrechner betreiben.</li> <li>{{ _('Den Quellcode dieser App habe ich auf') }} <a href="https://codeberg.org/elpatron/datecalc" target="_blank">Codeberg</a> {{ _('veröffentlicht, du kannst ihn einsehen, verändern oder damit deinen eigenen kleinen Datumsrechner betreiben.') }}</li>
<li>Die App läuft auf meinem kleinen Home-Server und ist derzeit nicht für große Besucherzahlen ausgelegt.</li> <li>{{ _('Die App läuft auf meinem kleinen Home-Server und ist derzeit nicht für große Besucherzahlen ausgelegt.') }}</li>
<li>Ich übernehme keine Gewähr für die Funktionalität und die Rechenergebnisse. Die KI, die das programmiert hat, übrigens auch nicht.</li> <li>{{ _('Ich übernehme keine Gewähr für die Funktionalität und die Rechenergebnisse. Die KI, die das programmiert hat, übrigens auch nicht.') }}</li>
<li>Falls du einen Fehler findest oder eine weitere Funktion wünschst, kannst du mir eine Mail schreiben (siehe Mailto Link in der Fußzeile)</li> <li>{{ _('Falls du einen Fehler findest oder eine weitere Funktion wünschst, kannst du mir eine Mail schreiben (siehe Mailto Link in der Fußzeile)') }}</li>
</ul> </ul>
<p><strong>Hab Spaß mit Elpatrons Datumsrechner! Dein M. Busche</strong></p> <p><strong>{{ _('Hab Spaß mit Elpatrons Datumsrechner! Dein M. Busche') }}</strong></p>
</div> </div>
<div id="help-content" class="sr-only"> <div id="help-content" class="sr-only">
Hilfe-Informationen für den Datumsrechner mit Erklärungen zu allen Funktionen {{ _('Hilfe-Informationen für den Datumsrechner mit Erklärungen zu allen Funktionen') }}
</div> </div>
</div> </div>
<footer style="text-align:center; margin-top:2em; color:#475569; font-size:0.98em; padding-bottom:1.5em;"> <footer style="text-align:center; margin-top:2em; color:#475569; font-size:0.98em; padding-bottom:1.5em;">
Dies ist ein werbe- und trackingfreier <a href="https://codeberg.org/elpatron/datecalc/src/branch/main/README.md" target="_blank" style="color:#1e40af; text-decoration:underline;">Open Source Datumsrechner</a><br> Dies ist ein werbe- und trackingfreier <a href="https://codeberg.org/elpatron/datecalc/src/branch/main/README.md" target="_blank" style="color:#1e40af; text-decoration:underline;">Open Source</a> Datumsrechner<br>
<a href="/api-docs" target="_blank" style="color:#1e40af; text-decoration:underline;">REST API Dokumentation (Swagger)</a><br> <a href="/api-docs" target="_blank" style="color:#1e40af; text-decoration:underline;">REST API Dokumentation (Swagger)</a><br>
© 2025 <a href="mailto:elpatron@mailbox.org?subject=Datumsrechner" style="color:#1e40af; text-decoration:underline;">M. Busche</a> © 2025 <a href="mailto:elpatron@mailbox.org?subject=Datumsrechner" style="color:#1e40af; text-decoration:underline;">Markus Busche</a>
<div style="margin-top:0.5em; font-size:0.85em; color:#64748b;">v{{ app_version }}</div> <div style="margin-top:0.5em; font-size:0.85em; color:#64748b;">v{{ app_version }}</div>
</footer> </footer>
<script> <script>

View File

@@ -19,6 +19,32 @@
.stats-label { color: #64748b; } .stats-label { color: #64748b; }
.stats-value { font-size: 1.5em; font-weight: bold; } .stats-value { font-size: 1.5em; font-weight: bold; }
.chart-container { margin: 2em 0; } .chart-container { margin: 2em 0; }
.toggle-container {
display: flex;
justify-content: center;
margin-bottom: 1.5em;
gap: 0.5em;
}
.toggle-btn {
padding: 0.5em 1em;
border: 1px solid #d1d5db;
background: #f9fafb;
color: #6b7280;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
}
.toggle-btn.active {
background: #2563eb;
color: white;
border-color: #2563eb;
}
.toggle-btn:hover {
background: #e5e7eb;
}
.toggle-btn.active:hover {
background: #1d4ed8;
}
</style> </style>
</head> </head>
<body> <body>
@@ -28,6 +54,12 @@
<div class="stats-label">Gesamt-Pageviews (7 Tage):</div> <div class="stats-label">Gesamt-Pageviews (7 Tage):</div>
<div class="stats-value">{{ pageviews }}</div> <div class="stats-value">{{ pageviews }}</div>
</div> </div>
<div class="toggle-container">
<button class="toggle-btn active" data-period="week">Wochenverlauf</button>
<button class="toggle-btn" data-period="day">24-Stunden-Verlauf</button>
</div>
<div class="chart-container"> <div class="chart-container">
<canvas id="imprChart" width="400" height="180"></canvas> <canvas id="imprChart" width="400" height="180"></canvas>
</div> </div>
@@ -43,75 +75,196 @@
</div> </div>
<script type="text/javascript"> <script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
// Impressions pro Tag // Daten für verschiedene Zeiträume
// eslint-disable-next-line const weekData = {{ impressions_per_day|tojson }};
const imprData = {{ impressions_per_day|tojson }}; const dayData = {{ impressions_per_hour|tojson }};
const imprLabels = Object.keys(imprData); const weekFuncData = {{ func_counts|tojson }};
const imprCounts = Object.values(imprData); const dayFuncData = {{ func_counts_hourly|tojson }};
new Chart(document.getElementById('imprChart').getContext('2d'), { const weekApiData = {{ api_counts|tojson }};
type: 'line', const dayApiData = {{ api_counts_hourly|tojson }};
data: {
labels: imprLabels, let currentPeriod = 'week';
datasets: [{ let currentImprChart = null;
label: 'Impressions/Tag', let currentFuncChart = null;
data: imprCounts, let currentApiChart = null;
borderColor: '#059669',
backgroundColor: 'rgba(5,150,105,0.1)', // Toggle-Buttons Event Listener
tension: 0.2, document.querySelectorAll('.toggle-btn').forEach(btn => {
fill: true btn.addEventListener('click', function() {
}] // Aktiven Button aktualisieren
}, document.querySelectorAll('.toggle-btn').forEach(b => b.classList.remove('active'));
options: { this.classList.add('active');
plugins: { legend: { display: true } },
scales: { // Zeitraum wechseln
y: { beginAtZero: true, ticks: { stepSize: 1 } } currentPeriod = this.dataset.period;
} updateAllCharts();
} });
}); });
// Funktionsaufrufe
// eslint-disable-next-line function updateImpressionsChart() {
const funcCounts = {{ func_counts|tojson }}; const ctx = document.getElementById('imprChart').getContext('2d');
const labels = Object.keys(funcCounts);
const data = Object.values(funcCounts); // Bestehenden Chart zerstören
new Chart(document.getElementById('funcChart').getContext('2d'), { if (currentImprChart) {
type: 'bar', currentImprChart.destroy();
data: {
labels: labels,
datasets: [{
label: 'Funktionsaufrufe',
data: data,
backgroundColor: '#2563eb',
}]
},
options: {
plugins: { legend: { display: false } },
scales: {
y: { beginAtZero: true, ticks: { stepSize: 1 } }
}
} }
});
// API-Nutzung let data, labels, counts;
// eslint-disable-next-line
const apiCounts = {{ api_counts|tojson }}; if (currentPeriod === 'week') {
if (Object.keys(apiCounts).length > 0 && document.getElementById('apiChart')) { data = weekData;
new Chart(document.getElementById('apiChart').getContext('2d'), { labels = Object.keys(data);
type: 'bar', counts = Object.values(data);
} else {
data = dayData;
labels = Object.keys(data);
counts = Object.values(data);
}
currentImprChart = new Chart(ctx, {
type: 'line',
data: { data: {
labels: Object.keys(apiCounts), labels: labels,
datasets: [{ datasets: [{
label: 'API-Aufrufe nach Endpunkt', label: currentPeriod === 'week' ? 'Impressions/Tag' : 'Impressions/Stunde',
data: Object.values(apiCounts), data: counts,
backgroundColor: '#f59e42', borderColor: '#059669',
backgroundColor: 'rgba(5,150,105,0.1)',
tension: 0.2,
fill: true
}] }]
}, },
options: { options: {
plugins: { legend: { display: false } }, plugins: {
legend: { display: true },
title: {
display: true,
text: currentPeriod === 'week' ? 'Wochenverlauf' : '24-Stunden-Verlauf'
}
},
scales: { scales: {
y: { beginAtZero: true, ticks: { stepSize: 1 } } y: { beginAtZero: true, ticks: { stepSize: 1 } }
} }
} }
}); });
} }
function updateFunctionChart() {
const ctx = document.getElementById('funcChart').getContext('2d');
// Bestehenden Chart zerstören
if (currentFuncChart) {
currentFuncChart.destroy();
}
let data, labels, counts;
if (currentPeriod === 'week') {
data = weekFuncData;
labels = Object.keys(data);
counts = Object.values(data);
} else {
// Für stündliche Daten: Summe aller Stunden für jede Funktion
const aggregatedData = {};
Object.values(dayFuncData).forEach(hourData => {
Object.keys(hourData).forEach(func => {
aggregatedData[func] = (aggregatedData[func] || 0) + hourData[func];
});
});
data = aggregatedData;
labels = Object.keys(data);
counts = Object.values(data);
}
currentFuncChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Funktionsaufrufe',
data: counts,
backgroundColor: '#2563eb',
}]
},
options: {
plugins: {
legend: { display: false },
title: {
display: true,
text: currentPeriod === 'week' ? 'Funktionsaufrufe (Woche)' : 'Funktionsaufrufe (24h)'
}
},
scales: {
y: { beginAtZero: true, ticks: { stepSize: 1 } }
}
}
});
}
function updateApiChart() {
const apiChartElement = document.getElementById('apiChart');
if (!apiChartElement) return;
const ctx = apiChartElement.getContext('2d');
// Bestehenden Chart zerstören
if (currentApiChart) {
currentApiChart.destroy();
}
let data, labels, counts;
if (currentPeriod === 'week') {
data = weekApiData;
} else {
// Für stündliche Daten: Summe aller Stunden für jede API
const aggregatedData = {};
Object.values(dayApiData).forEach(hourData => {
Object.keys(hourData).forEach(api => {
aggregatedData[api] = (aggregatedData[api] || 0) + hourData[api];
});
});
data = aggregatedData;
}
if (Object.keys(data).length === 0) return;
labels = Object.keys(data);
counts = Object.values(data);
currentApiChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'API-Aufrufe nach Endpunkt',
data: counts,
backgroundColor: '#f59e42',
}]
},
options: {
plugins: {
legend: { display: false },
title: {
display: true,
text: currentPeriod === 'week' ? 'API-Nutzung (Woche)' : 'API-Nutzung (24h)'
}
},
scales: {
y: { beginAtZero: true, ticks: { stepSize: 1 } }
}
}
});
}
function updateAllCharts() {
updateImpressionsChart();
updateFunctionChart();
updateApiChart();
}
// Initial Charts erstellen
updateAllCharts();
}); });
</script> </script>
</body> </body>

View File

@@ -221,10 +221,11 @@ def test_api_plusminus(client):
def test_api_stats(client): def test_api_stats(client):
resp = client.get('/api/stats') resp = client.get('/api/stats')
assert resp.status_code == 200 assert resp.status_code == 200
# Die Route gibt HTML zurück, nicht JSON data = resp.get_json()
html = resp.data.decode('utf-8') assert "pageviews" in data
# Prüfe auf typische HTML-Elemente des Dashboards assert "func_counts" in data
assert 'Statistik-Dashboard' in html or 'Dashboard' in html assert "impressions_per_day" in data
assert "api_counts" in data
def test_api_monitor(client): def test_api_monitor(client):
resp = client.get('/api/monitor') resp = client.get('/api/monitor')