- 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>
518 lines
27 KiB
Python
518 lines
27 KiB
Python
"""Food diary: what you ate, per meal, against your daily targets.
|
||
|
||
/food a day (?d=YYYY-MM-DD): the week strip, the meals with their foods,
|
||
energy ring + nutrient bars, the describe box (a local language model
|
||
turns "2 eggs and toast for breakfast" into entries to confirm)
|
||
/food/history energy per day / week stacked by macro, averages, most eaten (?r=1m|3m|1y|all)
|
||
/food/foods My foods: your own food database (values per 100 g, portions) and your meals
|
||
(made of other foods: the meal builder) — add, edit, delete
|
||
/food/export.csv every entry
|
||
/food/api/… JSON writes + the food suggestions (same-origin only, like the core's);
|
||
api/archive = every product: what's here, then every Open Food Facts one (searched on the sync server)
|
||
(its /v1/food/search, with this dashboard's sync token); api/product keeps
|
||
a picked one (food.db `product`, synced)
|
||
|
||
Data: dash_data/food/food.db (the diary, SQLite, see db.py; Lifesum entries come in with
|
||
Health's Health Connect import) + foods.db (the food database, read-only: fdc.py builds it
|
||
from USDA FoodData Central, fooddb.py reads it). The energy target comes from Health's
|
||
energy estimate (ctx.ask("health", "energy"), views.plan). A section of Health, like the cycle tracker. Never shown on the
|
||
wall screens.
|
||
"""
|
||
import csv
|
||
import io
|
||
import json
|
||
import os
|
||
import re
|
||
import urllib.parse
|
||
from contextlib import closing
|
||
from datetime import date, timedelta
|
||
|
||
from flask import Response, abort, jsonify, render_template, request
|
||
|
||
from . import db, fooddb, parse, sugar, views
|
||
|
||
META = {
|
||
"title": "Food diary",
|
||
"glyph": "🍴",
|
||
"glyph_color": "#7fd6a3",
|
||
"description": "Log what you eat per meal — by hand, from foods you had before, or by describing it "
|
||
"(a local language model fills in the rest). Energy and nutrients against your targets.",
|
||
"links": [{"label": "Open the diary", "href": "/food"}, {"label": "History", "href": "/food/history"}],
|
||
"settings": [
|
||
{"key": "goal_rate", "label": "Weight goal", "type": "select", "default": 0.0, "options": views.RATES,
|
||
"help": "Sets the energy target: your usual day in Health minus what that rate needs (1 kg ≈ 7700 kcal). "
|
||
"The box above shows the numbers."},
|
||
{"key": "kcal_target", "label": "Energy per day (kcal) — your own", "type": "number", "default": 0,
|
||
"min": 0, "max": 6000, "integer": True, "help": "0 = the calculated target (above). Any other number replaces it."},
|
||
{"key": "macro_preset", "label": "Protein / carbs / fat", "type": "select", "default": "balanced",
|
||
"options": [[k, f"{p[0]}" + (f" — {p[1]} / {p[2]} / {p[3]} %" if p[1] else " — the three fields below")]
|
||
for k, p in views.PRESETS.items()]},
|
||
{"key": "custom_protein", "label": "Custom: protein (% of the energy)", "type": "number", "default": 25,
|
||
"min": 5, "max": 60, "integer": True},
|
||
{"key": "custom_carbs", "label": "Custom: carbs (%)", "type": "number", "default": 45,
|
||
"min": 5, "max": 80, "integer": True},
|
||
{"key": "custom_fat", "label": "Custom: fat (%)", "type": "number", "default": 30,
|
||
"min": 10, "max": 70, "integer": True, "help": "The three should add up to 100."},
|
||
{"key": "fiber_min", "label": "Fibre, at least (g)", "type": "number", "default": 25,
|
||
"min": 0, "max": 100, "integer": True},
|
||
{"key": "sugar_max", "label": "Sugar, at most (g)", "type": "number", "default": 50,
|
||
"min": 0, "max": 300, "integer": True},
|
||
{"key": "sodium_max", "label": "Sodium, at most (mg)", "type": "number", "default": 2000,
|
||
"min": 0, "max": 10000, "integer": True, "help": "WHO: under 2000 mg (= 5 g salt)."},
|
||
{"key": "use_model", "label": "Describe box (language model) on", "type": "bool", "default": True,
|
||
"help": "Off: the diary has only the form; nothing is sent to the model."},
|
||
{"key": "model_url", "label": "Language model address (Ollama)", "type": "text", "default": "",
|
||
"max": 200, "help": "e.g. http://localhost:11434 — empty = the describe box is off."},
|
||
{"key": "model", "label": "Model", "type": "text", "default": "qwen3:1.7b", "max": 80},
|
||
],
|
||
# what syncs between devices (sync.py / syncdb.py): My foods, then the diary pointing at them;
|
||
# imported entries keep their import id, a meal's ingredients ("my:ID" in recipe) travel as ids
|
||
"sync": {"food.db": {
|
||
"product": {"key": "'p:' || NEW.food_id"},
|
||
"food": {"refs_in": {"recipe": "my:"}},
|
||
"entry": {"key": "CASE WHEN NEW.src_id IS NOT NULL THEN 'src:' || NEW.src_id END", "refs": {"my_food_id": "food"}},
|
||
}},
|
||
}
|
||
PARSE_MAX = 1000 # characters in the describe box
|
||
|
||
|
||
def validate_settings(sec): # pluginhost: cross-field check
|
||
if sec.get("macro_preset") == "custom":
|
||
total = sum(sec.get(k) or 0 for k in ("custom_protein", "custom_carbs", "custom_fat"))
|
||
if total != 100:
|
||
return "custom_fat", f"Protein + carbs + fat make {total} %, not 100."
|
||
return None
|
||
|
||
|
||
def register(ctx):
|
||
# Settings ▸ Food for the phone app (the Health summary carries it as meta:food): the same targets there
|
||
ctx.provide("diet", lambda: {"goal_rate": float(ctx.settings.get("goal_rate") or 0), "split": list(views.split(ctx.settings)),
|
||
"kcal_target": int(ctx.settings.get("kcal_target") or 0),
|
||
"fiber_min": int(ctx.settings.get("fiber_min") or 25),
|
||
"sugar_max": int(ctx.settings.get("sugar_max") or 50),
|
||
"sodium_max": int(ctx.settings.get("sodium_max") or 2000)})
|
||
bp = ctx.blueprint("/food")
|
||
ctx.warm("/food", "/food/history", "/food/foods")
|
||
ctx.nav("Food", "/food")
|
||
here = os.path.dirname(os.path.abspath(__file__))
|
||
|
||
@bp.context_processor
|
||
def asset_version(): # cache-buster for food.css / .js
|
||
st = os.path.join(here, "static")
|
||
return {"asset_v": "%x" % int(max(os.path.getmtime(os.path.join(st, f)) for f in os.listdir(st)))}
|
||
|
||
def con(): # one connection per request, closed after
|
||
return closing(db.connect(ctx.data_path("food.db")))
|
||
|
||
foods_db = ctx.data_path("foods.db") # the food database (fdc.py builds it; read-only here)
|
||
bundled = os.path.join(here, "..", "..", "..", "app", "assets", "foods.db")
|
||
if not os.path.exists(foods_db) and os.path.exists(bundled): # run from the repo: start with the app's copy
|
||
import shutil # (install.sh does the same for /opt/dashboard)
|
||
shutil.copyfile(bundled, foods_db)
|
||
os.chmod(foods_db, 0o600)
|
||
|
||
energy_memo = {"key": None, "val": None}
|
||
|
||
def energy(): # Health's energy summary (weight, resting, usual day) or None
|
||
key = (ctx.ask("health", "version"), date.today())
|
||
if energy_memo["key"] != key:
|
||
energy_memo.update(key=key, val=ctx.ask("health", "energy"))
|
||
return energy_memo["val"]
|
||
|
||
def health_version(): # pages show targets worked out from Health's data
|
||
return ctx.ask("health", "version")
|
||
|
||
def version(): # Health caches pages with our blocks on them
|
||
return ctx.data_version("food.db")
|
||
|
||
def summary():
|
||
with con() as c:
|
||
return views.summary(lambda a, z: db.entries_between(c, a, z), ctx.settings, date.today(), energy())
|
||
|
||
def report_part(days):
|
||
with con() as c:
|
||
r = views.report(lambda a, z: db.day_totals(c, a, z), ctx.settings, days, date.today())
|
||
return render_template("food/_report.html", r=r)
|
||
|
||
ctx.inside("health", add=("Food", "/food#add"), report=report_part,
|
||
blocks=[{"id": "food.card", "kind": "card", "label": "Food today", "w": 33,
|
||
"render": lambda: render_template("food/_ovcard.html", s=summary()), "version": version},
|
||
{"id": "food.tile", "kind": "tile", "label": "Energy eaten today", "w": 20,
|
||
"href": "/food", "render": lambda: render_template("food/_ovtile.html", s=summary()),
|
||
"version": version}])
|
||
|
||
def body():
|
||
if not ctx.same_origin():
|
||
abort(403)
|
||
return request.get_json(silent=True) or {}
|
||
|
||
def parser_on():
|
||
return bool(ctx.settings.get("use_model") and ctx.settings.get("model_url"))
|
||
|
||
def archive_on(): # the archive is searched through this dashboard's sync
|
||
import sync
|
||
return sync.configured()
|
||
|
||
def common(): # what every page's dialogs need
|
||
return {"fields": db.FIELDS, "units": db.UNITS, "meals": views.MEAL_LABELS, "parser": parser_on(),
|
||
"model_off": not ctx.settings.get("use_model"), "has_db": os.path.exists(foods_db),
|
||
"archive": archive_on()}
|
||
|
||
ctx.settings_panel("food/_settings.html",
|
||
lambda: {"p": views.plan(ctx.settings, energy()), "presets": views.presets(ctx.settings, energy()),
|
||
"e": energy(), "has_db": os.path.exists(foods_db)})
|
||
|
||
def added_of(c):
|
||
"""entry → its added sugar (g), sugar.py — the foods it was made from looked up once per page."""
|
||
foods, mine = {}, {}
|
||
|
||
def food_of(fid):
|
||
if fid not in foods:
|
||
foods[fid] = db_food(c, int(fid))
|
||
return foods[fid]
|
||
|
||
def my_food_of(mid):
|
||
if mid not in mine:
|
||
try:
|
||
mine[mid] = db.my_food(c, int(mid))
|
||
except (TypeError, ValueError):
|
||
mine[mid] = None
|
||
return mine[mid]
|
||
return lambda r: sugar.entry_added(r, food_of, my_food_of)
|
||
|
||
@bp.route("/", strict_slashes=False)
|
||
@ctx.cached_page("food.db", extra=health_version)
|
||
def index():
|
||
today = date.today()
|
||
try:
|
||
d = min(today + timedelta(days=views.AHEAD), date.fromisoformat(request.args.get("d", "")))
|
||
except ValueError:
|
||
d = today
|
||
act = ctx.ask("health", "day", d) if d <= today else None
|
||
with con() as c:
|
||
v = views.day(lambda a, z: db.entries_between(c, a, z), lambda a, z: db.day_totals(c, a, z),
|
||
ctx.settings, d, today, energy(), act, added_of(c))
|
||
return render_template("food/day.html", v=v, page="food", tab="day", **common())
|
||
|
||
@bp.route("/history")
|
||
@ctx.cached_page("food.db", extra=health_version)
|
||
def history():
|
||
today = date.today()
|
||
with con() as c:
|
||
v = views.history(lambda a, z: db.day_totals(c, a, z), lambda a, z: db.top_foods(c, a, z),
|
||
db.first_day(c), ctx.settings, request.args.get("r"), today, energy())
|
||
now = views.day(lambda a, z: db.entries_between(c, a, z), lambda a, z: db.day_totals(c, a, z),
|
||
ctx.settings, today, today, energy(), ctx.ask("health", "day", today), added_of(c)) # the left column
|
||
return render_template("food/history.html", v=v, now=now, page="food", tab="history", **common())
|
||
|
||
@bp.route("/foods")
|
||
@ctx.cached_page("food.db", extra=health_version)
|
||
def my_foods_page(): # My foods: your own food database (values per 100 g, portions)
|
||
today = date.today()
|
||
with con() as c:
|
||
foods = db.my_foods(c)
|
||
now = views.day(lambda a, z: db.entries_between(c, a, z), lambda a, z: db.day_totals(c, a, z),
|
||
ctx.settings, today, today, energy(), ctx.ask("health", "day", today), added_of(c)) # the left column
|
||
return render_template("food/foods.html", foods=foods, now=now, page="food", tab="foods", **common())
|
||
|
||
@bp.route("/export.csv")
|
||
def export_csv():
|
||
with con() as c:
|
||
rows = db.entries_between(c, "0000-01-01", "9999-12-31")
|
||
cols = ["day", "time", "meal", "name", "amount", "unit", "grams"] + list(db.FIELDS) + db.NUTRIENTS + ["note", "source", "food_id", "my_food_id"]
|
||
buf = io.StringIO()
|
||
w = csv.writer(buf)
|
||
w.writerow(cols)
|
||
for r in rows:
|
||
w.writerow(["" if r[k] is None else (round(r[k], 2) if isinstance(r[k], float) else r[k]) for k in cols])
|
||
return Response("\ufeff" + buf.getvalue(), mimetype="text/csv", # BOM: Excel / LibreOffice read UTF-8
|
||
headers={"Content-Disposition": f'attachment; filename="food-{date.today()}.csv"'})
|
||
|
||
def db_food(c, fid):
|
||
"""A food of the database: foods.db's, else a product kept from the archive."""
|
||
return fooddb.food(foods_db, fid) or db.product(c, fid)
|
||
|
||
def resolve(c, ref):
|
||
"""'my:ID' → one of My foods, 'usda:ID' → the food database's (or a kept product); None if unknown."""
|
||
kind, _, fid = str(ref or "").partition(":")
|
||
if not fid.isdigit():
|
||
return None
|
||
return db.my_food(c, int(fid)) if kind == "my" else db_food(c, int(fid)) if kind == "usda" else None
|
||
|
||
def archive(params):
|
||
"""GET the sync server's /v1/food/search → its items (RuntimeError: not set up / unreachable)."""
|
||
import sync
|
||
st = sync.load_state()
|
||
if not sync.configured(st):
|
||
raise RuntimeError("Sync isn't set up on this dashboard — the archive is searched through it.")
|
||
q = urllib.parse.urlencode({k: v for k, v in params.items() if v})
|
||
try:
|
||
return sync.call(st, "GET", "/v1/food/search?" + q).get("items", [])
|
||
except OSError:
|
||
raise RuntimeError("The sync server can't be reached.")
|
||
|
||
def lookup(c, name):
|
||
"""The describe box: the likeliest of My foods (every word in its name), else the database's."""
|
||
mine = db.my_foods(c, name, limit=1)
|
||
return mine[0] if mine else fooddb.best(foods_db, name)
|
||
|
||
def ref_of(e):
|
||
return f"my:{e['my_food_id']}" if e.get("my_food_id") else f"usda:{e['food_id']}" if e.get("food_id") else None
|
||
|
||
def by_code(c, code):
|
||
"""A barcode or the start of one (4–14 digits) → (My foods, products: the database's, else kept ones)."""
|
||
return (db.my_foods_by_barcode(c, code, prefix=True),
|
||
fooddb.by_barcode(foods_db, code, prefix=True) or db.products(c, barcode=code, prefix=True, limit=20))
|
||
|
||
def code_of(q):
|
||
return q.strip() if re.fullmatch(r"\s*\d{4,14}\s*", q) else None
|
||
|
||
@bp.route("/api/foods")
|
||
def api_foods(): # ?q= → {recent, mine, db, products} — the form's suggestions (a barcode or a part: My foods / products)
|
||
q = request.args.get("q", "")[:60]
|
||
code = code_of(q)
|
||
with con() as c:
|
||
if code: # scanned / typed off the pack
|
||
mine, products = by_code(c, code)
|
||
return jsonify(recent=[], mine=mine, db=[], products=products[:8])
|
||
rows = db.foods(c, q, limit=5)
|
||
mine = db.my_foods(c, q, limit=8)
|
||
kept = db.products(c, q, limit=4, fold=sugar.fold) # picked from the archive before
|
||
keep = ["id", "name", "amount", "unit", "grams", "meal", "times"] + list(db.FIELDS)
|
||
recent = [dict({k: r.get(k) for k in keep}, food=ref_of(r)) for r in rows]
|
||
found = fooddb.search(foods_db, q, limit=16) # generic (USDA) and shop products (Open Food Facts)
|
||
ids = {f["id"] for f in kept}
|
||
return jsonify(recent=recent, mine=mine, db=[f for f in found if f["kind"] == "usda"][:8],
|
||
products=(kept + [f for f in found if f["kind"] == "off" and f["id"] not in ids])[:8])
|
||
|
||
@bp.route("/api/archive")
|
||
def api_archive(): # ?q, country, brand, nutriscore, barcode → {items[, error]}: what's here (My foods, the food
|
||
# database, kept products) first, then the archive's (sync server); unreachable → what's here + the error
|
||
p = {k: request.args.get(k, "")[:60] for k in ("q", "country", "brand", "category", "nutriscore", "barcode")}
|
||
code = code_of(p["barcode"] or p["q"])
|
||
if code:
|
||
p.update(barcode=code, q="")
|
||
with con() as c:
|
||
here = []
|
||
if not any(p[k] for k in ("country", "brand", "category", "nutriscore")): # filters: the archive's facts
|
||
if code:
|
||
mine, products = by_code(c, code)
|
||
here = mine[:8] + products[:8]
|
||
elif len(p["q"].strip()) >= 3:
|
||
kept = db.products(c, p["q"], limit=4, fold=sugar.fold)
|
||
found = [f for f in fooddb.search(foods_db, p["q"], limit=12) if f["id"] not in {k["id"] for k in kept}]
|
||
here = db.my_foods(c, p["q"], limit=6) + kept + found[:8]
|
||
for f in here:
|
||
f["saved"] = True
|
||
error = None
|
||
try:
|
||
items = archive(dict(p, limit=25))
|
||
except RuntimeError as e:
|
||
items, error = [], str(e)
|
||
ids = {f["id"] for f in here if f["kind"] != "my"}
|
||
for f in items: # ones you have here already say so
|
||
f["saved"] = bool(fooddb.food(foods_db, f["id"]) or db.product(c, f["id"]))
|
||
return jsonify(items=here + [f for f in items if f["id"] not in ids], **({"error": error} if error else {}))
|
||
|
||
@bp.route("/api/product", methods=["POST"])
|
||
def api_product(): # {id, barcode} — keep a product picked from the archive → {food}
|
||
d = body()
|
||
code = re.sub(r"\D", "", str(d.get("barcode") or ""))
|
||
with con() as c:
|
||
have = db_food(c, int(d.get("id") or 0)) if str(d.get("id") or "").isdigit() else None
|
||
if have:
|
||
return jsonify(food=have)
|
||
try:
|
||
found = [f for f in archive({"barcode": code}) if f.get("id") == d.get("id")] if code else []
|
||
except RuntimeError as e:
|
||
return jsonify(error=str(e)), 502
|
||
if not found:
|
||
return jsonify(error="The archive doesn't have that product (any more)."), 404
|
||
try:
|
||
return jsonify(food=db.save_product(c, found[0]))
|
||
except db.Invalid as e:
|
||
return jsonify(error=str(e)), 400
|
||
|
||
@bp.route("/api/food")
|
||
def api_food(): # ?ref=my:ID | usda:ID → the food: per 100 g + portions (a meal: + its ingredients' foods)
|
||
with con() as c:
|
||
f = resolve(c, request.args.get("ref"))
|
||
if f and f.get("recipe"):
|
||
for i in f["recipe"]["ingredients"]:
|
||
i["f"] = resolve(c, i["food"]) # None = gone since
|
||
return jsonify(food=f) if f else (jsonify(error="That food is gone."), 404)
|
||
|
||
def prepare(c, d):
|
||
"""A submitted entry → (columns to save, food to write or None), nothing written yet.
|
||
With `food` (a ref) and/or `edit` ({name, per100, portions, note} — the food's values,
|
||
changed or new), the entry's numbers are worked out here: values per 100 g × the grams
|
||
of amount × unit. edit + a USDA food = a new food in My foods (a copy); edit + one of
|
||
My foods = that food changed; edit alone = a new food. Without either: the numbers
|
||
come as typed (older entries, the describe box's estimates)."""
|
||
food = resolve(c, d["food"]) if d.get("food") else None
|
||
if d.get("food") and not food:
|
||
raise db.Invalid("name", "That food is gone — pick it again.")
|
||
edit = d.get("edit")
|
||
if edit and food and food.get("recipe"):
|
||
raise db.Invalid("name", "That's a meal — change it with Edit meal.")
|
||
if not (food or edit):
|
||
return dict(d, food_id=None, my_food_id=None), None
|
||
f = food
|
||
if edit:
|
||
try:
|
||
v = db.clean_food(edit, base=food)
|
||
except db.Invalid as e:
|
||
raise db.Invalid("food." + e.field, str(e))
|
||
f = {"name": v["name"], "per100": {k: v[k] for k in db.FOOD_COLS}, "portions": json.loads(v["portions"])}
|
||
try:
|
||
amount = float(str(d.get("amount") or "").replace(",", "."))
|
||
except ValueError:
|
||
amount = None
|
||
g, label = fooddb.portion(f, amount, d.get("unit") or "g")
|
||
if not g:
|
||
raise db.Invalid("amount", "How much — amount and unit?")
|
||
n = fooddb.nutrients(f, g)
|
||
e = {k: d.get(k) for k in ("id", "day", "time", "meal", "note")}
|
||
e.update({k: n[k] for k in db.FIELDS}, name=f["name"], amount=amount, unit=label, grams=round(g, 2),
|
||
food_id=food["id"] if food and food["kind"] != "my" and not edit else None,
|
||
my_food_id=food["id"] if food and food["kind"] == "my" else None)
|
||
db.clean(e) # day, meal … checked before anything is written
|
||
extra = {k: n[k] for k in db.NUTRIENTS}
|
||
return dict(e, _extra=extra), ((edit, food) if edit else None)
|
||
|
||
def commit(c, prep, source):
|
||
e, write = prep
|
||
extra = e.pop("_extra", None)
|
||
if write:
|
||
edit, food = write
|
||
mine = food if food and food["kind"] == "my" else None
|
||
e["my_food_id"] = db.save_food(c, edit, base=food, fid=mine["id"] if mine else None)
|
||
db.follow_meals(c, e["my_food_id"], lambda ref: resolve(c, ref))
|
||
return db.save(c, e, source=source, extra=extra)
|
||
|
||
@bp.route("/api/entry", methods=["POST"])
|
||
def api_entry(): # {id?, food?, edit?, from?, day, time, meal, amount, unit, note (+ name, kcal … without a food)}
|
||
d = body()
|
||
with con() as c:
|
||
try:
|
||
return jsonify(ok=True, id=commit(c, prepare(c, d), "manual"))
|
||
except db.Invalid as e:
|
||
return jsonify(error=str(e), field=e.field), 400
|
||
|
||
@bp.route("/api/entries", methods=["POST"])
|
||
def api_entries(): # {items: [entry, …]} — the describe box's confirmed list, all or nothing
|
||
items = body().get("items") or []
|
||
if not isinstance(items, list) or not items:
|
||
return jsonify(error="Nothing to save."), 400
|
||
with con() as c:
|
||
try:
|
||
preps = []
|
||
for i, it in enumerate(items):
|
||
try:
|
||
p = prepare(c, it)
|
||
db.clean(p[0])
|
||
preps.append(p)
|
||
except db.Invalid as e:
|
||
raise db.Invalid(f"{i}.{e.field}", str(e))
|
||
ids = [commit(c, p, "parsed") for p in preps]
|
||
except db.Invalid as e:
|
||
return jsonify(error=str(e), field=e.field), 400
|
||
return jsonify(ok=True, ids=ids)
|
||
|
||
@bp.route("/api/myfood", methods=["POST"])
|
||
def api_myfood(): # {id?, name, per100, portions, note, sugar_kind, barcode} — My foods page
|
||
d = body()
|
||
with con() as c:
|
||
try:
|
||
fid = int(d["id"]) if d.get("id") else None
|
||
base = db.my_food(c, fid) if fid else None
|
||
if fid and not base:
|
||
raise db.Invalid("name", "That food is gone.")
|
||
if base and base.get("recipe"):
|
||
raise db.Invalid("name", "That's a meal — change it with Edit meal.")
|
||
fid = db.save_food(c, d, base=base, fid=fid)
|
||
db.follow_meals(c, fid, lambda ref: resolve(c, ref))
|
||
return jsonify(ok=True, id=fid)
|
||
except db.Invalid as e:
|
||
return jsonify(error=str(e), field="food." + e.field), 400
|
||
|
||
@bp.route("/api/meal", methods=["POST"])
|
||
def api_meal(): # {id?, name, ingredients, done_grams, portions, note, replace?, log?} — the meal builder
|
||
# replace = [entry ids] (a meal made of entries already logged) + log = {day, meal, time}:
|
||
# those entries become one entry of the meal, its whole weight — the day's numbers stay the same
|
||
d = body()
|
||
with con() as c:
|
||
try:
|
||
fid = int(d["id"]) if d.get("id") else None
|
||
if fid and not db.my_food(c, fid):
|
||
raise db.Invalid("name", "That meal is gone.")
|
||
ids = [int(x) for x in (d.get("replace") or [])]
|
||
if ids:
|
||
if any(not db.entry(c, x) for x in ids):
|
||
raise db.Invalid("replace", "Some of those entries are gone — reload the page.")
|
||
log = d.get("log") or {}
|
||
db.clean(dict(log, name="-", kcal=0)) # day / meal / time valid before anything is written
|
||
fid = db.save_meal(c, d, lambda ref: resolve(c, ref), fid)
|
||
db.follow_meals(c, fid, lambda ref: resolve(c, ref))
|
||
eid = None
|
||
if ids:
|
||
eid = commit(c, prepare(c, {**{k: log.get(k) for k in ("day", "meal", "time")}, "food": f"my:{fid}",
|
||
"amount": 1, "unit": "whole meal", "note": ""}), "manual")
|
||
for x in ids:
|
||
db.delete(c, x)
|
||
return jsonify(ok=True, id=fid, ref=f"my:{fid}", entry=eid) # entry: the one replacing them
|
||
except db.Invalid as e:
|
||
return jsonify(error=str(e), field=e.field), 400
|
||
except (TypeError, ValueError):
|
||
return jsonify(error="Which entries?"), 400
|
||
|
||
@bp.route("/api/myfood/delete", methods=["POST"])
|
||
def api_myfood_delete(): # {id} — hidden; entries made from it keep their numbers
|
||
try:
|
||
fid = int(body().get("id"))
|
||
except (TypeError, ValueError):
|
||
return jsonify(error="Which food?"), 400
|
||
with con() as c:
|
||
db.delete_food(c, fid)
|
||
return jsonify(ok=True)
|
||
|
||
@bp.route("/api/entry/delete", methods=["POST"])
|
||
def api_delete(): # {id}
|
||
try:
|
||
eid = int(body().get("id"))
|
||
except (TypeError, ValueError):
|
||
return jsonify(error="Which entry?"), 400
|
||
with con() as c:
|
||
db.delete(c, eid)
|
||
return jsonify(ok=True)
|
||
|
||
@bp.route("/api/entry/move", methods=["POST"])
|
||
def api_move(): # {id, meal} — dragged into another meal
|
||
d = body()
|
||
try:
|
||
eid = int(d.get("id"))
|
||
except (TypeError, ValueError):
|
||
return jsonify(error="Which entry?"), 400
|
||
with con() as c:
|
||
try:
|
||
db.move(c, eid, d.get("meal"))
|
||
except db.Invalid as e:
|
||
return jsonify(error=str(e), field=e.field), 400
|
||
return jsonify(ok=True)
|
||
|
||
@bp.route("/api/parse", methods=["POST"])
|
||
def api_parse(): # {text} → {items} to confirm; nothing saved
|
||
text = str(body().get("text") or "").strip()[:PARSE_MAX]
|
||
if not text:
|
||
return jsonify(error="Write what you ate first."), 400
|
||
if not ctx.settings.get("use_model"):
|
||
return jsonify(error="The describe box is switched off — Settings ▸ Food."), 503
|
||
with con() as c:
|
||
known = [f["name"] for f in db.foods(c, limit=40)]
|
||
try:
|
||
items = parse.parse(text, ctx.settings, known, lambda n: db.match(c, n), lambda n: lookup(c, n))
|
||
except parse.Unavailable as e:
|
||
return jsonify(error=str(e)), 503
|
||
if not items:
|
||
return jsonify(error="No food found in that — try naming the foods."), 422
|
||
return jsonify(items=items)
|