Files
pdga-rating/index.html
T
shcizo 858143d149 Add course layouts scraping and rating calculation system
Features added:
- Course directory scraping with pagination for Swedish courses
- Layout scraping from course detail pages (AJAX tabs)
- Event results scraping to calculate layout ratings
- Mean rating calculation based on players who shot par
- Last played date tracking for each layout (extracted from event pages)
- Multi-event aggregation for accurate ratings across tournaments

Database:
- Added courses table (name, link, city, last_updated)
- Added layouts table (name, par, mean_rating, rating_count, last_played)
- Added database migrations for new columns
- Foreign key relationship between courses and layouts

API endpoints:
- POST /api/scrape-courses - scrape course directory
- POST /api/scrape-layouts/:courseId - scrape layouts and events (combined)
- POST /api/scrape-all-layouts - bulk scrape all courses
- POST /api/scrape-event-results/:courseId - process event results
- GET /api/courses - fetch all courses
- GET /api/layouts/:courseId - fetch layouts for course

UI:
- New courses.html page for course/layout management
- Expandable course rows showing layouts
- Display layout par, mean rating, and last played date
- Layouts sorted by most recently played (newest first)
- Individual and bulk scraping controls

Technical details:
- Date extraction using regex pattern matching from event pages
- Proper detection of division results in details/table.results structure
- Round score and rating extraction from td.round/td.round-rating pairs
- Course location from td.views-field-field-course-location

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-09-30 23:45:07 +02:00

976 lines
41 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDGA Ratings</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}
@media (max-width: 768px) {
body {
padding: 10px;
}
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
overflow-x: auto;
}
@media (max-width: 768px) {
.container {
padding: 15px;
border-radius: 0;
box-shadow: none;
}
}
h1 {
color: #333;
text-align: center;
margin-bottom: 30px;
}
@media (max-width: 768px) {
h1 {
font-size: 24px;
margin-bottom: 20px;
}
}
.loading {
text-align: center;
padding: 20px;
font-size: 18px;
color: #666;
}
.progress-container {
width: 100%;
background-color: #f0f0f0;
border-radius: 10px;
padding: 3px;
margin: 20px 0;
}
.progress-bar {
width: 0%;
height: 30px;
background-color: #007bff;
border-radius: 8px;
text-align: center;
line-height: 30px;
color: white;
font-weight: bold;
transition: width 0.3s ease;
}
.progress-text {
text-align: center;
margin: 10px 0;
font-size: 16px;
color: #666;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
font-size: 14px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
@media (max-width: 768px) {
table {
font-size: 12px;
}
th, td {
padding: 8px 4px;
}
/* Hide less important columns on mobile */
.mobile-hide {
display: none;
}
/* Show mobile-only elements only on mobile */
.mobile-only {
display: block;
}
/* Make player names more prominent on mobile */
.player-name {
font-weight: bold;
}
}
/* Hide mobile-only elements on desktop */
.mobile-only {
display: none;
}
@media (max-width: 768px) {
/* Adjust colspan for mobile - fewer visible columns */
.expanded-cell {
/* Mobile shows: Player Name, Rating, Action = 3 columns */
/* But we need to account for the fact that mobile-hide columns still exist in DOM */
}
/* Better mobile chart sizing */
.chart-container {
height: 250px;
margin: 5px 0;
}
.chart-title {
font-size: 14px;
}
}
th {
background-color: #f8f9fa;
font-weight: bold;
color: #495057;
}
tr:hover {
background-color: #f5f5f5;
}
.expandable-row {
cursor: pointer;
}
.expandable-row:hover {
background-color: #e3f2fd;
}
.expanded-content {
display: none;
background-color: #f8f9fa;
border-top: 2px solid #007bff;
}
.expanded-content td {
padding: 20px;
}
.chart-container {
width: 100%;
height: 300px;
margin: 10px 0;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
}
.chart-title {
text-align: center;
font-weight: bold;
margin-bottom: 10px;
color: #333;
}
.loading-chart {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
color: #666;
}
.chart-tooltip {
position: fixed;
background-color: rgba(0, 0, 0, 0.9);
color: white;
padding: 8px 12px;
border-radius: 4px;
font-size: 12px;
pointer-events: none;
z-index: 10000;
display: none;
white-space: nowrap;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.2);
}
.rating {
font-weight: bold;
color: #007bff;
}
.pdga-number {
color: #6c757d;
font-size: 14px;
}
.difference {
font-weight: bold;
}
.positive {
color: #28a745;
}
.negative {
color: #dc3545;
}
.neutral {
color: #6c757d;
}
.rating-change {
font-weight: bold;
font-size: 14px;
}
a {
color: #007bff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.refresh-icon {
cursor: pointer;
opacity: 0.6;
margin-left: 8px;
font-size: 13px;
color: #6c757d;
transition: all 0.2s ease;
padding: 2px;
border-radius: 3px;
}
.refresh-icon:hover {
opacity: 1;
color: #007bff;
background-color: rgba(0, 123, 255, 0.1);
transform: scale(1.1);
}
.refresh-icon.spinning {
animation: spin 1s linear infinite;
color: #007bff;
opacity: 1;
background-color: rgba(0, 123, 255, 0.1);
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.refresh-section {
display: inline-flex;
align-items: center;
}
.debug-icon:hover {
opacity: 1 !important;
color: #007bff !important;
transform: scale(1.1);
}
.debug-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 10001;
display: none;
justify-content: center;
align-items: center;
}
.debug-content {
background: white;
border-radius: 8px;
padding: 20px;
max-width: 600px;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}
.debug-header {
font-weight: bold;
font-size: 18px;
margin-bottom: 15px;
color: #333;
border-bottom: 2px solid #007bff;
padding-bottom: 10px;
}
.debug-log {
font-family: 'Courier New', monospace;
background-color: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 4px;
padding: 15px;
font-size: 12px;
line-height: 1.4;
white-space: pre-line;
color: #495057;
}
.debug-close {
position: absolute;
top: 10px;
right: 15px;
font-size: 24px;
color: #999;
cursor: pointer;
background: none;
border: none;
}
.debug-close:hover {
color: #333;
}
</style>
</head>
<body>
<div class="container">
<h1>PDGA Player Ratings</h1>
<div style="text-align: center; margin-bottom: 20px;">
<a href="/" style="margin: 0 15px; color: #333; text-decoration: none; font-weight: bold;">Player Ratings</a>
<a href="/courses.html" style="margin: 0 15px; color: #007bff; text-decoration: none; font-weight: bold;">Courses</a>
</div>
<div style="position: absolute; top: 10px; right: 15px;">
<a href="#" onclick="loadAllPlayers(); return false;" style="color: #007bff; font-size: 11px; text-decoration: none; margin-right: 10px;" title="Load all player data" id="load-all-btn">Load All</a>
<a href="#" onclick="clearCache(); return false;" style="color: #ccc; font-size: 12px; text-decoration: none; opacity: 0.3;" title="Clear cache"><i class="fas fa-cog"></i></a>
</div>
<div id="loading" class="loading" style="display: none;">Loading ratings...</div>
<div id="progress-section" style="display: none;">
<div class="progress-container">
<div id="progress-bar" class="progress-bar">0%</div>
</div>
<div id="progress-text" class="progress-text">Preparing to load ratings...</div>
</div>
<div id="ratings-table"></div>
</div>
<!-- Debug Modal -->
<div id="debug-modal" class="debug-modal" onclick="closeDebugModal(event)">
<div class="debug-content" onclick="event.stopPropagation()">
<button class="debug-close" onclick="closeDebugModal()">&times;</button>
<div class="debug-header" id="debug-header">Prediction Calculation Details</div>
<div class="debug-log" id="debug-log">Loading...</div>
</div>
</div>
<script>
function fetchRatingsWithProgress() {
const progressSection = document.getElementById('progress-section');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const tableDiv = document.getElementById('ratings-table');
progressSection.style.display = 'block';
tableDiv.innerHTML = '';
const eventSource = new EventSource('/api/ratings/progress');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.status === 'loading') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Loading player ${data.current}/${data.total}: PDGA #${data.pdgaNumber}`;
} else if (data.status === 'completed') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Loaded ${data.name} (${data.current}/${data.total})`;
} else if (data.status === 'error') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
progressText.textContent = `Error loading PDGA #${data.pdgaNumber} (${data.current}/${data.total})`;
} else if (data.status === 'complete') {
progressSection.style.display = 'none';
displayRatings(data.ratings);
eventSource.close();
} else if (data.status === 'error') {
progressSection.style.display = 'none';
tableDiv.innerHTML = '<p>Error loading ratings. Please try again.</p>';
eventSource.close();
}
};
eventSource.onerror = function() {
progressSection.style.display = 'none';
tableDiv.innerHTML = '<p>Connection error. Please refresh the page.</p>';
eventSource.close();
};
}
function displayRatings(ratings) {
const tableDiv = document.getElementById('ratings-table');
if (ratings.length === 0) {
tableDiv.innerHTML = '<p>No ratings found.</p>';
return;
}
let tableHTML = `
<table>
<thead>
<tr>
<th class="mobile-hide">Rank</th>
<th>Player Name</th>
<th class="mobile-hide">PDGA #</th>
<th>Rating</th>
<th class="mobile-hide">Change</th>
<th class="mobile-hide">Predicted</th>
</tr>
</thead>
<tbody>
`;
ratings.forEach((player, index) => {
const difference = player.predictedRating && player.rating ?
player.predictedRating - player.rating : 0;
const diffText = difference > 0 ? `+${difference}` : difference.toString();
const diffClass = difference > 0 ? 'positive' : difference < 0 ? 'negative' : 'neutral';
const ratingChangeText = player.ratingChange ?
(player.ratingChange > 0 ? `+${player.ratingChange}` : player.ratingChange.toString()) : 'N/A';
const ratingChangeClass = player.ratingChange > 0 ? 'positive' :
player.ratingChange < 0 ? 'negative' : 'neutral';
tableHTML += `
<tr id="row-${player.pdgaNumber}" class="expandable-row" onclick="togglePlayerHistory(${player.pdgaNumber})">
<td class="mobile-hide">${index + 1}</td>
<td class="player-name">
<a href="https://www.pdga.com/player/${player.pdgaNumber}" target="_blank" onclick="event.stopPropagation()">${player.name}</a>
<div class="mobile-only pdga-number" style="font-size: 11px; color: #999; margin-top: 2px;">PDGA #${player.pdgaNumber}</div>
</td>
<td class="pdga-number mobile-hide">#${player.pdgaNumber}</td>
<td class="rating">
<div class="refresh-section">
${player.rating || '<span style="color: #999; font-style: italic;">Click refresh</span>'}
<i class="fas fa-sync-alt refresh-icon" onclick="refreshPlayer(${player.pdgaNumber})" title="Refresh player data"></i>
</div>
<div class="mobile-only rating-change ${ratingChangeClass}" style="font-size: 11px; margin-top: 2px;">${ratingChangeText}</div>
</td>
<td class="rating-change ${ratingChangeClass} mobile-hide">${ratingChangeText}</td>
<td class="predicted-rating mobile-hide" id="predicted-${player.pdgaNumber}">
<div class="refresh-section">
${player.predictedRating || 'N/A'}
<i class="fas fa-question-circle debug-icon" onclick="showDebugInfo(${player.pdgaNumber})" title="Show calculation details" style="margin-left: 5px; color: #6c757d; cursor: pointer; opacity: 0.6;"></i>
<i class="fas fa-sync-alt refresh-icon" onclick="refreshRoundHistory(${player.pdgaNumber})" title="Refresh prediction data"></i>
</div>
</td>
</tr>
<tr id="history-${player.pdgaNumber}" class="expanded-content">
<td colspan="6" class="expanded-cell">
<div class="chart-title">
<div class="refresh-section">
Rating History for ${player.name}
<i class="fas fa-sync-alt refresh-icon" onclick="refreshRatingHistory(${player.pdgaNumber})" title="Refresh rating history"></i>
</div>
</div>
<div class="chart-container" id="chart-${player.pdgaNumber}" style="position: relative;">
<div class="loading-chart">Click to load rating history...</div>
</div>
<div class="chart-tooltip" id="tooltip-${player.pdgaNumber}"></div>
</td>
</tr>
`;
});
tableHTML += `
</tbody>
</table>
`;
tableDiv.innerHTML = tableHTML;
}
async function togglePlayerHistory(pdgaNumber) {
const historyRow = document.getElementById(`history-${pdgaNumber}`);
const chartContainer = document.getElementById(`chart-${pdgaNumber}`);
if (historyRow.style.display === 'table-row') {
historyRow.style.display = 'none';
return;
}
historyRow.style.display = 'table-row';
// Check if chart is already loaded
if (chartContainer.dataset.loaded === 'true') {
return;
}
// Show loading state
chartContainer.innerHTML = '<div class="loading-chart">Loading rating history...</div>';
try {
const response = await fetch(`/api/rating-history/${pdgaNumber}`);
const data = await response.json();
if (data.history && data.history.length > 0) {
createRatingChart(chartContainer, data.history);
chartContainer.dataset.loaded = 'true';
} else {
chartContainer.innerHTML = '<div class="loading-chart">No rating history available</div>';
}
} catch (error) {
console.error('Error loading rating history:', error);
chartContainer.innerHTML = '<div class="loading-chart">Error loading rating history</div>';
}
}
function createRatingChart(container, history) {
const width = container.clientWidth - 40;
const height = 250;
const margin = { top: 20, right: 30, bottom: 40, left: 60 };
const chartWidth = width - margin.left - margin.right;
const chartHeight = height - margin.top - margin.bottom;
// Get the tooltip element
const pdgaNumber = container.id.replace('chart-', '');
const tooltip = document.getElementById(`tooltip-${pdgaNumber}`);
// Calculate scales
const ratings = history.map(h => h.rating);
const minRating = Math.min(...ratings) - 10;
const maxRating = Math.max(...ratings) + 10;
const xStep = chartWidth / (history.length - 1 || 1);
const yScale = chartHeight / (maxRating - minRating);
// Create SVG
let svg = `<svg width="${width}" height="${height}" style="font-family: Arial, sans-serif;" id="svg-${pdgaNumber}">`;
// Background
svg += `<rect x="0" y="0" width="${width}" height="${height}" fill="white" stroke="#ddd"/>`;
// Chart area background
svg += `<rect x="${margin.left}" y="${margin.top}" width="${chartWidth}" height="${chartHeight}" fill="#f9f9f9" stroke="#ccc"/>`;
// Grid lines
for (let i = 0; i <= 5; i++) {
const y = margin.top + (i * chartHeight / 5);
const rating = Math.round(maxRating - (i * (maxRating - minRating) / 5));
svg += `<line x1="${margin.left}" y1="${y}" x2="${margin.left + chartWidth}" y2="${y}" stroke="#e0e0e0"/>`;
svg += `<text x="${margin.left - 5}" y="${y + 4}" text-anchor="end" font-size="12" fill="#666">${rating}</text>`;
}
// Data line
let pathData = '';
const points = [];
history.forEach((point, i) => {
const x = margin.left + (i * xStep);
const y = margin.top + ((maxRating - point.rating) * yScale);
points.push({ x, y, rating: point.rating, date: point.displayDate });
if (i === 0) {
pathData += `M ${x} ${y}`;
} else {
pathData += ` L ${x} ${y}`;
}
});
// Draw line
svg += `<path d="${pathData}" stroke="#007bff" stroke-width="2" fill="none"/>`;
// Draw points with enhanced hover areas
points.forEach((point, i) => {
svg += `<circle cx="${point.x}" cy="${point.y}" r="12" fill="transparent" class="hover-area" data-index="${i}" style="cursor: pointer;"/>`;
svg += `<circle cx="${point.x}" cy="${point.y}" r="4" fill="#007bff" stroke="white" stroke-width="2" class="data-point" data-index="${i}" style="pointer-events: none;"/>`;
});
// X-axis labels (show every few dates to avoid crowding)
const labelStep = Math.max(1, Math.floor(history.length / 6));
history.forEach((point, i) => {
if (i % labelStep === 0 || i === history.length - 1) {
const x = margin.left + (i * xStep);
const date = new Date(point.date).toLocaleDateString('en-US', { month: 'short', year: '2-digit' });
svg += `<text x="${x}" y="${height - 10}" text-anchor="middle" font-size="11" fill="#666">${date}</text>`;
}
});
// Y-axis label
svg += `<text x="20" y="${height/2}" text-anchor="middle" font-size="12" fill="#333" transform="rotate(-90, 20, ${height/2})">Rating</text>`;
svg += '</svg>';
container.innerHTML = svg;
// Add event listeners for tooltips after a small delay to ensure DOM is ready
setTimeout(() => {
const svgElement = document.getElementById(`svg-${pdgaNumber}`);
if (svgElement) {
const hoverAreas = svgElement.querySelectorAll('.hover-area');
const dataPoints = svgElement.querySelectorAll('.data-point');
let currentTooltip = null;
let tooltipTimeout = null;
hoverAreas.forEach((area, i) => {
area.addEventListener('mouseenter', (e) => {
// Clear any pending hide
if (tooltipTimeout) {
clearTimeout(tooltipTimeout);
tooltipTimeout = null;
}
// Hide current tooltip if different
if (currentTooltip !== null && currentTooltip !== i) {
dataPoints[currentTooltip].setAttribute('r', '4');
dataPoints[currentTooltip].setAttribute('fill', '#007bff');
}
currentTooltip = i;
const point = points[i];
tooltip.innerHTML = `<strong>${point.date}</strong><br>Rating: ${point.rating}`;
tooltip.style.display = 'block';
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
// Highlight the data point
dataPoints[i].setAttribute('r', '6');
dataPoints[i].setAttribute('fill', '#0056b3');
});
area.addEventListener('mousemove', (e) => {
if (currentTooltip === i) {
tooltip.style.left = `${e.clientX + 15}px`;
tooltip.style.top = `${e.clientY - 35}px`;
}
});
area.addEventListener('mouseleave', () => {
if (currentTooltip === i) {
// Delay hiding to prevent flicker
tooltipTimeout = setTimeout(() => {
tooltip.style.display = 'none';
dataPoints[i].setAttribute('r', '4');
dataPoints[i].setAttribute('fill', '#007bff');
currentTooltip = null;
}, 100);
}
});
});
}
}, 100);
}
async function clearCache() {
try {
const response = await fetch('/api/clear-cache', {
method: 'POST'
});
const data = await response.json();
if (data.success) {
alert(data.message);
// Optionally reload the page to reflect fresh data
if (confirm('Reload page to fetch fresh data?')) {
location.reload();
}
} else {
alert('Failed to clear cache');
}
} catch (error) {
console.error('Error clearing cache:', error);
alert('Error clearing cache');
}
}
// Refresh functions
async function refreshPlayer(pdgaNumber) {
const icon = document.querySelector(`#row-${pdgaNumber} .rating .refresh-icon`);
icon.classList.add('spinning');
try {
const response = await fetch(`/api/refresh-player/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (data.success) {
// Update the table with new data
const row = document.getElementById(`row-${pdgaNumber}`);
const ratingCell = row.querySelector('.rating');
const ratingChangeCell = row.querySelector('.rating-change');
// Update player name
const nameLink = row.querySelector('.player-name a');
nameLink.textContent = data.player.name;
const ratingChangeText = data.player.ratingChange ?
(data.player.ratingChange > 0 ? `+${data.player.ratingChange}` : data.player.ratingChange.toString()) : 'N/A';
const ratingChangeClass = data.player.ratingChange > 0 ? 'positive' :
data.player.ratingChange < 0 ? 'negative' : 'neutral';
const refreshSection = ratingCell.querySelector('.refresh-section');
refreshSection.innerHTML = `${data.player.rating || 'N/A'} <i class="fas fa-sync-alt refresh-icon" onclick="refreshPlayer(${pdgaNumber})" title="Refresh player data"></i>`;
if (ratingChangeCell) ratingChangeCell.textContent = ratingChangeText;
if (ratingChangeCell) ratingChangeCell.className = `rating-change ${ratingChangeClass} mobile-hide`;
// Update mobile rating change
const mobileChange = ratingCell.querySelector('.mobile-only.rating-change');
if (mobileChange) {
mobileChange.textContent = ratingChangeText;
mobileChange.className = `mobile-only rating-change ${ratingChangeClass}`;
}
}
} catch (error) {
console.error('Error refreshing player:', error);
alert('Failed to refresh player data');
} finally {
icon.classList.remove('spinning');
}
}
async function refreshRoundHistory(pdgaNumber) {
const icon = document.querySelector(`#predicted-${pdgaNumber} .refresh-icon`);
icon.classList.add('spinning');
try {
const response = await fetch(`/api/refresh-round-history/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (!response.ok) {
// Handle server error responses
throw new Error(JSON.stringify(data));
}
if (data.success) {
// Cache debug info for later use
if (data.debugLog) {
cachedDebugInfo[pdgaNumber] = data.debugLog;
}
// Update predicted rating if the element exists
const predictedCell = document.getElementById(`predicted-${pdgaNumber}`);
if (predictedCell) {
const refreshSection = predictedCell.querySelector('.refresh-section');
if (refreshSection && refreshSection.firstChild) {
refreshSection.firstChild.textContent = data.predictedRating || 'N/A';
}
}
// Update difference calculation if the element exists
const diffCell = document.getElementById(`diff-${pdgaNumber}`);
if (diffCell) {
const currentRatingElement = document.querySelector(`#row-${pdgaNumber} .rating .refresh-section`);
if (currentRatingElement && currentRatingElement.firstChild) {
const currentRatingText = currentRatingElement.firstChild.textContent;
const currentRating = parseInt(currentRatingText);
if (data.predictedRating && currentRating && !isNaN(currentRating)) {
const difference = data.predictedRating - currentRating;
const diffText = difference > 0 ? `+${difference}` : difference.toString();
const diffClass = difference > 0 ? 'positive' : difference < 0 ? 'negative' : 'neutral';
diffCell.className = `difference ${diffClass}`;
diffCell.textContent = diffText;
} else {
diffCell.innerHTML = '<span style="color: #999; font-style: italic;">Use refresh</span>';
}
}
}
}
} catch (error) {
console.error('Error refreshing round history:', error);
// Try to get detailed error information
let errorMessage = 'Failed to refresh prediction data';
let errorDetails = '';
try {
// If error message is JSON, parse it
const errorData = JSON.parse(error.message);
errorMessage = errorData.error || errorMessage;
errorDetails = errorData.details || '';
if (errorData.suggestion) {
errorDetails += '\n\nSuggestion: ' + errorData.suggestion;
}
if (errorData.errorType) {
errorDetails += '\n\nError Type: ' + errorData.errorType;
}
if (errorData.timestamp) {
errorDetails += '\n\nTime: ' + new Date(errorData.timestamp).toLocaleString();
}
} catch (parseError) {
// If not JSON, just use the error message
errorDetails = error.message;
}
const fullMessage = errorDetails ? errorMessage + '\n\nDetails:\n' + errorDetails : errorMessage;
alert(fullMessage);
} finally {
icon.classList.remove('spinning');
}
}
async function refreshRatingHistory(pdgaNumber) {
const icon = document.querySelector(`#history-${pdgaNumber} .chart-title .refresh-icon`);
icon.classList.add('spinning');
try {
const response = await fetch(`/api/refresh-rating-history/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (data.success) {
// Refresh the chart
const chartContainer = document.getElementById(`chart-${pdgaNumber}`);
chartContainer.dataset.loaded = 'false'; // Mark as not loaded to force refresh
if (data.history && data.history.length > 0) {
createRatingChart(chartContainer, data.history);
chartContainer.dataset.loaded = 'true';
} else {
chartContainer.innerHTML = '<div class="loading-chart">No rating history available</div>';
}
}
} catch (error) {
console.error('Error refreshing rating history:', error);
alert('Failed to refresh rating history');
} finally {
icon.classList.remove('spinning');
}
}
async function refreshAllPlayers() {
const icons = document.querySelectorAll('th .refresh-icon');
const ratingIcon = icons[0]; // First refresh icon in Rating header
ratingIcon.classList.add('spinning');
try {
const ratings = await getAllPlayersFromDB();
displayRatings(ratings);
} catch (error) {
console.error('Error refreshing all players:', error);
alert('Failed to refresh player data');
} finally {
ratingIcon.classList.remove('spinning');
}
}
async function refreshAllPredictions() {
const icons = document.querySelectorAll('th .refresh-icon');
const predictedIcon = icons[1]; // Second refresh icon in Predicted header
predictedIcon.classList.add('spinning');
try {
// This would be a bulk operation - for now just show message
alert('Bulk prediction refresh not implemented yet. Use individual refresh icons.');
} catch (error) {
console.error('Error refreshing all predictions:', error);
alert('Failed to refresh predictions');
} finally {
predictedIcon.classList.remove('spinning');
}
}
async function loadAllPlayers() {
const button = document.getElementById('load-all-btn');
const originalText = button.textContent;
button.textContent = 'Loading...';
button.style.pointerEvents = 'none';
try {
const progressSection = document.getElementById('progress-section');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const tableDiv = document.getElementById('ratings-table');
progressSection.style.display = 'block';
tableDiv.innerHTML = '';
const eventSource = new EventSource('/api/load-all-players');
eventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.status === 'loading' || data.status === 'completed' || data.status === 'error') {
const percentage = Math.round((data.current / data.total) * 100);
progressBar.style.width = `${percentage}%`;
progressBar.textContent = `${percentage}%`;
if (data.status === 'loading') {
progressText.textContent = `Loading player ${data.current}/${data.total}: PDGA #${data.pdgaNumber}`;
} else if (data.status === 'completed') {
progressText.textContent = `Loaded ${data.name} (${data.current}/${data.total})`;
} else if (data.status === 'error') {
progressText.textContent = `Error loading PDGA #${data.pdgaNumber} (${data.current}/${data.total})`;
}
} else if (data.status === 'complete') {
progressSection.style.display = 'none';
displayRatings(data.ratings);
eventSource.close();
button.textContent = originalText;
button.style.pointerEvents = 'auto';
}
};
eventSource.onerror = function() {
progressSection.style.display = 'none';
tableDiv.innerHTML = '<p>Connection error. Please refresh the page.</p>';
eventSource.close();
button.textContent = originalText;
button.style.pointerEvents = 'auto';
};
} catch (error) {
console.error('Error loading all players:', error);
button.textContent = originalText;
button.style.pointerEvents = 'auto';
}
}
// Debug modal functions
let cachedDebugInfo = {};
async function showDebugInfo(pdgaNumber) {
const modal = document.getElementById('debug-modal');
const header = document.getElementById('debug-header');
const log = document.getElementById('debug-log');
// Get player name for header
const playerNameElement = document.querySelector(`#row-${pdgaNumber} .player-name a`);
const playerName = playerNameElement ? playerNameElement.textContent : `PDGA #${pdgaNumber}`;
header.textContent = `Prediction Calculation Details - ${playerName}`;
log.textContent = 'Loading calculation details...';
modal.style.display = 'flex';
try {
// Check if we have cached debug info
if (cachedDebugInfo[pdgaNumber]) {
log.textContent = cachedDebugInfo[pdgaNumber].join('\n');
return;
}
// Try to get debug info from the latest refresh call
const response = await fetch(`/api/refresh-round-history/${pdgaNumber}`, {
method: 'POST'
});
const data = await response.json();
if (data.success && data.debugLog) {
cachedDebugInfo[pdgaNumber] = data.debugLog;
log.textContent = data.debugLog.join('\n');
} else {
log.textContent = 'No debug information available. Try refreshing the prediction first.';
}
} catch (error) {
console.error('Error fetching debug info:', error);
log.textContent = 'Error loading debug information. Please try again.';
}
}
function closeDebugModal(event) {
const modal = document.getElementById('debug-modal');
modal.style.display = 'none';
}
fetchRatingsWithProgress();
</script>
</body>
</html>