// TeeTracker Application // Datenmodell und Logik const App = { // Initialer Zustand state: { teaTypes: [], consumption: [], currentFilter: 'all' }, // Storage Keys storageKeys: { teaTypes: 'teetracker_teaTypes', consumption: 'teetracker_consumption' }, // Initialisierung init() { this.loadData(); this.bindEvents(); this.renderAll(); this.updateDate(); }, // Daten laden loadData() { const savedTeaTypes = localStorage.getItem(this.storageKeys.teaTypes); const savedConsumption = localStorage.getItem(this.storageKeys.consumption); if (savedTeaTypes) { this.state.teaTypes = JSON.parse(savedTeaTypes); } else { // Standard-Teetypen this.state.teaTypes = [ { id: 1, name: 'Grüner Tee', color: '#4CAF50' }, { id: 2, name: 'Schwarzer Tee', color: '#795548' }, { id: 3, name: 'Weißer Tee', color: '#E9E9E9' }, { id: 4, name: 'Oolong Tee', color: '#FF9800' }, { id: 5, name: 'Kräutertee', color: '#9C27B0' }, { id: 6, name: 'Früchtetee', color: '#F44336' }, { id: 7, name: 'Chai', color: '#FF5722' }, { id: 8, name: 'Matcha', color: '#2E7D32' } ]; this.saveTeaTypes(); } if (savedConsumption) { this.state.consumption = JSON.parse(savedConsumption); } // Alte Daten migrieren (falls nötig) this.migrateData(); }, // Daten migrieren (für zukünftige Versionen) migrateData() { // Hier können Migrationen für ältere Datenformate hinzugefügt werden }, // Daten speichern saveTeaTypes() { localStorage.setItem(this.storageKeys.teaTypes, JSON.stringify(this.state.teaTypes)); }, saveConsumption() { localStorage.setItem(this.storageKeys.consumption, JSON.stringify(this.state.consumption)); }, // Events binden bindEvents() { // Formular für neue Teesorte document.getElementById('addTeaForm').addEventListener('submit', (e) => { e.preventDefault(); this.addTeaType(); }); // Formular für Tracking document.getElementById('trackForm').addEventListener('submit', (e) => { e.preventDefault(); this.trackConsumption(); }); // Filter-Buttons document.getElementById('filterToday').addEventListener('click', () => { this.setFilter('today'); }); document.getElementById('filterWeek').addEventListener('click', () => { this.setFilter('week'); }); document.getElementById('filterMonth').addEventListener('click', () => { this.setFilter('month'); }); document.getElementById('filterAll').addEventListener('click', () => { this.setFilter('all'); }); // Datum auf heute setzen document.getElementById('trackDate').valueAsDate = new Date(); }, // Filter setzen setFilter(filter) { this.state.currentFilter = filter; this.renderHistory(); this.updateFilterButtons(); }, // Filter-Buttons aktualisieren updateFilterButtons() { const buttons = [ { id: 'filterToday', filter: 'today' }, { id: 'filterWeek', filter: 'week' }, { id: 'filterMonth', filter: 'month' }, { id: 'filterAll', filter: 'all' } ]; buttons.forEach(btn => { const element = document.getElementById(btn.id); if (this.state.currentFilter === btn.filter) { element.classList.add('active'); } else { element.classList.remove('active'); } }); }, // Neue Teesorte hinzufügen addTeaType() { const nameInput = document.getElementById('teaName'); const colorInput = document.getElementById('teaColor'); const name = nameInput.value.trim(); const color = colorInput.value; if (!name) { this.showToast('Bitte geben Sie einen Namen für die Teesorte ein', 'error'); return; } // Prüfen, ob die Sorte bereits existiert const exists = this.state.teaTypes.some(t => t.name.toLowerCase() === name.toLowerCase()); if (exists) { this.showToast('Diese Teesorte existiert bereits', 'error'); return; } const newTeaType = { id: Date.now(), name: name, color: color }; this.state.teaTypes.push(newTeaType); this.saveTeaTypes(); this.renderTeaTypes(); this.renderTrackForm(); this.renderCharts(); nameInput.value = ''; colorInput.value = '#4CAF50'; this.showToast('Teesorte erfolgreich hinzugefügt', 'success'); }, // Teesorte entfernen removeTeaType(teaId) { const teaType = this.state.teaTypes.find(t => t.id === teaId); if (!teaType) return; // Prüfen, ob die Sorte in Konsumdaten verwendet wird const isUsed = this.state.consumption.some(c => c.teaId === teaId); if (isUsed) { if (!confirm('Diese Teesorte wird in Konsumdaten verwendet. Möchten Sie sie trotzdem entfernen?')) { return; } } this.state.teaTypes = this.state.teaTypes.filter(t => t.id !== teaId); // Konsumdaten bereinigen this.state.consumption = this.state.consumption.map(c => { if (c.teaId === teaId) { c.teaId = null; c.teaName = '[Gelöschte Sorte]'; } return c; }); this.saveTeaTypes(); this.saveConsumption(); this.renderTeaTypes(); this.renderTrackForm(); this.renderHistory(); this.renderCharts(); this.showToast('Teesorte entfernt', 'success'); }, // Konsum tracken trackConsumption() { const dateInput = document.getElementById('trackDate'); const teaSelect = document.getElementById('trackTea'); const amountInput = document.getElementById('trackAmount'); const notesInput = document.getElementById('trackNotes'); const date = dateInput.value; const teaId = parseInt(teaSelect.value); const amount = parseInt(amountInput.value) || 1; const notes = notesInput.value.trim(); // Brühzeit const brewTimeRadio = document.querySelector('input[name="brewTime"]:checked'); const brewTime = brewTimeRadio ? brewTimeRadio.value : 'normal'; if (!date) { this.showToast('Bitte wählen Sie ein Datum aus', 'error'); return; } if (!teaId || isNaN(teaId)) { this.showToast('Bitte wählen Sie eine Teesorte aus', 'error'); return; } const teaType = this.state.teaTypes.find(t => t.id === teaId); if (!teaType) { this.showToast('Ungültige Teesorte', 'error'); return; } const consumptionEntry = { id: Date.now(), date: date, teaId: teaId, teaName: teaType.name, teaColor: teaType.color, brewTime: brewTime, amount: amount, notes: notes, createdAt: new Date().toISOString() }; this.state.consumption.push(consumptionEntry); this.saveConsumption(); // Formular zurücksetzen dateInput.valueAsDate = new Date(); teaSelect.selectedIndex = 0; amountInput.value = 1; notesInput.value = ''; brewTimeRadio.checked = true; this.renderAll(); this.showToast('Tee-Konsum erfolgreich getrackt!', 'success'); }, // Konsum-Eintrag entfernen removeConsumption(entryId) { if (!confirm('Möchten Sie diesen Eintrag wirklich entfernen?')) { return; } this.state.consumption = this.state.consumption.filter(c => c.id !== entryId); this.saveConsumption(); this.renderAll(); this.showToast('Eintrag entfernt', 'success'); }, // Alle Render-Funktionen renderAll() { this.renderTeaTypes(); this.renderTrackForm(); this.renderHistory(); this.renderStats(); this.renderCharts(); }, // Teetypen rendern renderTeaTypes() { const teaList = document.getElementById('teaList'); if (this.state.teaTypes.length === 0) { teaList.innerHTML = `
🍃

Keine Teesorten hinterlegt

Fügen Sie oben eine neue Teesorte hinzu

`; return; } teaList.innerHTML = this.state.teaTypes.map(tea => `
${this.escapeHtml(tea.name)}
`).join(''); }, // Track-Formular rendern renderTrackForm() { const teaSelect = document.getElementById('trackTea'); const options = this.state.teaTypes.map(tea => `` ); // Standard-Option options.unshift(''); teaSelect.innerHTML = options.join(''); }, // Konsum-Historie rendern renderHistory() { const historyList = document.getElementById('historyList'); let filteredConsumption = [...this.state.consumption]; // Filter anwenden const today = new Date().toISOString().split('T')[0]; const weekAgo = new Date(); weekAgo.setDate(weekAgo.getDate() - 7); const weekAgoStr = weekAgo.toISOString().split('T')[0]; const monthAgo = new Date(); monthAgo.setMonth(monthAgo.getMonth() - 1); const monthAgoStr = monthAgo.toISOString().split('T')[0]; switch (this.state.currentFilter) { case 'today': filteredConsumption = filteredConsumption.filter(c => c.date === today); break; case 'week': filteredConsumption = filteredConsumption.filter(c => c.date >= weekAgoStr); break; case 'month': filteredConsumption = filteredConsumption.filter(c => c.date >= monthAgoStr); break; } // Sortieren nach Datum (neueste zuerst) filteredConsumption.sort((a, b) => new Date(b.date) - new Date(a.date)); if (filteredConsumption.length === 0) { historyList.innerHTML = `
☕

Keine Einträge gefunden

Tracken Sie Ihren ersten Tee!

`; return; } historyList.innerHTML = filteredConsumption.map(entry => { const date = new Date(entry.date); const dateStr = date.toLocaleDateString('de-DE', { weekday: 'short', day: '2-digit', month: '2-digit', year: 'numeric' }); const brewTimeLabel = this.getBrewTimeLabel(entry.brewTime); const brewTimeClass = entry.brewTime; return `
${entry.amount}x ${this.escapeHtml(entry.teaName)} ${brewTimeLabel} ${entry.notes ? `📝 ${this.escapeHtml(entry.notes)}` : ''}
`; }).join(''); }, // Statistiken rendern renderStats() { const today = new Date().toISOString().split('T')[0]; const currentMonth = new Date().getMonth(); const currentYear = new Date().getFullYear(); // Heute const todayConsumption = this.state.consumption.filter(c => c.date === today); const todayCount = todayConsumption.reduce((sum, c) => sum + c.amount, 0); document.getElementById('today-count').textContent = todayCount; // Dieser Monat const monthConsumption = this.state.consumption.filter(c => { const entryDate = new Date(c.date); return entryDate.getMonth() === currentMonth && entryDate.getFullYear() === currentYear; }); const monthCount = monthConsumption.reduce((sum, c) => sum + c.amount, 0); document.getElementById('month-count').textContent = monthCount; // Dieses Jahr const yearConsumption = this.state.consumption.filter(c => { const entryDate = new Date(c.date); return entryDate.getFullYear() === currentYear; }); const yearCount = yearConsumption.reduce((sum, c) => sum + c.amount, 0); document.getElementById('year-count').textContent = yearCount; // Lieblingssorte (meist konsumiert in diesem Jahr) const yearTeaCounts = {}; yearConsumption.forEach(c => { const teaName = c.teaName || 'Unbekannt'; yearTeaCounts[teaName] = (yearTeaCounts[teaName] || 0) + c.amount; }); const sortedTeas = Object.entries(yearTeaCounts).sort((a, b) => b[1] - a[1]); if (sortedTeas.length > 0) { document.getElementById('favorite-tea').textContent = this.escapeHtml(sortedTeas[0][0]); document.getElementById('favorite-count').textContent = sortedTeas[0][1]; } else { document.getElementById('favorite-tea').textContent = '-'; document.getElementById('favorite-count').textContent = '0'; } }, // Charts rendern renderCharts() { this.renderTodayChart(); this.renderMonthChart(); this.renderYearChart(); }, // Heute-Chart renderTodayChart() { const today = new Date().toISOString().split('T')[0]; const todayConsumption = this.state.consumption.filter(c => c.date === today); // Nach Teesorte gruppieren const teaCounts = {}; const teaColors = {}; todayConsumption.forEach(c => { const teaName = c.teaName || 'Unbekannt'; teaCounts[teaName] = (teaCounts[teaName] || 0) + c.amount; teaColors[teaName] = c.teaColor || '#CCCCCC'; }); const teaNames = Object.keys(teaCounts); const counts = Object.values(teaCounts); const colors = teaNames.map(name => teaColors[name]); const ctx = document.getElementById('todayChart').getContext('2d'); // Zerstören Sie das vorherige Chart, falls vorhanden if (this.todayChart) { this.todayChart.destroy(); } this.todayChart = new Chart(ctx, { type: 'doughnut', data: { labels: teaNames, datasets: [{ data: counts, backgroundColor: colors, borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { position: 'bottom', labels: { padding: 10, font: { size: 11 } } } } } }); }, // Monat-Chart renderMonthChart() { const currentMonth = new Date().getMonth(); const currentYear = new Date().getFullYear(); const monthConsumption = this.state.consumption.filter(c => { const entryDate = new Date(c.date); return entryDate.getMonth() === currentMonth && entryDate.getFullYear() === currentYear; }); // Nach Tag gruppieren const dayCounts = {}; monthConsumption.forEach(c => { const day = new Date(c.date).getDate(); dayCounts[day] = (dayCounts[day] || 0) + c.amount; }); // Alle Tage des Monats const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate(); const labels = Array.from({ length: daysInMonth }, (_, i) => (i + 1).toString()); const data = labels.map(day => dayCounts[parseInt(day)] || 0); const ctx = document.getElementById('monthChart').getContext('2d'); if (this.monthChart) { this.monthChart.destroy(); } this.monthChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Tassen pro Tag', data: data, backgroundColor: 'rgba(76, 175, 80, 0.7)', borderColor: 'rgba(76, 175, 80, 1)', borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } } } }); }, // Jahr-Chart renderYearChart() { const currentYear = new Date().getFullYear(); const yearConsumption = this.state.consumption.filter(c => { const entryDate = new Date(c.date); return entryDate.getFullYear() === currentYear; }); // Nach Teesorte gruppieren const teaCounts = {}; const teaColors = {}; yearConsumption.forEach(c => { const teaName = c.teaName || 'Unbekannt'; teaCounts[teaName] = (teaCounts[teaName] || 0) + c.amount; teaColors[teaName] = c.teaColor || '#CCCCCC'; }); const teaNames = Object.keys(teaCounts); const counts = Object.values(teaCounts); const colors = teaNames.map(name => teaColors[name]); const ctx = document.getElementById('yearChart').getContext('2d'); if (this.yearChart) { this.yearChart.destroy(); } this.yearChart = new Chart(ctx, { type: 'bar', data: { labels: teaNames, datasets: [{ label: 'Tassen', data: counts, backgroundColor: colors, borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: true, indexAxis: 'y', plugins: { legend: { display: false } }, scales: { x: { beginAtZero: true, ticks: { stepSize: 1 } } } } }); }, // Brühzeit-Label getBrewTimeLabel(brewTime) { const labels = { 'kurz': 'Kurz', 'normal': 'Normal', 'lang': 'Lang' }; return labels[brewTime] || brewTime; }, // HTML escape escapeHtml(text) { if (!text) return ''; const div = document.createElement('div'); div.textContent = text; return div.innerHTML; }, // Toast-Nachricht anzeigen showToast(message, type = 'success') { // Entferne bestehende Toasts const existingToast = document.querySelector('.toast'); if (existingToast) { existingToast.remove(); } const toast = document.createElement('div'); toast.className = `toast ${type}`; toast.textContent = message; document.body.appendChild(toast); setTimeout(() => { toast.style.animation = 'slideIn 0.3s ease-out reverse'; setTimeout(() => { toast.remove(); }, 300); }, 3000); }, // Datum aktualisieren (Fußzeile) updateDate() { const yearSpan = document.getElementById('current-year'); if (yearSpan) { yearSpan.textContent = new Date().getFullYear(); } } }; // Initialisierung beim Laden der Seite document.addEventListener('DOMContentLoaded', () => { App.init(); });