energytracker / index.html
aaronxavier's picture
Modify
736c10e verified
Raw
History Blame Contribute Delete
27.9 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Energy Consumption Tracker</title>
<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">
<style>
.gradient-bg {
background: linear-gradient(135deg, #6b73ff 0%, #000dff 100%);
}
.reading-card:hover {
transform: translateY(-5px);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
.chart-container {
height: 300px;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}
.animate-pulse {
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- Header -->
<header class="gradient-bg text-white shadow-lg">
<div class="container mx-auto px-4 py-6">
<div class="flex justify-between items-center">
<div class="flex items-center space-x-3">
<i class="fas fa-bolt text-2xl"></i>
<h1 class="text-2xl font-bold">EnergyTracker</h1>
</div>
<div class="hidden md:flex space-x-6">
<a href="#" class="hover:text-blue-200 transition">Dashboard</a>
<a href="#" class="hover:text-blue-200 transition">History</a>
<a href="#" class="hover:text-blue-200 transition">Reports</a>
<a href="#" class="hover:text-blue-200 transition">Settings</a>
</div>
<button class="md:hidden text-xl">
<i class="fas fa-bars"></i>
</button>
</div>
</div>
</header>
<!-- Main Content -->
<main class="container mx-auto px-4 py-8">
<div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
<!-- Input Form -->
<div class="lg:col-span-1 bg-white rounded-xl shadow-md p-6">
<h2 class="text-xl font-semibold mb-4 text-gray-800">Add New Reading</h2>
<form id="readingForm" class="space-y-4">
<div>
<label for="readingDate" class="block text-sm font-medium text-gray-700 mb-1">Date</label>
<input type="date" id="readingDate" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" value="">
</div>
<div>
<label for="meterReading" class="block text-sm font-medium text-gray-700 mb-1">Meter Reading (kWh)</label>
<input type="number" step="0.01" id="meterReading" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="Enter current reading">
</div>
<div>
<label for="meterType" class="block text-sm font-medium text-gray-700 mb-1">Meter Type</label>
<select id="meterType" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
<option value="electricity">Electricity</option>
<option value="gas">Gas</option>
<option value="water">Water</option>
</select>
</div>
<div>
<label for="notes" class="block text-sm font-medium text-gray-700 mb-1">Notes</label>
<textarea id="notes" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500" placeholder="Any additional notes"></textarea>
</div>
<button type="submit" class="w-full gradient-bg text-white py-3 px-4 rounded-lg font-medium hover:opacity-90 transition flex items-center justify-center space-x-2">
<i class="fas fa-save"></i>
<span>Save Reading</span>
</button>
</form>
</div>
<!-- Dashboard -->
<div class="lg:col-span-2 space-y-6">
<!-- Summary Cards -->
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="bg-white rounded-xl shadow-md p-4 flex items-center">
<div class="p-3 rounded-full bg-blue-100 text-blue-600 mr-4">
<i class="fas fa-bolt text-xl"></i>
</div>
<div>
<p class="text-sm text-gray-500">Current Month</p>
<h3 class="text-xl font-semibold" id="currentMonthUsage">-- kWh</h3>
</div>
</div>
<div class="bg-white rounded-xl shadow-md p-4 flex items-center">
<div class="p-3 rounded-full bg-green-100 text-green-600 mr-4">
<i class="fas fa-chart-line text-xl"></i>
</div>
<div>
<p class="text-sm text-gray-500">Avg Daily Usage</p>
<h3 class="text-xl font-semibold" id="avgDailyUsage">-- kWh</h3>
</div>
</div>
<div class="bg-white rounded-xl shadow-md p-4 flex items-center">
<div class="p-3 rounded-full bg-purple-100 text-purple-600 mr-4">
<i class="fas fa-calendar-alt text-xl"></i>
</div>
<div>
<p class="text-sm text-gray-500">Projected Month</p>
<h3 class="text-xl font-semibold" id="projectedUsage">-- kWh</h3>
</div>
</div>
</div>
<!-- Chart -->
<div class="bg-white rounded-xl shadow-md p-6">
<div class="flex justify-between items-center mb-4">
<h2 class="text-lg font-semibold text-gray-800">Consumption Trend</h2>
<div class="flex space-x-2">
<button class="px-3 py-1 text-sm bg-blue-100 text-blue-600 rounded-lg">Monthly</button>
<button class="px-3 py-1 text-sm bg-gray-100 text-gray-600 rounded-lg">Yearly</button>
</div>
</div>
<div class="chart-container">
<canvas id="consumptionChart"></canvas>
</div>
</div>
<!-- Recent Readings -->
<div class="bg-white rounded-xl shadow-md p-6">
<h2 class="text-lg font-semibold text-gray-800 mb-4">Recent Readings</h2>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Reading</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Daily Avg</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
</tr>
</thead>
<tbody id="readingsTableBody" class="bg-white divide-y divide-gray-200">
<!-- Readings will be inserted here by JavaScript -->
<tr>
<td colspan="5" class="px-6 py-4 text-center text-gray-500">No readings yet. Add your first reading!</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</main>
<!-- Modal for editing -->
<div id="editModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden">
<div class="bg-white rounded-xl p-6 w-full max-w-md">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-semibold">Edit Reading</h3>
<button id="closeModal" class="text-gray-500 hover:text-gray-700">
<i class="fas fa-times"></i>
</button>
</div>
<form id="editForm" class="space-y-4">
<input type="hidden" id="editId">
<div>
<label for="editDate" class="block text-sm font-medium text-gray-700 mb-1">Date</label>
<input type="date" id="editDate" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
</div>
<div>
<label for="editReading" class="block text-sm font-medium text-gray-700 mb-1">Reading (kWh)</label>
<input type="number" step="0.01" id="editReading" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
</div>
<div>
<label for="editType" class="block text-sm font-medium text-gray-700 mb-1">Meter Type</label>
<select id="editType" class="w-full px-4 py-2 border border-gray-300 rounded-lg">
<option value="electricity">Electricity</option>
<option value="gas">Gas</option>
<option value="water">Water</option>
</select>
</div>
<div>
<label for="editNotes" class="block text-sm font-medium text-gray-700 mb-1">Notes</label>
<textarea id="editNotes" rows="3" class="w-full px-4 py-2 border border-gray-300 rounded-lg"></textarea>
</div>
<div class="flex justify-end space-x-3">
<button type="button" id="deleteReading" class="px-4 py-2 bg-red-100 text-red-600 rounded-lg hover:bg-red-200">Delete</button>
<button type="submit" class="px-4 py-2 gradient-bg text-white rounded-lg hover:opacity-90">Save Changes</button>
</div>
</form>
</div>
</div>
<!-- Loading overlay -->
<div id="loadingOverlay" class="fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center hidden">
<div class="bg-white p-8 rounded-xl text-center max-w-sm">
<div class="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-blue-500 mx-auto mb-4"></div>
<h3 class="text-lg font-medium text-gray-800">Processing Data</h3>
<p class="text-gray-600 mt-2">Calculating projections and updating dashboard...</p>
</div>
</div>
<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Initialize date field with current date
document.addEventListener('DOMContentLoaded', function() {
const today = new Date();
const formattedDate = today.toISOString().substr(0, 10);
document.getElementById('readingDate').value = formattedDate;
});
// Mock database using localStorage
const db = {
readings: JSON.parse(localStorage.getItem('energyReadings')) || [],
save: function() {
localStorage.setItem('energyReadings', JSON.stringify(this.readings));
},
addReading: function(reading) {
reading.id = Date.now().toString();
this.readings.push(reading);
this.save();
return reading;
},
updateReading: function(id, updatedData) {
const index = this.readings.findIndex(r => r.id === id);
if (index !== -1) {
this.readings[index] = {...this.readings[index], ...updatedData};
this.save();
return true;
}
return false;
},
deleteReading: function(id) {
const index = this.readings.findIndex(r => r.id === id);
if (index !== -1) {
this.readings.splice(index, 1);
this.save();
return true;
}
return false;
},
getReadings: function() {
return [...this.readings].sort((a, b) => new Date(b.date) - new Date(a.date));
},
getReadingsByMonth: function(month, year) {
return this.readings.filter(r => {
const d = new Date(r.date);
return d.getMonth() === month && d.getFullYear() === year;
}).sort((a, b) => new Date(a.date) - new Date(b.date));
}
};
// DOM Elements
const readingForm = document.getElementById('readingForm');
const readingsTableBody = document.getElementById('readingsTableBody');
const editModal = document.getElementById('editModal');
const closeModal = document.getElementById('closeModal');
const editForm = document.getElementById('editForm');
const deleteReadingBtn = document.getElementById('deleteReading');
const loadingOverlay = document.getElementById('loadingOverlay');
// Initialize Chart
let consumptionChart;
function initChart() {
const ctx = document.getElementById('consumptionChart').getContext('2d');
consumptionChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Energy Consumption (kWh)',
data: [],
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 2,
tension: 0.1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
// Format date for display
function formatDate(dateString) {
const options = { year: 'numeric', month: 'short', day: 'numeric' };
return new Date(dateString).toLocaleDateString(undefined, options);
}
// Calculate daily average
function calculateDailyAverage(reading, previousReading) {
if (!previousReading) return 0;
const date1 = new Date(previousReading.date);
const date2 = new Date(reading.date);
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
if (diffDays === 0) return 0;
return ((reading.value - previousReading.value) / diffDays).toFixed(2);
}
// Update dashboard metrics
function updateDashboard() {
const readings = db.getReadings();
if (readings.length === 0) return;
const currentDate = new Date();
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getFullYear();
// Get readings for current month
const monthReadings = db.getReadingsByMonth(currentMonth, currentYear);
if (monthReadings.length >= 2) {
const firstReading = monthReadings[0];
const lastReading = monthReadings[monthReadings.length - 1];
// Calculate days between first and last reading
const date1 = new Date(firstReading.date);
const date2 = new Date(lastReading.date);
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) || 1;
// Calculate total consumption and daily average
const totalConsumption = lastReading.value - firstReading.value;
const dailyAvg = (totalConsumption / diffDays).toFixed(2);
// Update metrics
document.getElementById('currentMonthUsage').textContent = `${totalConsumption.toFixed(2)} kWh`;
document.getElementById('avgDailyUsage').textContent = `${dailyAvg} kWh`;
// Projected monthly usage
const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
const projectedUsage = (dailyAvg * daysInMonth).toFixed(2);
document.getElementById('projectedUsage').textContent = `${projectedUsage} kWh`;
}
}
// Update chart data
function updateChart() {
const readings = db.getReadings();
if (readings.length >= 2) {
// Group readings by month and calculate monthly totals
const monthlyData = {};
readings.forEach(reading => {
const date = new Date(reading.date);
const monthYear = `${date.getFullYear()}-${date.getMonth()}`;
if (!monthlyData[monthYear]) {
monthlyData[monthYear] = {
date: new Date(date.getFullYear(), date.getMonth(), 1),
total: 0,
count: 0
};
}
monthlyData[monthYear].total += reading.value;
monthlyData[monthYear].count++;
});
// Calculate monthly averages
const chartLabels = [];
const chartData = [];
Object.keys(monthlyData).sort().forEach(key => {
const monthData = monthlyData[key];
const avg = monthData.total / monthData.count;
chartLabels.push(monthData.date.toLocaleDateString(undefined, { month: 'short', year: 'numeric' }));
chartData.push(avg);
});
// Update chart
if (consumptionChart) {
consumptionChart.data.labels = chartLabels;
consumptionChart.data.datasets[0].data = chartData;
consumptionChart.update();
}
}
}
// Render readings table
function renderReadingsTable() {
const readings = db.getReadings();
if (readings.length === 0) {
readingsTableBody.innerHTML = `
<tr>
<td colspan="5" class="px-6 py-4 text-center text-gray-500">No readings yet. Add your first reading!</td>
</tr>
`;
return;
}
let tableHTML = '';
for (let i = 0; i < readings.length; i++) {
const reading = readings[i];
const previousReading = i < readings.length - 1 ? readings[i + 1] : null;
const dailyAvg = calculateDailyAverage(reading, previousReading);
tableHTML += `
<tr class="hover:bg-gray-50">
<td class="px-6 py-4 whitespace-nowrap">${formatDate(reading.date)}</td>
<td class="px-6 py-4 whitespace-nowrap capitalize">${reading.type}</td>
<td class="px-6 py-4 whitespace-nowrap">${reading.value.toFixed(2)} kWh</td>
<td class="px-6 py-4 whitespace-nowrap">${dailyAvg} kWh/day</td>
<td class="px-6 py-4 whitespace-nowrap">
<button class="text-blue-600 hover:text-blue-800 mr-3 edit-btn" data-id="${reading.id}">
<i class="fas fa-edit"></i>
</button>
<button class="text-red-600 hover:text-red-800 delete-btn" data-id="${reading.id}">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
`;
}
readingsTableBody.innerHTML = tableHTML;
// Add event listeners to edit and delete buttons
document.querySelectorAll('.edit-btn').forEach(btn => {
btn.addEventListener('click', function() {
const id = this.getAttribute('data-id');
openEditModal(id);
});
});
document.querySelectorAll('.delete-btn').forEach(btn => {
btn.addEventListener('click', function() {
const id = this.getAttribute('data-id');
if (confirm('Are you sure you want to delete this reading?')) {
db.deleteReading(id);
renderReadingsTable();
updateDashboard();
updateChart();
}
});
});
}
// Open edit modal with reading data
function openEditModal(id) {
const reading = db.readings.find(r => r.id === id);
if (!reading) return;
document.getElementById('editId').value = reading.id;
document.getElementById('editDate').value = reading.date;
document.getElementById('editReading').value = reading.value;
document.getElementById('editType').value = reading.type;
document.getElementById('editNotes').value = reading.notes || '';
editModal.classList.remove('hidden');
}
// Close edit modal
function closeEditModal() {
editModal.classList.add('hidden');
}
// Initialize app
function initApp() {
initChart();
renderReadingsTable();
updateDashboard();
updateChart();
// Form submission for new reading
readingForm.addEventListener('submit', function(e) {
e.preventDefault();
const date = document.getElementById('readingDate').value;
const value = parseFloat(document.getElementById('meterReading').value);
const type = document.getElementById('meterType').value;
const notes = document.getElementById('notes').value;
if (!date || isNaN(value)) {
alert('Please enter a valid date and reading value');
return;
}
// Show loading overlay
loadingOverlay.classList.remove('hidden');
// Simulate processing delay
setTimeout(() => {
// Add new reading
db.addReading({
date,
value,
type,
notes
});
// Reset form (but keep current date)
document.getElementById('meterReading').value = '';
document.getElementById('notes').value = '';
document.getElementById('readingDate').value = new Date().toISOString().substr(0, 10);
// Update UI
renderReadingsTable();
updateDashboard();
updateChart();
// Hide loading overlay
loadingOverlay.classList.add('hidden');
}, 1000);
});
// Form submission for editing reading
editForm.addEventListener('submit', function(e) {
e.preventDefault();
const id = document.getElementById('editId').value;
const date = document.getElementById('editDate').value;
const value = parseFloat(document.getElementById('editReading').value);
const type = document.getElementById('editType').value;
const notes = document.getElementById('editNotes').value;
if (!date || isNaN(value)) {
alert('Please enter a valid date and reading value');
return;
}
db.updateReading(id, {
date,
value,
type,
notes
});
closeEditModal();
renderReadingsTable();
updateDashboard();
updateChart();
});
// Delete reading button
deleteReadingBtn.addEventListener('click', function() {
const id = document.getElementById('editId').value;
if (confirm('Are you sure you want to delete this reading?')) {
db.deleteReading(id);
closeEditModal();
renderReadingsTable();
updateDashboard();
updateChart();
}
});
// Close modal button
closeModal.addEventListener('click', closeEditModal);
}
// Start the app when DOM is loaded
document.addEventListener('DOMContentLoaded', initApp);
</script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=aaronxavier/energytracker" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>