diff --git a/script.js b/script.js index 0d33734..1e305f1 100644 --- a/script.js +++ b/script.js @@ -1,7 +1,7 @@ -// TeeTracker Application mit Firebase (Browser-kompatibel) -// ===================================================== +// TeeTracker Application mit Firebase +// ====================================== -var App = { +const App = { // Initialer Zustand state: { teaTypes: [], @@ -12,235 +12,228 @@ var App = { }, // Initialisierung - init: function() { + init() { this.bindEvents(); this.setupFirebaseAuth(); this.updateDate(); }, // Firebase Auth einrichten - setupFirebaseAuth: function() { - var self = this; - firebase.auth().onAuthStateChanged(function(user) { + setupFirebaseAuth() { + firebase.auth().onAuthStateChanged((user) => { if (user) { - self.state.currentUser = user; - self.loadUserData(); - self.hideAuthSection(); - self.showSignedInUI(); + this.state.currentUser = user; + this.loadUserData(); + this.hideAuthSection(); + this.showSignedInUI(); } else { - self.state.currentUser = null; - self.state.teaTypes = []; - self.state.consumption = []; - self.showAuthSection(); - self.showSignedOutUI(); - self.renderAll(); + this.state.currentUser = null; + this.state.teaTypes = []; + this.state.consumption = []; + this.showAuthSection(); + this.showSignedOutUI(); + this.renderAll(); } }); }, // Benutzerdaten laden - loadUserData: function() { - var self = this; + async loadUserData() { if (!this.state.currentUser) return; - this.state.loading = true; + 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() + })); - // Teesorten laden - db.collection('users/' + this.state.currentUser.uid + '/teaTypes') - .orderBy('name') - .get() - .then(function(snapshot) { - self.state.teaTypes = snapshot.docs.map(function(doc) { - return { id: doc.id, name: doc.data().name, color: doc.data().color }; - }); - return db.collection('users/' + self.state.currentUser.uid + '/consumption') - .orderBy('date', 'desc') - .get(); - }) - .then(function(snapshot) { - self.state.consumption = snapshot.docs.map(function(doc) { - return { - id: doc.id, - date: doc.data().date, - teaId: doc.data().teaId, - teaName: doc.data().teaName, - teaColor: doc.data().teaColor, - brewTime: doc.data().brewTime, - amount: doc.data().amount, - notes: doc.data().notes - }; - }); - self.state.loading = false; - self.renderAll(); - self.setupRealtimeUpdates(); - }) - .catch(function(error) { - console.error('Fehler beim Laden der Daten:', error); - self.state.loading = false; - self.showToast('Fehler beim Laden der Daten', 'error'); - }); + // 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: function() { - var self = this; + setupRealtimeUpdates() { if (!this.state.currentUser) return; // Teesorten-Updates - db.collection('users/' + this.state.currentUser.uid + '/teaTypes') + db.collection(`users/${this.state.currentUser.uid}/teaTypes`) .orderBy('name') - .onSnapshot(function(snapshot) { - self.state.teaTypes = snapshot.docs.map(function(doc) { - return { id: doc.id, name: doc.data().name, color: doc.data().color }; - }); - self.renderTeaTypes(); - self.renderTrackForm(); + .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') + db.collection(`users/${this.state.currentUser.uid}/consumption`) .orderBy('date', 'desc') - .onSnapshot(function(snapshot) { - self.state.consumption = snapshot.docs.map(function(doc) { - return { - id: doc.id, - date: doc.data().date, - teaId: doc.data().teaId, - teaName: doc.data().teaName, - teaColor: doc.data().teaColor, - brewTime: doc.data().brewTime, - amount: doc.data().amount, - notes: doc.data().notes - }; - }); - self.renderHistory(); - self.renderStats(); - self.renderCharts(); + .onSnapshot((snapshot) => { + this.state.consumption = snapshot.docs.map(doc => ({ + id: doc.id, + ...doc.data() + })); + this.renderHistory(); + this.renderStats(); + this.renderCharts(); }); }, // Events binden - bindEvents: function() { - var self = this; - + bindEvents() { // Google Sign-In - var googleSignIn = document.getElementById('googleSignIn'); - if (googleSignIn) { - googleSignIn.addEventListener('click', function() { - self.signInWithGoogle(); - }); - } + var el; + el = document.getElementById('googleSignIn'); + if (el) el.addEventListener('click', () => { this.signInWithGoogle(); }); // Sign Out - var signOut = document.getElementById('signOut'); - if (signOut) { - signOut.addEventListener('click', function() { - self.signOut(); - }); - } + el = document.getElementById('signOut'); + if (el) el.addEventListener('click', () => { this.signOut(); }); // Formular für neue Teesorte - var addTeaForm = document.getElementById('addTeaForm'); - if (addTeaForm) { - addTeaForm.addEventListener('submit', function(e) { - e.preventDefault(); - self.addTeaType(); - }); - } + el = document.getElementById('addTeaForm'); + if (el) el.addEventListener('submit', (e) => { e.preventDefault(); this.addTeaType(); }); // Formular für Tracking - var trackForm = document.getElementById('trackForm'); - if (trackForm) { - trackForm.addEventListener('submit', function(e) { - e.preventDefault(); - self.trackConsumption(); - }); - } + el = document.getElementById('trackForm'); + if (el) el.addEventListener('submit', (e) => { e.preventDefault(); this.trackConsumption(); }); // Filter-Buttons - var filterToday = document.getElementById('filterToday'); - if (filterToday) { - filterToday.addEventListener('click', function() { - self.setFilter('today'); - }); - } + el = document.getElementById('filterToday'); + if (el) el.addEventListener('click', () => { this.setFilter('today'); }); - var filterWeek = document.getElementById('filterWeek'); - if (filterWeek) { - filterWeek.addEventListener('click', function() { - self.setFilter('week'); - }); - } + el = document.getElementById('filterWeek'); + if (el) el.addEventListener('click', () => { this.setFilter('week'); }); - var filterMonth = document.getElementById('filterMonth'); - if (filterMonth) { - filterMonth.addEventListener('click', function() { - self.setFilter('month'); - }); - } + el = document.getElementById('filterMonth'); + if (el) el.addEventListener('click', () => { this.setFilter('month'); }); - var filterAll = document.getElementById('filterAll'); - if (filterAll) { - filterAll.addEventListener('click', function() { - self.setFilter('all'); - }); - } + el = document.getElementById('filterAll'); + if (el) el.addEventListener('click', () => { this.setFilter('all'); }); // Datum auf heute setzen - var trackDate = document.getElementById('trackDate'); - if (trackDate) { - trackDate.value = new Date().toISOString().split('T')[0]; - } + el = document.getElementById('trackDate'); + if (el) el.setAttribute('value', new Date().toISOString().split('T')[0]); }, // Google Sign-In - signInWithGoogle: function() { - var self = this; - var provider = new firebase.auth.GoogleAuthProvider(); + signInWithGoogle() { + const provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider) - .then(function() { - self.showToast('Erfolgreich angemeldet!', 'success'); + .then((result) => { + this.showToast('Erfolgreich angemeldet!', 'success'); }) - .catch(function(error) { + .catch((error) => { console.error('Anmeldung fehlgeschlagen:', error); - self.showToast('Anmeldung fehlgeschlagen: ' + error.message, 'error'); + this.showToast('Anmeldung fehlgeschlagen: ' + error.message, 'error'); }); }, // Sign Out - signOut: function() { - var self = this; + signOut() { firebase.auth().signOut() - .then(function() { - self.showToast('Erfolgreich abgemeldet', 'success'); + .then(() => { + this.showToast('Erfolgreich abgemeldet', 'success'); }) - .catch(function(error) { + .catch((error) => { console.error('Abmeldung fehlgeschlagen:', error); - self.showToast('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: function(filter) { + setFilter(filter) { this.state.currentFilter = filter; this.renderHistory(); this.updateFilterButtons(); }, // Filter-Buttons aktualisieren - updateFilterButtons: function() { - var buttons = [ + updateFilterButtons() { + const buttons = [ { id: 'filterToday', filter: 'today' }, { id: 'filterWeek', filter: 'week' }, { id: 'filterMonth', filter: 'month' }, { id: 'filterAll', filter: 'all' } ]; - var self = this; - buttons.forEach(function(btn) { - var element = document.getElementById(btn.id); + buttons.forEach(btn => { + const element = document.getElementById(btn.id); if (element) { - if (self.state.currentFilter === btn.filter) { + if (this.state.currentFilter === btn.filter) { element.classList.add('active'); } else { element.classList.remove('active'); @@ -250,17 +243,17 @@ var App = { }, // Neue Teesorte hinzufügen - addTeaType: function() { + async addTeaType() { if (!this.state.currentUser) { this.showToast('Bitte melden Sie sich zuerst an', 'error'); return; } - var nameInput = document.getElementById('teaName'); - var colorInput = document.getElementById('teaColor'); + const nameInput = document.getElementById('teaName'); + const colorInput = document.getElementById('teaColor'); - var name = nameInput ? nameInput.value.trim() : ''; - var color = colorInput ? colorInput.value : '#4CAF50'; + 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'); @@ -268,117 +261,98 @@ var App = { } // Prüfen, ob die Sorte bereits existiert - var exists = false; - for (var i = 0; i < this.state.teaTypes.length; i++) { - if (this.state.teaTypes[i].name.toLowerCase() === name.toLowerCase()) { - exists = true; - break; - } - } + const exists = this.state.teaTypes.some(t => t.name.toLowerCase() === name.toLowerCase()); if (exists) { this.showToast('Diese Teesorte existiert bereits', 'error'); return; } - var self = this; - db.collection('users/' + this.state.currentUser.uid + '/teaTypes') - .add({ - name: name, - color: color, - createdAt: firebase.firestore.FieldValue.serverTimestamp() - }) - .then(function() { - if (nameInput) nameInput.value = ''; - if (colorInput) colorInput.value = '#4CAF50'; - self.showToast('Teesorte erfolgreich hinzugefügt', 'success'); - }) - .catch(function(error) { - console.error('Fehler beim Hinzufügen der Teesorte:', error); - self.showToast('Fehler beim Hinzufügen der Teesorte', 'error'); - }); + 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 - removeTeaType: function(teaId) { + async removeTeaType(teaId) { if (!this.state.currentUser) { this.showToast('Bitte melden Sie sich zuerst an', 'error'); return; } - var teaType = null; - for (var i = 0; i < this.state.teaTypes.length; i++) { - if (this.state.teaTypes[i].id === teaId) { - teaType = this.state.teaTypes[i]; - break; - } - } + const teaType = this.state.teaTypes.find(t => t.id === teaId); if (!teaType) return; // Prüfen, ob die Sorte in Konsumdaten verwendet wird - var isUsed = false; - for (var i = 0; i < this.state.consumption.length; i++) { - if (this.state.consumption[i].teaId === teaId) { - isUsed = true; - break; - } - } - + 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; } } - var self = this; - var batch = db.batch(); + try { + // Konsumdaten bereinigen + const consumptionRefs = await db + .collection(`users/${this.state.currentUser.uid}/consumption`) + .where('teaId', '==', teaId) + .get(); - // Konsumdaten bereinigen - db.collection('users/' + this.state.currentUser.uid + '/consumption') - .where('teaId', '==', teaId) - .get() - .then(function(snapshot) { - snapshot.forEach(function(doc) { - batch.update(doc.ref, { - teaName: '[Gelöschte Sorte]', - teaId: null - }); + const batch = db.batch(); + consumptionRefs.forEach(doc => { + batch.update(doc.ref, { + teaName: '[Gelöschte Sorte]', + teaId: null }); - - // Teesorte löschen - var teaRef = db.collection('users/' + self.state.currentUser.uid + '/teaTypes').doc(teaId); - batch.delete(teaRef); - - return batch.commit(); - }) - .then(function() { - self.showToast('Teesorte entfernt', 'success'); - }) - .catch(function(error) { - console.error('Fehler beim Entfernen der Teesorte:', error); - self.showToast('Fehler beim Entfernen der Teesorte', 'error'); }); + + // 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 - trackConsumption: function() { + async trackConsumption() { if (!this.state.currentUser) { this.showToast('Bitte melden Sie sich zuerst an', 'error'); return; } - var dateInput = document.getElementById('trackDate'); - var teaSelect = document.getElementById('trackTea'); - var amountInput = document.getElementById('trackAmount'); - var notesInput = document.getElementById('trackNotes'); + const dateInput = document.getElementById('trackDate'); + const teaSelect = document.getElementById('trackTea'); + const amountInput = document.getElementById('trackAmount'); + const notesInput = document.getElementById('trackNotes'); - var date = dateInput ? dateInput.value : ''; - var teaId = teaSelect ? teaSelect.value : ''; - var amount = amountInput ? parseInt(amountInput.value) || 1 : 1; - var notes = notesInput ? notesInput.value.trim() : ''; + 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 - var brewTimeRadio = document.querySelector('input[name="brewTime"]:checked'); - var brewTime = brewTimeRadio ? brewTimeRadio.value : 'normal'; + 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'); @@ -390,46 +364,43 @@ var App = { return; } - var teaType = null; - for (var i = 0; i < this.state.teaTypes.length; i++) { - if (this.state.teaTypes[i].id === teaId) { - teaType = this.state.teaTypes[i]; - break; - } - } + const teaType = this.state.teaTypes.find(t => t.id === teaId); if (!teaType) { this.showToast('Ungültige Teesorte', 'error'); return; } - var self = this; - 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() - }) - .then(function() { - if (dateInput) dateInput.valueAsDate = new Date(); - if (teaSelect) teaSelect.selectedIndex = 0; - if (amountInput) amountInput.value = 1; - if (notesInput) notesInput.value = ''; - if (brewTimeRadio) brewTimeRadio.checked = true; - self.showToast('Tee-Konsum erfolgreich getrackt!', 'success'); - }) - .catch(function(error) { - console.error('Fehler beim Tracken:', error); - self.showToast('Fehler beim Tracken', 'error'); - }); + 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 - removeConsumption: function(entryId) { + async removeConsumption(entryId) { if (!this.state.currentUser) { this.showToast('Bitte melden Sie sich zuerst an', 'error'); return; @@ -439,230 +410,245 @@ var App = { return; } - var self = this; - db.collection('users/' + this.state.currentUser.uid + '/consumption') - .doc(entryId) - .delete() - .then(function() { - self.showToast('Eintrag entfernt', 'success'); - }) - .catch(function(error) { - console.error('Fehler beim Entfernen des Eintrags:', error); - self.showToast('Fehler beim Entfernen des Eintrags', 'error'); - }); + 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: function() { - var teaList = document.getElementById('teaList'); + renderTeaTypes() { + const teaList = document.getElementById('teaList'); if (!teaList) return; if (this.state.loading) { - teaList.innerHTML = '
Daten werden geladen...
Daten werden geladen...
Keine Teesorten hinterlegt
Add a new tea type above
Keine Teesorten hinterlegt
+Fügen Sie oben eine neue Teesorte hinzu
+Please log in to see your tea types
Bitte melden Sie sich an, um Ihre Teesorten zu sehen
+Please log in to see your history
Bitte melden Sie sich an, um Ihre Historie zu sehen
+No entries found
Track your first tea!
Keine Einträge gefunden
+Tracken Sie Ihren ersten Tee!
+