dashboard/dashboard/plugins/food/views.py
bashynx 4193de4262 Food, sync and warmer updates from 2026-10-26
- Food: "All products" lists what's here first (My foods, the food database, kept
  products), then Open Food Facts; the start of a barcode (4+ digits) finds the
  products starting with it (dashboard, app, server search).
- Food: My foods barcodes; entries follow edits of their food or meal, and meals
  made with a changed food are worked out again (nested meals too); a save that
  changes nothing isn't written.
- Food: the week strip shows protein / carbs / fat per day, over-target calories
  in red; the header's arrows go by week, days swap in place with prefetch on
  hover; the app's arrows go by week, a sideways swipe by day.
- Food search: stomach / žalúdok / pipotă find gizzards, kurací / pui chicken,
  morčací / curcan turkey.
- Sync: tables a plugin makes after start-up are prepared at the next sync and
  their file read from the start once.
- Warmers build pages as each admin account and wait while someone is using
  the dashboard; slow page builds are logged.
- Stations: impossible sensor readings are dropped; chart ticks never fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:45:32 +02:00

341 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""View models for the food pages: plain dicts, geometry computed here (the templates only draw).
day(…) /food?d=YYYY-MM-DD: the week strip, the day's meals, totals vs targets, the ring
history(…) /food/history?r=: tiles, energy per day (or week) stacked by macro, top foods
summary(…) Health ▸ Overview: today's card / tile
report(…) Health's report page: averages over its range
"""
import math
from datetime import date, timedelta
from .db import MEAL_KEYS
MEAL_LABELS = {"breakfast": "Breakfast", "lunch": "Lunch", "dinner": "Dinner", "snack": "Snacks"}
KCAL_PER_G = {"protein": 4, "carbs": 4, "fat": 9}
MACROS = ("protein", "carbs", "fat")
RANGES = {"1m": ("Last 30 days", 30), "3m": ("Last 3 months", 91), "1y": ("Last year", 365), "all": ("Everything", None)}
WEEKLY_FROM = 120 # days in range: from here the chart shows weeks, not days
CHART_W, CHART_H = 1000, 240
# Weight goal: % of body weight a week (negative = gain). 1 kg of body fat ≈ 7700 kcal.
RATES = [[0.0, "Keep my weight"], [0.25, "Lose 0.25 % a week — slow"], [0.5, "Lose 0.5 % a week — steady"],
[0.75, "Lose 0.75 % a week — faster"], [1.0, "Lose 1 % a week — fast"], [-0.25, "Gain 0.25 % a week"]]
KCAL_PER_KG = 7700
MAX_DEFICIT = 1000 # kcal a day: more than this costs muscle and is hard to keep up
MIN_KCAL = {"female": 1200, "male": 1500} # below this, only with a doctor (very-low-calorie diets)
ACTIVITY_FALLBACK = 1.4 # × resting energy, while Health has under MIN_DAYS of step data
MIN_DAYS = 7
# Macro presets: % of the energy from protein / carbs / fat. All but "lower carb" sit inside the
# Acceptable Macronutrient Distribution Ranges (IOM: protein 10–35, carbs 45–65*, fat 20–35 %).
PRESETS = {"balanced": ("Balanced", 20, 50, 30, "The middle of the recommended ranges."),
"high_protein": ("Higher protein", 30, 40, 30, "Keeps muscle while losing weight and keeps you full "
"longer — the usual advice when eating less."),
"mediterranean": ("Mediterranean", 20, 45, 35, "More fat, mostly olive oil, nuts and fish; fewer starches."),
"lower_carb": ("Lower carb", 30, 25, 45, "Below the recommended carbs — some find it easier to stay "
"full; keep the fibre up (vegetables, nuts, seeds)."),
"custom": ("Custom", None, None, None, "Your own split (Settings ▸ Food).")}
def plan(s, energy):
"""The daily energy target and how it was worked out. energy = Health's energy summary
(ctx.ask("health", "energy"): weight, bmr, tdee, days) or None.
→ {kcal, calc (None if it can't be worked out), set (the override or None), maintenance,
basis, bmr, weight, deficit, rate, capped, floor, kg_week, options: [{rate, label, kcal}]}"""
e = energy or {}
bmr, weight = e.get("bmr"), e.get("weight")
if e.get("tdee") and e.get("days", 0) >= MIN_DAYS:
maint, basis = e["tdee"], f"your average day in Health (resting + walking + workouts, {e['days']} days)"
elif bmr:
maint, basis = round(bmr * ACTIVITY_FALLBACK), f"resting energy × {ACTIVITY_FALLBACK} (not enough step data in Health yet)"
else:
maint, basis = None, None
floor = MIN_KCAL.get(e.get("sex"), 1200)
def target(rate):
if not (maint and weight):
return None, 0, False
deficit = weight * rate / 100 * KCAL_PER_KG / 7
capped = deficit > MAX_DEFICIT
deficit = min(deficit, MAX_DEFICIT)
kcal = maint - deficit
if kcal < floor:
kcal, capped = floor, True
return int(round(kcal / 10) * 10), round(deficit), capped
rate = float(s.get("goal_rate") or 0)
calc, deficit, capped = target(rate)
kcal = s.get("kcal_target") or calc or 2000
return {"kcal": kcal, "calc": calc, "set": s.get("kcal_target") or None, "maintenance": maint, "basis": basis,
"bmr": round(bmr) if bmr else None, "weight": weight, "weight_day": e.get("weight_day"), "rate": rate,
"deficit": deficit, "capped": capped, "floor": floor,
"kg_week": round(weight * rate / 100, 2) if weight else None,
"options": [{"rate": r, "label": l, "kcal": target(r)[0], "capped": target(r)[2],
"kg_week": round(weight * r / 100, 2) if weight else None} for r, l in RATES]}
def split(s):
"""(protein, carbs, fat) % of the energy, from the preset or the custom fields."""
p = PRESETS.get(s.get("macro_preset")) or PRESETS["balanced"]
if p[1] is None:
return (s.get("custom_protein") or 20, s.get("custom_carbs") or 50, s.get("custom_fat") or 30)
return p[1:4]
def targets(s, energy=None):
"""Settings + Health's energy → the day's goals: {key: (value, kind)} — kind "goal" (aim
for it), "min" (at least) or "max" (at most)."""
kcal = plan(s, energy)["kcal"]
t = {"kcal": (kcal, "goal")}
for m, pct in zip(MACROS, split(s)):
t[m] = (round(kcal * pct / 100 / KCAL_PER_G[m]), "goal")
t["fiber"] = (s.get("fiber_min") or 25, "min")
t["sugar"] = (None, "info") # total sugar: shown, no limit (natural sugar counts too)
t["added_sugar"] = (round(kcal * 0.10 / 4), "max") # WHO: added ("free") sugars under 10 % of the energy (sugar.py)
t["sat_fat"] = (round(kcal * 0.10 / 9), "max") # under 10 % of the energy (WHO)
t["sodium_mg"] = (s.get("sodium_max") or 2000, "max")
return t
def presets(s, energy):
"""Settings ▸ Food: every preset in grams for today's target (+ protein per kg)."""
kcal = plan(s, energy)["kcal"]
w = (energy or {}).get("weight")
out = []
for k, (label, *pcts, note) in PRESETS.items():
pcts = split(dict(s, macro_preset=k))
g = [round(kcal * pct / 100 / KCAL_PER_G[m]) for m, pct in zip(MACROS, pcts)]
out.append({"key": k, "label": label, "pct": pcts, "g": g, "note": note, "on": (s.get("macro_preset") or "balanced") == k,
"per_kg": round(g[0] / w, 1) if w else None})
return out
def _sum(rows, k):
vals = [r[k] for r in rows if r.get(k) is not None]
return sum(vals) if vals else None
def totals(rows):
out = {k: _sum(rows, k) for k in ("kcal", "protein", "carbs", "sugar", "fiber", "fat", "sat_fat", "sodium_mg")}
out["kcal"] = out["kcal"] or 0
return out
def _arc(a, b, r=50):
"""SVG path of a circle arc from fraction a to b (0 = top, clockwise)."""
if b - a >= 0.9999:
b = a + 0.9999
p = lambda f: (round(r * math.sin(2 * math.pi * f), 2), round(-r * math.cos(2 * math.pi * f), 2))
(x1, y1), (x2, y2) = p(a), p(b)
return f"M{x1} {y1}A{r} {r} 0 {1 if b - a > 0.5 else 0} 1 {x2} {y2}"
def ring(t, target):
"""The energy ring: arcs per macro (their share of the energy eaten), all together as far
round as eaten ÷ target (a full ring = the target; over it the ring turns red)."""
kcal = t["kcal"] or 0
frac = min(1.0, kcal / target) if target else 0
from_macros = {m: (t[m] or 0) * KCAL_PER_G[m] for m in MACROS}
known = sum(from_macros.values())
arcs, at = [], 0.0
if known and frac:
gap = 0.006 if frac > 0.05 else 0
for m in MACROS:
f = frac * from_macros[m] / known
if f > gap * 2:
arcs.append({"m": m, "d": _arc(at + gap, at + f - gap)})
at += f
elif frac:
arcs.append({"m": "kcal", "d": _arc(0, frac)})
return {"arcs": arcs, "over": kcal > target * 1.05, "left": round(target - kcal), "kcal": round(kcal),
"target": target}
def bars(t, tg):
"""Nutrient bars under the ring: value vs target (goal / min / max)."""
rows = [("protein", "Protein", "g"), ("carbs", "Carbs", "g"), ("fat", "Fat", "g"), ("fiber", "Fibre", "g"),
("sugar", "Sugar", "g"), ("added_sugar", "Added sugar ≈", "g"), ("sat_fat", "Saturated fat", "g"),
("sodium_mg", "Sodium", "mg")]
out = []
for k, label, unit in rows:
target, kind = tg[k]
v = t.get(k)
if k == "added_sugar" and v is None:
continue # not worked out (no added_of): leave the bar out
frac = (v or 0) / target if target else 0
state = ""
if v is not None:
if kind == "max" and v > target:
state = "over"
elif kind == "min" and v >= target:
state = "ok"
elif kind == "goal" and v > target * 1.15:
state = "high"
out.append({"k": k, "label": label, "unit": unit, "v": v, "target": target, "kind": kind,
"w": round(min(frac, 1) * 100, 1), "state": state})
return out
AHEAD = 60 # days into the future the diary goes (planning meals)
def _macro_segs(v, kcal):
"""A week-strip pill's fill, bottom up: protein / carbs / fat by their share of the energy (% of the
fill), the rest (alcohol, labels that don't add up) grey — as the History chart stacks them."""
if not kcal:
return []
e = {m: (v.get(m) or 0) * KCAL_PER_G[m] for m in MACROS}
total = max(kcal, sum(e.values())) # labels' macros can add up past the kcal
segs = [{"m": m, "h": round(100 * e[m] / total, 1)} for m in MACROS if e[m] > 0]
rest = 100 - sum(x["h"] for x in segs)
return segs + ([{"m": "rest", "h": round(rest, 1)}] if rest > 0.5 else [])
def day(entries_of, totals_of, s, d, today, energy=None, activity=None, added_of=None):
"""entries_of(a, z) / totals_of(a, z): db reads (ISO days); energy: Health's (plan());
activity: Health's day ({steps, workouts, energy}) or None; added_of(entry) → its added sugar, g (sugar.py)."""
tg = targets(s, energy)
rows = entries_of(d.isoformat(), d.isoformat())
meals = []
for k in MEAL_KEYS:
items = [r for r in rows if r["meal"] == k]
meals.append({"key": k, "label": MEAL_LABELS[k], "rows": items, "t": totals(items)})
other = [r for r in rows if r["meal"] not in MEAL_KEYS] # imports without a meal
if other:
meals.append({"key": "", "label": "Other", "rows": other, "t": totals(other)})
t = totals(rows)
t["added_sugar"] = round(sum(added_of(r) for r in rows), 1) if added_of and rows else (0 if added_of else None)
yday = (d - timedelta(days=1)).isoformat()
yesterday = [r for r in entries_of(yday, yday) if r["meal"] in MEAL_KEYS] # the add box offers them again
mon = d - timedelta(days=d.weekday())
wk = totals_of((mon).isoformat(), (mon + timedelta(days=6)).isoformat())
strip = []
for i in range(7):
x = mon + timedelta(days=i)
v = wk.get(x.isoformat()) or {}
k = v.get("kcal")
strip.append({"d": x, "kcal": round(k) if k else None, "h": round(min(1.15, (k or 0) / tg["kcal"][0]) * 100),
"segs": _macro_segs(v, k), "today": x == today, "sel": x == d,
"future": x > today + timedelta(days=AHEAD), "ahead": x > today,
"over": bool(k and k > tg["kcal"][0] * 1.05),
"tip": f"{round(k)} kcal · protein {round(v.get('protein') or 0)} g, carbs {round(v.get('carbs') or 0)} g, "
f"fat {round(v.get('fat') or 0)} g" if k else "nothing logged"})
burned = ((activity or {}).get("energy") or {}).get("total")
return {"day": d, "today": today, "prev": d - timedelta(days=7), # the header's arrows: a week
"next": d + timedelta(days=7) if d + timedelta(days=7) <= today + timedelta(days=AHEAD) else None, "future": d > today,
"plan": plan(s, energy), "activity": activity, "balance": round(t["kcal"] - burned) if burned and rows else None, # nothing logged: no balance
"meals": meals, "yesterday": yesterday, "t": t, "n": len(rows), "ring": ring(t, tg["kcal"][0]), "bars": bars(t, tg), "strip": strip,
"week_kcal": round(sum((v.get("kcal") or 0) for v in wk.values())),
"week_days": sum(1 for v in wk.values() if v.get("kcal"))}
def _range(r, first, today):
r = r if r in RANGES else "1m"
n = RANGES[r][1]
if n is None:
a = date.fromisoformat(first) if first else today
else:
a = today - timedelta(days=n - 1)
return r, a
def history(totals_of, top_of, first, s, r, today, energy=None):
tg = targets(s, energy)
r, a = _range(r, first, today)
days = totals_of(a.isoformat(), today.isoformat())
logged = [v for v in days.values() if v.get("kcal")]
n_days = (today - a).days + 1
avg = lambda k: (sum(v[k] or 0 for v in logged) / len(logged)) if logged else None
av = {k: avg(k) for k in ("kcal", "protein", "carbs", "fat", "fiber", "sugar", "sodium_mg", "sat_fat")}
split = None
if logged:
e = {m: (av[m] or 0) * KCAL_PER_G[m] for m in MACROS}
tot = sum(e.values())
split = {m: round(100 * e[m] / tot) for m in MACROS} if tot else None
on_target = sum(1 for v in logged if abs(v["kcal"] - tg["kcal"][0]) <= tg["kcal"][0] * 0.1)
return {"range": r, "ranges": RANGES, "from": a, "to": today, "n_days": n_days, "logged": len(logged),
"avg": av, "split": split, "on_target": on_target, "chart": chart(days, a, today, tg["kcal"][0]),
"top": top_of(a.isoformat(), today.isoformat()), "targets": tg}
def chart(days, a, z, target):
"""Energy per day (or per week from WEEKLY_FROM days: the average logged day) as bars
stacked protein / carbs / fat (by their energy; the rest — alcohol, rounding — grey),
a dashed target line. Coordinates in a CHART_W × CHART_H box."""
n = (z - a).days + 1
weekly = n >= WEEKLY_FROM
buckets = []
if weekly:
start = a - timedelta(days=a.weekday())
while start <= z:
vs = [days[(start + timedelta(days=i)).isoformat()] for i in range(7)
if (start + timedelta(days=i)).isoformat() in days]
vs = [v for v in vs if v.get("kcal")]
buckets.append((start, vs, f"Week of {start.day} {start.strftime('%b %Y')}"))
start += timedelta(days=7)
else:
for i in range(n):
x = a + timedelta(days=i)
v = days.get(x.isoformat())
buckets.append((x, [v] if v and v.get("kcal") else [], x.strftime("%a %-d %b %Y")))
peak = max([target * 1.25] + [sum(v["kcal"] for v in vs) / len(vs) for _, vs, _ in buckets if vs])
y = lambda k: round(CHART_H - CHART_H * k / peak, 1)
bw = CHART_W / max(1, len(buckets))
out = []
for i, (x, vs, label) in enumerate(buckets):
if not vs:
out.append({"x": round(i * bw, 2), "w": round(bw, 2), "segs": [], "tip": f"{label} · nothing logged", "d": x})
continue
k = sum(v["kcal"] for v in vs) / len(vs)
e = {m: sum((v[m] or 0) for v in vs) / len(vs) * KCAL_PER_G[m] for m in MACROS}
scale = k / sum(e.values()) if sum(e.values()) > k else 1 # labels' macros can add up past the kcal
segs, base = [], 0.0
for m in MACROS:
h = e[m] * scale
if h > 0:
segs.append({"m": m, "y": y(base + h), "h": round(y(base) - y(base + h), 1)})
base += h
if k - base > 1:
segs.append({"m": "rest", "y": y(k), "h": round(y(base) - y(k), 1)})
g = {m: round(sum((v[m] or 0) for v in vs) / len(vs)) for m in MACROS}
tip = f"{label} · {round(k)} kcal" + (f" (average of {len(vs)} days)" if weekly else "") + \
f" · protein {g['protein']} g, carbs {g['carbs']} g, fat {g['fat']} g"
out.append({"x": round(i * bw, 2), "w": round(bw, 2), "segs": segs, "tip": tip, "d": x, "kcal": round(k)})
# x labels: months (long ranges) or Mondays
every = 1 if len(buckets) <= 60 else 3 if len(buckets) <= 160 else 6 # months between labels
ticks = []
for i, (x, _, _) in enumerate(buckets):
if weekly:
if x.day <= 7 and (x.month - 1) % every == 0:
ticks.append({"x": round(i * bw + bw / 2, 1), "t": x.strftime("%b %Y" if x.month == 1 else "%b")})
elif n > 35 and x.day == 1:
ticks.append({"x": round(i * bw + bw / 2, 1), "t": x.strftime("%b")})
elif n <= 35 and x.weekday() == 0:
ticks.append({"x": round(i * bw + bw / 2, 1), "t": x.strftime("%-d %b")})
return {"bars": out, "target_y": y(target), "target": target, "w": CHART_W, "h": CHART_H, "ticks": ticks,
"weekly": weekly, "pad": round(bw * 0.18, 2) if bw > 4 else 0}
def summary(entries_of, s, today, energy=None):
"""Health ▸ Overview: today's numbers (the card and the tile)."""
tg = targets(s, energy)
rows = entries_of(today.isoformat(), today.isoformat())
t = totals(rows)
return {"n": len(rows), "t": t, "ring": ring(t, tg["kcal"][0]), "bars": bars(t, tg)[:4], "target": tg["kcal"][0]}
def report(totals_of, s, days, today):
"""Health's report: the average logged day over the report's range, with references."""
a = today - timedelta(days=days - 1)
logged = [v for v in totals_of(a.isoformat(), today.isoformat()).values() if v.get("kcal")]
if not logged:
return {"since": a, "today": today, "logged": 0}
avg = lambda k: sum(v[k] or 0 for v in logged) / len(logged)
kcal = avg("kcal")
pct = lambda k: round(100 * avg(k) * KCAL_PER_G.get(k, 9) / kcal) if kcal else None
return {"since": a, "today": today, "logged": len(logged), "days": days, "kcal": round(kcal),
"protein": round(avg("protein")), "protein_pct": pct("protein"),
"carbs": round(avg("carbs")), "carbs_pct": pct("carbs"),
"fat": round(avg("fat")), "fat_pct": pct("fat"),
"sat_pct": round(100 * avg("sat_fat") * 9 / kcal) if kcal else None,
"sugar": round(avg("sugar")), "fiber": round(avg("fiber")), "sodium": round(avg("sodium_mg"))}