WASTELESSV6 / reports.html
EHDEM's picture
Update reports.html
df74b9d verified
Raw History Blame Contribute Delete
25.6 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WASTE-LESS - Reports & Analytics</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-100 min-h-screen">
<div class="container mx-auto px-4 py-8 max-w-6xl">
<!-- Header -->
<header class="bg-gradient-to-r from-green-600 to-emerald-600 text-white rounded-2xl shadow-lg p-6 mb-8">
<div class="flex items-center justify-between">
<div class="flex items-center">
<a href="index.html" class="text-white/80 hover:text-white mr-4 text-xl transition"><i class="fas fa-home"></i></a>
<div>
<h1 class="text-3xl font-bold">Reports & Analytics</h1>
<p class="text-white/80">Real-time insights from live GitHub data</p>
</div>
</div>
<button onclick="location.reload()" class="bg-white/20 hover:bg-white/30 text-white px-4 py-2 rounded-lg transition">
<i class="fas fa-sync-alt mr-2"></i>Refresh
</button>
</div>
</header>
<!-- Loading State -->
<div id="loading" class="text-center py-12">
<div class="inline-block animate-spin rounded-full h-12 w-12 border-t-4 border-b-4 border-green-500 mb-4"></div>
<p class="text-gray-600 text-lg">Fetching data from GitHub...</p>
</div>
<!-- Error State -->
<div id="error-msg" class="hidden bg-red-50 border border-red-200 text-red-700 p-6 rounded-xl mb-8">
<div class="flex items-center">
<i class="fas fa-exclamation-circle text-2xl mr-3"></i>
<div>
<h3 class="font-bold text-lg">Failed to load data</h3>
<p id="error-detail" class="text-sm mt-1"></p>
</div>
</div>
</div>
<!-- Dashboard Content -->
<div id="dashboard" class="hidden space-y-8">
<!-- KPI Cards -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
<div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-blue-500">
<div class="flex justify-between items-start">
<div>
<p class="text-gray-500 text-sm font-medium uppercase">Planned Today</p>
<p class="text-3xl font-bold text-gray-800 mt-1" id="kpi-planned">0</p>
</div>
<div class="bg-blue-100 p-3 rounded-lg"><i class="fas fa-utensils text-blue-600"></i></div>
</div>
</div>
<div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-green-500">
<div class="flex justify-between items-start">
<div>
<p class="text-gray-500 text-sm font-medium uppercase">Actually Ate</p>
<p class="text-3xl font-bold text-gray-800 mt-1" id="kpi-ate">0</p>
</div>
<div class="bg-green-100 p-3 rounded-lg"><i class="fas fa-check-circle text-green-600"></i></div>
</div>
</div>
<div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-red-500">
<div class="flex justify-between items-start">
<div>
<p class="text-gray-500 text-sm font-medium uppercase">No-Shows</p>
<p class="text-3xl font-bold text-gray-800 mt-1" id="kpi-noshow">0</p>
</div>
<div class="bg-red-100 p-3 rounded-lg"><i class="fas fa-user-times text-red-600"></i></div>
</div>
</div>
<div class="bg-white rounded-xl shadow-md p-6 border-l-4 border-yellow-500">
<div class="flex justify-between items-start">
<div>
<p class="text-gray-500 text-sm font-medium uppercase">Est. Waste</p>
<p class="text-3xl font-bold text-gray-800 mt-1"><span id="kpi-waste">0</span><span class="text-lg text-gray-500">kg</span></p>
</div>
<div class="bg-yellow-100 p-3 rounded-lg"><i class="fas fa-trash-alt text-yellow-600"></i></div>
</div>
</div>
</div>
<!-- Charts Row 1 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="bg-white rounded-xl shadow-md p-6">
<h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-chart-bar mr-2 text-blue-500"></i>Attendance vs Consumption (Last 7 Days)</h3>
<canvas id="trendChart" height="220"></canvas>
</div>
<div class="bg-white rounded-xl shadow-md p-6">
<h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-chart-pie mr-2 text-green-500"></i>Meal Period Breakdown</h3>
<canvas id="mealChart" height="220"></canvas>
</div>
</div>
<!-- Charts Row 2 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="bg-white rounded-xl shadow-md p-6">
<h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-building mr-2 text-purple-500"></i>Attendance by Class</h3>
<canvas id="classChart" height="220"></canvas>
</div>
<div class="bg-white rounded-xl shadow-md p-6">
<h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-layer-group mr-2 text-indigo-500"></i>Attendance by Form</h3>
<canvas id="formChart" height="220"></canvas>
</div>
</div>
<!-- Who Actually Ate -->
<div class="bg-white rounded-xl shadow-md p-6 mb-8">
<h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-check-double mr-2 text-green-500"></i>Who Actually Ate (Form B Records)</h3>
<div class="overflow-x-auto max-h-96 overflow-y-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50 sticky top-0">
<tr>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Meal</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Student</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Class</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Form</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Time</th>
</tr>
</thead>
<tbody id="ate-body" class="bg-white divide-y divide-gray-200"></tbody>
</table>
<p id="ate-empty" class="text-center py-8 text-gray-500 hidden">No consumption records found.</p>
</div>
</div>
<!-- No-Show Analysis -->
<div class="bg-white rounded-xl shadow-md p-6">
<h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-exclamation-triangle mr-2 text-red-500"></i>No-Show Analysis (Planned but Did Not Eat)</h3>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Meal</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Student</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Class</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Form</th>
</tr>
</thead>
<tbody id="noshow-body" class="bg-white divide-y divide-gray-200"></tbody>
</table>
<p id="noshow-empty" class="text-center py-8 text-gray-500 hidden">No no-shows detected — great job!</p>
</div>
</div>
<!-- Raw Data Summary -->
<div class="bg-white rounded-xl shadow-md p-6">
<h3 class="text-lg font-bold text-gray-800 mb-4"><i class="fas fa-database mr-2 text-gray-500"></i>Data Source Summary</h3>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
<div class="bg-gray-50 p-4 rounded-lg">
<p class="font-semibold text-gray-700">Form A Records</p>
<p class="text-2xl font-bold text-blue-600 mt-1" id="summary-formA">0</p>
<p class="text-gray-500">Students who want to eat</p>
</div>
<div class="bg-gray-50 p-4 rounded-lg">
<p class="font-semibold text-gray-700">Form B Records</p>
<p class="text-2xl font-bold text-green-600 mt-1" id="summary-formB">0</p>
<p class="text-gray-500">Students who have eaten</p>
</div>
<div class="bg-gray-50 p-4 rounded-lg">
<p class="font-semibold text-gray-700">Data Freshness</p>
<p class="text-2xl font-bold text-purple-600 mt-1" id="summary-fresh">--</p>
<p class="text-gray-500">Last updated</p>
</div>
</div>
</div>
</div>
<!-- Footer -->
<footer class="text-center text-gray-500 text-sm mt-12 pt-8 border-t border-gray-200">
<p>Data sourced live from GitHub repositories</p>
<p class="mt-1">Form A: SMSS-Waste-Less/Waste-LessV5 &middot; Form B: WaffleExecutors/Waste-LessV5</p>
</footer>
</div>
<script src="config.js"></script>
<script>
// Parse line-delimited JSON from GitHub file content
function parseLineJson(base64Content) {
try {
const text = atob(base64Content);
if (!text.trim()) return [];
return text.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0)
.map(line => {
try { return JSON.parse(line); }
catch (e) { return null; }
})
.filter(r => r !== null);
} catch (e) {
console.error('Parse error:', e);
return [];
}
}
async function fetchGitHubFile(repo, path) {
const url = `https://api.github.com/repos/${repo}/contents/${path}`;
const resp = await fetch(url, {
headers: {
'Authorization': `token ${GITHUB_CONFIG.TOKEN}`,
'Accept': 'application/vnd.github.v3+json'
}
});
if (resp.status === 404) return { records: [], sha: null, exists: false };
if (!resp.ok) throw new Error(`HTTP ${resp.status} for ${path}`);
const data = await resp.json();
return { records: parseLineJson(data.content), sha: data.sha, exists: true };
}
function getTodayStr() {
return new Date().toISOString().split('T')[0];
}
function getDateStr(ts) {
try { return new Date(ts).toISOString().split('T')[0]; }
catch (e) { return ''; }
}
function formatDate(ts) {
try {
const d = new Date(ts);
return d.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
} catch (e) { return ts; }
}
function formatTime(ts) {
try {
const d = new Date(ts);
return d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
} catch (e) { return ''; }
}
// 0.4kg estimated per no-show student
const WASTE_PER_NOSHOW = 0.4;
let charts = {};
function destroyCharts() {
Object.values(charts).forEach(c => c && c.destroy && c.destroy());
charts = {};
}
function renderTrendChart(dailyStats) {
const ctx = document.getElementById('trendChart').getContext('2d');
const labels = dailyStats.map(d => d.label);
const planned = dailyStats.map(d => d.planned);
const ate = dailyStats.map(d => d.ate);
charts.trend = new Chart(ctx, {
type: 'bar',
data: {
labels,
datasets: [
{ label: 'Planned (Form A)', data: planned, backgroundColor: 'rgba(59,130,246,0.7)', borderRadius: 6 },
{ label: 'Ate (Form B)', data: ate, backgroundColor: 'rgba(16,185,129,0.7)', borderRadius: 6 }
]
},
options: {
responsive: true,
plugins: { legend: { position: 'top' } },
scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
}
});
}
function renderMealChart(mealStats) {
const ctx = document.getElementById('mealChart').getContext('2d');
const meals = ['breakfast','lunch','dinner','supper'];
const labels = meals.map(m => m.charAt(0).toUpperCase() + m.slice(1));
const planned = meals.map(m => mealStats[m]?.planned || 0);
const ate = meals.map(m => mealStats[m]?.ate || 0);
charts.meal = new Chart(ctx, {
type: 'doughnut',
data: {
labels,
datasets: [{
label: 'Ate',
data: ate,
backgroundColor: [
'rgba(234,179,8,0.7)',
'rgba(22,163,74,0.7)',
'rgba(99,102,241,0.7)',
'rgba(168,85,247,0.7)'
],
borderWidth: 2,
borderColor: '#fff'
}]
},
options: {
responsive: true,
plugins: { legend: { position: 'bottom' } }
}
});
}
function renderClassChart(classStats) {
const ctx = document.getElementById('classChart').getContext('2d');
const classes = Object.keys(classStats).sort();
const ate = classes.map(c => classStats[c].ate);
charts.class = new Chart(ctx, {
type: 'bar',
data: {
labels: classes,
datasets: [{
label: 'Students Ate',
data: ate,
backgroundColor: 'rgba(139,92,246,0.7)',
borderRadius: 6
}]
},
options: {
responsive: true,
indexAxis: 'y',
plugins: { legend: { display: false } },
scales: { x: { beginAtZero: true, ticks: { precision: 0 } } }
}
});
}
function renderFormChart(formStats) {
const ctx = document.getElementById('formChart').getContext('2d');
const forms = Object.keys(formStats).sort((a,b) => parseInt(a)-parseInt(b));
const ate = forms.map(f => formStats[f].ate);
const planned = forms.map(f => formStats[f].planned);
charts.form = new Chart(ctx, {
type: 'bar',
data: {
labels: forms.map(f => `Form ${f}`),
datasets: [
{ label: 'Planned', data: planned, backgroundColor: 'rgba(59,130,246,0.6)', borderRadius: 6 },
{ label: 'Ate', data: ate, backgroundColor: 'rgba(16,185,129,0.6)', borderRadius: 6 }
]
},
options: {
responsive: true,
plugins: { legend: { position: 'top' } },
scales: { y: { beginAtZero: true, ticks: { precision: 0 } } }
}
});
}
async function loadData() {
const loading = document.getElementById('loading');
const dashboard = document.getElementById('dashboard');
const errorMsg = document.getElementById('error-msg');
const errorDetail = document.getElementById('error-detail');
loading.classList.remove('hidden');
dashboard.classList.add('hidden');
errorMsg.classList.add('hidden');
destroyCharts();
try {
const [formA, formB] = await Promise.all([
fetchGitHubFile(GITHUB_CONFIG.REPOS.ATTENDANCE, GITHUB_CONFIG.PATHS.FORM_A),
fetchGitHubFile(GITHUB_CONFIG.REPOS.CONSUMED, GITHUB_CONFIG.PATHS.FORM_B)
]);
const aRecords = formA.records;
const bRecords = formB.records;
const today = getTodayStr();
// Filter "yes" attendance from Form A (those who planned to eat)
const aYes = aRecords.filter(r => r.attendance === 'yes');
// All Form B records are "have eaten"
const bYes = bRecords;
// Today's stats
const aToday = aYes.filter(r => getDateStr(r.timestamp) === today);
const bToday = bYes.filter(r => getDateStr(r.timestamp) === today);
// No-shows: planned yes today but not in Form B today (match by name+class+form+meal)
const bTodayKeys = new Set(bToday.map(r => `${r.studentName}|${r.class}|${r.form}|${r.mealTime}`));
const noShows = aToday.filter(r => !bTodayKeys.has(`${r.studentName}|${r.class}|${r.form}|${r.mealTime}`));
// KPIs
document.getElementById('kpi-planned').textContent = aToday.length;
document.getElementById('kpi-ate').textContent = bToday.length;
document.getElementById('kpi-noshow').textContent = noShows.length;
document.getElementById('kpi-waste').textContent = (noShows.length * WASTE_PER_NOSHOW).toFixed(1);
// Daily stats for last 7 days
const last7 = [];
for (let i = 6; i >= 0; i--) {
const d = new Date(); d.setDate(d.getDate() - i);
const ds = d.toISOString().split('T')[0];
const aDay = aYes.filter(r => getDateStr(r.timestamp) === ds).length;
const bDay = bYes.filter(r => getDateStr(r.timestamp) === ds).length;
last7.push({
label: i === 0 ? 'Today' : d.toLocaleDateString('en-US', { weekday: 'short' }),
planned: aDay,
ate: bDay
});
}
renderTrendChart(last7);
// Meal stats (all time)
const mealStats = {};
['breakfast','lunch','dinner','supper'].forEach(m => mealStats[m] = { planned: 0, ate: 0 });
aYes.forEach(r => { if (mealStats[r.mealTime]) mealStats[r.mealTime].planned++; });
bYes.forEach(r => { if (mealStats[r.mealTime]) mealStats[r.mealTime].ate++; });
renderMealChart(mealStats);
// Class stats (all time)
const classStats = {};
bYes.forEach(r => {
if (!classStats[r.class]) classStats[r.class] = { planned: 0, ate: 0 };
classStats[r.class].ate++;
});
aYes.forEach(r => {
if (!classStats[r.class]) classStats[r.class] = { planned: 0, ate: 0 };
classStats[r.class].planned++;
});
renderClassChart(classStats);
// Form stats (all time)
const formStats = {};
bYes.forEach(r => {
if (!formStats[r.form]) formStats[r.form] = { planned: 0, ate: 0 };
formStats[r.form].ate++;
});
aYes.forEach(r => {
if (!formStats[r.form]) formStats[r.form] = { planned: 0, ate: 0 };
formStats[r.form].planned++;
});
renderFormChart(formStats);
// Who Actually Ate table
const ateTbody = document.getElementById('ate-body');
ateTbody.innerHTML = '';
const recentAte = bYes.slice().reverse().slice(0, 100);
if (recentAte.length === 0) {
document.getElementById('ate-empty').classList.remove('hidden');
} else {
document.getElementById('ate-empty').classList.add('hidden');
recentAte.forEach(r => {
const row = document.createElement('tr');
row.className = 'hover:bg-gray-50';
const d = r.date || getDateStr(r.timestamp);
row.innerHTML = `
<td class="px-4 py-2 text-sm text-gray-500">${d}</td>
<td class="px-4 py-2 text-sm"><span class="capitalize px-2 py-1 rounded bg-green-100 text-green-700 text-xs font-medium">${r.mealTime || '-'}</span></td>
<td class="px-4 py-2 text-sm font-medium text-gray-800">${r.studentName || 'Unknown'}</td>
<td class="px-4 py-2 text-sm text-gray-600">${r.class || '-'}</td>
<td class="px-4 py-2 text-sm text-gray-600">${r.form || '-'}</td>
<td class="px-4 py-2 text-sm text-gray-500">${formatTime(r.timestamp)}</td>
`;
ateTbody.appendChild(row);
});
}
// No-show table
const tbody = document.getElementById('noshow-body');
tbody.innerHTML = '';
if (noShows.length === 0) {
document.getElementById('noshow-empty').classList.remove('hidden');
} else {
document.getElementById('noshow-empty').classList.add('hidden');
noShows.slice(0, 50).forEach(r => {
const row = document.createElement('tr');
row.className = 'hover:bg-gray-50';
row.innerHTML = `
<td class="px-4 py-2 text-sm text-gray-700">${formatDate(r.timestamp)}</td>
<td class="px-4 py-2 text-sm"><span class="capitalize px-2 py-1 rounded bg-gray-100 text-gray-700 text-xs font-medium">${r.mealTime || '-'}</span></td>
<td class="px-4 py-2 text-sm font-medium text-gray-800">${r.studentName || 'Unknown'}</td>
<td class="px-4 py-2 text-sm text-gray-600">${r.class || '-'}</td>
<td class="px-4 py-2 text-sm text-gray-600">${r.form || '-'}</td>
`;
tbody.appendChild(row);
});
}
// Summary
document.getElementById('summary-formA').textContent = aRecords.length;
document.getElementById('summary-formB').textContent = bRecords.length;
document.getElementById('summary-fresh').textContent = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
loading.classList.add('hidden');
dashboard.classList.remove('hidden');
} catch (err) {
console.error(err);
loading.classList.add('hidden');
errorMsg.classList.remove('hidden');
errorDetail.textContent = err.message;
}
}
document.addEventListener('DOMContentLoaded', loadData);
</script>
</body>
</html>