[S-12] Связка Mealie → Grocy: команда !рецепт, ингредиенты в список покупок
This commit is contained in:
1 parent
0a6aaab7d3
commit
bd2a228d2b
3 files changed
+183
No files matched your search
@@ -49,6 +49,7 @@
|
||||
|
||||
| S-10 | Настроить 2FA заново (TOTP или код в Matrix) | ⏳ | следующий спринт; сейчас отключена (`ops/auth/2FA-TEMP-OFF.md`) |
|
||||
| S-11 | Vikunja: задачи и дела | ✅ | CT110:9285, OIDC Authentik, бэкап `ct/vikunja-db.tgz` |
|
||||
| S-12 | Mealie → Grocy: рецепт в покупки | ✅ | `!рецепт`, `ops/home/MEALIE-GROCY.md` |
|
||||
## X. Инфраструктура
|
||||
|
||||
| # | Задача | Статус | Артефакт |
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# Mealie → Grocy: рецепт в список покупок
|
||||
|
||||
## Что делает
|
||||
|
||||
```
|
||||
!рецепт <название>
|
||||
```
|
||||
|
||||
Берёт рецепт из Mealie, находит ингредиенты и добавляет их в список Grocy
|
||||
«Shopping list» (создавая продукты при необходимости).
|
||||
|
||||
## Как устроено
|
||||
|
||||
| Часть | Где |
|
||||
|---|---|
|
||||
| Скрипт | `/opt/hub-core/mealie2grocy.py` |
|
||||
| Команда бота | `!рецепт` |
|
||||
| Данные Mealie | Postgres `mealie_db` (прямые SQL-запросы) |
|
||||
| Grocy API | `http://192.168.1.110:9283/api/objects/...` |
|
||||
| Ключ Grocy | `/root/.mealie-grocy.json` |
|
||||
|
||||
## Почему через БД Mealie
|
||||
|
||||
API Mealie требовал токен, а ручная вставка в `long_live_tokens` не принималась
|
||||
(401). Прямой SQL-запрос к `recipes` + `recipes_ingredients` проще и надёжнее,
|
||||
данные локальные.
|
||||
|
||||
## Ловушки (все проверены на практике)
|
||||
|
||||
1. **Таблица ингредиентов** — `recipes_ingredients`, не `recipe_ingredients`.
|
||||
2. **Справочники** — `ingredient_units` и `ingredient_foods`, не `units`/`foods`.
|
||||
3. **Grocy: создание продукта** требует `location_id`, `qu_id_*`,
|
||||
`min_stock_amount` — иначе `NOT NULL constraint failed`.
|
||||
4. **Grocy: список покупок** — `POST /api/objects/shopping_list` с
|
||||
`shopping_list_id`, а не `/shopping_list/{id}/items`.
|
||||
5. **Grocy API и reverse-proxy auth** — middleware требует заголовок,
|
||||
поэтому в запросах передаём и `GROCY-API-KEY`, и `X-Auth-Request-Email`.
|
||||
|
||||
## Проверено
|
||||
|
||||
```
|
||||
рецепт: Тестовый салат
|
||||
+ 2 помидоры
|
||||
+ 1 огурец
|
||||
итого добавлено: 2
|
||||
```
|
||||
Позиции появились в Grocy (`GET /api/objects/shopping_list`).
|
||||
|
||||
## Дальше
|
||||
|
||||
- Автоматически при добавлении рецепта в план на неделю.
|
||||
- Сопоставление продуктов по штрихкодам.
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Mealie (БД) → Grocy (API): рецепт превращается в список покупок."""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
PG = ("PGPASSWORD='Buryan20261016mrAzbQ5SWdxwYg' psql -h 192.168.1.151 -U postgres "
|
||||
"-d mealie_db -t -A -F '|'")
|
||||
GROCY = "http://192.168.1.110:9283"
|
||||
EMAIL = "roman@buryans.ru"
|
||||
TOKENS = "/root/.mealie-grocy.json"
|
||||
|
||||
|
||||
def sh(cmd):
|
||||
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=60)
|
||||
return (r.stdout or "").strip()
|
||||
|
||||
|
||||
def grocy(method, path, key, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
req = urllib.request.Request(GROCY + path, data=data, method=method,
|
||||
headers={"GROCY-API-KEY": key,
|
||||
"X-Auth-Request-Email": EMAIL,
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=25) as r:
|
||||
raw = r.read()
|
||||
return r.status, (json.loads(raw) if raw else {})
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read()[:200].decode("utf-8", "replace")
|
||||
|
||||
|
||||
def find_recipe(name):
|
||||
q = name.replace("'", "''")
|
||||
out = sh(f"{PG} -c \"select slug||'~'||name from recipes where name ilike '%{q}%' limit 5\"")
|
||||
rows = [r.split("~", 1) for r in out.splitlines() if "~" in r]
|
||||
if not rows:
|
||||
return None, []
|
||||
exact = [r for r in rows if r[1].lower() == name.lower()]
|
||||
slug, title = (exact or rows)[0]
|
||||
return title, ingredient_rows(slug)
|
||||
|
||||
|
||||
def ingredient_rows(slug):
|
||||
q = slug.replace("'", "''")
|
||||
sql = ("select coalesce(ri.quantity::text,''), coalesce(u.name,''), "
|
||||
"coalesce(f.name,''), coalesce(ri.note,''), coalesce(ri.original_text,'') "
|
||||
"from recipes_ingredients ri "
|
||||
"left join ingredient_units u on u.id = ri.unit_id "
|
||||
"left join ingredient_foods f on f.id = ri.food_id "
|
||||
f"join recipes r on r.id = ri.recipe_id where r.slug = '{q}'")
|
||||
out = sh(f"{PG} -c \"{sql}\"")
|
||||
items = []
|
||||
for line in out.splitlines():
|
||||
parts = line.split("|")
|
||||
if len(parts) < 4:
|
||||
continue
|
||||
qty, unit, food, note = parts[0], parts[1], parts[2], parts[3]
|
||||
label = " ".join(x for x in [qty, unit, food or note] if x).strip()
|
||||
if not label:
|
||||
continue
|
||||
items.append({"label": label, "product": (food or note or label)[:60],
|
||||
"amount": float(qty) if qty else 1})
|
||||
return items
|
||||
|
||||
|
||||
def ensure_list(key, title="Покупки"):
|
||||
st, data = grocy("GET", "/api/objects/shopping_lists", key)
|
||||
if st == 200 and isinstance(data, list):
|
||||
for l in data:
|
||||
if l.get("name") == title:
|
||||
return l["id"]
|
||||
if data:
|
||||
return data[0]["id"]
|
||||
st, created = grocy("POST", "/api/objects/shopping_lists", key, {"name": title})
|
||||
return created.get("id") if st in (200, 201) else None
|
||||
|
||||
|
||||
def ensure_product(key, name):
|
||||
q = "/api/objects/products?query%5B%5D=" + urllib.parse.quote("name=" + name)
|
||||
st, data = grocy("GET", q, key)
|
||||
if st == 200 and isinstance(data, list) and data:
|
||||
return data[0]["id"]
|
||||
st, created = grocy("POST", "/api/objects/products", key, {
|
||||
"name": name, "location_id": 2,
|
||||
"qu_id_purchase": 2, "qu_id_stock": 2, "qu_id_consume": 2,
|
||||
"min_stock_amount": 0,
|
||||
})
|
||||
return created.get("id") if st in (200, 201) else None
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
return
|
||||
name = sys.argv[1]
|
||||
tok = json.load(open(TOKENS))
|
||||
key = tok["grocy_key"]
|
||||
title, items = find_recipe(name)
|
||||
if not title:
|
||||
print(f"рецепт «{name}» не найден в Mealie")
|
||||
return
|
||||
print(f"рецепт: {title}")
|
||||
if not items:
|
||||
print("ингредиентов нет")
|
||||
return
|
||||
list_id = ensure_list(key)
|
||||
if not list_id:
|
||||
print("не удалось получить список Grocy")
|
||||
return
|
||||
added = 0
|
||||
for it in items:
|
||||
pid = ensure_product(key, it["product"])
|
||||
if not pid:
|
||||
continue
|
||||
st, _ = grocy("POST", "/api/objects/shopping_list", key, {
|
||||
"shopping_list_id": list_id, "product_id": pid,
|
||||
"amount": it["amount"] or 1})
|
||||
if st in (200, 201):
|
||||
added += 1
|
||||
print(" +", it["label"])
|
||||
print(f"итого добавлено: {added}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user