Compare commits
No commits in common. "main" and "0.2.11" have entirely different histories.
@ -2,7 +2,7 @@ steps:
|
||||
build:
|
||||
image: plugins/kaniko
|
||||
settings:
|
||||
repo: ${FORGE_NAME}/${CI_REPO}
|
||||
repo: gitea.hottis.de/moerp/elo-rezept-rechner
|
||||
registry:
|
||||
from_secret: container_registry
|
||||
tags: latest,${CI_COMMIT_SHA},${CI_COMMIT_TAG}
|
||||
@ -10,34 +10,10 @@ steps:
|
||||
from_secret: container_registry_username
|
||||
password:
|
||||
from_secret: container_registry_password
|
||||
build_args:
|
||||
- VERSION_ID1=${CI_COMMIT_SHA}
|
||||
- VERSION_ID2=${CI_COMMIT_TAG}
|
||||
dockerfile: Dockerfile
|
||||
when:
|
||||
- event: [push, tag]
|
||||
|
||||
# scan_image:
|
||||
# image: aquasec/trivy
|
||||
# commands:
|
||||
# - trivy image $FORGE_NAME/$CI_REPO:$CI_COMMIT_SHA --quiet --exit-code 1
|
||||
|
||||
deploytest:
|
||||
image: portainer/kubectl-shell:latest
|
||||
secrets:
|
||||
- source: kube_config
|
||||
target: KUBE_CONFIG_CONTENT
|
||||
- source: encryption_key
|
||||
target: ENCRYPTION_KEY
|
||||
- source: secrets_checksum
|
||||
target: MD5_CHECKSUM
|
||||
commands:
|
||||
- printf "$KUBE_CONFIG_CONTENT" > /tmp/kubeconfig
|
||||
- export KUBECONFIG=/tmp/kubeconfig
|
||||
- ./deployment/deploy.sh test
|
||||
when:
|
||||
- event: [push, tag]
|
||||
|
||||
deploy:
|
||||
image: portainer/kubectl-shell:latest
|
||||
secrets:
|
||||
|
12
Dockerfile
12
Dockerfile
@ -1,8 +1,6 @@
|
||||
FROM python:3.12-alpine3.21
|
||||
FROM python:3.12-alpine3.19
|
||||
|
||||
ARG APP_DIR="/opt/app"
|
||||
ARG VERSION_ID1="x"
|
||||
ARG VERSION_ID2="alpha"
|
||||
|
||||
COPY ./src/ ${APP_DIR}/
|
||||
COPY start.sh ${APP_DIR}/
|
||||
@ -10,12 +8,8 @@ COPY start.sh ${APP_DIR}/
|
||||
WORKDIR ${APP_DIR}
|
||||
|
||||
RUN \
|
||||
apk add --no-cache build-base libpq-dev npm && \
|
||||
pip install --upgrade pip && \
|
||||
pip install -r requirements.txt && \
|
||||
if [ "${VERSION_ID2}" != "" ]; then VERSION_ID=${VERSION_ID2}; else VERSION_ID=${VERSION_ID1}; fi && \
|
||||
sed -i -e 's/VERSION_ID/'$VERSION_ID'/' ${APP_DIR}/templates/index.html && \
|
||||
sed -i -e 's/VERSION_ID/'"$VERSION_ID"'/' ${APP_DIR}/templates/nutrition.html
|
||||
apk add --no-cache build-base libpq-dev && \
|
||||
pip install -r requirements.txt
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
|
@ -1,7 +1,5 @@
|
||||
#!/bin/bash
|
||||
|
||||
|
||||
|
||||
if [ "$ENCRYPTION_KEY" = "" ]; then
|
||||
echo "ENCRYPTION_KEY not set"
|
||||
exit 1
|
||||
@ -12,7 +10,6 @@ if [ "$MD5_CHECKSUM" = "" ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
SECRETS_CIPHERTEXT_FILE=secrets.enc
|
||||
SECRETS_PLAINTEXT_FILE=/tmp/secrets
|
||||
TMP_FILE=`mktemp`
|
||||
|
@ -46,10 +46,10 @@ metadata:
|
||||
spec:
|
||||
tls:
|
||||
- hosts:
|
||||
- nutri%POSTFIX%.hottis.de
|
||||
- nutri.hottis.de
|
||||
secretName: nutri-cert
|
||||
rules:
|
||||
- host: nutri%POSTFIX%.hottis.de
|
||||
- host: nutri.hottis.de
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
|
@ -1,19 +1,13 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [ "$1" == "test" ]; then
|
||||
POSTFIX="-test"
|
||||
IMAGE_TAG=${CI_COMMIT_SHA}
|
||||
else
|
||||
POSTFIX=""
|
||||
fi
|
||||
|
||||
if [ "$IMAGE_TAG" == "" ]; then
|
||||
echo "Make sure IMAGE_TAG is set"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
IMAGE_NAME=gitea.hottis.de/moerp/elo-rezept-rechner
|
||||
NAMESPACE=moerp${POSTFIX}
|
||||
NAMESPACE=moerp
|
||||
DEPLOYMENT_DIR=$PWD/deployment
|
||||
|
||||
pushd $DEPLOYMENT_DIR > /dev/null
|
||||
@ -21,7 +15,7 @@ pushd $DEPLOYMENT_DIR > /dev/null
|
||||
. /tmp/secrets
|
||||
rm /tmp/secrets
|
||||
|
||||
CLIENT_SECRETS=`cat oidc-config${POSTFIX}.json | sed -e's!%CLIENT_SECRET%!'$CLIENT_SECRET'!'`
|
||||
CLIENT_SECRETS=`cat oidc-config.json | sed -e's!%CLIENT_SECRET%!'$CLIENT_SECRET'!'`
|
||||
|
||||
kubectl create namespace $NAMESPACE \
|
||||
--dry-run=client \
|
||||
@ -36,14 +30,13 @@ kubectl create secret generic nutri-secrets \
|
||||
--from-literal=CLIENT_SECRETS="$CLIENT_SECRETS" \
|
||||
--from-literal=PGUSER="$PGUSER" \
|
||||
--from-literal=PGPASSWORD="$PGPASSWORD" \
|
||||
--from-literal=PGDATABASE="$PGDATABASE$POSTFIX" \
|
||||
--from-literal=PGDATABASE="$PGDATABASE" \
|
||||
--from-literal=PGHOST="timescaledb.database.svc.cluster.local" \
|
||||
--from-literal=PGSSLMODE="require" | \
|
||||
kubectl apply -f - -n $NAMESPACE
|
||||
|
||||
cat $DEPLOYMENT_DIR/deploy-yml.tmpl | \
|
||||
sed -e 's,%IMAGE%,'$IMAGE_NAME':'$IMAGE_TAG','g | \
|
||||
sed -e 's,%POSTFIX%,'$POSTFIX','g | \
|
||||
kubectl apply -f - -n $NAMESPACE
|
||||
|
||||
popd > /dev/null
|
||||
|
@ -1,13 +0,0 @@
|
||||
{
|
||||
"web": {
|
||||
"issuer": "https://auth2.hottis.de/realms/hottis",
|
||||
"auth_uri": "https://auth2.hottis.de/ealms/hottis/protocol/openid-connect/auth",
|
||||
"client_id": "nutri",
|
||||
"client_secret": "%CLIENT_SECRET%",
|
||||
"redirect_uris": [
|
||||
"https://nutri-test.hottis.de/*"
|
||||
],
|
||||
"userinfo_uri": "https://auth2.hottis.de/realms/hottis/protocol/openid-connect/userinfo",
|
||||
"token_uri": "https://auth2.hottis.de/realms/hottis/protocol/openid-connect/token"
|
||||
}
|
||||
}
|
95
src/Run.py
95
src/Run.py
@ -1,6 +1,4 @@
|
||||
from flask import Flask, request, render_template, jsonify, redirect, url_for, g
|
||||
from flask_session import Session
|
||||
import redis
|
||||
import sqlite3
|
||||
from flask_oidc import OpenIDConnect
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
@ -8,29 +6,20 @@ import os
|
||||
import json
|
||||
import psycopg2
|
||||
import logging
|
||||
from math import ceil, floor
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config.update({
|
||||
'SECRET_KEY': os.environ['SECRET'],
|
||||
'DEBUG': True,
|
||||
'DEBUG': False,
|
||||
'OIDC_CLIENT_SECRETS': json.loads(os.environ['CLIENT_SECRETS']),
|
||||
'OIDC_ID_TOKEN_COOKIE_SECURE': True,
|
||||
'OIDC_ID_TOKEN_COOKIE_SECURE': False,
|
||||
'OIDC_USER_INFO_ENABLED': True,
|
||||
'OIDC_OPENID_REALM': 'hottis',
|
||||
'OIDC_SCOPES': ['openid', 'email'],
|
||||
'SESSION_TYPE': 'redis',
|
||||
'SESSION_PERMANENT': False,
|
||||
'SESSION_USE_SIGNER': True,
|
||||
'SESSION_KEY_PREFIX': 'nutri',
|
||||
'SESSION_REDIS': redis.StrictRedis(host='redis-master.redis.svc.cluster.local', port=6379, db=4)
|
||||
'OIDC_SCOPES': ['openid', 'email', 'profile']
|
||||
})
|
||||
|
||||
oidc = OpenIDConnect(app)
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
app.logger.handlers = logging.getLogger('gunicorn.error').handlers
|
||||
|
||||
datapw = 'dasrtwegdffgtewrt4335wferg'
|
||||
|
||||
def calculate_nutrition(food, weight):
|
||||
try:
|
||||
@ -46,12 +35,12 @@ def calculate_nutrition(food, weight):
|
||||
# Runden und Berechnen der Nährwerte basierend auf dem Gewicht
|
||||
kcal, ew, fett, kh, bst, ca = result
|
||||
nutrition_values = [
|
||||
schulrunden(kcal * weight / 100, ist_kcal=True), # kcal gerundet auf ganze Zahl
|
||||
schulrunden(ew * weight / 100, 1), # EW gerundet auf eine Dezimalstelle
|
||||
schulrunden(fett * weight / 100, 1), # Fett gerundet auf eine Dezimalstelle
|
||||
schulrunden(kh * weight / 100, 1), # KH gerundet auf eine Dezimalstelle
|
||||
schulrunden(bst * weight / 100, 1), # BST gerundet auf eine Dezimalstelle
|
||||
schulrunden(ca * weight / 100) # CA gerundet auf ganze Zahl
|
||||
round(kcal * weight / 100), # kcal gerundet auf ganze Zahl
|
||||
round(ew * weight / 100, 1), # EW gerundet auf eine Dezimalstelle
|
||||
round(fett * weight / 100, 1), # Fett gerundet auf eine Dezimalstelle
|
||||
round(kh * weight / 100, 1), # KH gerundet auf eine Dezimalstelle
|
||||
round(bst * weight / 100, 1), # BST gerundet auf eine Dezimalstelle
|
||||
round(ca * weight / 100) # CA gerundet auf ganze Zahl
|
||||
]
|
||||
return nutrition_values
|
||||
else:
|
||||
@ -62,38 +51,21 @@ def calculate_nutrition(food, weight):
|
||||
|
||||
|
||||
|
||||
|
||||
def schulrunden(zahl, stellen=0, ist_kcal=False):
|
||||
# Wenn es sich um kcal handelt und der Wert vor der Rundung zwischen 0 und 1 liegt
|
||||
if ist_kcal and 0 < zahl < 1:
|
||||
return 1
|
||||
|
||||
faktor = 10 ** stellen
|
||||
zahl = zahl * faktor
|
||||
basis = floor(zahl)
|
||||
if zahl - basis >= 0.5:
|
||||
gerundet = basis + 1
|
||||
else:
|
||||
gerundet = basis
|
||||
return gerundet / faktor
|
||||
|
||||
|
||||
|
||||
# Index-Route
|
||||
@app.route('/')
|
||||
# @oidc.require_login
|
||||
@oidc.require_login
|
||||
def index():
|
||||
return render_template('index.html')
|
||||
|
||||
# ...
|
||||
|
||||
@app.route('/get_products')
|
||||
# @oidc.require_login
|
||||
@oidc.require_login
|
||||
def get_products():
|
||||
try:
|
||||
conn = psycopg2.connect()
|
||||
with conn.cursor() as cursor:
|
||||
cursor.execute('SELECT name FROM nutrition_table ORDER BY name')
|
||||
cursor.execute('SELECT name FROM nutrition_table')
|
||||
products = cursor.fetchall()
|
||||
return {'products': [product[0] for product in products]}
|
||||
finally:
|
||||
@ -103,7 +75,7 @@ def get_products():
|
||||
|
||||
# Route zum Hinzufügen und Berechnen von Lebensmitteln
|
||||
@app.route('/add_lm', methods=['GET'])
|
||||
# @oidc.require_login
|
||||
@oidc.require_login
|
||||
def add_lm():
|
||||
food = request.args.get('food')
|
||||
weight = float(request.args.get('weight'))
|
||||
@ -133,10 +105,8 @@ def convert_decimal(value):
|
||||
|
||||
|
||||
@app.route('/add_nutrition', methods=['POST'])
|
||||
# @oidc.accept_token(['openid'])
|
||||
@oidc.accept_token(['openid'])
|
||||
def add_nutrition():
|
||||
app.logger.info("add_nutrition")
|
||||
|
||||
food = request.form.get('food')
|
||||
kcal = convert_decimal(request.form.get('kcal'))
|
||||
ew = convert_decimal(request.form.get('ew'))
|
||||
@ -163,18 +133,18 @@ def add_nutrition():
|
||||
|
||||
|
||||
@app.route('/nutrition')
|
||||
# @oidc.require_login
|
||||
@oidc.require_login
|
||||
def nutrition():
|
||||
return render_template('nutrition.html')
|
||||
|
||||
@app.route('/get_token')
|
||||
# @oidc.require_login
|
||||
@oidc.require_login
|
||||
def get_token():
|
||||
return jsonify(token=oidc.get_access_token())
|
||||
|
||||
|
||||
@app.route('/get_database_entries')
|
||||
# @oidc.require_login
|
||||
@oidc.require_login
|
||||
def get_database_entries():
|
||||
try:
|
||||
# Ersetzen Sie diese Werte mit Ihren Datenbank-Verbindungsinformationen
|
||||
@ -203,37 +173,8 @@ def get_database_entries():
|
||||
if conn:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route('/delete_nutrition', methods=['POST'])
|
||||
# @oidc.accept_token(['openid'])
|
||||
def delete_nutrition():
|
||||
data = request.get_json()
|
||||
foodNames = data['foodNames']
|
||||
|
||||
if not foodNames:
|
||||
return jsonify({'error': 'Keine Lebensmittel zum Löschen angegeben'}), 400
|
||||
|
||||
try:
|
||||
conn = psycopg2.connect()
|
||||
with conn.cursor() as cursor:
|
||||
query = "DELETE FROM nutrition_table WHERE name = ANY(%s)"
|
||||
cursor.execute(query, (foodNames,))
|
||||
conn.commit()
|
||||
return jsonify({'message': 'Erfolgreich gelöscht'}), 200
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
finally:
|
||||
if conn:
|
||||
conn.close()
|
||||
app = ProxyFix(app, x_for=1, x_host=1)
|
||||
|
||||
|
||||
@app.route('/random')
|
||||
@oidc.require_login
|
||||
def random_page():
|
||||
# Diese Route gibt die HTML-Seite 'random.html' zurück
|
||||
return render_template('random.html')
|
||||
|
||||
|
||||
exposed_app = ProxyFix(app, x_for=1, x_host=1)
|
||||
|
||||
#
|
||||
|
@ -20,6 +20,3 @@ requests==2.31.0
|
||||
typing_extensions==4.9.0
|
||||
urllib3==2.1.0
|
||||
Werkzeug==3.0.1
|
||||
Flask-Session
|
||||
redis
|
||||
|
||||
|
Binary file not shown.
Before Width: | Height: | Size: 64 KiB |
Binary file not shown.
Before Width: | Height: | Size: 256 KiB |
Binary file not shown.
Before Width: | Height: | Size: 56 KiB |
Binary file not shown.
Before Width: | Height: | Size: 167 KiB |
@ -46,30 +46,13 @@ button#remove-button:not(:disabled):hover {
|
||||
background-color: #490000; /* Dunkleres Rot */
|
||||
}
|
||||
|
||||
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: separate; /* Erlaubt die Anwendung von border-radius */
|
||||
border-spacing: 0;
|
||||
border-radius: 10px;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
table th:first-child {
|
||||
border-top-left-radius: 10px;
|
||||
}
|
||||
|
||||
table th:last-child {
|
||||
border-top-right-radius: 10px;
|
||||
}
|
||||
|
||||
table tr:last-child td:first-child {
|
||||
border-bottom-left-radius: 10px;
|
||||
}
|
||||
|
||||
table tr:last-child td:last-child {
|
||||
border-bottom-right-radius: 10px;
|
||||
}
|
||||
|
||||
|
||||
table, th, td {
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
@ -89,7 +72,7 @@ tr:nth-child(even) {
|
||||
}
|
||||
|
||||
.selected, tr.selected {
|
||||
background-color: #efcccc; /* Hervorhebung der Auswahl */
|
||||
background-color: #e5b5b5; /* Hervorhebung der Auswahl */
|
||||
}
|
||||
|
||||
tr:hover:not(.selected) {
|
||||
@ -106,20 +89,9 @@ tr:hover:not(.selected) {
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
#navbar .navbar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
#navbar h1 {
|
||||
margin: 0;
|
||||
font-size: 24px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#navbar .versionid {
|
||||
margin-left: 20px;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
#navbar ul {
|
||||
@ -141,10 +113,13 @@ tr:hover:not(.selected) {
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
#navbar a:hover, #navbar a.active {
|
||||
#navbar a:hover {
|
||||
background-color: #007344; /* Etwas helleres Grün */
|
||||
}
|
||||
|
||||
#navbar a.active {
|
||||
background-color: #008C50; /* Mittleres Grün */
|
||||
}
|
||||
|
||||
|
||||
.content {
|
||||
@ -155,8 +130,10 @@ tr:hover:not(.selected) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
#nutrition-input-table {
|
||||
width: 100%; /* Tabelle nimmt die volle Breite ein */
|
||||
border-collapse: collapse; /* Entfernt doppelte Ränder */
|
||||
}
|
||||
|
||||
#nutrition-input-table th, #nutrition-input-table td {
|
||||
border: 1px solid #ddd; /* Fügt Ränder hinzu */
|
||||
@ -176,17 +153,16 @@ tr:hover:not(.selected) {
|
||||
}
|
||||
}
|
||||
|
||||
.table-container {
|
||||
#table-container {
|
||||
overflow-y: auto;
|
||||
max-height: 500px; /* Passen Sie die Höhe nach Bedarf an */
|
||||
max-height: 400px; /* Passen Sie die Höhe nach Bedarf an */
|
||||
border-radius: 10px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
#database-nutrition-table {
|
||||
width: 100%;
|
||||
border-collapse: separate; /* Erlaubt die Anwendung von border-radius */
|
||||
border-spacing: 0;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
#database-nutrition-table th, #database-nutrition-table td {
|
||||
@ -196,7 +172,7 @@ tr:hover:not(.selected) {
|
||||
}
|
||||
|
||||
#database-nutrition-table tr.selected {
|
||||
background-color: #efcccc;
|
||||
background-color: #f0e68c;
|
||||
}
|
||||
|
||||
|
||||
@ -207,61 +183,34 @@ tr:hover:not(.selected) {
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
button#delete-row-button {
|
||||
#password-prompt input[type="password"] {
|
||||
padding: 8px;
|
||||
margin-right: 10px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
#password-prompt button {
|
||||
padding: 8px 15px;
|
||||
margin-right: 10px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
color: white;
|
||||
}
|
||||
|
||||
#password-prompt button[type="submit"] {
|
||||
background-color: #008C50; /* Helles Grün */
|
||||
}
|
||||
|
||||
#password-prompt button[type="submit"]:hover {
|
||||
background-color: #007344; /* Dunkleres Grün */
|
||||
}
|
||||
|
||||
#password-prompt button[type="button"] {
|
||||
background-color: #640000; /* Helles Rot */
|
||||
}
|
||||
|
||||
button#delete-row-button:disabled {
|
||||
background-color: #cccccc;
|
||||
color: #666666;
|
||||
}
|
||||
|
||||
button#delete-row-button:not(:disabled):hover {
|
||||
#password-prompt button[type="button"]:hover {
|
||||
background-color: #490000; /* Dunkleres Rot */
|
||||
}
|
||||
|
||||
button#cancel-button {
|
||||
background-color: #640000; /* Helles Rot */
|
||||
}
|
||||
|
||||
button#cancel-button:disabled {
|
||||
background-color: #cccccc;
|
||||
color: #666666;
|
||||
}
|
||||
|
||||
button#cancel-button:not(:disabled):hover {
|
||||
background-color: #490000; /* Dunkleres Rot */
|
||||
}
|
||||
|
||||
.form-layout {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
|
||||
button#submit-button {
|
||||
background-image: url('images/elisa.jpg'); /* Pfad zum Bild */
|
||||
background-size: contain; /* Passt das Bild innerhalb des Buttons an, ohne es zu strecken */
|
||||
background-repeat: no-repeat; /* Verhindert das Wiederholen des Bildes */
|
||||
background-position: center; /* Zentriert das Bild im Button */
|
||||
color: transparent; /* Macht den Text unsichtbar, damit nur das Bild sichtbar ist */
|
||||
width: 62px; /* Setzt die Breite automatisch entsprechend des Inhalts */
|
||||
height: 85px; /* Passt die Höhe an, um das Bild vollständig anzuzeigen */
|
||||
padding: 10px 20px; /* Hinzufügen von etwas Platz um das Bild */
|
||||
}
|
||||
|
||||
button#remove-button {
|
||||
background-image: url('images/marie2.jpg'); /* Pfad zum Bild */
|
||||
background-size: contain; /* Passt das Bild innerhalb des Buttons an, ohne es zu strecken */
|
||||
background-repeat: no-repeat; /* Verhindert das Wiederholen des Bildes */
|
||||
background-position: center; /* Zentriert das Bild im Button */
|
||||
color: transparent; /* Macht den Text unsichtbar, damit nur das Bild sichtbar ist */
|
||||
width: 78px; /* Setzt die Breite automatisch entsprechend des Inhalts */
|
||||
height: 85px; /* Passt die Höhe an, um das Bild vollständig anzuzeigen */
|
||||
padding: 10px 20px; /* Hinzufügen von etwas Platz um das Bild */
|
||||
}
|
||||
|
||||
|
@ -2,16 +2,14 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Elo's Rezept Rechner</title>
|
||||
<title>Nährwertberechnungs-App</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();
|
||||
restorePortions()
|
||||
restoreTableFromLocalStorage();
|
||||
|
||||
updateTotalNutrition();
|
||||
fetch('/get_products')
|
||||
.then(response => response.json())
|
||||
@ -34,65 +32,6 @@
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('portions').addEventListener('input', function() {
|
||||
const portions = this.value;
|
||||
localStorage.setItem('savedPortions', portions); // Speichern der Portionen im localStorage
|
||||
recalculateTableBasedOnPortions(); // Bestehende Funktion, um die Tabelle zu aktualisieren
|
||||
});
|
||||
|
||||
|
||||
function restorePortions() {
|
||||
const savedPortions = localStorage.getItem('savedPortions');
|
||||
if (savedPortions) {
|
||||
document.getElementById('portions').value = savedPortions;
|
||||
recalculateTableBasedOnPortions(); // Falls notwendig, um die Tabelle direkt zu aktualisieren
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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);
|
||||
@ -110,14 +49,14 @@ function updateRowWithNewData(row, 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;
|
||||
row.insertCell(0).innerHTML = food;
|
||||
row.insertCell(1).innerHTML = weight;
|
||||
row.insertCell(2).innerHTML = nutritionData.kcal;
|
||||
row.insertCell(3).innerHTML = nutritionData.ew;
|
||||
row.insertCell(4).innerHTML = nutritionData.fett;
|
||||
row.insertCell(5).innerHTML = nutritionData.kh;
|
||||
row.insertCell(6).innerHTML = nutritionData.bst;
|
||||
row.insertCell(7).innerHTML = nutritionData.ca;
|
||||
}
|
||||
|
||||
|
||||
@ -156,13 +95,9 @@ function updateRowWithNewData(row, weight, nutritionData) {
|
||||
|
||||
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);
|
||||
entries = entries.filter(entry => entry.food !== rowData.food || entry.weight !== rowData.weight);
|
||||
localStorage.setItem('nutritionEntries', JSON.stringify(entries));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function updateRemoveButtonState() {
|
||||
const selectedRows = document.querySelectorAll('#nutrition-table .selected').length;
|
||||
@ -176,29 +111,11 @@ function updateRowWithNewData(row, weight, nutritionData) {
|
||||
document.getElementById('submit-button').disabled = !(food && weight);
|
||||
}
|
||||
|
||||
|
||||
function schulrunden(zahl) {
|
||||
// Multipliziere die Zahl mit 10, um die relevante Dezimalstelle vor das Komma zu bekommen
|
||||
zahl = zahl * 10;
|
||||
// Wende Math.ceil an, um auf die nächste ganze Zahl aufzurunden,
|
||||
// aber nur, wenn der Dezimalteil >= 0.5 ist. Andernfalls verwende Math.floor.
|
||||
zahl = (zahl - Math.floor(zahl) >= 0.5) ? Math.ceil(zahl) : Math.floor(zahl);
|
||||
// Teile durch 10, um die ursprüngliche Skalierung wiederherzustellen,
|
||||
// aber mit der erforderlichen Rundung
|
||||
return zahl / 10;
|
||||
}
|
||||
|
||||
|
||||
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 = portionsInput.value ? parseInt(portionsInput.value, 10) : 1;
|
||||
|
||||
// Teilen des Gewichts durch die Anzahl der Portionen und Aufrunden
|
||||
weight = schulrunden(weight / portions);
|
||||
const weight = weightInput.value;
|
||||
|
||||
|
||||
fetch(`/add_lm?food=${encodeURIComponent(food)}&weight=${encodeURIComponent(weight)}`)
|
||||
@ -207,14 +124,14 @@ function updateRowWithNewData(row, weight, nutritionData) {
|
||||
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;
|
||||
row.insertCell(0).innerHTML = food;
|
||||
row.insertCell(1).innerHTML = weight;
|
||||
row.insertCell(2).innerHTML = data.kcal;
|
||||
row.insertCell(3).innerHTML = data.ew;
|
||||
row.insertCell(4).innerHTML = data.fett;
|
||||
row.insertCell(5).innerHTML = data.kh;
|
||||
row.insertCell(6).innerHTML = data.bst;
|
||||
row.insertCell(7).innerHTML = data.ca;
|
||||
|
||||
foodInput.value = ''; // Zurücksetzen des Lebensmittel-Eingabefeldes
|
||||
weightInput.value = ''; // Zurücksetzen des Gewicht-Eingabefeldes
|
||||
@ -258,10 +175,7 @@ function updateTotalNutrition() {
|
||||
</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>
|
||||
@ -270,24 +184,16 @@ function updateTotalNutrition() {
|
||||
|
||||
|
||||
<div class="content">
|
||||
<form onsubmit="event.preventDefault(); addProduct();" id="product-form" class="form-layout">
|
||||
<div class="form-row">
|
||||
<label for="portions">Wählen Sie die Anzahl an Portionen</label>
|
||||
<input type="number" id="portions" name="portions" placeholder="Portionen" min="1" value="1" oninput="recalculateTableBasedOnPortions()">
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<form onsubmit="event.preventDefault(); addProduct();" id="product-form">
|
||||
<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>
|
||||
<input type="number" id="weight" name="weight" placeholder="Gramm" step="0.1" min="0" oninput="updateButtonState()">
|
||||
|
||||
<input type="number" id="weight" name="weight" placeholder="Gramm" oninput="updateButtonState()">
|
||||
<button type="submit" id="submit-button" disabled>Hinzufügen</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
|
||||
<table id="nutrition-table">
|
||||
<tr>
|
||||
<th>Lebensmittel</th>
|
||||
@ -301,7 +207,7 @@ function updateTotalNutrition() {
|
||||
</tr>
|
||||
<!-- Zeilen werden hier dynamisch hinzugefügt -->
|
||||
</table>
|
||||
<button id="remove-button" onclick="removeSelectedRow()" disabled></button>
|
||||
<button id="remove-button" onclick="removeSelectedRow()" disabled>Entfernen</button>
|
||||
<table id="total-nutrition-table">
|
||||
<tr>
|
||||
<th>Lebensmittel</th>
|
||||
|
@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Elo's Rezept Rechner</title>
|
||||
<title>Neue Lebensmittel hinzufügen</title>
|
||||
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
|
||||
<link rel="shortcut icon" href="../static/images/favicon.ico">
|
||||
|
||||
@ -40,7 +40,6 @@
|
||||
// Beispielsweise das Formular zurücksetzen
|
||||
form.reset();
|
||||
updateSubmitButtonState();
|
||||
loadDatabaseEntries();
|
||||
}).catch(error => {
|
||||
console.error('Fehler:', error);
|
||||
});
|
||||
@ -70,33 +69,13 @@
|
||||
|
||||
function deleteSelectedRows() {
|
||||
const table = document.getElementById('database-nutrition-table');
|
||||
const selectedRows = Array.from(table.querySelectorAll('tr.selected'));
|
||||
const foodNames = selectedRows.map(row => row.cells[0].innerText); // Annahme, der Name des Lebensmittels befindet sich in der ersten Zelle
|
||||
|
||||
if (foodNames.length > 0) {
|
||||
// Holen des Tokens und Senden einer Anfrage an das Backend, um die Einträge zu löschen
|
||||
getBearerToken(token => {
|
||||
fetch('/delete_nutrition', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ' + token
|
||||
},
|
||||
body: JSON.stringify({foodNames: foodNames})
|
||||
}).then(response => {
|
||||
if (response.ok) {
|
||||
// Erfolgreich gelöscht, entferne Zeilen aus der Tabelle
|
||||
selectedRows.forEach(row => {
|
||||
Array.from(table.rows).forEach(row => {
|
||||
if (row.classList.contains('selected')) {
|
||||
// Logik zum Löschen der Zeile aus der Datenbank
|
||||
table.deleteRow(row.rowIndex);
|
||||
});
|
||||
} else {
|
||||
console.error('Fehler beim Löschen der Datenbank-Einträge');
|
||||
}
|
||||
}).catch(error => console.error('Fehler:', error));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function showPasswordPrompt() {
|
||||
document.getElementById('delete-row-button').style.display = 'none';
|
||||
@ -110,7 +89,7 @@
|
||||
|
||||
function deleteRowsIfPasswordCorrect() {
|
||||
const password = document.getElementById('password-input').value;
|
||||
if (password === 'geheim') {
|
||||
if (password === 'wowmuchsecurity') {
|
||||
deleteSelectedRows(); // Funktion, die die ausgewählten Zeilen löscht
|
||||
hidePasswordPrompt();
|
||||
} else {
|
||||
@ -119,7 +98,7 @@
|
||||
}
|
||||
|
||||
function updateDeleteButtonState() {
|
||||
const selectedRows = document.querySelectorAll('#database-nutrition-table .selected').length;
|
||||
const selectedRows = document.querySelectorAll('#nutrition-table .selected').length;
|
||||
const deleteButton = document.getElementById('delete-row-button');
|
||||
deleteButton.disabled = selectedRows === 0;
|
||||
if (selectedRows === 0) {
|
||||
@ -128,13 +107,11 @@
|
||||
}
|
||||
|
||||
|
||||
|
||||
function loadDatabaseEntries() {
|
||||
fetch('/get_database_entries') // Pfad zur entsprechenden Flask-Route
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
const tableBody = document.getElementById('database-nutrition-table').getElementsByTagName('tbody')[0];
|
||||
tableBody.innerHTML = '';
|
||||
data.forEach(entry => {
|
||||
const row = tableBody.insertRow();
|
||||
row.insertCell(0).innerHTML = entry.food;
|
||||
@ -151,45 +128,20 @@
|
||||
.catch(error => console.error('Fehler:', error));
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', loadDatabaseEntries);
|
||||
document.addEventListener('DOMContentLoaded', loadDatabaseEntries);
|
||||
|
||||
function filterTable() {
|
||||
const searchInput = document.getElementById('search-input');
|
||||
const filterText = searchInput.value.toUpperCase();
|
||||
const table = document.getElementById('database-nutrition-table');
|
||||
const rows = table.getElementsByTagName('tr');
|
||||
|
||||
for (let i = 1; i < rows.length; i++) { // Beginnen bei 1, um die Kopfzeile auszulassen
|
||||
const cell = rows[i].getElementsByTagName('td')[0]; // Angenommen, der zu suchende Text befindet sich in der ersten Spalte
|
||||
if (cell) {
|
||||
const textValue = cell.textContent || cell.innerText;
|
||||
if (textValue.toUpperCase().indexOf(filterText) > -1) {
|
||||
rows[i].style.display = ""; // Zeile anzeigen
|
||||
} else {
|
||||
rows[i].style.display = "none"; // Zeile verstecken
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function openImagePage() {
|
||||
window.open('random', '_blank'); // Öffnet die neue Seite in einem neuen Tab
|
||||
}
|
||||
</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="/">Rechner</a></li>
|
||||
<li><a href="/nutrition" class="active">Neue Lebensmittel</a></li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
|
||||
<div class="content">
|
||||
<form onsubmit="event.preventDefault(); addNutritionEntry();" method="POST" id="nutrition-form">
|
||||
<table id="nutrition-input-table">
|
||||
@ -215,16 +167,7 @@
|
||||
<button type="submit" id="submit-button" disabled>Hinzufügen</button>
|
||||
</form>
|
||||
|
||||
<div class="search-container">
|
||||
<input type="text" id="search-input" placeholder="Lebensmittel suchen..." oninput="filterTable()">
|
||||
<button onclick="openImagePage()" style="background-image: url('../static/images/marie.jpg'); border: none; cursor: pointer; background-size: cover; width: 62px; height: 85px; vertical-align: middle;">
|
||||
<!-- Der Text wird durch den transparenten Text ersetzt, falls nötig -->
|
||||
<span style="opacity: 0;">Öffnen</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="table-container">
|
||||
<div id="table-container">
|
||||
<table id="database-nutrition-table">
|
||||
<thead>
|
||||
<tr>
|
||||
@ -246,8 +189,8 @@
|
||||
|
||||
<div id="password-prompt" style="display: none;">
|
||||
<input type="password" id="password-input" placeholder="Passwort">
|
||||
<button id="ok-button" onclick="deleteRowsIfPasswordCorrect()">OK</button>
|
||||
<button id="cancel-button" onclick="hidePasswordPrompt()">Abbrechen</button>
|
||||
<button onclick="deleteRowsIfPasswordCorrect()">OK</button>
|
||||
<button onclick="hidePasswordPrompt()">Abbrechen</button>
|
||||
</div>
|
||||
|
||||
|
||||
|
@ -1,10 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Bildansicht</title>
|
||||
</head>
|
||||
<body style="margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh;">
|
||||
<img src="../static/images/elo.jpg" alt="Elo Bild" style="max-width: 100%; max-height: 100%;">
|
||||
</body>
|
||||
</html>
|
Loading…
x
Reference in New Issue
Block a user