Files
elo-rezept-rechner/src/templates/index.html
moerp 43b74dc3c2
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
style
2024-04-04 13:29:03 +02:00

302 lines
13 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Elo's Rezept Rechner</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<link rel="shortcut icon" href="../static/images/favicon.ico">
<script>
document.addEventListener('DOMContentLoaded', function() {
cleanUpLocalStorage();
restoreTableFromLocalStorage();
updateTotalNutrition();
fetch('/get_products')
.then(response => response.json())
.then(data => {
const productList = document.getElementById('products');
data.products.forEach(product => {
const option = document.createElement('option');
option.value = product;
productList.appendChild(option);
});
});
const table = document.getElementById('nutrition-table');
table.addEventListener('click', function(e) {
if (e.target.tagName === 'TD') {
// Toggle der Auswahlklasse
e.target.parentNode.classList.toggle('selected');
updateRemoveButtonState();
}
});
});
function recalculateTableBasedOnPortions() {
const portions = parseInt(document.getElementById('portions').value, 10) || 1;
let entries = JSON.parse(localStorage.getItem('nutritionEntries')) || [];
entries.forEach((entry, index) => {
const newWeight = Math.ceil(entry.weight / portions);
// Da die Server-Anfrage möglicherweise nicht sofort antwortet, passen wir den Index an, um die korrekte Zeile zu aktualisieren.
fetchUpdatedNutrition(entry.food, newWeight, index + 1); // +1, um den Kopfzeilenindex zu überspringen
});
}
function fetchUpdatedNutrition(food, weight, rowIndex) {
fetch(`/add_lm?food=${encodeURIComponent(food)}&weight=${encodeURIComponent(weight)}`)
.then(response => response.json())
.then(data => {
// Direktes Aktualisieren der Zeile mit den neuen Daten
const table = document.getElementById('nutrition-table');
if (table.rows[rowIndex]) {
updateRowWithNewData(table.rows[rowIndex], weight, data);
}
updateTotalNutrition(); // Aktualisiert die Gesamtnährwerte
})
.catch(error => {
console.error('Fehler:', error);
// Behandlung spezifischer Fehler, z.B. Zurücksetzen der Werte oder Anzeigen einer Fehlermeldung
});
}
function updateRowWithNewData(row, weight, nutritionData) {
if (nutritionData && row.cells.length > 7) {
row.cells[1].innerText = weight; // Aktualisiere Gewicht
row.cells[2].innerText = nutritionData.kcal;
row.cells[3].innerText = nutritionData.ew;
row.cells[4].innerText = nutritionData.fett;
row.cells[5].innerText = nutritionData.kh;
row.cells[6].innerText = nutritionData.bst;
row.cells[7].innerText = nutritionData.ca;
} else {
// Fehlerbehandlung, falls die Datenstruktur nicht wie erwartet ist
console.error('Unvollständige Daten erhalten: ', nutritionData);
}
}
function restoreTableFromLocalStorage() {
let entries = JSON.parse(localStorage.getItem('nutritionEntries')) || [];
let oneHourAgo = new Date().getTime() - (60 * 60 * 1000);
entries = entries.filter(entry => entry.timestamp > oneHourAgo); // Entfernen alter Einträge
entries.forEach(entry => {
addToTable(entry.food, entry.weight, entry.nutritionData);
});
localStorage.setItem('nutritionEntries', JSON.stringify(entries)); // Aktualisiere localStorage
}
function addToTable(food, weight, nutritionData) {
const table = document.getElementById('nutrition-table');
const row = table.insertRow();
row.insertCell(0).innerText = food;
row.insertCell(1).innerText = weight;
row.insertCell(2).innerText = nutritionData.kcal;
row.insertCell(3).innerText = nutritionData.ew;
row.insertCell(4).innerText = nutritionData.fett;
row.insertCell(5).innerText = nutritionData.kh;
row.insertCell(6).innerText = nutritionData.bst;
row.insertCell(7).innerText = nutritionData.ca;
}
function cleanUpLocalStorage() {
let entries = JSON.parse(localStorage.getItem('nutritionEntries')) || [];
let oneHourAgo = new Date().getTime() - (60 * 60 * 1000);
entries = entries.filter(entry => entry.timestamp > oneHourAgo);
localStorage.setItem('nutritionEntries', JSON.stringify(entries));
}
function updateRemoveButtonState() {
const selectedRows = document.querySelectorAll('#nutrition-table .selected').length;
document.getElementById('remove-button').disabled = selectedRows === 0;
}
function removeSelectedRow() {
const table = document.getElementById('nutrition-table');
Array.from(table.rows).forEach(row => {
if (row.classList.contains('selected')) {
let rowData = {
food: row.cells[0].innerText,
weight: row.cells[1].innerText,
// Weitere Daten bei Bedarf
};
// Entfernen des Eintrags aus dem lokalen Speicher
removeEntryFromLocalStorage(rowData);
table.deleteRow(row.rowIndex);
}
});
updateRemoveButtonState();
updateTotalNutrition();
}
function removeEntryFromLocalStorage(rowData) {
let entries = JSON.parse(localStorage.getItem('nutritionEntries')) || [];
// Konvertieren von rowData.weight in eine Zahl, um eine korrekte Vergleichsbasis zu schaffen
const weightToCompare = parseFloat(rowData.weight);
// Verwendung einer strikten Gleichheitsprüfung für beide Werte
entries = entries.filter(entry => entry.food !== rowData.food || parseFloat(entry.weight) !== weightToCompare);
localStorage.setItem('nutritionEntries', JSON.stringify(entries));
}
function updateRemoveButtonState() {
const selectedRows = document.querySelectorAll('#nutrition-table .selected').length;
document.getElementById('remove-button').disabled = selectedRows === 0;
}
// JavaScript-Funktionen
function updateButtonState() {
const food = document.getElementById('my_combobox').value;
const weight = document.getElementById('weight').value;
document.getElementById('submit-button').disabled = !(food && weight);
}
function addProduct() {
const foodInput = document.getElementById('my_combobox');
const weightInput = document.getElementById('weight');
const portionsInput = document.getElementById('portions');
const food = foodInput.value;
let weight = parseFloat(weightInput.value);
const portions = Math.max(parseInt(portionsInput.value, 10), 1); // Stellt sicher, dass mindestens 1 Portion angegeben wird
// Teilen des Gewichts durch die Anzahl der Portionen und Aufrunden
weight = Math.ceil(weight / portions);
fetch(`/add_lm?food=${encodeURIComponent(food)}&weight=${encodeURIComponent(weight)}`)
.then(response => response.json())
.then(data => {
const table = document.getElementById('nutrition-table');
const row = table.insertRow();
// Fügt die einzelnen Nährwerte zur neuen Zeile hinzu
row.insertCell(0).innerText = food;
row.insertCell(1).innerText = weight;
row.insertCell(2).innerText = data.kcal;
row.insertCell(3).innerText = data.ew;
row.insertCell(4).innerText = data.fett;
row.insertCell(5).innerText = data.kh;
row.insertCell(6).innerText = data.bst;
row.insertCell(7).innerText = data.ca;
foodInput.value = ''; // Zurücksetzen des Lebensmittel-Eingabefeldes
weightInput.value = ''; // Zurücksetzen des Gewicht-Eingabefeldes
document.getElementById('submit-button').disabled = true; // Deaktivieren des Hinzufügen-Buttons
updateTotalNutrition();
saveToLocalStorage(food, weight, data);
})
.catch(error => console.error('Fehler:', error));
}
function saveToLocalStorage(food, weight, nutritionData) {
let entries = JSON.parse(localStorage.getItem('nutritionEntries')) || [];
entries.push({ food, weight, nutritionData, timestamp: new Date().getTime() });
localStorage.setItem('nutritionEntries', JSON.stringify(entries));
}
function updateTotalNutrition() {
let totalWeight = 0, totalKcal = 0, totalEw = 0, totalFett = 0, totalKh = 0, totalBst = 0, totalCa = 0;
// Durchlaufen aller Zeilen in der Haupttabelle und Addition der Werte
Array.from(document.getElementById('nutrition-table').rows).slice(1).forEach(row => {
totalKcal += parseFloat(row.cells[2].innerText);
totalEw += parseFloat(row.cells[3].innerText);
totalFett += parseFloat(row.cells[4].innerText);
totalKh += parseFloat(row.cells[5].innerText);
totalBst += parseFloat(row.cells[6].innerText);
totalCa += parseFloat(row.cells[7].innerText);
});
// Rundung und Aktualisierung der Gesamtwerte
document.getElementById('total-kcal').innerText = Math.round(totalKcal);
document.getElementById('total-ew').innerText = totalEw.toFixed(1);
document.getElementById('total-fett').innerText = totalFett.toFixed(1);
document.getElementById('total-kh').innerText = totalKh.toFixed(1);
document.getElementById('total-bst').innerText = totalBst.toFixed(1);
document.getElementById('total-ca').innerText = Math.round(totalCa);
}
</script>
</head>
<body>
<nav id="navbar">
<div class="navbar-header">
<h1>Elo's Rezept Rechner</h1>
<li class="versionid">VERSION_ID</li>
</div>
<ul>
<li><a href="/" class="active">Rechner</a></li>
<li><a href="/nutrition">Neue Lebensmittel</a></li>
</ul>
</nav>
<div class="content">
<form onsubmit="event.preventDefault(); addProduct();" id="product-form" class="form-layout">
<div class="form-row">
<input type="number" id="portions" name="portions" placeholder="Portionen" min="1" value="1" oninput="recalculateTableBasedOnPortions()">
</div>
<div class="form-row">
<label for="my_combobox">Wählen Sie ein Lebensmittel</label>
<input list="products" name="my_combobox" id="my_combobox" placeholder="Lebensmittel" oninput="updateButtonState()" autocomplete="off">
<datalist id="products">
<!-- Produkte werden hier dynamisch eingefügt -->
</datalist>
</div>
<div class="form-row">
<input type="number" id="weight" name="weight" placeholder="Gramm" oninput="updateButtonState()">
</div>
<div class="form-row">
<button type="submit" id="submit-button" disabled>Hinzufügen</button>
</div>
</form>
<table id="nutrition-table">
<tr>
<th>Lebensmittel</th>
<th>Gewicht (g)</th>
<th>kcal</th>
<th>EW</th>
<th>Fett</th>
<th>KH</th>
<th>BST</th>
<th>CA</th>
</tr>
<!-- Zeilen werden hier dynamisch hinzugefügt -->
</table>
<button id="remove-button" onclick="removeSelectedRow()" disabled>Entfernen</button>
<table id="total-nutrition-table">
<tr>
<th>Lebensmittel</th>
<th>Gewicht (g)</th>
<th>kcal</th>
<th>EW</th>
<th>Fett</th>
<th>KH</th>
<th>BST</th>
<th>CA</th>
</tr>
<tr>
<td>Gesamtwerte</td>
<td>-</td>
<td id="total-kcal">0</td>
<td id="total-ew">0</td>
<td id="total-fett">0</td>
<td id="total-kh">0</td>
<td id="total-bst">0</td>
<td id="total-ca">0</td>
</tr>
</table>
</div>
</body>
</html>