120 lines
3.5 KiB
Python
120 lines
3.5 KiB
Python
import os
|
|
import requests
|
|
from flask import Flask, render_template
|
|
from datetime import datetime, timedelta
|
|
from collections import defaultdict
|
|
|
|
app = Flask(__name__)
|
|
|
|
TANDOOR_URL = os.environ.get("TANDOOR_URL", "http://web_recipes:8080")
|
|
TANDOOR_API_TOKEN = os.environ.get("TANDOOR_API_TOKEN", "")
|
|
|
|
|
|
def get_meal_plan():
|
|
if not TANDOOR_API_TOKEN:
|
|
return None, "Todavía no se configuró el token de API. Tu madre debe crearlo desde el panel de Tandoor."
|
|
|
|
headers = {
|
|
"Authorization": f"Token {TANDOOR_API_TOKEN}",
|
|
"Content-Type": "application/json",
|
|
"Host": "tandoor.local",
|
|
}
|
|
|
|
# Obtener meal plan de los próximos 7 días
|
|
today = datetime.now().date()
|
|
end = today + timedelta(days=6)
|
|
|
|
params = {
|
|
"from_date": today.isoformat(),
|
|
"to_date": end.isoformat(),
|
|
}
|
|
|
|
try:
|
|
resp = requests.get(
|
|
f"{TANDOOR_URL}/api/meal-plan/",
|
|
headers=headers,
|
|
params=params,
|
|
timeout=10,
|
|
)
|
|
resp.raise_for_status()
|
|
data = resp.json()
|
|
# Tandoor devuelve paginación: { "count": ..., "results": [...] }
|
|
results = data.get("results", data) if isinstance(data, dict) else data
|
|
return results, None
|
|
except requests.exceptions.ConnectionError:
|
|
return None, "No se pudo conectar con Tandoor. ¿Está iniciado el servicio?"
|
|
except requests.exceptions.HTTPError as e:
|
|
if resp.status_code == 401:
|
|
return None, "Token de API inválido. Verificá la configuración."
|
|
return None, f"Error de API: {e}"
|
|
except Exception as e:
|
|
return None, f"Error inesperado: {e}"
|
|
|
|
|
|
def group_by_day(meal_plans):
|
|
days = defaultdict(list)
|
|
dias_semana = ["Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo"]
|
|
|
|
for item in meal_plans:
|
|
date_str = item.get("from_date") or item.get("to_date")
|
|
if not date_str:
|
|
continue
|
|
try:
|
|
d = datetime.fromisoformat(date_str).date()
|
|
except Exception:
|
|
continue
|
|
|
|
recipe = item.get("recipe")
|
|
title = None
|
|
image = None
|
|
if recipe:
|
|
title = recipe.get("name", "Sin nombre")
|
|
image = recipe.get("image")
|
|
else:
|
|
title = item.get("title", "Sin nombre")
|
|
|
|
meal_type = item.get("meal_type", {})
|
|
tipo = meal_type.get("name", "Menú") if meal_type else "Menú"
|
|
|
|
days[d.isoformat()].append({
|
|
"title": title,
|
|
"image": image,
|
|
"tipo": tipo,
|
|
"servings": item.get("servings", 1),
|
|
})
|
|
|
|
# Ordenar por fecha
|
|
sorted_days = []
|
|
today = datetime.now().date()
|
|
for i in range(7):
|
|
d = today + timedelta(days=i)
|
|
key = d.isoformat()
|
|
sorted_days.append({
|
|
"fecha": d,
|
|
"nombre_dia": dias_semana[d.weekday()],
|
|
"meals": days.get(key, []),
|
|
})
|
|
|
|
return sorted_days
|
|
|
|
|
|
@app.route("/")
|
|
def index():
|
|
meal_plans, error = get_meal_plan()
|
|
if error:
|
|
return render_template("index.html", error=error, days=[])
|
|
|
|
if not meal_plans:
|
|
return render_template(
|
|
"index.html",
|
|
error="No hay platos planificados para esta semana. Tu madre puede cargarlos desde el panel de Tandoor.",
|
|
days=[],
|
|
)
|
|
|
|
days = group_by_day(meal_plans)
|
|
return render_template("index.html", error=None, days=days)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", port=5000)
|