No volunteer activity to display.
`;
}
renderTeamChart(metrics.hoursByTeam);
renderTimeChart(metrics.hoursByDate);
};
const renderTeamChart = (hoursByTeam) => {
const ctx = elements.teamChartCanvas?.getContext('2d');
if (!ctx) return;
const labels = Object.keys(hoursByTeam);
const data = Object.values(hoursByTeam);
if (teamChart) teamChart.destroy();
teamChart = new Chart(ctx, {
type: 'doughnut',
data: { labels, datasets: [{ label: 'Hours by Team', data, backgroundColor: ['#ec4899', '#3b82f6', '#10b981', '#f59e0b', '#8b5cf6'], hoverOffset: 4 }] },
options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { position: 'top' } } }
});
};
const renderTimeChart = (hoursByDate) => {
const ctx = elements.timeChartCanvas?.getContext('2d');
if (!ctx) return;
const sortedDates = Object.keys(hoursByDate).sort((a, b) => new Date(a) - new Date(b));
const chartData = sortedDates.map(date => hoursByDate[date]);
if (timeChart) timeChart.destroy();
timeChart = new Chart(ctx, {
type: 'bar',
data: { labels: sortedDates, datasets: [{ label: 'Hours Contributed', data: chartData, backgroundColor: 'rgba(59, 130, 246, 0.5)', borderColor: '#3b82f6', borderWidth: 1 }] },
options: { responsive: true, maintainAspectRatio: true }
});
};
const renderConfigPanel = () => {
const container = elements.editableLogList;
if (!container) return;
container.innerHTML = '';
volunteerData.forEach(v => {
const card = document.createElement('div');
card.className = 'grid grid-cols-1 md:grid-cols-5 gap-4 items-center bg-white p-3 rounded-lg border';
card.innerHTML = `
`;
container.appendChild(card);
});
};
const handleAddLog = (e) => {
e.preventDefault();
try {
const newLog = {
id: volunteerData.length > 0 ? Math.max(...volunteerData.map(v => v.id)) + 1 : 1,
name: document.getElementById('volunteerName').value,
team: document.getElementById('volunteerTeam').value,
date: document.getElementById('activityDate').value,
hours: parseFloat(document.getElementById('hoursContributed').value) || 0,
};
volunteerData.push(newLog);
elements.addForm.reset();
renderAll();
showToast('Volunteer log added!');
} catch (error) {
console.error("Error adding log:", error);
showToast("Error: Could not add log.");
}
};
const handleConfigListClick = (e) => {
const target = e.target.closest('button');
if (!target) return;
const action = target.dataset.action;
const id = parseInt(target.dataset.id, 10);
if (action === 'update') {
try {
const index = volunteerData.findIndex(v => v.id === id);
if (index === -1) return;
const inputs = target.closest('.grid').querySelectorAll('input');
inputs.forEach(input => {
const field = input.dataset.field;
let value = input.value;
if (input.type === 'number') value = parseFloat(value) || 0;
volunteerData[index][field] = value;
});
renderAll();
showToast('Log updated!');
} catch (error) {
console.error("Error updating log:", error);
showToast("Error: Could not save data.");
}
} else if (action === 'delete') {
volunteerData = volunteerData.filter(v => v.id !== id);
renderAll();
showToast('Log deleted.');
}
};
const handleGeneratePDF = () => {
try {
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
const metrics = calculateMetrics();
if (metrics.totalVolunteers === 0) {
showToast("Cannot generate PDF with no data.");
return;
}
doc.setFontSize(20);
doc.text("Volunteer Hours Contributed Report", 105, 20, null, null, 'center');
doc.setFontSize(10);
doc.text(`Generated on: ${new Date().toLocaleDateString()}`, 105, 26, null, null, 'center');
doc.autoTable({ startY: 35, head: [['Metric', 'Value']], body: [ ['Total Volunteers', metrics.totalVolunteers], ['Total Hours', metrics.totalHours.toFixed(1)], ['Avg. Hours / Volunteer', metrics.avgHours.toFixed(1)], ['Top Team', metrics.topTeam] ], theme: 'grid' });
let finalY = doc.lastAutoTable.finalY || 60;
doc.setFontSize(14);
doc.text("Hours by Team", 14, finalY + 15);
doc.addImage(elements.teamChartCanvas.toDataURL('image/png', 1.0), 'PNG', 14, finalY + 20, 80, 80);
doc.text("Hours Over Time", 105, finalY + 15);
doc.addImage(elements.timeChartCanvas.toDataURL('image/png', 1.0), 'PNG', 105, finalY + 20, 90, 50);
finalY += 95;
doc.setFontSize(14);
doc.text("Recent Activity Log", 14, finalY);
const sortedData = [...volunteerData].sort((a, b) => new Date(b.date) - new Date(a.date));
const tableBody = sortedData.slice(0, 20).map(v => [v.name, v.team, new Date(v.date).toLocaleDateString(), v.hours]);
doc.autoTable({ head: [['Volunteer', 'Team/Project', 'Date', 'Hours']], body: tableBody, startY: finalY + 5, theme: 'striped', headStyles: { fillColor: [219, 39, 119] } });
doc.save('Volunteer-Hours-Report.pdf');
} catch (error) {
console.error("Failed to generate PDF:", error);
showToast("Error: Could not generate PDF.");
}
};
const switchTab = (tabName) => {
currentTab = tabName;
Object.values(elements.tabs).forEach(tab => tab.classList.add('hidden'));
Object.values(elements.tabButtons).forEach(btn => btn.classList.remove('active'));
elements.tabs[tabName].classList.remove('hidden');
elements.tabButtons[tabName].classList.add('active');
updateNavButtons();
};
const navigateTabs = (direction) => {
const currentIndex = tabOrder.indexOf(currentTab);
const newIndex = direction === 'next' ? Math.min(currentIndex + 1, tabOrder.length - 1) : Math.max(currentIndex - 1, 0);
if (newIndex !== currentIndex) switchTab(tabOrder[newIndex]);
};
const updateNavButtons = () => {
const currentIndex = tabOrder.indexOf(currentTab);
elements.navButtons.prev.disabled = currentIndex === 0;
elements.navButtons.next.disabled = currentIndex === tabOrder.length - 1;
};
const showToast = (message) => {
if (!elements.toast) return;
elements.toast.textContent = message;
elements.toast.classList.add('show');
setTimeout(() => { elements.toast.classList.remove('show'); }, 3000);
}
elements.addForm.addEventListener('submit', handleAddLog);
elements.editableLogList.addEventListener('click', handleConfigListClick);
elements.pdfButton.addEventListener('click', handleGeneratePDF);
elements.tabButtons.dashboard.addEventListener('click', () => switchTab('dashboard'));
elements.tabButtons.config.addEventListener('click', () => switchTab('config'));
elements.navButtons.prev.addEventListener('click', () => navigateTabs('prev'));
elements.navButtons.next.addEventListener('click', () => navigateTabs('next'));
renderAll();
updateNavButtons();
});