Separieren vom css und js und fixes
This commit is contained in:
737
public/js/admin-dashboard.js
Normal file
737
public/js/admin-dashboard.js
Normal file
@@ -0,0 +1,737 @@
|
||||
let currentUser = null;
|
||||
let currentDataType = null;
|
||||
let currentData = [];
|
||||
|
||||
// Beim Laden der Seite
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
checkAuth();
|
||||
loadStatistics();
|
||||
setupEventListeners();
|
||||
});
|
||||
|
||||
function setupEventListeners() {
|
||||
// Logout Button
|
||||
document.getElementById('logoutBtn').addEventListener('click', logout);
|
||||
|
||||
// Generator Button
|
||||
document.getElementById('generatorBtn').addEventListener('click', function() {
|
||||
window.location.href = '/generator';
|
||||
});
|
||||
|
||||
// Modal Close Buttons
|
||||
document.querySelectorAll('.close').forEach(closeBtn => {
|
||||
closeBtn.addEventListener('click', closeModal);
|
||||
});
|
||||
|
||||
// Confirm Modal Buttons
|
||||
document.getElementById('confirmNo').addEventListener('click', closeModal);
|
||||
|
||||
// Search Input
|
||||
document.getElementById('searchInput').addEventListener('input', filterData);
|
||||
|
||||
// Add Form
|
||||
document.getElementById('addForm').addEventListener('submit', handleAddSubmit);
|
||||
}
|
||||
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const response = await fetch('/api/check-session');
|
||||
const result = await response.json();
|
||||
|
||||
if (!result.success) {
|
||||
window.location.href = '/adminlogin.html';
|
||||
return;
|
||||
}
|
||||
|
||||
currentUser = result.user;
|
||||
document.getElementById('username').textContent = currentUser.username;
|
||||
|
||||
const accessBadge = document.getElementById('accessBadge');
|
||||
accessBadge.textContent = `Level ${currentUser.access_level}`;
|
||||
accessBadge.className = `access-badge level-${currentUser.access_level}`;
|
||||
|
||||
// Generator-Button nur für Level 2
|
||||
if (currentUser.access_level >= 2) {
|
||||
document.getElementById('generatorBtn').style.display = 'inline-block';
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Auth check failed:', error);
|
||||
window.location.href = '/adminlogin.html';
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await fetch('/api/logout', { method: 'POST' });
|
||||
window.location.href = '/adminlogin.html';
|
||||
} catch (error) {
|
||||
console.error('Logout failed:', error);
|
||||
window.location.href = '/adminlogin.html';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadStatistics() {
|
||||
try {
|
||||
const response = await fetch('/api/admin-stats');
|
||||
const stats = await response.json();
|
||||
|
||||
if (stats.success) {
|
||||
document.getElementById('totalPlayers').textContent = stats.data.players || 0;
|
||||
document.getElementById('totalRuns').textContent = stats.data.runs || 0;
|
||||
document.getElementById('totalLocations').textContent = stats.data.locations || 0;
|
||||
document.getElementById('totalAdminUsers').textContent = stats.data.adminUsers || 0;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load statistics:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function showUserManagement() {
|
||||
showDataSection('users', 'Benutzer-Verwaltung');
|
||||
loadUsers();
|
||||
}
|
||||
|
||||
function showPlayerManagement() {
|
||||
showDataSection('players', 'Spieler-Verwaltung');
|
||||
loadPlayers();
|
||||
}
|
||||
|
||||
function showRunManagement() {
|
||||
showDataSection('runs', 'Läufe-Verwaltung');
|
||||
loadRuns();
|
||||
}
|
||||
|
||||
function showLocationManagement() {
|
||||
showDataSection('locations', 'Standort-Verwaltung');
|
||||
loadLocations();
|
||||
}
|
||||
|
||||
function showAdminUserManagement() {
|
||||
showDataSection('adminusers', 'Admin-Benutzer');
|
||||
loadAdminUsers();
|
||||
}
|
||||
|
||||
function showSystemInfo() {
|
||||
showDataSection('system', 'System-Informationen');
|
||||
loadSystemInfo();
|
||||
}
|
||||
|
||||
function showDataSection(type, title) {
|
||||
currentDataType = type;
|
||||
document.getElementById('dataTitle').textContent = title;
|
||||
document.getElementById('dataSection').style.display = 'block';
|
||||
document.getElementById('searchInput').value = '';
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
// Implementation für Supabase-Benutzer
|
||||
document.getElementById('dataContent').innerHTML = '<div class="no-data">Supabase-Benutzer werden über die Supabase-Console verwaltet</div>';
|
||||
}
|
||||
|
||||
async function loadPlayers() {
|
||||
try {
|
||||
const response = await fetch('/api/admin-players');
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
currentData = result.data;
|
||||
displayPlayersTable(result.data);
|
||||
} else {
|
||||
showError('Fehler beim Laden der Spieler');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load players:', error);
|
||||
showError('Fehler beim Laden der Spieler');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRuns() {
|
||||
try {
|
||||
const response = await fetch('/api/admin-runs');
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
currentData = result.data;
|
||||
displayRunsTable(result.data);
|
||||
} else {
|
||||
showError('Fehler beim Laden der Läufe');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load runs:', error);
|
||||
showError('Fehler beim Laden der Läufe');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLocations() {
|
||||
try {
|
||||
const response = await fetch('/api/admin-locations');
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
currentData = result.data;
|
||||
displayLocationsTable(result.data);
|
||||
} else {
|
||||
showError('Fehler beim Laden der Standorte');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load locations:', error);
|
||||
showError('Fehler beim Laden der Standorte');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAdminUsers() {
|
||||
try {
|
||||
const response = await fetch('/api/admin-adminusers');
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
currentData = result.data;
|
||||
displayAdminUsersTable(result.data);
|
||||
} else {
|
||||
showError('Fehler beim Laden der Admin-Benutzer');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load admin users:', error);
|
||||
showError('Fehler beim Laden der Admin-Benutzer');
|
||||
}
|
||||
}
|
||||
|
||||
function displayPlayersTable(players) {
|
||||
let html = '<div class="table-container"><table class="data-table">';
|
||||
html += '<thead><tr><th>ID</th><th>Name</th><th>RFID UID</th><th>Supabase User</th><th>Registriert</th><th>Aktionen</th></tr></thead><tbody>';
|
||||
|
||||
players.forEach(player => {
|
||||
html += `<tr>
|
||||
<td>${player.id}</td>
|
||||
<td>${player.full_name || '-'}</td>
|
||||
<td>${player.rfiduid || '-'}</td>
|
||||
<td>${player.supabase_user_id ? '✅' : '❌'}</td>
|
||||
<td>${new Date(player.created_at).toLocaleDateString('de-DE')}</td>
|
||||
<td class="action-buttons">
|
||||
<button class="btn btn-small btn-warning" onclick="editPlayer('${player.id}')">Bearbeiten</button>
|
||||
<button class="btn btn-small btn-danger" onclick="deletePlayer('${player.id}')">Löschen</button>
|
||||
</td>
|
||||
</tr>`;
|
||||
});
|
||||
|
||||
html += '</tbody></table></div>';
|
||||
document.getElementById('dataContent').innerHTML = html;
|
||||
}
|
||||
|
||||
function displayRunsTable(runs) {
|
||||
let html = '<div class="table-container"><table class="data-table">';
|
||||
html += '<thead><tr><th>ID</th><th>Spieler</th><th>Standort</th><th>Zeit</th><th>Datum</th><th>Aktionen</th></tr></thead><tbody>';
|
||||
|
||||
runs.forEach(run => {
|
||||
// Use the time_seconds value from the backend
|
||||
const timeInSeconds = parseFloat(run.time_seconds) || 0;
|
||||
|
||||
html += `<tr>
|
||||
<td>${run.id}</td>
|
||||
<td>${run.player_name || `Player ${run.player_id}`}</td>
|
||||
<td>${run.location_name || `Location ${run.location_id}`}</td>
|
||||
<td>${timeInSeconds.toFixed(3)}s</td>
|
||||
<td>${new Date(run.created_at).toLocaleDateString('de-DE')} ${new Date(run.created_at).toLocaleTimeString('de-DE')}</td>
|
||||
<td class="action-buttons">
|
||||
<button class="btn btn-small btn-warning" onclick="editRun('${run.id}')">Bearbeiten</button>
|
||||
<button class="btn btn-small btn-danger" onclick="deleteRun('${run.id}')">Löschen</button>
|
||||
</td>
|
||||
</tr>`;
|
||||
});
|
||||
|
||||
html += '</tbody></table></div>';
|
||||
document.getElementById('dataContent').innerHTML = html;
|
||||
}
|
||||
|
||||
function displayLocationsTable(locations) {
|
||||
let html = '<div class="table-container"><table class="data-table">';
|
||||
html += '<thead><tr><th>ID</th><th>Name</th><th>Latitude</th><th>Longitude</th><th>Erstellt</th><th>Aktionen</th></tr></thead><tbody>';
|
||||
|
||||
locations.forEach(location => {
|
||||
html += `<tr>
|
||||
<td>${location.id}</td>
|
||||
<td>${location.name}</td>
|
||||
<td>${location.latitude}</td>
|
||||
<td>${location.longitude}</td>
|
||||
<td>${new Date(location.created_at).toLocaleDateString('de-DE')}</td>
|
||||
<td class="action-buttons">
|
||||
<button class="btn btn-small btn-warning" onclick="editLocation('${location.id}')">Bearbeiten</button>
|
||||
<button class="btn btn-small btn-danger" onclick="deleteLocation('${location.id}')">Löschen</button>
|
||||
</td>
|
||||
</tr>`;
|
||||
});
|
||||
|
||||
html += '</tbody></table></div>';
|
||||
document.getElementById('dataContent').innerHTML = html;
|
||||
}
|
||||
|
||||
function displayAdminUsersTable(users) {
|
||||
let html = '<div class="table-container"><table class="data-table">';
|
||||
html += '<thead><tr><th>ID</th><th>Benutzername</th><th>Access Level</th><th>Aktiv</th><th>Letzter Login</th><th>Aktionen</th></tr></thead><tbody>';
|
||||
|
||||
users.forEach(user => {
|
||||
const isCurrentUser = user.id === currentUser.id;
|
||||
html += `<tr>
|
||||
<td>${user.id}</td>
|
||||
<td>${user.username} ${isCurrentUser ? '(Du)' : ''}</td>
|
||||
<td>Level ${user.access_level}</td>
|
||||
<td>${user.is_active ? '✅' : '❌'}</td>
|
||||
<td>${user.last_login ? new Date(user.last_login).toLocaleDateString('de-DE') : 'Nie'}</td>
|
||||
<td class="action-buttons">
|
||||
${!isCurrentUser ? `<button class="btn btn-small btn-danger" onclick="deleteAdminUser(${user.id})">Löschen</button>` : ''}
|
||||
</td>
|
||||
</tr>`;
|
||||
});
|
||||
|
||||
html += '</tbody></table></div>';
|
||||
document.getElementById('dataContent').innerHTML = html;
|
||||
}
|
||||
|
||||
function loadSystemInfo() {
|
||||
document.getElementById('dataContent').innerHTML = `
|
||||
<div style="padding: 20px;">
|
||||
<h4>Server-Informationen</h4>
|
||||
<p><strong>Node.js Version:</strong> ${navigator.userAgent}</p>
|
||||
<p><strong>Aktuelle Zeit:</strong> ${new Date().toLocaleString('de-DE')}</p>
|
||||
<p><strong>Angemeldeter Benutzer:</strong> ${currentUser.username} (Level ${currentUser.access_level})</p>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function filterData() {
|
||||
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
|
||||
if (!currentData) return;
|
||||
|
||||
let filteredData = currentData.filter(item => {
|
||||
return Object.values(item).some(value =>
|
||||
value && value.toString().toLowerCase().includes(searchTerm)
|
||||
);
|
||||
});
|
||||
|
||||
switch(currentDataType) {
|
||||
case 'players':
|
||||
displayPlayersTable(filteredData);
|
||||
break;
|
||||
case 'runs':
|
||||
displayRunsTable(filteredData);
|
||||
break;
|
||||
case 'locations':
|
||||
displayLocationsTable(filteredData);
|
||||
break;
|
||||
case 'adminusers':
|
||||
displayAdminUsersTable(filteredData);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function refreshData() {
|
||||
switch(currentDataType) {
|
||||
case 'players':
|
||||
loadPlayers();
|
||||
break;
|
||||
case 'runs':
|
||||
loadRuns();
|
||||
break;
|
||||
case 'locations':
|
||||
loadLocations();
|
||||
break;
|
||||
case 'adminusers':
|
||||
loadAdminUsers();
|
||||
break;
|
||||
case 'system':
|
||||
loadSystemInfo();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function showAddModal() {
|
||||
const modal = document.getElementById('addModal');
|
||||
const modalTitle = document.getElementById('modalTitle');
|
||||
const formFields = document.getElementById('formFields');
|
||||
|
||||
// Modal-Titel basierend auf aktuellem Datentyp setzen
|
||||
switch(currentDataType) {
|
||||
case 'players':
|
||||
modalTitle.textContent = 'Neuen Spieler hinzufügen';
|
||||
formFields.innerHTML = `
|
||||
<div class="form-group">
|
||||
<label for="playerName">Vollständiger Name:</label>
|
||||
<input type="text" id="playerName" name="full_name" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="playerRfid">RFID UID:</label>
|
||||
<input type="text" id="playerRfid" name="rfiduid" placeholder="z.B. 1234567890">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="playerSupabaseId">Supabase User ID (optional):</label>
|
||||
<input type="text" id="playerSupabaseId" name="supabase_user_id" placeholder="UUID">
|
||||
</div>
|
||||
`;
|
||||
break;
|
||||
|
||||
case 'locations':
|
||||
modalTitle.textContent = 'Neuen Standort hinzufügen';
|
||||
formFields.innerHTML = `
|
||||
<div class="form-group">
|
||||
<label for="locationName">Standort-Name:</label>
|
||||
<input type="text" id="locationName" name="name" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="locationLat">Breitengrad (Latitude):</label>
|
||||
<input type="number" id="locationLat" name="latitude" step="any" required placeholder="z.B. 48.385337">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="locationLng">Längengrad (Longitude):</label>
|
||||
<input type="number" id="locationLng" name="longitude" step="any" required placeholder="z.B. 9.986960">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="locationThreshold">Zeit-Schwellenwert (optional):</label>
|
||||
<input type="number" id="locationThreshold" name="time_threshold" step="0.001" placeholder="z.B. 60.000">
|
||||
</div>
|
||||
`;
|
||||
break;
|
||||
|
||||
case 'adminusers':
|
||||
modalTitle.textContent = 'Neuen Admin-Benutzer hinzufügen';
|
||||
formFields.innerHTML = `
|
||||
<div class="form-group">
|
||||
<label for="adminUsername">Benutzername:</label>
|
||||
<input type="text" id="adminUsername" name="username" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="adminPassword">Passwort:</label>
|
||||
<input type="password" id="adminPassword" name="password" required minlength="6">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="adminAccessLevel">Zugriffslevel:</label>
|
||||
<select id="adminAccessLevel" name="access_level" required>
|
||||
<option value="1">Level 1 - Basis-Admin</option>
|
||||
<option value="2">Level 2 - Vollzugriff</option>
|
||||
</select>
|
||||
</div>
|
||||
`;
|
||||
break;
|
||||
|
||||
case 'runs':
|
||||
modalTitle.textContent = 'Neuen Lauf hinzufügen';
|
||||
formFields.innerHTML = `
|
||||
<div class="form-group">
|
||||
<label for="runPlayerId">Spieler ID:</label>
|
||||
<input type="number" id="runPlayerId" name="player_id" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="runLocationId">Standort ID:</label>
|
||||
<input type="number" id="runLocationId" name="location_id" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="runTime">Zeit (Sekunden):</label>
|
||||
<input type="number" id="runTime" name="time_seconds" step="0.001" required placeholder="z.B. 60.123">
|
||||
</div>
|
||||
`;
|
||||
break;
|
||||
|
||||
default:
|
||||
modalTitle.textContent = 'Element hinzufügen';
|
||||
formFields.innerHTML = '<p>Keine Felder für diesen Datentyp verfügbar.</p>';
|
||||
}
|
||||
|
||||
modal.style.display = 'block';
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
document.querySelectorAll('.modal').forEach(modal => {
|
||||
modal.style.display = 'none';
|
||||
});
|
||||
// Formular zurücksetzen
|
||||
document.getElementById('addForm').reset();
|
||||
document.getElementById('modalMessage').style.display = 'none';
|
||||
}
|
||||
|
||||
async function handleAddSubmit(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(e.target);
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
|
||||
// Prüfen ob es sich um eine Edit-Operation handelt
|
||||
const isEdit = data.edit_id;
|
||||
const editId = data.edit_id;
|
||||
delete data.edit_id; // edit_id aus den Daten entfernen
|
||||
|
||||
try {
|
||||
let endpoint = '';
|
||||
let successMessage = '';
|
||||
let method = 'POST';
|
||||
|
||||
switch(currentDataType) {
|
||||
case 'players':
|
||||
endpoint = isEdit ? `/api/admin-players/${editId}` : '/api/admin-players';
|
||||
successMessage = isEdit ? 'Spieler erfolgreich aktualisiert' : 'Spieler erfolgreich hinzugefügt';
|
||||
method = isEdit ? 'PUT' : 'POST';
|
||||
break;
|
||||
case 'locations':
|
||||
endpoint = isEdit ? `/api/admin-locations/${editId}` : '/api/admin-locations';
|
||||
successMessage = isEdit ? 'Standort erfolgreich aktualisiert' : 'Standort erfolgreich hinzugefügt';
|
||||
method = isEdit ? 'PUT' : 'POST';
|
||||
break;
|
||||
case 'adminusers':
|
||||
endpoint = isEdit ? `/api/admin-adminusers/${editId}` : '/api/admin-adminusers';
|
||||
successMessage = isEdit ? 'Admin-Benutzer erfolgreich aktualisiert' : 'Admin-Benutzer erfolgreich hinzugefügt';
|
||||
method = isEdit ? 'PUT' : 'POST';
|
||||
break;
|
||||
case 'runs':
|
||||
endpoint = isEdit ? `/api/admin-runs/${editId}` : '/api/admin-runs';
|
||||
successMessage = isEdit ? 'Lauf erfolgreich aktualisiert' : 'Lauf erfolgreich hinzugefügt';
|
||||
method = isEdit ? 'PUT' : 'POST';
|
||||
break;
|
||||
default:
|
||||
showError('Unbekannter Datentyp');
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetch(endpoint, {
|
||||
method: method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
showSuccess(successMessage);
|
||||
closeModal();
|
||||
refreshData(); // Daten neu laden
|
||||
} else {
|
||||
showError(result.message || `Fehler beim ${isEdit ? 'Aktualisieren' : 'Hinzufügen'}`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Submit failed:', error);
|
||||
showError(`Fehler beim ${isEdit ? 'Aktualisieren' : 'Hinzufügen'}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Edit-Funktionen
|
||||
async function editPlayer(id) {
|
||||
const player = currentData.find(p => p.id == id);
|
||||
if (!player) return;
|
||||
|
||||
const modal = document.getElementById('addModal');
|
||||
const modalTitle = document.getElementById('modalTitle');
|
||||
const formFields = document.getElementById('formFields');
|
||||
|
||||
modalTitle.textContent = 'Spieler bearbeiten';
|
||||
formFields.innerHTML = `
|
||||
<div class="form-group">
|
||||
<label for="playerName">Vollständiger Name:</label>
|
||||
<input type="text" id="playerName" name="full_name" value="${player.full_name || ''}" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="playerRfid">RFID UID:</label>
|
||||
<input type="text" id="playerRfid" name="rfiduid" value="${player.rfiduid || ''}" placeholder="z.B. 1234567890">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="playerSupabaseId">Supabase User ID (optional):</label>
|
||||
<input type="text" id="playerSupabaseId" name="supabase_user_id" value="${player.supabase_user_id || ''}" placeholder="UUID">
|
||||
</div>
|
||||
<input type="hidden" name="edit_id" value="${player.id}">
|
||||
`;
|
||||
|
||||
modal.style.display = 'block';
|
||||
}
|
||||
|
||||
async function editLocation(id) {
|
||||
const location = currentData.find(l => l.id == id);
|
||||
if (!location) return;
|
||||
|
||||
const modal = document.getElementById('addModal');
|
||||
const modalTitle = document.getElementById('modalTitle');
|
||||
const formFields = document.getElementById('formFields');
|
||||
|
||||
modalTitle.textContent = 'Standort bearbeiten';
|
||||
formFields.innerHTML = `
|
||||
<div class="form-group">
|
||||
<label for="locationName">Standort-Name:</label>
|
||||
<input type="text" id="locationName" name="name" value="${location.name}" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="locationLat">Breitengrad (Latitude):</label>
|
||||
<input type="number" id="locationLat" name="latitude" step="any" value="${location.latitude}" required placeholder="z.B. 48.385337">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="locationLng">Längengrad (Longitude):</label>
|
||||
<input type="number" id="locationLng" name="longitude" step="any" value="${location.longitude}" required placeholder="z.B. 9.986960">
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="locationThreshold">Zeit-Schwellenwert (optional):</label>
|
||||
<input type="number" id="locationThreshold" name="time_threshold" step="0.001" value="${location.time_threshold || ''}" placeholder="z.B. 60.000">
|
||||
</div>
|
||||
<input type="hidden" name="edit_id" value="${location.id}">
|
||||
`;
|
||||
|
||||
modal.style.display = 'block';
|
||||
}
|
||||
|
||||
async function editRun(id) {
|
||||
try {
|
||||
// Lade die spezifischen Lauf-Daten direkt von der API
|
||||
const response = await fetch(`/api/admin-runs/${id}`);
|
||||
const result = await response.json();
|
||||
|
||||
if (!result.success) {
|
||||
showError('Fehler beim Laden der Lauf-Daten: ' + (result.message || 'Unbekannter Fehler'));
|
||||
return;
|
||||
}
|
||||
|
||||
const run = result.data;
|
||||
if (!run) {
|
||||
showError('Lauf nicht gefunden');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Editing run:', run); // Debug log
|
||||
|
||||
const modal = document.getElementById('addModal');
|
||||
const modalTitle = document.getElementById('modalTitle');
|
||||
const formFields = document.getElementById('formFields');
|
||||
|
||||
modalTitle.textContent = 'Lauf bearbeiten';
|
||||
formFields.innerHTML = `
|
||||
<div class="form-group">
|
||||
<label for="runPlayerId">Spieler ID:</label>
|
||||
<input type="text" id="runPlayerId" name="player_id" value="${run.player_id || ''}" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="runLocationId">Standort ID:</label>
|
||||
<input type="text" id="runLocationId" name="location_id" value="${run.location_id || ''}" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="runTime">Zeit (Sekunden):</label>
|
||||
<input type="number" id="runTime" name="time_seconds" step="0.001" value="${parseFloat(run.time_seconds || 0)}" required placeholder="z.B. 60.123">
|
||||
</div>
|
||||
<input type="hidden" name="edit_id" value="${run.id}">
|
||||
`;
|
||||
|
||||
modal.style.display = 'block';
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error loading run data:', error);
|
||||
showError('Fehler beim Laden der Lauf-Daten');
|
||||
}
|
||||
}
|
||||
|
||||
async function deletePlayer(id) {
|
||||
if (await confirmDelete(`Spieler mit ID ${id} löschen?`)) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin-players/${id}`, { method: 'DELETE' });
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
showSuccess('Spieler erfolgreich gelöscht');
|
||||
loadPlayers();
|
||||
} else {
|
||||
showError('Fehler beim Löschen des Spielers');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Delete failed:', error);
|
||||
showError('Fehler beim Löschen des Spielers');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteRun(id) {
|
||||
if (await confirmDelete(`Lauf mit ID ${id} löschen?`)) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin-runs/${id}`, { method: 'DELETE' });
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
showSuccess('Lauf erfolgreich gelöscht');
|
||||
loadRuns();
|
||||
} else {
|
||||
showError('Fehler beim Löschen des Laufs');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Delete failed:', error);
|
||||
showError('Fehler beim Löschen des Laufs');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteLocation(id) {
|
||||
if (await confirmDelete(`Standort mit ID ${id} löschen?`)) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin-locations/${id}`, { method: 'DELETE' });
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
showSuccess('Standort erfolgreich gelöscht');
|
||||
loadLocations();
|
||||
} else {
|
||||
showError('Fehler beim Löschen des Standorts');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Delete failed:', error);
|
||||
showError('Fehler beim Löschen des Standorts');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteAdminUser(id) {
|
||||
if (await confirmDelete(`Admin-Benutzer mit ID ${id} löschen?`)) {
|
||||
try {
|
||||
const response = await fetch(`/api/admin-adminusers/${id}`, { method: 'DELETE' });
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
showSuccess('Admin-Benutzer erfolgreich gelöscht');
|
||||
loadAdminUsers();
|
||||
} else {
|
||||
showError('Fehler beim Löschen des Admin-Benutzers');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Delete failed:', error);
|
||||
showError('Fehler beim Löschen des Admin-Benutzers');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function confirmDelete(message) {
|
||||
return new Promise((resolve) => {
|
||||
document.getElementById('confirmMessage').textContent = message;
|
||||
document.getElementById('confirmModal').style.display = 'block';
|
||||
|
||||
document.getElementById('confirmYes').onclick = () => {
|
||||
closeModal();
|
||||
resolve(true);
|
||||
};
|
||||
|
||||
document.getElementById('confirmNo').onclick = () => {
|
||||
closeModal();
|
||||
resolve(false);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function showSuccess(message) {
|
||||
const messageDiv = document.getElementById('modalMessage');
|
||||
messageDiv.textContent = message;
|
||||
messageDiv.className = 'message success';
|
||||
messageDiv.style.display = 'block';
|
||||
setTimeout(() => {
|
||||
messageDiv.style.display = 'none';
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
function showError(message) {
|
||||
const messageDiv = document.getElementById('modalMessage');
|
||||
messageDiv.textContent = message;
|
||||
messageDiv.className = 'message error';
|
||||
messageDiv.style.display = 'block';
|
||||
setTimeout(() => {
|
||||
messageDiv.style.display = 'none';
|
||||
}, 3000);
|
||||
}
|
||||
500
public/js/leaderboard.js
Normal file
500
public/js/leaderboard.js
Normal file
@@ -0,0 +1,500 @@
|
||||
// Supabase configuration
|
||||
const SUPABASE_URL = 'https://lfxlplnypzvjrhftaoog.supabase.co';
|
||||
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxmeGxwbG55cHp2anJoZnRhb29nIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDkyMTQ3NzIsImV4cCI6MjA2NDc5MDc3Mn0.XR4preBqWAQ1rT4PFbpkmRdz57BTwIusBI89fIxDHM8';
|
||||
|
||||
// Initialize Supabase client
|
||||
const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
|
||||
|
||||
// Initialize Socket.IO connection
|
||||
const socket = io();
|
||||
|
||||
// Global variable to store locations with coordinates
|
||||
let locationsData = [];
|
||||
|
||||
// WebSocket Event Handlers
|
||||
socket.on('connect', () => {
|
||||
console.log('🔌 WebSocket verbunden');
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('🔌 WebSocket getrennt');
|
||||
});
|
||||
|
||||
socket.on('newTime', (data) => {
|
||||
console.log('🏁 Neue Zeit empfangen:', data);
|
||||
showNotification(data);
|
||||
// Reload data to show the new time
|
||||
loadData();
|
||||
});
|
||||
|
||||
// Notification Functions
|
||||
function showNotification(timeData) {
|
||||
const notificationBubble = document.getElementById('notificationBubble');
|
||||
const notificationTitle = document.getElementById('notificationTitle');
|
||||
const notificationSubtitle = document.getElementById('notificationSubtitle');
|
||||
|
||||
// Format the time data
|
||||
const playerName = timeData.player_name || 'Unbekannter Spieler';
|
||||
const locationName = timeData.location_name || 'Unbekannter Standort';
|
||||
const timeString = timeData.recorded_time || '--:--';
|
||||
|
||||
// Update notification content
|
||||
notificationTitle.textContent = `🏁 Neue Zeit von ${playerName}!`;
|
||||
notificationSubtitle.textContent = `${timeString} • ${locationName}`;
|
||||
|
||||
// Show notification
|
||||
notificationBubble.classList.remove('hide');
|
||||
notificationBubble.classList.add('show');
|
||||
|
||||
// Auto-hide after 5 seconds
|
||||
setTimeout(() => {
|
||||
hideNotification();
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
function hideNotification() {
|
||||
const notificationBubble = document.getElementById('notificationBubble');
|
||||
notificationBubble.classList.remove('show');
|
||||
notificationBubble.classList.add('hide');
|
||||
|
||||
// Remove hide class after animation
|
||||
setTimeout(() => {
|
||||
notificationBubble.classList.remove('hide');
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// Check authentication status
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const { data: { session } } = await supabase.auth.getSession();
|
||||
|
||||
if (session) {
|
||||
// User is logged in, show dashboard button
|
||||
document.getElementById('adminLoginBtn').style.display = 'none';
|
||||
document.getElementById('dashboardBtn').style.display = 'inline-block';
|
||||
document.getElementById('logoutBtn').style.display = 'inline-block';
|
||||
} else {
|
||||
// User is not logged in, show admin login button
|
||||
document.getElementById('adminLoginBtn').style.display = 'inline-block';
|
||||
document.getElementById('dashboardBtn').style.display = 'none';
|
||||
document.getElementById('logoutBtn').style.display = 'none';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking auth:', error);
|
||||
// Fallback: show login button if auth check fails
|
||||
document.getElementById('adminLoginBtn').style.display = 'inline-block';
|
||||
document.getElementById('dashboardBtn').style.display = 'none';
|
||||
document.getElementById('logoutBtn').style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
// Logout function
|
||||
async function logout() {
|
||||
try {
|
||||
const { error } = await supabase.auth.signOut();
|
||||
if (error) {
|
||||
console.error('Error logging out:', error);
|
||||
} else {
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error during logout:', error);
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
// Load locations from database
|
||||
async function loadLocations() {
|
||||
try {
|
||||
const response = await fetch('/public-api/locations');
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch locations');
|
||||
}
|
||||
|
||||
const responseData = await response.json();
|
||||
const locations = responseData.data || responseData; // Handle both formats
|
||||
const locationSelect = document.getElementById('locationSelect');
|
||||
|
||||
// Store locations globally for distance calculations
|
||||
locationsData = locations;
|
||||
|
||||
// Clear existing options except "Alle Standorte"
|
||||
locationSelect.innerHTML = '<option value="all">🌍 Alle Standorte</option>';
|
||||
|
||||
// Add locations from database
|
||||
locations.forEach(location => {
|
||||
const option = document.createElement('option');
|
||||
option.value = location.name;
|
||||
option.textContent = `📍 ${location.name}`;
|
||||
locationSelect.appendChild(option);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error loading locations:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate distance between two points using Haversine formula
|
||||
function calculateDistance(lat1, lon1, lat2, lon2) {
|
||||
const R = 6371; // Earth's radius in kilometers
|
||||
const dLat = toRadians(lat2 - lat1);
|
||||
const dLon = toRadians(lon2 - lon1);
|
||||
|
||||
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
|
||||
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
|
||||
Math.sin(dLon / 2) * Math.sin(dLon / 2);
|
||||
|
||||
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
const distance = R * c; // Distance in kilometers
|
||||
|
||||
return distance;
|
||||
}
|
||||
|
||||
function toRadians(degrees) {
|
||||
return degrees * (Math.PI / 180);
|
||||
}
|
||||
|
||||
// Find nearest location based on user's current position
|
||||
async function findNearestLocation() {
|
||||
const btn = document.getElementById('findLocationBtn');
|
||||
const locationSelect = document.getElementById('locationSelect');
|
||||
|
||||
// Check if geolocation is supported
|
||||
if (!navigator.geolocation) {
|
||||
showLocationError('Geolocation wird von diesem Browser nicht unterstützt.');
|
||||
return;
|
||||
}
|
||||
|
||||
// Update button state to loading
|
||||
btn.disabled = true;
|
||||
btn.classList.add('loading');
|
||||
btn.textContent = '🔍 Suche...';
|
||||
|
||||
try {
|
||||
// Get user's current position
|
||||
const position = await new Promise((resolve, reject) => {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
resolve,
|
||||
reject,
|
||||
{
|
||||
enableHighAccuracy: true,
|
||||
timeout: 10000,
|
||||
maximumAge: 300000 // 5 minutes
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
const userLat = position.coords.latitude;
|
||||
const userLon = position.coords.longitude;
|
||||
|
||||
// Calculate distances to all locations
|
||||
const locationsWithDistance = locationsData.map(location => ({
|
||||
...location,
|
||||
distance: calculateDistance(
|
||||
userLat,
|
||||
userLon,
|
||||
parseFloat(location.latitude),
|
||||
parseFloat(location.longitude)
|
||||
)
|
||||
}));
|
||||
|
||||
// Find the nearest location
|
||||
const nearestLocation = locationsWithDistance.reduce((nearest, current) => {
|
||||
return current.distance < nearest.distance ? current : nearest;
|
||||
});
|
||||
|
||||
// Select the nearest location in the dropdown
|
||||
locationSelect.value = nearestLocation.name;
|
||||
|
||||
// Trigger change event to update the leaderboard
|
||||
locationSelect.dispatchEvent(new Event('change'));
|
||||
|
||||
// Show success notification
|
||||
showLocationSuccess(nearestLocation.name, nearestLocation.distance);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error getting location:', error);
|
||||
let errorMessage = 'Standort konnte nicht ermittelt werden.';
|
||||
|
||||
if (error.code) {
|
||||
switch(error.code) {
|
||||
case error.PERMISSION_DENIED:
|
||||
errorMessage = 'Standortzugriff wurde verweigert. Bitte erlaube den Standortzugriff in den Browser-Einstellungen.';
|
||||
break;
|
||||
case error.POSITION_UNAVAILABLE:
|
||||
errorMessage = 'Standortinformationen sind nicht verfügbar.';
|
||||
break;
|
||||
case error.TIMEOUT:
|
||||
errorMessage = 'Zeitüberschreitung beim Abrufen des Standorts.';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
showLocationError(errorMessage);
|
||||
} finally {
|
||||
// Reset button state
|
||||
btn.disabled = false;
|
||||
btn.classList.remove('loading');
|
||||
btn.textContent = '📍 Mein Standort';
|
||||
}
|
||||
}
|
||||
|
||||
// Show success notification for location finding
|
||||
function showLocationSuccess(locationName, distance) {
|
||||
const notificationBubble = document.getElementById('notificationBubble');
|
||||
const notificationTitle = document.getElementById('notificationTitle');
|
||||
const notificationSubtitle = document.getElementById('notificationSubtitle');
|
||||
|
||||
// Update notification content
|
||||
notificationTitle.textContent = `📍 Standort gefunden!`;
|
||||
notificationSubtitle.textContent = `${locationName} (${distance.toFixed(1)} km entfernt)`;
|
||||
|
||||
// Show notification
|
||||
notificationBubble.classList.remove('hide');
|
||||
notificationBubble.classList.add('show');
|
||||
|
||||
// Auto-hide after 4 seconds
|
||||
setTimeout(() => {
|
||||
hideNotification();
|
||||
}, 4000);
|
||||
}
|
||||
|
||||
// Show error notification for location finding
|
||||
function showLocationError(message) {
|
||||
const notificationBubble = document.getElementById('notificationBubble');
|
||||
const notificationTitle = document.getElementById('notificationTitle');
|
||||
const notificationSubtitle = document.getElementById('notificationSubtitle');
|
||||
|
||||
// Change notification style to error
|
||||
notificationBubble.style.background = 'linear-gradient(135deg, #dc3545, #c82333)';
|
||||
|
||||
// Update notification content
|
||||
notificationTitle.textContent = '❌ Fehler';
|
||||
notificationSubtitle.textContent = message;
|
||||
|
||||
// Show notification
|
||||
notificationBubble.classList.remove('hide');
|
||||
notificationBubble.classList.add('show');
|
||||
|
||||
// Auto-hide after 6 seconds
|
||||
setTimeout(() => {
|
||||
hideNotification();
|
||||
// Reset notification style
|
||||
notificationBubble.style.background = 'linear-gradient(135deg, #00d4ff, #0891b2)';
|
||||
}, 6000);
|
||||
}
|
||||
|
||||
// Load data from local database via MCP
|
||||
async function loadData() {
|
||||
try {
|
||||
const location = document.getElementById('locationSelect').value;
|
||||
const period = document.querySelector('.time-tab.active').dataset.period;
|
||||
|
||||
// Build query parameters
|
||||
const params = new URLSearchParams();
|
||||
if (location && location !== 'all') {
|
||||
params.append('location', location);
|
||||
}
|
||||
if (period && period !== 'all') {
|
||||
params.append('period', period);
|
||||
}
|
||||
|
||||
// Fetch times with player and location data from local database
|
||||
const response = await fetch(`/public-api/times-with-details?${params.toString()}`);
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to fetch times');
|
||||
}
|
||||
|
||||
const times = await response.json();
|
||||
|
||||
// Convert to the format expected by the leaderboard
|
||||
const leaderboardData = times.map(time => {
|
||||
const { minutes, seconds, milliseconds } = time.recorded_time;
|
||||
const timeString = `${minutes}:${seconds.toString().padStart(2, '0')}.${milliseconds}`;
|
||||
const playerName = time.player ?
|
||||
`${time.player.firstname} ${time.player.lastname}` :
|
||||
'Unknown Player';
|
||||
const locationName = time.location ? time.location.name : 'Unknown Location';
|
||||
const date = new Date(time.created_at).toISOString().split('T')[0];
|
||||
|
||||
return {
|
||||
name: playerName,
|
||||
time: timeString,
|
||||
date: date,
|
||||
location: locationName
|
||||
};
|
||||
});
|
||||
|
||||
// Sort by time (fastest first)
|
||||
leaderboardData.sort((a, b) => {
|
||||
const timeA = timeToSeconds(a.time);
|
||||
const timeB = timeToSeconds(b.time);
|
||||
return timeA - timeB;
|
||||
});
|
||||
|
||||
updateLeaderboard(leaderboardData);
|
||||
updateStats(leaderboardData);
|
||||
updateCurrentSelection();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error loading data:', error);
|
||||
// Fallback to sample data if API fails
|
||||
loadSampleData();
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback sample data based on real database data
|
||||
function loadSampleData() {
|
||||
const sampleData = [
|
||||
{ name: "Carsten Graf", time: "01:28.945", date: "2025-08-30", location: "Ulm Donaubad" },
|
||||
{ name: "Carsten Graf", time: "01:30.945", date: "2025-08-30", location: "Ulm Donaubad" },
|
||||
{ name: "Max Mustermann", time: "01:50.945", date: "2025-08-30", location: "Ulm Donaubad" },
|
||||
{ name: "Carsten Graf", time: "02:50.945", date: "2025-08-31", location: "Test" },
|
||||
{ name: "Max Mustermann", time: "02:50.945", date: "2025-08-31", location: "Test" },
|
||||
{ name: "Carsten Graf", time: "01:10.945", date: "2025-09-02", location: "Test" },
|
||||
{ name: "Carsten Graf", time: "01:11.945", date: "2025-09-02", location: "Test" },
|
||||
{ name: "Carsten Graf", time: "01:11.945", date: "2025-09-02", location: "Ulm Donaubad" }
|
||||
];
|
||||
|
||||
updateLeaderboard(sampleData);
|
||||
updateStats(sampleData);
|
||||
updateCurrentSelection();
|
||||
}
|
||||
|
||||
function timeToSeconds(timeStr) {
|
||||
const [minutes, seconds] = timeStr.split(':');
|
||||
return parseFloat(minutes) * 60 + parseFloat(seconds);
|
||||
}
|
||||
|
||||
function updateStats(data) {
|
||||
const totalPlayers = new Set(data.map(item => item.name)).size;
|
||||
const bestTime = data.length > 0 ? data[0].time : '--:--';
|
||||
const totalRecords = data.length;
|
||||
|
||||
document.getElementById('totalPlayers').textContent = totalPlayers;
|
||||
document.getElementById('bestTime').textContent = bestTime;
|
||||
document.getElementById('totalRecords').textContent = totalRecords;
|
||||
}
|
||||
|
||||
function updateCurrentSelection() {
|
||||
const location = document.getElementById('locationSelect').value;
|
||||
const period = document.querySelector('.time-tab.active').dataset.period;
|
||||
|
||||
// Get the display text from the selected option
|
||||
const locationSelect = document.getElementById('locationSelect');
|
||||
const selectedLocationOption = locationSelect.options[locationSelect.selectedIndex];
|
||||
const locationDisplay = selectedLocationOption ? selectedLocationOption.textContent : '🌍 Alle Standorte';
|
||||
|
||||
const periodIcons = {
|
||||
'today': '📅 Heute',
|
||||
'week': '📊 Diese Woche',
|
||||
'month': '📈 Dieser Monat',
|
||||
'all': '♾️ Alle Zeiten'
|
||||
};
|
||||
|
||||
document.getElementById('currentSelection').textContent =
|
||||
`${locationDisplay} • ${periodIcons[period]}`;
|
||||
|
||||
document.getElementById('lastUpdated').textContent =
|
||||
`Letzter Sync: ${new Date().toLocaleTimeString('de-DE')}`;
|
||||
}
|
||||
|
||||
function updateLeaderboard(data) {
|
||||
const rankingList = document.getElementById('rankingList');
|
||||
|
||||
if (data.length === 0) {
|
||||
rankingList.innerHTML = `
|
||||
<div class="empty-state">
|
||||
<div class="empty-icon">🏁</div>
|
||||
<div class="empty-title">Keine Rekorde gefunden</div>
|
||||
<div class="empty-description">
|
||||
Für diese Filtereinstellungen liegen noch keine Zeiten vor.<br>
|
||||
Versuche es mit einem anderen Zeitraum oder Standort.
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
rankingList.innerHTML = data.map((player, index) => {
|
||||
const rank = index + 1;
|
||||
let positionClass = '';
|
||||
let trophy = '';
|
||||
|
||||
if (rank === 1) {
|
||||
positionClass = 'gold';
|
||||
trophy = '👑';
|
||||
} else if (rank === 2) {
|
||||
positionClass = 'silver';
|
||||
trophy = '🥈';
|
||||
} else if (rank === 3) {
|
||||
positionClass = 'bronze';
|
||||
trophy = '🥉';
|
||||
} else if (rank <= 10) {
|
||||
trophy = '⭐';
|
||||
}
|
||||
|
||||
const formatDate = new Date(player.date).toLocaleDateString('de-DE', {
|
||||
day: '2-digit',
|
||||
month: 'short'
|
||||
});
|
||||
|
||||
return `
|
||||
<div class="rank-entry">
|
||||
<div class="position ${positionClass}">#${rank}</div>
|
||||
<div class="player-data">
|
||||
<div class="player-name">${player.name}</div>
|
||||
<div class="player-meta">
|
||||
<span class="location-tag">${player.location}</span>
|
||||
<span>🗓️ ${formatDate}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="time-result">${player.time}</div>
|
||||
${trophy ? `<div class="trophy-icon">${trophy}</div>` : '<div class="trophy-icon"></div>'}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// Event Listeners Setup
|
||||
function setupEventListeners() {
|
||||
// Location select event listener
|
||||
document.getElementById('locationSelect').addEventListener('change', loadData);
|
||||
|
||||
// Time tab event listeners
|
||||
document.querySelectorAll('.time-tab').forEach(tab => {
|
||||
tab.addEventListener('click', function() {
|
||||
// Remove active class from all tabs
|
||||
document.querySelectorAll('.time-tab').forEach(t => t.classList.remove('active'));
|
||||
// Add active class to clicked tab
|
||||
this.classList.add('active');
|
||||
// Load data with new period
|
||||
loadData();
|
||||
});
|
||||
});
|
||||
|
||||
// Smooth scroll for better UX
|
||||
const rankingsList = document.querySelector('.rankings-list');
|
||||
if (rankingsList) {
|
||||
rankingsList.style.scrollBehavior = 'smooth';
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize page
|
||||
async function init() {
|
||||
await checkAuth();
|
||||
await loadLocations();
|
||||
await loadData();
|
||||
setupEventListeners();
|
||||
}
|
||||
|
||||
// Auto-refresh function
|
||||
function startAutoRefresh() {
|
||||
setInterval(loadData, 45000);
|
||||
}
|
||||
|
||||
// Start the application when DOM is loaded
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
init();
|
||||
startAutoRefresh();
|
||||
});
|
||||
187
public/js/login.js
Normal file
187
public/js/login.js
Normal file
@@ -0,0 +1,187 @@
|
||||
// Supabase configuration
|
||||
const SUPABASE_URL = 'https://lfxlplnypzvjrhftaoog.supabase.co';
|
||||
const SUPABASE_ANON_KEY = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImxmeGxwbG55cHp2anJoZnRhb29nIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NDkyMTQ3NzIsImV4cCI6MjA2NDc5MDc3Mn0.XR4preBqWAQ1rT4PFbpkmRdz57BTwIusBI89fIxDHM8';
|
||||
|
||||
// Initialize Supabase client
|
||||
const supabase = window.supabase.createClient(SUPABASE_URL, SUPABASE_ANON_KEY);
|
||||
|
||||
// Check if user is already logged in
|
||||
async function checkAuth() {
|
||||
const { data: { session } } = await supabase.auth.getSession();
|
||||
if (session) {
|
||||
window.location.href = '/';
|
||||
}
|
||||
}
|
||||
|
||||
// Toggle between login and register forms
|
||||
function toggleForm() {
|
||||
const loginForm = document.getElementById('loginForm');
|
||||
const registerForm = document.getElementById('registerForm');
|
||||
|
||||
if (loginForm.classList.contains('active')) {
|
||||
loginForm.classList.remove('active');
|
||||
registerForm.classList.add('active');
|
||||
} else {
|
||||
registerForm.classList.remove('active');
|
||||
loginForm.classList.add('active');
|
||||
}
|
||||
clearMessage();
|
||||
showPasswordReset(false); // Hide password reset when switching forms
|
||||
}
|
||||
|
||||
// Show message
|
||||
function showMessage(message, type = 'success') {
|
||||
const messageDiv = document.getElementById('message');
|
||||
messageDiv.innerHTML = `<div class="message ${type}">${message}</div>`;
|
||||
setTimeout(() => {
|
||||
messageDiv.innerHTML = '';
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
// Clear message
|
||||
function clearMessage() {
|
||||
document.getElementById('message').innerHTML = '';
|
||||
}
|
||||
|
||||
// Show/hide password reset container
|
||||
function showPasswordReset(show) {
|
||||
const resetContainer = document.getElementById('passwordResetContainer');
|
||||
if (show) {
|
||||
resetContainer.classList.add('active');
|
||||
} else {
|
||||
resetContainer.classList.remove('active');
|
||||
}
|
||||
}
|
||||
|
||||
// Show/hide loading
|
||||
function setLoading(show) {
|
||||
const loading = document.getElementById('loading');
|
||||
if (show) {
|
||||
loading.classList.add('active');
|
||||
} else {
|
||||
loading.classList.remove('active');
|
||||
}
|
||||
}
|
||||
|
||||
// Event Listeners Setup
|
||||
function setupEventListeners() {
|
||||
// Handle login
|
||||
document.getElementById('loginFormElement').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
clearMessage();
|
||||
showPasswordReset(false); // Hide reset button initially
|
||||
|
||||
const email = document.getElementById('loginEmail').value;
|
||||
const password = document.getElementById('loginPassword').value;
|
||||
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signInWithPassword({
|
||||
email: email,
|
||||
password: password
|
||||
});
|
||||
|
||||
if (error) {
|
||||
showMessage(error.message, 'error');
|
||||
// Show password reset button on login failure
|
||||
showPasswordReset(true);
|
||||
} else {
|
||||
showMessage('Login successful! Redirecting...', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/';
|
||||
}, 1000);
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage('An unexpected error occurred', 'error');
|
||||
showPasswordReset(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle registration
|
||||
document.getElementById('registerFormElement').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
clearMessage();
|
||||
|
||||
const email = document.getElementById('registerEmail').value;
|
||||
const password = document.getElementById('registerPassword').value;
|
||||
const confirmPassword = document.getElementById('confirmPassword').value;
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
showMessage('Passwords do not match', 'error');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (password.length < 6) {
|
||||
showMessage('Password must be at least 6 characters', 'error');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { data, error } = await supabase.auth.signUp({
|
||||
email: email,
|
||||
password: password
|
||||
});
|
||||
|
||||
if (error) {
|
||||
showMessage(error.message, 'error');
|
||||
} else {
|
||||
if (data.user && !data.user.email_confirmed_at) {
|
||||
showMessage('Registration successful! Please check your email to confirm your account.', 'success');
|
||||
} else {
|
||||
showMessage('Registration successful! Redirecting...', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/';
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage('An unexpected error occurred', 'error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle password reset
|
||||
document.getElementById('resetPasswordBtn').addEventListener('click', async () => {
|
||||
const email = document.getElementById('loginEmail').value;
|
||||
|
||||
if (!email) {
|
||||
showMessage('Bitte geben Sie zuerst Ihre E-Mail-Adresse ein', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
clearMessage();
|
||||
|
||||
try {
|
||||
const { error } = await supabase.auth.resetPasswordForEmail(email, {
|
||||
redirectTo: `${window.location.origin}/reset-password.html`
|
||||
});
|
||||
|
||||
if (error) {
|
||||
showMessage('Fehler beim Senden der E-Mail: ' + error.message, 'error');
|
||||
} else {
|
||||
showMessage('Passwort-Reset-E-Mail wurde gesendet! Bitte überprüfen Sie Ihr E-Mail-Postfach.', 'success');
|
||||
showPasswordReset(false);
|
||||
}
|
||||
} catch (error) {
|
||||
showMessage('Ein unerwarteter Fehler ist aufgetreten', 'error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize page
|
||||
async function init() {
|
||||
await checkAuth();
|
||||
setupEventListeners();
|
||||
}
|
||||
|
||||
// Start the application when DOM is loaded
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
Reference in New Issue
Block a user