// TeeTracker Application mit Firebase // ====================================== const App = { // Initialer Zustand state: { teaTypes: [], consumption: [], currentFilter: 'all', currentUser: null, loading: true }, // Initialisierung init() { this.bindEvents(); this.setupFirebaseAuth(); this.updateDate(); }, // Firebase Auth einrichten setupFirebaseAuth() { firebase.auth().onAuthStateChanged((user) => { if (user) { this.state.currentUser = user; this.loadUserData(); this.hideAuthSection(); this.showSignedInUI(); } else { this.state.currentUser = null; this.state.teaTypes = []; this.state.consumption = []; this.showAuthSection(); this.showSignedOutUI(); this.renderAll(); } }); }, // Benutzerdaten laden async loadUserData() { if (!this.state.currentUser) return; try { this.state.loading = true; // Teesorten laden const teaTypesSnapshot = await db .collection(`users/${this.state.currentUser.uid}/teaTypes`) .orderBy('name') .get(); this.state.teaTypes = teaTypesSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); // Konsumdaten laden const consumptionSnapshot = await db .collection(`users/${this.state.currentUser.uid}/consumption`) .orderBy('date', 'desc') .get(); this.state.consumption = consumptionSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); this.state.loading = false; this.renderAll(); // Echtzeit-Updates abonnieren this.setupRealtimeUpdates(); } catch (error) { console.error('Fehler beim Laden der Daten:', error); this.state.loading = false; this.showToast('Fehler beim Laden der Daten', 'error'); } }, // Echtzeit-Updates einrichten setupRealtimeUpdates() { if (!this.state.currentUser) return; // Teesorten-Updates db.collection(`users/${this.state.currentUser.uid}/teaTypes`) .orderBy('name') .onSnapshot((snapshot) => { this.state.teaTypes = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); this.renderTeaTypes(); this.renderTrackForm(); }); // Konsum-Updates db.collection(`users/${this.state.currentUser.uid}/consumption`) .orderBy('date', 'desc') .onSnapshot((snapshot) => { this.state.consumption = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); this.renderHistory(); this.renderStats(); this.renderCharts(); }); }, // Events binden bindEvents() { // Google Sign-In var el; el = document.getElementById('googleSignIn'); if (el) el.addEventListener('click', () => { this.signInWithGoogle(); }); // Sign Out el = document.getElementById('signOut'); if (el) el.addEventListener('click', () => { this.signOut(); }); // Formular für neue Teesorte el = document.getElementById('addTeaForm'); if (el) el.addEventListener('submit', (e) => { e.preventDefault(); this.addTeaType(); }); // Formular für Tracking el = document.getElementById('trackForm'); if (el) el.addEventListener('submit', (e) => { e.preventDefault(); this.trackConsumption(); }); // Filter-Buttons el = document.getElementById('filterToday'); if (el) el.addEventListener('click', () => { this.setFilter('today'); }); el = document.getElementById('filterWeek'); if (el) el.addEventListener('click', () => { this.setFilter('week'); }); el = document.getElementById('filterMonth'); if (el) el.addEventListener('click', () => { this.setFilter('month'); }); el = document.getElementById('filterAll'); if (el) el.addEventListener('click', () => { this.setFilter('all'); }); // Datum auf heute setzen el = document.getElementById('trackDate'); if (el) el.setAttribute('value', new Date().toISOString().split('T')[0]); }, // Google Sign-In signInWithGoogle() { const provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider) .then((result) => { this.showToast('Erfolgreich angemeldet!', 'success'); }) .catch((error) => { console.error('Anmeldung fehlgeschlagen:', error); this.showToast('Anmeldung fehlgeschlagen: ' + error.message, 'error'); }); }, // Sign Out signOut() { firebase.auth().signOut() .then(() => { this.showToast('Erfolgreich abgemeldet', 'success'); }) .catch((error) => { console.error('Abmeldung fehlgeschlagen:', error); this.showToast('Abmeldung fehlgeschlagen', 'error'); }); }, // Auth-Bereich verstecken hideAuthSection() { const authSection = document.getElementById('auth-section'); if (authSection) { authSection.classList.add('hidden'); } }, // Auth-Bereich anzeigen showAuthSection() { const authSection = document.getElementById('auth-section'); if (authSection) { authSection.classList.remove('hidden'); } }, // Angemeldete UI anzeigen showSignedInUI() { const signInBtn = document.getElementById('googleSignIn'); const signOutBtn = document.getElementById('signOut'); const authStatus = document.getElementById('auth-status'); if (signInBtn) signInBtn.classList.add('hidden'); if (signOutBtn) signOutBtn.classList.remove('hidden'); if (authStatus) { var u = this.state.currentUser; authStatus.innerHTML = 'Angemeldet als: ' + ((u && u.displayName) || (u && u.email) || '') + ''; } }, // Abgemeldete UI anzeigen showSignedOutUI() { const signInBtn = document.getElementById('googleSignIn'); const signOutBtn = document.getElementById('signOut'); const authStatus = document.getElementById('auth-status'); if (signInBtn) signInBtn.classList.remove('hidden'); if (signOutBtn) signOutBtn.classList.add('hidden'); if (authStatus) { authStatus.innerHTML = 'Nicht angemeldet'; } }, // 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 (element) { if (this.state.currentFilter === btn.filter) { element.classList.add('active'); } else { element.classList.remove('active'); } } }); }, // Neue Teesorte hinzufügen async addTeaType() { if (!this.state.currentUser) { this.showToast('Bitte melden Sie sich zuerst an', 'error'); return; } const nameInput = document.getElementById('teaName'); const colorInput = document.getElementById('teaColor'); const name = (nameInput && nameInput.value) ? nameInput.value.trim() : ''; const color = (colorInput && colorInput.value) ? colorInput.value : '#4CAF50'; 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; } try { const docRef = await db .collection(`users/${this.state.currentUser.uid}/teaTypes`) .add({ name: name, color: color, createdAt: firebase.firestore.FieldValue.serverTimestamp() }); nameInput.value = ''; colorInput.value = '#4CAF50'; this.showToast('Teesorte erfolgreich hinzugefügt', 'success'); } catch (error) { console.error('Fehler beim Hinzufügen der Teesorte:', error); this.showToast('Fehler beim Hinzufügen der Teesorte', 'error'); } }, // Teesorte entfernen async removeTeaType(teaId) { if (!this.state.currentUser) { this.showToast('Bitte melden Sie sich zuerst an', 'error'); return; } 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; } } try { // Konsumdaten bereinigen const consumptionRefs = await db .collection(`users/${this.state.currentUser.uid}/consumption`) .where('teaId', '==', teaId) .get(); const batch = db.batch(); consumptionRefs.forEach(doc => { batch.update(doc.ref, { teaName: '[Gelöschte Sorte]', teaId: null }); }); // Teesorte löschen const teaRef = db.collection(`users/${this.state.currentUser.uid}/teaTypes`).doc(teaId); batch.delete(teaRef); await batch.commit(); this.showToast('Teesorte entfernt', 'success'); } catch (error) { console.error('Fehler beim Entfernen der Teesorte:', error); this.showToast('Fehler beim Entfernen der Teesorte', 'error'); } }, // Konsum tracken async trackConsumption() { if (!this.state.currentUser) { this.showToast('Bitte melden Sie sich zuerst an', 'error'); return; } const dateInput = document.getElementById('trackDate'); const teaSelect = document.getElementById('trackTea'); const amountInput = document.getElementById('trackAmount'); const notesInput = document.getElementById('trackNotes'); const date = dateInput ? dateInput.value : ''; const teaId = teaSelect ? teaSelect.value : ''; const amount = parseInt((amountInput && amountInput.value) || '1') || 1; const notes = (notesInput && notesInput.value) ? notesInput.value.trim() : ''; // Brühzeit const brewTimeRadio = document.querySelector('input[name="brewTime"]:checked'); const brewTime = (brewTimeRadio && brewTimeRadio.value) ? brewTimeRadio.value : 'normal'; if (!date) { this.showToast('Bitte wählen Sie ein Datum aus', 'error'); return; } if (!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; } try { await db .collection(`users/${this.state.currentUser.uid}/consumption`) .add({ date: date, teaId: teaId, teaName: teaType.name, teaColor: teaType.color, brewTime: brewTime, amount: amount, notes: notes, createdAt: firebase.firestore.FieldValue.serverTimestamp() }); // Formular zurücksetzen dateInput.valueAsDate = new Date(); teaSelect.selectedIndex = 0; amountInput.value = 1; notesInput.value = ''; brewTimeRadio.checked = true; this.showToast('Tee-Konsum erfolgreich getrackt!', 'success'); } catch (error) { console.error('Fehler beim Tracken:', error); this.showToast('Fehler beim Tracken', 'error'); } }, // Konsum-Eintrag entfernen async removeConsumption(entryId) { if (!this.state.currentUser) { this.showToast('Bitte melden Sie sich zuerst an', 'error'); return; } if (!confirm('Möchten Sie diesen Eintrag wirklich entfernen?')) { return; } try { await db .collection(`users/${this.state.currentUser.uid}/consumption`) .doc(entryId) .delete(); this.showToast('Eintrag entfernt', 'success'); } catch (error) { console.error('Fehler beim Entfernen des Eintrags:', error); this.showToast('Fehler beim Entfernen des Eintrags', 'error'); } }, // Alle Render-Funktionen renderAll() { this.renderTeaTypes(); this.renderTrackForm(); this.renderHistory(); this.renderStats(); this.renderCharts(); }, // Teetypen rendern renderTeaTypes() { const teaList = document.getElementById('teaList'); if (!teaList) return; if (this.state.loading) { teaList.innerHTML = '
Daten werden geladen...
Keine Teesorten hinterlegt
Fügen Sie oben eine neue Teesorte hinzu
Bitte melden Sie sich an, um Ihre Teesorten zu sehen
Bitte melden Sie sich an, um Ihre Historie zu sehen
Keine Einträge gefunden
Tracken Sie Ihren ersten Tee!