Firebase-Integration für Multi-Device-Zugriff

- Firebase SDK hinzugefügt (Firestore & Auth)
- config.js mit Firebase-Konfigurationstemplate
- Google Sign-In für Benutzerauthentifizierung
- Daten werden jetzt in Firestore gespeichert (pro Benutzer)
- Echtzeit-Updates auf allen Geräten
- Datenstruktur: users/{uid}/teaTypes und users/{uid}/consumption
- Anleitung in config.js für die Einrichtung

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
wralto-user-1
2026-11-21 21:34:26 +01:00
parent ca2ec1ce9e
commit 83e6dcbdc9
4 changed files with 553 additions and 205 deletions

74
config.js Normal file
View File

@ -0,0 +1,74 @@
// Firebase Configuration
// ERSETZEN SIE DIESE WERTE MIT IHREN FIREBASE-KONFIGURATIONSDATEN
// Sie finden diese unter: Project Settings > General > Your apps > SDK setup and configuration
const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_SENDER_ID",
appId: "YOUR_APP_ID"
};
// ============================================
// ANLEITUNG ZUR EINRICHTUNG:
// ============================================
//
// 1. Gehen Sie zu https://console.firebase.google.com/
// 2. Klicken Sie auf "Projekt hinzufügen"
// - Geben Sie einen Projektnamen ein (z. B. "TeeTracker")
// - Akzeptieren Sie die Bedingungen
// 3. Aktivieren Sie Firestore Database:
// - Im linken Menü: "Firestore Database" auswählen
// - Klicken Sie auf "Datenbank erstellen"
// - Wählen Sie "Produktionsmodus" (für mehr Sicherheit) oder "Testmodus" (für Entwicklung)
// - Wählen Sie einen Standort (z. B. "europe-west1" für Europa)
// 4. Registrieren Sie Ihre Web-App:
// - Im linken Menü: Project Overview (Übersicht)
// - Klicken Sie auf "</>" (Web-Icon) unter "Get started by adding Firebase to your app"
// - Geben Sie einen App-Namen ein (z. B. "TeeTracker Web")
// - Klicken Sie auf "App registrieren"
// 5. Kopieren Sie die Konfigurationsdaten:
// - Sie sehen Code wie: const firebaseConfig = { ... };
// - Kopieren Sie diese Werte hierher (ersetzen Sie die Platzhalter oben)
//
// ============================================
// SICHERHEITSREGELN FÜR FIRESTORE:
// ============================================
//
// Gehen Sie zu: Firestore Database > Regeln
// Ersetzen Sie die Standardregeln durch:
//
/*
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Nur angemeldete Benutzer können lesen/schreiben
match /{document=**} {
allow read, write: if request.auth != null;
}
// Teesorten - jeder Benutzer hat seine eigenen
match /users/{userId}/teaTypes/{teaId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
// Konsumdaten - jeder Benutzer hat seine eigenen
match /users/{userId}/consumption/{consumptionId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
*/
//
// Klicken Sie auf "Veröffentlichen"
//
// ============================================
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
// Set timestamp field in Firestore
const timestamp = firebase.firestore.FieldValue.serverTimestamp;

View File

@ -5,6 +5,10 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TeeTracker</title> <title>TeeTracker</title>
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="styles.css">
<!-- Firebase SDK -->
<script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore-compat.js"></script>
<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head> </head>
<body> <body>
@ -15,6 +19,19 @@
</header> </header>
<main class="main-content"> <main class="main-content">
<!-- Firebase Login Section -->
<section id="auth-section" class="auth-section hidden">
<div class="auth-card">
<h2>🔐 Anmeldung</h2>
<p>Melden Sie sich an, um Ihre Daten auf allen Geraeten zu synchronisieren.</p>
<button id="googleSignIn" class="btn btn-primary google-btn">
<span class="google-icon">G</span> Mit Google anmelden
</button>
<button id="signOut" class="btn btn-secondary hidden">Abmelden</button>
<div id="auth-status" class="auth-status"></div>
</div>
</section>
<!-- Dashboard Section --> <!-- Dashboard Section -->
<section class="dashboard"> <section class="dashboard">
<h2>Dashboard</h2> <h2>Dashboard</h2>
@ -54,7 +71,7 @@
</div> </div>
<div class="chart-container full-width"> <div class="chart-container full-width">
<h3>Jährlicher Konsum nach Sorte</h3> <h3>Ja hrlicher Konsum nach Sorte</h3>
<canvas id="yearChart"></canvas> <canvas id="yearChart"></canvas>
</div> </div>
</section> </section>
@ -66,7 +83,7 @@
<form id="addTeaForm" class="add-form"> <form id="addTeaForm" class="add-form">
<input type="text" id="teaName" placeholder="Name der Teesorte" required> <input type="text" id="teaName" placeholder="Name der Teesorte" required>
<input type="color" id="teaColor" value="#4CAF50"> <input type="color" id="teaColor" value="#4CAF50">
<button type="submit" class="btn btn-primary">Hinzufügen</button> <button type="submit" class="btn btn-primary">Hinzufugen</button>
</form> </form>
<div id="teaList" class="tea-list"></div> <div id="teaList" class="tea-list"></div>
</div> </div>
@ -86,7 +103,7 @@
<select id="trackTea" required></select> <select id="trackTea" required></select>
</div> </div>
<div class="form-group"> <div class="form-group">
<label>Brühzeit:</label> <label>Bruhzeit:</label>
<div class="radio-group"> <div class="radio-group">
<label class="radio-label"> <label class="radio-label">
<input type="radio" name="brewTime" value="kurz" checked> <input type="radio" name="brewTime" value="kurz" checked>
@ -117,7 +134,7 @@
<!-- Consumption History Section --> <!-- Consumption History Section -->
<section class="history-section"> <section class="history-section">
<h2>📊 Letzte Einträge</h2> <h2>📊 Letzte Eintrage</h2>
<div class="history-controls"> <div class="history-controls">
<button id="filterToday" class="btn btn-secondary">Heute</button> <button id="filterToday" class="btn btn-secondary">Heute</button>
<button id="filterWeek" class="btn btn-secondary">Letzte 7 Tage</button> <button id="filterWeek" class="btn btn-secondary">Letzte 7 Tage</button>
@ -129,10 +146,12 @@
</main> </main>
<footer class="footer"> <footer class="footer">
<p>TeeTracker © <span id="current-year"></span> | Daten werden lokal gespeichert</p> <p>TeeTracker © <span id="current-year"></span> | Daten werden in Firebase gespeichert</p>
</footer> </footer>
</div> </div>
<!-- Firebase Configuration Template (wird durch config.js ersetzt) -->
<script src="config.js"></script>
<script src="script.js"></script> <script src="script.js"></script>
</body> </body>
</html> </html>

458
script.js
View File

@ -1,105 +1,224 @@
// TeeTracker Application // TeeTracker Application mit Firebase
// Datenmodell und Logik // ======================================
const App = { const App = {
// Initialer Zustand // Initialer Zustand
state: { state: {
teaTypes: [], teaTypes: [],
consumption: [], consumption: [],
currentFilter: 'all' currentFilter: 'all',
}, currentUser: null,
loading: true
// Storage Keys
storageKeys: {
teaTypes: 'teetracker_teaTypes',
consumption: 'teetracker_consumption'
}, },
// Initialisierung // Initialisierung
init() { init() {
this.loadData();
this.bindEvents(); this.bindEvents();
this.renderAll(); this.setupFirebaseAuth();
this.updateDate(); this.updateDate();
}, },
// Daten laden // Firebase Auth einrichten
loadData() { setupFirebaseAuth() {
const savedTeaTypes = localStorage.getItem(this.storageKeys.teaTypes); firebase.auth().onAuthStateChanged((user) => {
const savedConsumption = localStorage.getItem(this.storageKeys.consumption); if (user) {
this.state.currentUser = user;
if (savedTeaTypes) { this.loadUserData();
this.state.teaTypes = JSON.parse(savedTeaTypes); this.hideAuthSection();
this.showSignedInUI();
} else { } else {
// Standard-Teetypen this.state.currentUser = null;
this.state.teaTypes = [ this.state.teaTypes = [];
{ id: 1, name: 'Grüner Tee', color: '#4CAF50' }, this.state.consumption = [];
{ id: 2, name: 'Schwarzer Tee', color: '#795548' }, this.showAuthSection();
{ id: 3, name: 'Weißer Tee', color: '#E9E9E9' }, this.showSignedOutUI();
{ id: 4, name: 'Oolong Tee', color: '#FF9800' }, this.renderAll();
{ 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) { // Benutzerdaten laden
this.state.consumption = JSON.parse(savedConsumption); 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');
} }
// Alte Daten migrieren (falls nötig)
this.migrateData();
}, },
// Daten migrieren (für zukünftige Versionen) // Echtzeit-Updates einrichten
migrateData() { setupRealtimeUpdates() {
// Hier können Migrationen für ältere Datenformate hinzugefügt werden if (!this.state.currentUser) return;
},
// Daten speichern // Teesorten-Updates
saveTeaTypes() { db.collection(`users/${this.state.currentUser.uid}/teaTypes`)
localStorage.setItem(this.storageKeys.teaTypes, JSON.stringify(this.state.teaTypes)); .orderBy('name')
}, .onSnapshot((snapshot) => {
this.state.teaTypes = snapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
this.renderTeaTypes();
this.renderTrackForm();
});
saveConsumption() { // Konsum-Updates
localStorage.setItem(this.storageKeys.consumption, JSON.stringify(this.state.consumption)); 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 // Events binden
bindEvents() { bindEvents() {
// Google Sign-In
document.getElementById('googleSignIn')?.addEventListener('click', () => {
this.signInWithGoogle();
});
// Sign Out
document.getElementById('signOut')?.addEventListener('click', () => {
this.signOut();
});
// Formular für neue Teesorte // Formular für neue Teesorte
document.getElementById('addTeaForm').addEventListener('submit', (e) => { document.getElementById('addTeaForm')?.addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
this.addTeaType(); this.addTeaType();
}); });
// Formular für Tracking // Formular für Tracking
document.getElementById('trackForm').addEventListener('submit', (e) => { document.getElementById('trackForm')?.addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
this.trackConsumption(); this.trackConsumption();
}); });
// Filter-Buttons // Filter-Buttons
document.getElementById('filterToday').addEventListener('click', () => { document.getElementById('filterToday')?.addEventListener('click', () => {
this.setFilter('today'); this.setFilter('today');
}); });
document.getElementById('filterWeek').addEventListener('click', () => { document.getElementById('filterWeek')?.addEventListener('click', () => {
this.setFilter('week'); this.setFilter('week');
}); });
document.getElementById('filterMonth').addEventListener('click', () => { document.getElementById('filterMonth')?.addEventListener('click', () => {
this.setFilter('month'); this.setFilter('month');
}); });
document.getElementById('filterAll').addEventListener('click', () => { document.getElementById('filterAll')?.addEventListener('click', () => {
this.setFilter('all'); this.setFilter('all');
}); });
// Datum auf heute setzen // Datum auf heute setzen
document.getElementById('trackDate').valueAsDate = new Date(); document.getElementById('trackDate')?.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) {
authStatus.innerHTML = `<span style="color: #4CAF50">👤 Angemeldet als: ${this.state.currentUser?.displayName || this.state.currentUser?.email}</span>`;
}
},
// 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 = '<span style="color: #F44336">🔒 Nicht angemeldet</span>';
}
}, },
// Filter setzen // Filter setzen
@ -120,21 +239,28 @@ const App = {
buttons.forEach(btn => { buttons.forEach(btn => {
const element = document.getElementById(btn.id); const element = document.getElementById(btn.id);
if (element) {
if (this.state.currentFilter === btn.filter) { if (this.state.currentFilter === btn.filter) {
element.classList.add('active'); element.classList.add('active');
} else { } else {
element.classList.remove('active'); element.classList.remove('active');
} }
}
}); });
}, },
// Neue Teesorte hinzufügen // Neue Teesorte hinzufügen
addTeaType() { async addTeaType() {
if (!this.state.currentUser) {
this.showToast('Bitte melden Sie sich zuerst an', 'error');
return;
}
const nameInput = document.getElementById('teaName'); const nameInput = document.getElementById('teaName');
const colorInput = document.getElementById('teaColor'); const colorInput = document.getElementById('teaColor');
const name = nameInput.value.trim(); const name = nameInput?.value?.trim();
const color = colorInput.value; const color = colorInput?.value || '#4CAF50';
if (!name) { if (!name) {
this.showToast('Bitte geben Sie einen Namen für die Teesorte ein', 'error'); this.showToast('Bitte geben Sie einen Namen für die Teesorte ein', 'error');
@ -148,26 +274,32 @@ const App = {
return; return;
} }
const newTeaType = { try {
id: Date.now(), const docRef = await db
.collection(`users/${this.state.currentUser.uid}/teaTypes`)
.add({
name: name, name: name,
color: color color: color,
}; createdAt: timestamp()
});
this.state.teaTypes.push(newTeaType);
this.saveTeaTypes();
this.renderTeaTypes();
this.renderTrackForm();
this.renderCharts();
nameInput.value = ''; nameInput.value = '';
colorInput.value = '#4CAF50'; colorInput.value = '#4CAF50';
this.showToast('Teesorte erfolgreich hinzugefügt', 'success'); 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 // Teesorte entfernen
removeTeaType(teaId) { 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); const teaType = this.state.teaTypes.find(t => t.id === teaId);
if (!teaType) return; if (!teaType) return;
@ -180,49 +312,61 @@ const App = {
} }
} }
this.state.teaTypes = this.state.teaTypes.filter(t => t.id !== teaId); try {
// Konsumdaten bereinigen // Konsumdaten bereinigen
this.state.consumption = this.state.consumption.map(c => { const consumptionRefs = await db
if (c.teaId === teaId) { .collection(`users/${this.state.currentUser.uid}/consumption`)
c.teaId = null; .where('teaId', '==', teaId)
c.teaName = '[Gelöschte Sorte]'; .get();
}
return c; const batch = db.batch();
consumptionRefs.forEach(doc => {
batch.update(doc.ref, {
teaName: '[Gelöschte Sorte]',
teaId: null
});
}); });
this.saveTeaTypes(); // Teesorte löschen
this.saveConsumption(); const teaRef = db.collection(`users/${this.state.currentUser.uid}/teaTypes`).doc(teaId);
this.renderTeaTypes(); batch.delete(teaRef);
this.renderTrackForm();
this.renderHistory();
this.renderCharts();
await batch.commit();
this.showToast('Teesorte entfernt', 'success'); 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 // Konsum tracken
trackConsumption() { async trackConsumption() {
if (!this.state.currentUser) {
this.showToast('Bitte melden Sie sich zuerst an', 'error');
return;
}
const dateInput = document.getElementById('trackDate'); const dateInput = document.getElementById('trackDate');
const teaSelect = document.getElementById('trackTea'); const teaSelect = document.getElementById('trackTea');
const amountInput = document.getElementById('trackAmount'); const amountInput = document.getElementById('trackAmount');
const notesInput = document.getElementById('trackNotes'); const notesInput = document.getElementById('trackNotes');
const date = dateInput.value; const date = dateInput?.value;
const teaId = parseInt(teaSelect.value); const teaId = teaSelect?.value;
const amount = parseInt(amountInput.value) || 1; const amount = parseInt(amountInput?.value) || 1;
const notes = notesInput.value.trim(); const notes = notesInput?.value?.trim() || '';
// Brühzeit // Brühzeit
const brewTimeRadio = document.querySelector('input[name="brewTime"]:checked'); const brewTimeRadio = document.querySelector('input[name="brewTime"]:checked');
const brewTime = brewTimeRadio ? brewTimeRadio.value : 'normal'; const brewTime = brewTimeRadio?.value || 'normal';
if (!date) { if (!date) {
this.showToast('Bitte wählen Sie ein Datum aus', 'error'); this.showToast('Bitte wählen Sie ein Datum aus', 'error');
return; return;
} }
if (!teaId || isNaN(teaId)) { if (!teaId) {
this.showToast('Bitte wählen Sie eine Teesorte aus', 'error'); this.showToast('Bitte wählen Sie eine Teesorte aus', 'error');
return; return;
} }
@ -233,8 +377,10 @@ const App = {
return; return;
} }
const consumptionEntry = { try {
id: Date.now(), await db
.collection(`users/${this.state.currentUser.uid}/consumption`)
.add({
date: date, date: date,
teaId: teaId, teaId: teaId,
teaName: teaType.name, teaName: teaType.name,
@ -242,11 +388,8 @@ const App = {
brewTime: brewTime, brewTime: brewTime,
amount: amount, amount: amount,
notes: notes, notes: notes,
createdAt: new Date().toISOString() createdAt: timestamp()
}; });
this.state.consumption.push(consumptionEntry);
this.saveConsumption();
// Formular zurücksetzen // Formular zurücksetzen
dateInput.valueAsDate = new Date(); dateInput.valueAsDate = new Date();
@ -255,20 +398,37 @@ const App = {
notesInput.value = ''; notesInput.value = '';
brewTimeRadio.checked = true; brewTimeRadio.checked = true;
this.renderAll();
this.showToast('Tee-Konsum erfolgreich getrackt!', 'success'); this.showToast('Tee-Konsum erfolgreich getrackt!', 'success');
} catch (error) {
console.error('Fehler beim Tracken:', error);
this.showToast('Fehler beim Tracken', 'error');
}
}, },
// Konsum-Eintrag entfernen // Konsum-Eintrag entfernen
removeConsumption(entryId) { 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?')) { if (!confirm('Möchten Sie diesen Eintrag wirklich entfernen?')) {
return; return;
} }
this.state.consumption = this.state.consumption.filter(c => c.id !== entryId); try {
this.saveConsumption(); await db
this.renderAll(); .collection(`users/${this.state.currentUser.uid}/consumption`)
.doc(entryId)
.delete();
this.showToast('Eintrag entfernt', 'success'); 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 // Alle Render-Funktionen
@ -284,7 +444,14 @@ const App = {
renderTeaTypes() { renderTeaTypes() {
const teaList = document.getElementById('teaList'); const teaList = document.getElementById('teaList');
if (this.state.teaTypes.length === 0) { if (!teaList) return;
if (this.state.loading) {
teaList.innerHTML = '<div class="empty-state"><div class="icon">⏳</div><p>Daten werden geladen...</p></div>';
return;
}
if (this.state.teaTypes.length === 0 && this.state.currentUser) {
teaList.innerHTML = ` teaList.innerHTML = `
<div class="empty-state"> <div class="empty-state">
<div class="icon">🍃</div> <div class="icon">🍃</div>
@ -295,6 +462,16 @@ const App = {
return; return;
} }
if (!this.state.currentUser) {
teaList.innerHTML = `
<div class="empty-state">
<div class="icon">🔒</div>
<p>Bitte melden Sie sich an, um Ihre Teesorten zu sehen</p>
</div>
`;
return;
}
teaList.innerHTML = this.state.teaTypes.map(tea => ` teaList.innerHTML = this.state.teaTypes.map(tea => `
<div class="tea-item" data-tea-id="${tea.id}"> <div class="tea-item" data-tea-id="${tea.id}">
<div class="tea-info"> <div class="tea-info">
@ -302,7 +479,7 @@ const App = {
<span class="tea-name">${this.escapeHtml(tea.name)}</span> <span class="tea-name">${this.escapeHtml(tea.name)}</span>
</div> </div>
<div class="tea-actions"> <div class="tea-actions">
<button class="btn btn-danger btn-icon" onclick="App.removeTeaType(${tea.id})" <button class="btn btn-danger btn-icon" onclick="App.removeTeaType('${tea.id}')"
title="Entfernen">×</button> title="Entfernen">×</button>
</div> </div>
</div> </div>
@ -313,6 +490,18 @@ const App = {
renderTrackForm() { renderTrackForm() {
const teaSelect = document.getElementById('trackTea'); const teaSelect = document.getElementById('trackTea');
if (!teaSelect) return;
if (!this.state.currentUser) {
teaSelect.innerHTML = '<option value="" selected disabled>Bitte melden Sie sich an</option>';
return;
}
if (this.state.teaTypes.length === 0) {
teaSelect.innerHTML = '<option value="" selected disabled>Keine Teesorten verfügbar</option>';
return;
}
const options = this.state.teaTypes.map(tea => const options = this.state.teaTypes.map(tea =>
`<option value="${tea.id}" style="color: ${tea.color}">🎨 ${this.escapeHtml(tea.name)}</option>` `<option value="${tea.id}" style="color: ${tea.color}">🎨 ${this.escapeHtml(tea.name)}</option>`
); );
@ -327,6 +516,18 @@ const App = {
renderHistory() { renderHistory() {
const historyList = document.getElementById('historyList'); const historyList = document.getElementById('historyList');
if (!historyList) return;
if (!this.state.currentUser) {
historyList.innerHTML = `
<div class="empty-state">
<div class="icon">🔒</div>
<p>Bitte melden Sie sich an, um Ihre Historie zu sehen</p>
</div>
`;
return;
}
let filteredConsumption = [...this.state.consumption]; let filteredConsumption = [...this.state.consumption];
// Filter anwenden // Filter anwenden
@ -387,7 +588,7 @@ const App = {
</div> </div>
</div> </div>
<div class="entry-actions"> <div class="entry-actions">
<button class="btn btn-danger btn-icon" onclick="App.removeConsumption(${entry.id})" <button class="btn btn-danger btn-icon" onclick="App.removeConsumption('${entry.id}')"
title="Entfernen">×</button> title="Entfernen">×</button>
</div> </div>
</div> </div>
@ -397,6 +598,15 @@ const App = {
// Statistiken rendern // Statistiken rendern
renderStats() { renderStats() {
if (!this.state.currentUser) {
document.getElementById('today-count')?.textContent = '?';
document.getElementById('month-count')?.textContent = '?';
document.getElementById('year-count')?.textContent = '?';
document.getElementById('favorite-tea')?.textContent = '?';
document.getElementById('favorite-count')?.textContent = '?';
return;
}
const today = new Date().toISOString().split('T')[0]; const today = new Date().toISOString().split('T')[0];
const currentMonth = new Date().getMonth(); const currentMonth = new Date().getMonth();
const currentYear = new Date().getFullYear(); const currentYear = new Date().getFullYear();
@ -404,7 +614,7 @@ const App = {
// Heute // Heute
const todayConsumption = this.state.consumption.filter(c => c.date === today); const todayConsumption = this.state.consumption.filter(c => c.date === today);
const todayCount = todayConsumption.reduce((sum, c) => sum + c.amount, 0); const todayCount = todayConsumption.reduce((sum, c) => sum + c.amount, 0);
document.getElementById('today-count').textContent = todayCount; document.getElementById('today-count')?.textContent = todayCount;
// Dieser Monat // Dieser Monat
const monthConsumption = this.state.consumption.filter(c => { const monthConsumption = this.state.consumption.filter(c => {
@ -412,7 +622,7 @@ const App = {
return entryDate.getMonth() === currentMonth && entryDate.getFullYear() === currentYear; return entryDate.getMonth() === currentMonth && entryDate.getFullYear() === currentYear;
}); });
const monthCount = monthConsumption.reduce((sum, c) => sum + c.amount, 0); const monthCount = monthConsumption.reduce((sum, c) => sum + c.amount, 0);
document.getElementById('month-count').textContent = monthCount; document.getElementById('month-count')?.textContent = monthCount;
// Dieses Jahr // Dieses Jahr
const yearConsumption = this.state.consumption.filter(c => { const yearConsumption = this.state.consumption.filter(c => {
@ -420,7 +630,7 @@ const App = {
return entryDate.getFullYear() === currentYear; return entryDate.getFullYear() === currentYear;
}); });
const yearCount = yearConsumption.reduce((sum, c) => sum + c.amount, 0); const yearCount = yearConsumption.reduce((sum, c) => sum + c.amount, 0);
document.getElementById('year-count').textContent = yearCount; document.getElementById('year-count')?.textContent = yearCount;
// Lieblingssorte (meist konsumiert in diesem Jahr) // Lieblingssorte (meist konsumiert in diesem Jahr)
const yearTeaCounts = {}; const yearTeaCounts = {};
@ -431,21 +641,37 @@ const App = {
const sortedTeas = Object.entries(yearTeaCounts).sort((a, b) => b[1] - a[1]); const sortedTeas = Object.entries(yearTeaCounts).sort((a, b) => b[1] - a[1]);
if (sortedTeas.length > 0) { if (sortedTeas.length > 0) {
document.getElementById('favorite-tea').textContent = this.escapeHtml(sortedTeas[0][0]); document.getElementById('favorite-tea')?.textContent = this.escapeHtml(sortedTeas[0][0]);
document.getElementById('favorite-count').textContent = sortedTeas[0][1]; document.getElementById('favorite-count')?.textContent = sortedTeas[0][1];
} else { } else {
document.getElementById('favorite-tea').textContent = '-'; document.getElementById('favorite-tea')?.textContent = '-';
document.getElementById('favorite-count').textContent = '0'; document.getElementById('favorite-count')?.textContent = '0';
} }
}, },
// Charts rendern // Charts rendern
renderCharts() { renderCharts() {
if (!this.state.currentUser) {
// Charts leeren
this.clearCharts();
return;
}
this.renderTodayChart(); this.renderTodayChart();
this.renderMonthChart(); this.renderMonthChart();
this.renderYearChart(); this.renderYearChart();
}, },
// Charts leeren
clearCharts() {
['todayChart', 'monthChart', 'yearChart'].forEach(chartId => {
const ctx = document.getElementById(chartId);
if (ctx && this[chartId]) {
this[chartId].destroy();
this[chartId] = null;
}
});
},
// Heute-Chart // Heute-Chart
renderTodayChart() { renderTodayChart() {
const today = new Date().toISOString().split('T')[0]; const today = new Date().toISOString().split('T')[0];
@ -465,7 +691,9 @@ const App = {
const counts = Object.values(teaCounts); const counts = Object.values(teaCounts);
const colors = teaNames.map(name => teaColors[name]); const colors = teaNames.map(name => teaColors[name]);
const ctx = document.getElementById('todayChart').getContext('2d'); const ctx = document.getElementById('todayChart')?.getContext('2d');
if (!ctx) return;
// Zerstören Sie das vorherige Chart, falls vorhanden // Zerstören Sie das vorherige Chart, falls vorhanden
if (this.todayChart) { if (this.todayChart) {
@ -522,7 +750,9 @@ const App = {
const labels = Array.from({ length: daysInMonth }, (_, i) => (i + 1).toString()); const labels = Array.from({ length: daysInMonth }, (_, i) => (i + 1).toString());
const data = labels.map(day => dayCounts[parseInt(day)] || 0); const data = labels.map(day => dayCounts[parseInt(day)] || 0);
const ctx = document.getElementById('monthChart').getContext('2d'); const ctx = document.getElementById('monthChart')?.getContext('2d');
if (!ctx) return;
if (this.monthChart) { if (this.monthChart) {
this.monthChart.destroy(); this.monthChart.destroy();
@ -583,7 +813,9 @@ const App = {
const counts = Object.values(teaCounts); const counts = Object.values(teaCounts);
const colors = teaNames.map(name => teaColors[name]); const colors = teaNames.map(name => teaColors[name]);
const ctx = document.getElementById('yearChart').getContext('2d'); const ctx = document.getElementById('yearChart')?.getContext('2d');
if (!ctx) return;
if (this.yearChart) { if (this.yearChart) {
this.yearChart.destroy(); this.yearChart.destroy();

View File

@ -62,6 +62,72 @@ body {
gap: 30px; gap: 30px;
} }
/* Auth Section */
.auth-section {
background: var(--card-background);
border-radius: var(--border-radius);
padding: 25px;
box-shadow: var(--shadow);
text-align: center;
}
.auth-section.hidden {
display: none;
}
.auth-card {
max-width: 400px;
margin: 0 auto;
}
.auth-card h2 {
color: var(--primary-color);
margin-bottom: 15px;
font-size: 1.5rem;
}
.auth-card p {
color: var(--text-secondary);
margin-bottom: 20px;
}
.google-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
padding: 12px 20px;
font-size: 1rem;
background-color: #4285F4;
color: white;
border: none;
border-radius: var(--border-radius);
cursor: pointer;
transition: background-color 0.2s ease;
}
.google-btn:hover {
background-color: #3367D6;
}
.google-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
background-color: white;
color: #4285F4;
border-radius: 50%;
font-weight: bold;
}
.auth-status {
margin-top: 15px;
font-size: 0.9rem;
}
/* Sections */ /* Sections */
section { section {
background: var(--card-background); background: var(--card-background);
@ -299,6 +365,11 @@ section h2 {
background-color: #D32F2F; background-color: #D32F2F;
} }
/* Hidden class */
.hidden {
display: none !important;
}
/* Tea List */ /* Tea List */
.tea-list { .tea-list {
display: flex; display: flex;
@ -568,67 +639,19 @@ section h2 {
} }
} }
/* Modal */ /* Loading Spinner */
.modal { .loading-spinner {
display: none; display: inline-block;
position: fixed; width: 20px;
top: 0; height: 20px;
left: 0; border: 3px solid rgba(46, 125, 50, 0.3);
width: 100%; border-radius: 50%;
height: 100%; border-top-color: var(--primary-color);
background: rgba(0, 0, 0, 0.5); animation: spin 1s ease-in-out infinite;
z-index: 1000;
justify-content: center;
align-items: center;
} }
.modal.active { @keyframes spin {
display: flex; to {
} transform: rotate(360deg);
}
.modal-content {
background: var(--card-background);
border-radius: var(--border-radius);
padding: 25px;
max-width: 500px;
width: 90%;
max-height: 80vh;
overflow-y: auto;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 1px solid var(--border-color);
}
.modal-header h3 {
color: var(--primary-color);
margin: 0;
}
.modal-close {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: var(--text-secondary);
}
.modal-close:hover {
color: var(--text-primary);
}
.modal-body {
margin-bottom: 20px;
}
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 10px;
} }