eatback / py /app.py
kritpakin's picture
Pages free connections when hidden, real-data fix wording, kitchen purchase-order menu, School A/B five-bin wording
efb572d verified
Raw History Blame Contribute Delete
75.6 kB
"""EatBack local server — Python standard library only. One laptop = server + database + dashboard. ESP32 boards post weights and voice-box presses over the phone hotspot's Wi-Fi; the dashboard, kitchen phone and simulator are served from /public. No scales at all? Every weight can also be typed in from the kitchen screen. Run: python server/app.py (or double-click run.cmd) """ from __future__ import annotations import json import math import mimetypes import os import re import socket import sys import time from http.cookies import SimpleCookie from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import parse_qs, quote, urlparse sys.path.insert(0, str(Path(__file__).resolve().parent)) import auth # noqa: E402 import backup # noqa: E402 import devices # noqa: E402 import logic # noqa: E402 import planning # noqa: E402 from db import ALL_GRADES, DEFAULT_SETTINGS, LOCK, ROOT, data_mode, log_event, many, one, run, save_settings, settings, transaction # noqa: E402 from seed import SEED_VERSION, seed # noqa: E402 from util import meal_id_for, now_iso, rnd, today # noqa: E402 PORT = int(os.environ.get("PORT", "5184")) PUBLIC = ROOT / "public" PAGES = {"/": "index.html", "/kitchen": "kitchen.html", "/sim": "sim.html", "/recipe": "recipe.html", "/planner": "planner.html", "/opinions": "opinions.html", "/flow-3d": "flow-3d.html", "/scales-3d": "scales-3d.html", "/start": "start.html"} GRADE_TH = {"K1": "อ.1", "K2": "อ.2", "K3": "อ.3", "P1": "ป.1", "P2": "ป.2", "P3": "ป.3", "P4": "ป.4", "P5": "ป.5", "P6": "ป.6"} class HttpError(Exception): def __init__(self, status: int, message: str): super().__init__(message) self.status = status def fail(status: int, message: str): raise HttpError(status, message) # ---------------------------------------------------------------- change notification state = {"version": 1, "voice_enabled": False, "voice_meal": None} _matrix = {"key": None, "value": None} def bump() -> None: state["version"] += 1 m = open_meal() state["voice_enabled"] = bool(m and m["investigation"]) state["voice_meal"] = m["id"] if m else None def matrix() -> dict: """Grade x menu picture, rebuilt only when the data changed (every change bumps the version).""" key = (state["version"], today()) if _matrix["key"] != key: _matrix.update(key=key, value=logic.grade_matrix()) return _matrix["value"] def open_meal() -> dict | None: return one("SELECT * FROM meals WHERE status = 'open' LIMIT 1") def stable_reading(channel: str) -> dict: r = devices.reading(channel) if not r["online"]: fail(409, "ไม่มีสัญญาณจากเครื่องชั่ง ถ้าไม่มีเครื่องชั่ง เลือก “พิมพ์เอง”") if not r["stable"]: fail(409, "น้ำหนักยังไม่นิ่ง รอสักครู่แล้วกดใหม่") return r def unique_meal_id(day: str, grade: str) -> str: base = meal_id = meal_id_for(day, grade) i = 2 while one("SELECT 1 FROM meals WHERE id = ?", meal_id): meal_id = f"{base}-{i}" i += 1 return meal_id def flag(value) -> int: return 1 if value in (True, 1, "1", "true", "on") else 0 def number(value, name: str, minimum: float = 0, maximum: float | None = None) -> float: if isinstance(value, bool): # JSON true/false would otherwise pass as 1/0 fail(400, f"กรอก{name}เป็นตัวเลข") try: v = float(value) except (TypeError, ValueError): fail(400, f"กรอก{name}เป็นตัวเลข") if not math.isfinite(v): fail(400, f"กรอก{name}เป็นตัวเลขที่วัดได้จริง") if v < minimum: fail(400, f"{name}ต้องไม่น้อยกว่า {minimum:g}") if maximum is not None and v > maximum: fail(400, f"{name}ต้องไม่เกิน {maximum:g}") return v def grade_arg(value, required: bool = True) -> str | None: g = value or None if g is None and not required: return None if g not in settings()["grades"]: fail(400, "เลือกชั้นก่อน") return g def query_grade(q) -> str | None: """?grade=P1 -> one grade, ?grade=all -> whole school, no grade -> the grade eating now (else whole school).""" g = (q.get("grade") or [""])[0] if g == "all": return None if not g: om = open_meal() return om["grade"] if om else None return grade_arg(g) # ---------------------------------------------------------------- trials + verification def update_action(action_id: int) -> None: """After a trial serve: any high result -> not verified; N good results -> verified; otherwise plan the next trial. Kids said "unfamiliar": a new food usually needs several tries, so an early high serve does not end the trial. It passes once the last N counted serves are normal and fails only after the exposure limit.""" a = one("SELECT * FROM actions WHERE id = ?", action_id) ctx = logic.context(a["grade"]) summ = logic.action_summary(a, ctx) counted = [t for t in summ["trials"] if t["result"] in ("good", "high")] n = summ["verify_n"] if summ["exposure"]: last = counted[-n:] if len(last) == n and all(t["result"] == "good" for t in last): status = "verified" elif len(counted) >= summ["max_trials"]: status = "not_verified" else: status = "testing" elif any(t["result"] == "high" for t in counted): status = "not_verified" elif summ["good"] >= n: status = "verified" else: status = "testing" run("UPDATE actions SET status = ? WHERE id = ?", status, action_id) if status != "testing": run("DELETE FROM meals WHERE action_id = ? AND status = 'planned'", action_id) elif not one("SELECT 1 FROM meals WHERE action_id = ? AND status IN ('planned', 'open')", action_id): last = max(t["date"] for t in summ["trials"]) day = logic.next_trial_date(last, a["grade"], summ["gap_days"]) run("INSERT INTO meals (id, date, menu_id, grade, status, origin, action_id) VALUES (?, ?, ?, ?, 'planned', 'trial', ?)", unique_meal_id(day, a["grade"]), day, a["trial_menu_id"], a["grade"], action_id) log_event("action_result", action_id=action_id, grade=a["grade"], status=status, good=summ["good"]) # ---------------------------------------------------------------- routes def get_state(q, body): grade = query_grade(q) m = matrix() return logic.build_state(grade, {"version": state["version"], "network": lan_urls(), "grade_summary": m["summary"]}) def get_live(q, body): lockout = settings()["vote_lockout_s"] return { "version": state["version"], "scales": devices.snapshot(), "voice": {"enabled": state["voice_enabled"], "meal_id": state["voice_meal"], "locked_s": round(devices.voice_locked(lockout), 1)}, } def get_menus(q, body): grade = grade_arg((q.get("grade") or [""])[0], required=False) if (q.get("grade") or [""])[0] not in ("", "all") else None ctx = logic.context(grade) return {"menus": logic.menu_table(ctx), "budget": ctx["budget"], "settings": ctx["s"], "learning": ctx["learning"], **logic.prototype_metadata()} def get_patterns(q, body): g = (q.get("grade") or ["all"])[0] m = matrix() if g in ("", "all"): menus = {k: v for k, v in logic.context(None)["menus"].items()} return {"grade": None, "matrix": m, "menus": [menus[k] for k in sorted(menus)], "summary": m["summary"], **logic.prototype_metadata()} grade = grade_arg(g) ctx = logic.context(grade) rank = {"repeated_high": 0, "high": 1, "normal": 2, "nobase": 3, "learning": 3, "no_data": 4} rows = [] for mn in ctx["menus"].values(): rows.append({"menu": mn, "pattern": logic.menu_pattern(mn["id"], ctx), "audit": logic.latest_finding(mn["id"], grade, ctx)}) rows.sort(key=lambda r: (rank[r["pattern"]["flag"]], r["menu"]["id"])) s = ctx["s"] return {"grade": grade, "menus": rows, "repeat_n": s["repeat_n"], "margin": s["high_margin_pts"], "summary": m["summary"], "learning": {"active": ctx["learning"], "counted": ctx["counted_n"], "needed": s["learning_min_meals"]}, **logic.prototype_metadata()} def get_report(q, body): """The principal's monthly report (?month=YYYY-MM, default this month).""" month = (q.get("month") or [""])[0] if month and not re.fullmatch(r"\d{4}-(0[1-9]|1[0-2])", month): fail(400, "เดือนต้องเป็นรูปแบบ YYYY-MM") return logic.monthly_report(month or None, logic.issues(matrix())) def get_issues(q, body): m = matrix() alerts = [{"grade": g, **m["summary"][g]["grade_alert"]} for g in m["grades"] if m["summary"][g]["grade_alert"]] return {"issues": logic.issues(m), "grade_alerts": alerts, "summary": m["summary"], "grades": m["grades"], "repeat_n": m["repeat_n"], **logic.prototype_metadata()} def get_action(q, body): grade = grade_arg((q.get("grade") or [""])[0]) ctx = logic.context(grade) menu_id = (q.get("menu") or [""])[0] menu = ctx["menus"].get(menu_id) or fail(404, "ไม่พบเมนู") pattern = logic.menu_pattern(menu_id, ctx) ra = logic.replaceable_action(menu_id, grade) la = logic.latest_action(menu_id, grade) # Show the evidence behind the running/confirmed decision rather than an empty new investigation. shown = ra or (la if la and la["status"] in ("testing", "verified") else None) synth = logic.cause_synthesis(menu_id, ctx, shown["id"] if shown else None) opts = logic.options(menu_id, synth, ctx) if synth["ready"] else {"solution": None, "options": [], "rejected": []} actions = [logic.action_summary(a, ctx) for a in many("SELECT * FROM actions WHERE menu_id = ? AND grade = ? ORDER BY id DESC", menu_id, grade)] return { "grade": grade, "menu": menu, "pattern": pattern, "synthesis": synth, **opts, "actions": actions, **logic.prototype_metadata(), "replaceable_action_id": ra["id"] if ra else None, "needs_investigation": logic.needs_investigation(menu_id, ctx), "budget": ctx["budget"], "settings": ctx["s"], "solutions": logic.SOLUTIONS, "reasons": logic.REASONS, "learning": {"active": ctx["learning"], "counted": ctx["counted_n"], "needed": ctx["s"]["learning_min_meals"]}, "reuse": logic.reuse_targets(la) if la and la["status"] == "verified" else None, } def post_schedule(q, body): grade = grade_arg(body.get("grade")) ctx = logic.context(grade) menu_id, key = body.get("menu_id"), body.get("option_key") if menu_id not in ctx["menus"]: fail(404, "ไม่พบเมนู") pattern = logic.menu_pattern(menu_id, ctx) if pattern["flag"] != "repeated_high": fail(409, "เมนูนี้ยังไม่ได้เหลือเยอะ 3 ครั้งติด") la = logic.latest_action(menu_id, grade) if la and la["status"] == "verified": fail(409, "เมนูนี้ผ่านเกณฑ์การกินจากการทดลองแล้ว") ra = logic.replaceable_action(menu_id, grade) # a planned trial that has not been served can still be swapped if la and la["status"] == "testing" and not ra: fail(409, "กำลังทดลองอยู่ รอผลก่อนค่อยเปลี่ยนแผน") synth = logic.cause_synthesis(menu_id, ctx, ra["id"] if ra else None) if not synth["ready"]: fail(409, synth["blockers"][0]) opts = logic.options(menu_id, synth, ctx) opt = next((o for o in opts["options"] if o["key"] == key and o["eligible"]), None) or fail(400, "ตัวเลือกนี้ไม่ผ่านเงื่อนไขของแผนจำลองหรืองบ") with transaction(): if ra: run("DELETE FROM meals WHERE action_id = ? AND status = 'planned'", ra["id"]) run("DELETE FROM actions WHERE id = ?", ra["id"]) cur = run( """INSERT INTO actions (menu_id, grade, evidence_meals, audit_id, finding, cause, option_key, kind, trial_menu_id, change_th, status, before_pct, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'testing', ?, ?)""", menu_id, grade, json.dumps(synth["evidence_meals"]), synth["audit"]["audit_id"] if synth["audit"] else None, synth["what"]["key"] if synth["what"] else None, synth["why"]["key"], key, opt["kind"], opt["menu"]["id"], opt["change"], pattern["avg_last_pct"], now_iso(), ) day = logic.next_trial_date(today(), grade) meal_id = unique_meal_id(day, grade) run("INSERT INTO meals (id, date, menu_id, grade, status, origin, action_id) VALUES (?, ?, ?, ?, 'planned', 'trial', ?)", meal_id, day, opt["menu"]["id"], grade, cur.lastrowid) log_event("action_scheduled", menu_id=menu_id, grade=grade, option=key, cause=synth["why"]["key"], finding=synth["what"]["key"] if synth["what"] else None, trial_meal_id=meal_id) bump() return {"ok": True, "trial_meal_id": meal_id, "date": day, **logic.prototype_metadata()} def post_reuse(q, body): source = one("SELECT * FROM actions WHERE id = ?", body.get("action_id")) or fail(404, "ไม่พบวิธีแก้ต้นทาง") if source["status"] != "verified" or source["grade"] not in settings()["grades"]: fail(409, "ใช้ได้เฉพาะวิธีแก้ที่ผ่านเกณฑ์การกินแล้วในชั้นที่เปิดใช้งาน") selected = body.get("grades") if not isinstance(selected, list) or not selected or any(not isinstance(g, str) for g in selected): fail(400, "เลือกชั้นที่จะทดลองอย่างน้อยหนึ่งชั้น") selected = list(dict.fromkeys(selected)) created, existing = [], [] with transaction(): targets = {t["grade"]: t for t in logic.reuse_targets(source)["targets"]} for grade in selected: target = targets.get(grade) or fail(400, "เลือกชั้นปลายทางที่เปิดใช้งานและต่างจากต้นทาง") if target["reason_code"] == "already_reused": existing.append({"grade": grade, "action_id": target["existing_action_id"], "meal_id": target["meal_id"], "date": target["date"]}) elif not target["eligible"]: fail(409, f"{GRADE_TH.get(grade, grade)}: {target['reason']}") for grade in selected: if targets[grade]["reason_code"] == "already_reused": continue ctx = logic.context(grade) pattern = logic.menu_pattern(source["menu_id"], ctx) synth = logic.cause_synthesis(source["menu_id"], ctx) opt = next(o for o in logic.options(source["menu_id"], synth, ctx)["options"] if o["key"] == source["option_key"] and o["eligible"]) cur = run("""INSERT INTO actions (menu_id, grade, evidence_meals, audit_id, finding, cause, option_key, kind, trial_menu_id, change_th, status, before_pct, source_action_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'testing', ?, ?, ?)""", source["menu_id"], grade, json.dumps(synth["evidence_meals"]), synth["audit"]["audit_id"], synth["what"]["key"] if synth["what"] else None, synth["why"]["key"], source["option_key"], opt["kind"], opt["menu"]["id"], opt["change"], pattern["avg_last_pct"], source["id"], now_iso()) action_id = cur.lastrowid day = logic.next_trial_date(today(), grade) meal_id = unique_meal_id(day, grade) run("INSERT INTO meals (id, date, menu_id, grade, status, origin, action_id) VALUES (?, ?, ?, ?, 'planned', 'trial', ?)", meal_id, day, opt["menu"]["id"], grade, action_id) created.append({"grade": grade, "action_id": action_id, "meal_id": meal_id, "date": day}) log_event("action_reused", source_action_id=source["id"], action_id=action_id, grade=grade, trial_meal_id=meal_id) if created: bump() return {"ok": True, "created": created, "existing": existing, "reuse": logic.reuse_targets(source), **logic.prototype_metadata()} # ----- weekly plans and purchase quantities ----- def planner_dates(value): try: return planning.week_dates(value) except (TypeError, ValueError): fail(400, "เลือกวันที่รูปแบบ YYYY-MM-DD") def planner_grades(value): if value in (None, ""): return None selected = value.split(",") if isinstance(value, str) else value if not isinstance(selected, list) or not selected or any(g not in settings()["grades"] for g in selected): fail(400, "เลือกชั้นที่เปิดใช้งาน") return [g for g in settings()["grades"] if g in selected] def get_planner(q, body): dates = planner_dates((q.get("week") or [None])[0]) return {**planning.report(dates[0], planner_grades((q.get("grades") or [None])[0])), **logic.prototype_metadata()} def post_planner_save(q, body): dates = planner_dates(body.get("week")) grades = planner_grades(body.get("grades")) entries = body.get("entries") if not isinstance(entries, list) or len(entries) > 45: fail(400, "ส่งรายการแผนไม่เกิน 45 รอบต่อสัปดาห์") s = settings() seen = set() cleaned = [] for entry in entries: if not isinstance(entry, dict): fail(400, "รายการแผนไม่ถูกต้อง") grade = grade_arg(entry.get("grade")) day = entry.get("date") if day not in dates or day < today(): fail(400, "วางแผนได้เฉพาะวันเรียนในสัปดาห์ที่เลือก ตั้งแต่วันนี้เป็นต้นไป") if (day, grade) in seen: fail(400, "มีชั้นและวันที่ซ้ำในแผน") seen.add((day, grade)) menu_id = entry.get("menu_id") or None students = None if menu_id: one("SELECT 1 FROM menus WHERE id = ?", menu_id) or fail(404, "ไม่พบเมนู") heads = number(entry.get("students", s["grade_students"].get(grade, 0)), "จำนวนนักเรียน", 1, 2000) if not heads.is_integer(): fail(400, "จำนวนนักเรียนต้องเป็นจำนวนเต็ม") students = int(heads) cleaned.append((day, grade, menu_id, students)) with transaction(): for day, grade, menu_id, students in cleaned: rows = many("SELECT * FROM meals WHERE date = ? AND grade = ?", day, grade) if any(row["status"] != "planned" or row["action_id"] or row["origin"] == "trial" for row in rows): fail(409, f"{day} · {GRADE_TH[grade]} มีรอบทดลองหรือรอบที่เริ่มแล้ว แก้แผนไม่ได้") if len(rows) > 1: fail(409, f"{day} · {GRADE_TH[grade]} มีแผนมากกว่าหนึ่งรอบ กรุณาตรวจสอบก่อน") if not menu_id: if rows: run("DELETE FROM meals WHERE id = ?", rows[0]["id"]) elif rows: run("UPDATE meals SET menu_id = ?, students = ?, planned_students = ?, origin = 'weekly' WHERE id = ?", menu_id, students, students, rows[0]["id"]) else: run("INSERT INTO meals (id, date, menu_id, grade, students, planned_students, status, origin) VALUES (?, ?, ?, ?, ?, ?, 'planned', 'weekly')", unique_meal_id(day, grade), day, menu_id, grade, students, students) if cleaned: log_event("weekly_plan_saved", week=dates[0], cells=len(cleaned)) if cleaned: bump() return {"ok": True, **planning.report(dates[0], grades), **logic.prototype_metadata()} # ----- rounds (kitchen phone) ----- def post_open(q, body): om = open_meal() if om: fail(409, f"รอบ {GRADE_TH.get(om['grade'], om['grade'])} ยังไม่จบ จบรอบนั้นก่อน") grade = grade_arg(body.get("grade")) ctx = logic.context(grade) menu = ctx["menus"].get(body.get("menu_id")) or fail(400, "เลือกเมนูก่อน") students = int(number(body.get("students"), "จำนวนนักเรียน", 1)) manual_bins = body.get("bins") == "manual" rice = dish = 0.0 sorted_start = {} # five-bin station: each bin's reading now, so the round counts only what children add if not manual_bins: if settings()["return_bins"] == "five": sorted_start = {b: stable_reading(b)["raw"] for b in devices.FIVE_BINS} else: rice = stable_reading("rice")["raw"] dish = stable_reading("dish")["raw"] d = today() planned = (one("SELECT * FROM meals WHERE id = ? AND status = 'planned'", body["meal_id"]) if body.get("meal_id") else one("""SELECT * FROM meals WHERE status = 'planned' AND menu_id = ? AND grade = ? AND (origin <> 'weekly' OR date = ?) ORDER BY CASE WHEN date = ? THEN 0 ELSE 1 END, date LIMIT 1""", menu["id"], grade, d, d)) if body.get("meal_id") and not planned: fail(409, "แผนนี้ถูกเปลี่ยนหรือเปิดรอบแล้ว โหลดข้อมูลใหม่ก่อน") if planned and (planned["grade"] != grade or planned["menu_id"] != menu["id"]): fail(409, "ชั้นหรือเมนูไม่ตรงกับรอบที่วางแผนไว้") if planned and planned["origin"] == "weekly" and planned["date"] != d: fail(409, "เปิดรอบจากแผนรายสัปดาห์ได้เฉพาะวันที่วางแผนไว้") weekly_today = one("SELECT id FROM meals WHERE date = ? AND grade = ? AND origin = 'weekly' AND status = 'planned'", d, grade) if weekly_today and (not planned or planned["id"] != weekly_today["id"]): fail(409, "ชั้นนี้มีเมนูในแผนวันนี้แล้ว แก้เมนูที่หน้าวางแผนก่อนเปิดรอบ") investigation = 0 if (planned and planned["action_id"]) else int(logic.needs_investigation(menu["id"], ctx)) with transaction(): if planned: meal_id = planned["id"] if planned["date"] == d else unique_meal_id(d, grade) if planned["origin"] == "weekly": run("UPDATE meals SET planned_students = COALESCE(planned_students, students, ?) WHERE id = ?", settings()["grade_students"].get(grade, students), planned["id"]) run( """UPDATE meals SET id = ?, date = ?, menu_id = ?, students = ?, status = 'open', investigation = ?, bins_manual = ?, context_absence = ?, context_event = ?, return_rice_start = ?, return_dish_start = ?, opened_at = ? WHERE id = ?""", meal_id, d, menu["id"], students, investigation, int(manual_bins), flag(body.get("context_absence")), flag(body.get("context_event")), rice, dish, now_iso(), planned["id"], ) else: meal_id = unique_meal_id(d, grade) run( """INSERT INTO meals (id, date, menu_id, grade, students, status, origin, investigation, bins_manual, context_absence, context_event, return_rice_start, return_dish_start, opened_at) VALUES (?, ?, ?, ?, ?, 'open', 'live', ?, ?, ?, ?, ?, ?, ?)""", meal_id, d, menu["id"], grade, students, investigation, int(manual_bins), flag(body.get("context_absence")), flag(body.get("context_event")), rice, dish, now_iso(), ) for b, g in sorted_start.items(): run("INSERT OR REPLACE INTO sorted_bins (meal_id, bin, start_g, waste_g) VALUES (?, ?, ?, NULL)", meal_id, b, g) log_event("meal_opened", meal_id=meal_id, grade=grade, menu_id=menu["id"], students=students, investigation=bool(investigation), bins="manual" if manual_bins else "five" if sorted_start else "scale", return_start_g=sorted_start or {"rice": rice, "dish": dish}) devices.clear_tare("kitchen") bump() return {"ok": True, "meal_id": meal_id, "investigation": bool(investigation)} def post_context(q, body): meal = (one("SELECT * FROM meals WHERE id = ?", body["meal_id"]) if body.get("meal_id") else None) or open_meal() or fail(409, "ไม่พบมื้อ") run("UPDATE meals SET context_absence = ?, context_event = ? WHERE id = ?", flag(body.get("context_absence")), flag(body.get("context_event")), meal["id"]) log_event("meal_context", meal_id=meal["id"], context_absence=flag(body.get("context_absence")), context_event=flag(body.get("context_event"))) bump() return {"ok": True} def post_capture(q, body): """Pot before/after serving: from the kitchen scale, or typed in ("manual_g") when there is no scale.""" meal = open_meal() or fail(409, "ยังไม่ได้เริ่มมื้อ") pot, phase = body.get("pot"), body.get("phase") if pot not in ("rice", "dish") or phase not in ("before", "after"): fail(400, "bad request") active = next((p for p in logic.pots_for(meal["id"]) if p["pot"] == pot and p["after_g"] is None), None) if phase == "after" and not active: fail(409, 'ยังไม่ได้ชั่ง "ก่อนตัก"') if phase == "before" and active: fail(409, 'หม้อนี้ยังไม่ได้ชั่ง "หลังตัก"') if body.get("manual_g") is not None: raw, source = round(number(body.get("manual_g"), "น้ำหนักหม้อ", 0, 300000), 1), "manual" else: r = stable_reading("kitchen") raw, source = r["raw"], r["source"] if phase == "before" and raw < 50: fail(409, "ยังไม่ได้วางหม้อบนเครื่องชั่ง") if phase == "after" and raw > active["before_g"] + 20: fail(409, "หลังตักหนักกว่าก่อนตัก ลองเช็กว่าเป็นหม้อใบเดิมไหม") run("INSERT INTO weighings (meal_id, pot, phase, raw_g, source, ts) VALUES (?, ?, ?, ?, ?, ?)", meal["id"], pot, phase, raw, source, now_iso()) log_event("kitchen_weighing", meal_id=meal["id"], pot=pot, phase=phase, raw_g=raw, source=source) bump() return {"ok": True, "raw_g": raw} def post_undo(q, body): meal = open_meal() or fail(409, "ยังไม่ได้เริ่มมื้อ") w = one("SELECT * FROM weighings WHERE meal_id = ? ORDER BY id DESC LIMIT 1", meal["id"]) or fail(409, "ไม่มีรายการให้ย้อน") run("DELETE FROM weighings WHERE id = ?", w["id"]) log_event("kitchen_weighing_undone", meal_id=meal["id"], weighing=w) bump() return {"ok": True} def post_broth(q, body): meal = open_meal() or fail(409, "ยังไม่ได้เริ่มมื้อ") point = body.get("point") if point not in ("start", "middle", "end"): fail(400, "เลือกช่วงที่ตัก") ladle = number(body.get("ladle_g"), "น้ำหนักทัพพี", 1) solid = number(body.get("solid_g"), "น้ำหนักเนื้อหลังกรอง", 0) if solid > ladle: fail(400, "เนื้อหลังกรองต้องไม่หนักกว่าทั้งทัพพี") run("DELETE FROM broth_samples WHERE meal_id = ? AND point = ?", meal["id"], point) run("INSERT INTO broth_samples (meal_id, point, ladle_g, solid_g, ts) VALUES (?, ?, ?, ?, ?)", meal["id"], point, ladle, solid, now_iso()) log_event("broth_sample", meal_id=meal["id"], point=point, ladle_g=ladle, solid_g=solid) bump() return {"ok": True, "ratio": rnd(solid / ladle, 3)} def post_close(q, body): meal = open_meal() or fail(409, "ยังไม่ได้เริ่มมื้อ") ctx = logic.context(meal["grade"]) menu = ctx["menus"][meal["menu_id"]] pots = logic.pots_for(meal["id"]) if any(p["after_g"] is None for p in pots): fail(409, 'ยังมีหม้อที่ไม่ได้ชั่ง "หลังตัก"') served = logic.served_from_pots(pots) if served["rice_served_g"] + served["dish_served_g"] <= 0: fail(409, "ยังไม่ได้ชั่งหม้อเลย") broth = logic.broth_for(meal["id"]) if menu["has_broth"]: need = logic.broth_required(meal, ctx) if len(broth["samples"]) < need: fail(409, f"เมนูแกง ต้องวัดทัพพีให้ครบ {need} ครั้ง (ตอนนี้ {len(broth['samples'])} ครั้ง)") typed = body.get("rice_waste_g") is not None or body.get("dish_waste_g") is not None typed_bins = body.get("sorted_waste_g") # five bins weighed on any scale: {bin: grams} bone_w = None # weighed only by the five-bin station sorted_start = {r["bin"]: r["start_g"] for r in many("SELECT bin, start_g FROM sorted_bins WHERE meal_id = ?", meal["id"])} sorted_waste = {} if typed_bins is not None: if not isinstance(typed_bins, dict): fail(400, "น้ำหนักถังเศษไม่ถูกต้อง") sorted_waste = {b: number(typed_bins.get(b), f"น้ำหนักถัง{devices.BIN_TH[b]}", 0, 200000) for b in devices.FIVE_BINS} rice_w = sorted_waste["starch"] dish_w = sorted_waste["veg"] + sorted_waste["protein"] + sorted_waste["fat"] bone_w = sorted_waste["bone"] source = "manual" elif meal["bins_manual"] or typed: if body.get("rice_waste_g") is None or body.get("dish_waste_g") is None: fail(409, "กรอกน้ำหนักเศษข้าวและเศษกับข้าวก่อนจบรอบ") rice_w = number(body.get("rice_waste_g"), "น้ำหนักเศษข้าว", 0, 200000) dish_w = number(body.get("dish_waste_g"), "น้ำหนักเศษกับข้าว", 0, 200000) source = "manual" elif sorted_start: # Five bins the children sorted into. Rice is the starch bin; the side dish's leftovers are vegetables, meat # and the skin and fat picked off it. Bones and other inedible parts were never food: they come off what the # dish served (logic.dish_served_eff) instead of counting as leftovers. bins = {b: devices.reading(b) for b in devices.FIVE_BINS} if not all(r["online"] for r in bins.values()): fail(409, "ถังเศษบางใบไม่มีสัญญาณ เช็ก ESP32 หรือเปิดหน้าจำลอง") if not all(r["stable"] for r in bins.values()): fail(409, "ถังเศษยังไม่นิ่ง รอสักครู่ก่อนจบมื้อ") sorted_waste = {b: max(0.0, r["raw"] - sorted_start.get(b, 0.0)) for b, r in bins.items()} rice_w = sorted_waste["starch"] dish_w = sorted_waste["veg"] + sorted_waste["protein"] + sorted_waste["fat"] bone_w = sorted_waste["bone"] source = bins["starch"]["source"] else: rice, dish = devices.reading("rice"), devices.reading("dish") if not rice["online"] or not dish["online"]: fail(409, "ถังเศษไม่มีสัญญาณ เช็ก ESP32 หรือเปิดหน้าจำลอง") if not rice["stable"] or not dish["stable"]: fail(409, "ถังเศษยังไม่นิ่ง รอสักครู่ก่อนจบมื้อ") rice_w = max(0.0, rice["raw"] - (meal["return_rice_start"] or 0)) dish_w = max(0.0, dish["raw"] - (meal["return_dish_start"] or 0)) source = rice["source"] # Cause-finding round: what came back by food group. Five bins weigh it for the whole round; two bins need the # 4-compartment tray sorted and saved first. if meal["investigation"] and not sorted_waste and not one("SELECT 1 FROM audits WHERE meal_id = ?", meal["id"]): fail(409, "รอบหาสาเหตุ: แยกเศษ 4 ช่องแล้วบันทึกก่อนชั่งเศษและจบรอบ") # Leftovers cannot outweigh what was served (5% + 20 g allows for scale tolerance and wet scraps). A bigger # number means a mixed-up bin, a lost tare or a typing slip, and would show up as a negative acceptance. served_g = served["rice_served_g"] + served["dish_served_g"] back_g = rice_w + dish_w + (bone_w or 0) if back_g > served_g * 1.05 + 20: fail(409, f"เศษ {back_g:,.0f} ก. มากกว่าอาหารที่ตักเสิร์ฟ {served_g:,.0f} ก. " "ตรวจถังเศษ การตั้งศูนย์ หรือตัวเลขที่พิมพ์ แล้วจบรอบใหม่") if bone_w and bone_w > served["dish_served_g"] * 0.5 + 20: fail(409, f"ถังกระดูก {bone_w:,.0f} ก. เกินครึ่งของกับข้าวที่ตัก ตรวจว่ามีผลไม้ เปลือกผลไม้ หรือเศษอาหารลงผิดถัง") qc_ok = 1 if logic.qc_today(ctx)["all_ok"] else 0 with transaction(): run( """UPDATE meals SET status = 'closed', rice_served_g = ?, dish_served_g = ?, solid_ratio = ?, rice_waste_g = ?, dish_waste_g = ?, bone_g = ?, qc_ok = ?, bins_manual = ?, closed_at = ? WHERE id = ?""", served["rice_served_g"], served["dish_served_g"], broth["ratio"] if menu["has_broth"] else None, rice_w, dish_w, bone_w, qc_ok, int(source == "manual"), now_iso(), meal["id"], ) if sorted_waste: for b, g in sorted_waste.items(): # typed bins have no start reading run("""INSERT INTO sorted_bins (meal_id, bin, start_g, waste_g) VALUES (?, ?, 0, ?) ON CONFLICT(meal_id, bin) DO UPDATE SET waste_g = excluded.waste_g""", meal["id"], b, round(g, 1)) else: # typed in: there are no per-bin leftovers for this round run("DELETE FROM sorted_bins WHERE meal_id = ?", meal["id"]) log_event("meal_closed", meal_id=meal["id"], grade=meal["grade"], **served, rice_waste_g=rice_w, dish_waste_g=dish_w, bins=source, sorted_waste_g={b: round(g, 1) for b, g in sorted_waste.items()} or None, solid_ratio=broth["ratio"], qc_ok=bool(qc_ok)) if meal["action_id"]: update_action(meal["action_id"]) bump() safe_backup("close") return {"ok": True} def post_cancel(q, body): meal = open_meal() or fail(409, "ยังไม่ได้เริ่มมื้อ") with transaction(): for t in ("weighings", "broth_samples", "votes", "sorted_bins"): run(f"DELETE FROM {t} WHERE meal_id = ?", meal["id"]) run("""UPDATE meals SET status = 'planned', students = CASE WHEN origin = 'weekly' THEN COALESCE(planned_students, students) ELSE NULL END, investigation = 0, bins_manual = 0, return_rice_start = NULL, return_dish_start = NULL, opened_at = NULL WHERE id = ?""", meal["id"]) log_event("meal_cancelled", meal_id=meal["id"]) bump() return {"ok": True} def post_tare(q, body): r = stable_reading("kitchen") devices.tare("kitchen") log_event("kitchen_tare", raw_g=r["raw"]) return {"ok": True} # ----- 4-compartment sort: typed in from any scale, before the leftovers are weighed ----- def get_audits(q, body): g = (q.get("grade") or [""])[0] ctx = logic.context(grade_arg(g) if g not in ("", "all") else None) return {**logic.audit_meals(ctx), "settings": ctx["s"], "groups": logic.GROUPS} def post_audit(q, body): meal = one("SELECT * FROM meals WHERE id = ?", body.get("meal_id")) or fail(404, "ไม่พบมื้อ") # Sorted before the leftovers are weighed (open round), or typed in later for a finished one. if meal["status"] not in ("open", "closed"): fail(409, "ยังไม่ได้เริ่มรอบนี้") covers = int(number(body.get("covers") or meal["students"], "จำนวนนักเรียนที่รวมเศษ", 1)) g = {k: number(body.get(f"{k}_g"), f"น้ำหนัก{logic.GROUP_TH[k]}", 0) for k in ("starch", "veg", "protein", "fruit")} cur = run("INSERT INTO audits (meal_id, covers, starch_g, veg_g, protein_g, fruit_g, source, ts) VALUES (?, ?, ?, ?, ?, ?, 'manual', ?)", meal["id"], covers, g["starch"], g["veg"], g["protein"], g["fruit"], now_iso()) log_event("audit_saved", meal_id=meal["id"], covers=covers, **g) bump() a = one("SELECT * FROM audits WHERE id = ?", cur.lastrowid) return {"ok": True, "finding": logic.audit_finding(a, logic.context(meal["grade"]))} # ----- menus + recipes ----- PREPS = { # preparation style -> Thai / English name (the fix gate asks for a different style than the problem menu) "stirfry": ("ผัด", "Stir-fried"), "eggroll": ("ไข่ม้วน", "Rolled omelette"), "jpcurry": ("แกงกะหรี่", "Curry"), "steam": ("นึ่ง", "Steamed"), "soup": ("ต้มจืด", "Clear soup"), "fry": ("ทอด", "Fried"), "curry": ("แกงกะทิ", "Coconut curry"), "sauce": ("ผัดซอส", "In sauce"), "friedrice": ("ข้าวผัด", "Fried rice"), "noodle": ("ก๋วยเตี๋ยวน้ำ", "Noodle soup"), "poach": ("ต้ม", "Poached"), "pasta": ("เส้นราดซอส", "Pasta"), "bake": ("อบ", "Baked"), "grill": ("ย่าง", "Grilled"), "stew": ("ตุ๋น", "Braised"), "salad": ("ยำ/สลัด", "Salad"), } def get_menu(q, body): menu_id = (q.get("id") or [""])[0] if not one("SELECT 1 FROM menus WHERE id = ?", menu_id): fail(404, "ไม่พบเมนู") return {**logic.menu_detail(menu_id, matrix()), "preps": PREPS, **logic.prototype_metadata()} def post_menu_save(q, body): """Add or edit a menu. Grams are per student at the grade 4–6 portion.""" name_th = str(body.get("name_th") or "").strip() if not name_th: fail(400, "ใส่ชื่อเมนูภาษาไทย") category = body.get("category") if body.get("category") in ("rice_side", "one_dish") else fail(400, "เลือกประเภทเมนู") prep = body.get("prep") if body.get("prep") in PREPS else fail(400, "เลือกวิธีทำ") vals = {k: round(number(body.get(k) or 0, label, 0, 5000), 1) for k, label in ( ("starch_g", "ข้าวและแป้ง"), ("veg_g", "ผัก"), ("protein_g", "เนื้อสัตว์และไข่"), ("fruit_g", "ผลไม้"), ("kcal", "พลังงาน"))} cost = round(number(body.get("cost_thb") or 0, "ต้นทุนต่อคน", 0, 1000), 2) fields = { "name_th": name_th, "name_en": str(body.get("name_en") or "").strip() or name_th, "category": category, "prep": prep, "prep_th": PREPS[prep][0], "prep_en": PREPS[prep][1], "icon": str(body.get("icon") or "🍽️").strip()[:4], "has_broth": flag(body.get("has_broth")), "fruit_name": str(body.get("fruit_name") or "").strip(), "cost_thb": cost, "nutrition_pass": 0, "nutrition_status": "unverified", "nutrition_source": "", "nutrition_source_url": "", "nutrition_checked_at": "", "nutrition_scope": "", "data_origin": "user", **vals, } menu_id = body.get("id") with transaction(): if menu_id: one("SELECT 1 FROM menus WHERE id = ?", menu_id) or fail(404, "ไม่พบเมนู") run(f"UPDATE menus SET {', '.join(f'{k} = ?' for k in fields)} WHERE id = ?", *fields.values(), menu_id) else: n = max([int(r["id"][1:]) for r in many("SELECT id FROM menus WHERE id GLOB 'M[0-9]*'")] or [0]) + 1 menu_id = f"M{n:02d}" run(f"INSERT INTO menus (id, {', '.join(fields)}) VALUES (?, {', '.join('?' * len(fields))})", menu_id, *fields.values()) log_event("menu_saved", menu_id=menu_id, name_th=name_th) bump() return {"ok": True, "id": menu_id} def post_menu_delete(q, body): menu_id = body.get("id") one("SELECT 1 FROM menus WHERE id = ?", menu_id) or fail(404, "ไม่พบเมนู") if one("SELECT 1 FROM meals WHERE menu_id = ?", menu_id) or one("SELECT 1 FROM actions WHERE trial_menu_id = ? OR menu_id = ?", menu_id, menu_id): fail(409, "เมนูนี้เคยเสิร์ฟหรืออยู่ในแผนแล้ว ลบไม่ได้ แก้ไขแทนได้") with transaction(): run("DELETE FROM recipes WHERE menu_id = ?", menu_id) run("DELETE FROM menus WHERE id = ?", menu_id) log_event("menu_deleted", menu_id=menu_id) bump() return {"ok": True} def post_recipe_save(q, body): menu_id = body.get("menu_id") one("SELECT 1 FROM menus WHERE id = ?", menu_id) or fail(404, "ไม่พบเมนู") servings = int(number(body.get("servings"), "จำนวนที่ของสูตร", 1, 5000)) ingredients = [] for i in body.get("ingredients") or []: name, name_en = str(i.get("name") or "").strip(), str(i.get("name_en") or "").strip() if not name and not name_en: continue qty = i.get("qty") ingredients.append({"name": name or name_en, "name_en": name_en, "unit": str(i.get("unit") or "").strip(), "qty": None if qty in (None, "") else round(number(qty, "ปริมาณวัตถุดิบ", 0, 1e6), 2)}) clean = lambda xs: [str(x).strip() for x in (xs or []) if str(x).strip()] steps, steps_en = clean(body.get("steps")), clean(body.get("steps_en")) if not ingredients or not (steps or steps_en): fail(400, "ใส่วัตถุดิบและวิธีทำอย่างน้อยอย่างละ 1 ข้อ") old = logic.recipe_for(menu_id) or {} if body.get("lang") == "en": # the form edits one language at a time; keep the other one steps = steps or old.get("steps") or steps_en else: steps_en = steps_en if body.get("steps_en") is not None else old.get("steps_en", []) with transaction(): run("""INSERT INTO recipes (menu_id, servings, ingredients, steps, steps_en, tips, tips_en, updated_at, data_origin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'user') ON CONFLICT(menu_id) DO UPDATE SET servings = excluded.servings, ingredients = excluded.ingredients, steps = excluded.steps, steps_en = excluded.steps_en, tips = excluded.tips, tips_en = excluded.tips_en, updated_at = excluded.updated_at, data_origin = 'user'""", menu_id, servings, json.dumps(ingredients, ensure_ascii=False), json.dumps(steps, ensure_ascii=False), json.dumps(steps_en, ensure_ascii=False), str(body.get("tips", old.get("tips", "")) or "").strip(), str(body.get("tips_en", old.get("tips_en", "")) or "").strip(), now_iso()) run("""UPDATE menus SET nutrition_pass = 0, nutrition_status = 'unverified', nutrition_source = '', nutrition_source_url = '', nutrition_checked_at = '', nutrition_scope = '' WHERE id = ?""", menu_id) log_event("recipe_saved", menu_id=menu_id, servings=servings, ingredients=len(ingredients)) bump() return {"ok": True} # ----- kids' opinions: a teacher asks each child and taps one of the six answers in the app ----- def _opinion_meal(meal_id) -> dict: meal = one("SELECT * FROM meals WHERE id = ?", meal_id) or fail(404, "ไม่พบรอบนี้") if not meal["investigation"]: fail(409, "รอบนี้ไม่ต้องเก็บข้อคิดเห็นจากเด็ก ระบบจะขอเฉพาะรอบที่เมนูเหลือเยอะ 3 ครั้งติด") if meal["date"] != today() or meal["status"] not in ("open", "closed"): fail(409, "บันทึกข้อคิดเห็นจากเด็กได้เฉพาะรอบของวันนี้") return meal def _opinion_view(meal: dict) -> dict: counts = {b: 0 for b in devices.BUTTONS} for r in many("SELECT button, COUNT(*) AS n FROM votes WHERE meal_id = ? GROUP BY button", meal["id"]): counts[r["button"]] = r["n"] menu = one("SELECT id, name_th, name_en, icon FROM menus WHERE id = ?", meal["menu_id"]) total = sum(counts.values()) return {"meal_id": meal["id"], "grade": meal["grade"], "status": meal["status"], "students": meal["students"], "menu": menu, "counts": counts, "total": total, "over": total > (meal["students"] or 0), "can_undo": bool(one("SELECT 1 FROM votes WHERE meal_id = ? AND source = 'app'", meal["id"]))} def get_opinions(q, body): """Today's rounds that asked for the kids' opinions, and the one to record (the open round by default).""" rounds = many("""SELECT * FROM meals WHERE date = ? AND investigation = 1 AND status IN ('open', 'closed') ORDER BY COALESCE(opened_at, closed_at), id""", today()) want = (q.get("meal_id") or [""])[0] target = (next((m for m in rounds if m["id"] == want), None) or next((m for m in rounds if m["status"] == "open"), None) or (rounds[-1] if rounds else None)) s = settings() return {"buttons": list(devices.BUTTONS), "current": _opinion_view(target) if target else None, "rounds": [{"meal_id": m["id"], "grade": m["grade"], "status": m["status"]} for m in rounds], "low_pct": s["response_low_pct"], "high_pct": s["response_high_pct"], "school_name": s["school_name"]} def post_opinion(q, body): meal = _opinion_meal(body.get("meal_id")) button = body.get("button") if button not in devices.BUTTONS: fail(400, "ไม่รู้จักข้อคิดเห็นนี้") run("INSERT INTO votes (meal_id, button, source, ts) VALUES (?, ?, 'app', ?)", meal["id"], button, now_iso()) bump() return {"ok": True, **_opinion_view(meal)} def post_opinion_undo(q, body): """Remove the last answer tapped in the app for this round (a mistap).""" meal = _opinion_meal(body.get("meal_id")) last = one("SELECT id, button FROM votes WHERE meal_id = ? AND source = 'app' ORDER BY id DESC LIMIT 1", meal["id"]) if not last: fail(409, "ยังไม่มีข้อคิดเห็นให้ยกเลิก") run("DELETE FROM votes WHERE id = ?", last["id"]) bump() return {"ok": True, "removed": last["button"], **_opinion_view(meal)} # Older button-box endpoints (ESP32 B). The product now records opinions in the app; these stay for compatibility. def vote_status(q, body): s = settings() return {"enabled": state["voice_enabled"], "meal_id": state["voice_meal"], "locked_s": round(devices.voice_locked(s["vote_lockout_s"]), 1), "buttons": list(devices.BUTTONS)} def post_vote(q, body): """ESP32 B: {"button": "hard"}. Accepted only while an investigation round is open.""" button = body.get("button") if button not in devices.BUTTONS: fail(400, "unknown button") meal = open_meal() if not meal or not meal["investigation"]: fail(409, "รอบนี้ไม่ต้องเก็บข้อคิดเห็นจากเด็ก") s = settings() left = devices.voice_locked(s["vote_lockout_s"]) if left > 0: fail(429, f"รออีก {left:.1f} วินาทีแล้วกดใหม่ได้") devices.voice_press() source = "esp32" if body.get("source") != "sim" else "sim" run("INSERT INTO votes (meal_id, button, source, ts) VALUES (?, ?, ?, ?)", meal["id"], button, source, now_iso()) total = one("SELECT COUNT(*) AS n FROM votes WHERE meal_id = ?", meal["id"])["n"] bump() return {"ok": True, "total": total, "students": meal["students"], "over": total > (meal["students"] or 0)} def post_sim_votes(q, body): """Simulator: add a whole class's opinions at once (as if a teacher had tapped them).""" meal = open_meal() if not meal or not meal["investigation"]: fail(409, "รอบนี้ไม่ต้องเก็บข้อคิดเห็นจากเด็ก") counts = {k: int(v) for k, v in (body.get("counts") or {}).items() if k in devices.BUTTONS and int(v) > 0} ts = now_iso() with transaction(): for button, n in counts.items(): for _ in range(n): run("INSERT INTO votes (meal_id, button, source, ts) VALUES (?, ?, 'sim', ?)", meal["id"], button, ts) log_event("votes_simulated", meal_id=meal["id"], counts=counts) bump() return {"ok": True, "added": sum(counts.values())} # ----- QC ----- def post_qc_zero(q, body): if body.get("channel") not in devices.CHANNELS: fail(400, "bad channel") return {"ok": True, "zero_g": stable_reading(body["channel"])["raw"]} def post_qc_read(q, body): """Reference weight on the scale: read live, or typed in ("manual_g") for a scale without a board.""" s = settings() channel = body.get("channel") if channel not in devices.CHANNELS: fail(400, "bad channel") ref = number(body.get("reference_g") or s["qc_refs"][0], "ตุ้มมาตรฐาน", 1) if body.get("manual_g") is not None: reading, source = round(number(body.get("manual_g"), "ค่าที่อ่านได้", 0, 1e6), 1), "manual" else: r = stable_reading(channel) reading, source = round(r["raw"] - float(body.get("zero_g") or 0), 1), r["source"] dev = (reading - ref) / ref * 100 ok = 1 if abs(dev) <= s["qc_tolerance_pct"] else 0 run("""INSERT INTO qc_checks (channel, reference_g, reading_g, deviation_pct, tolerance_pct, pass, source, ts) VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", channel, ref, reading, dev, s["qc_tolerance_pct"], ok, source, now_iso()) log_event("qc_check", channel=channel, reference_g=ref, reading_g=reading, deviation_pct=rnd(dev, 2), pass_=bool(ok), source=source) bump() return {"ok": True, "reference_g": ref, "reading_g": reading, "deviation_pct": rnd(dev, 2), "tolerance_pct": s["qc_tolerance_pct"], "pass": bool(ok)} def get_qc(q, body): ctx = logic.context() events = many("SELECT * FROM events ORDER BY id DESC LIMIT 40") for e in events: e["detail"] = json.loads(e["detail"]) return {"today": logic.qc_today(ctx), "checks": many("SELECT * FROM qc_checks ORDER BY id DESC LIMIT 30"), "events": events, "settings": ctx["s"]} # ----- devices, settings, demo ----- def post_reading(q, body): """ESP32: {"device": "kitchen", "readings": {"kitchen": 2512.3}} or {"device": "return", "readings": {"rice": 1800, "dish": 4200}} or, five bins: {"device": "return", "readings": {"starch": g, "veg": g, "protein": g, "fat": g, "bone": g}}""" return {"ok": True, "accepted": devices.device_reading(body.get("readings") or {}), "voice_enabled": state["voice_enabled"]} def post_sim(q, body): if body.get("channel") not in devices.CHANNELS: fail(400, "bad channel") return {"ok": True, "channel": body["channel"], "value_g": devices.sim_set(body["channel"], body.get("value_g"), body.get("delta_g"))} # Every numeric rule a school can change: (Thai name for errors, whole number?, minimum, maximum). SETTING_RULES = { "high_margin_pts": ("เกณฑ์เหลือเยอะ", False, 0.5, 100), "repeat_n": ("จำนวนครั้งติด", True, 1, 20), "learning_min_meals": ("รอบเก็บข้อมูลตั้งต้น", True, 1, 500), "baseline_window_days": ("ช่วงวันของค่าปกติ", True, 7, 730), "baseline_min_meals": ("จำนวนรอบขั้นต่ำของค่าปกติ", True, 1, 200), "audit_flag_pct": ("เกณฑ์กลุ่มเด่นของการแยกเศษ", False, 1, 100), "audit_consistency_pct": ("เกณฑ์ความต่างของการแยกเศษ", False, 1, 100), "vote_lockout_s": ("เวลาล็อกปุ่ม", False, 0, 60), "response_low_pct": ("อัตราตอบขั้นต่ำ", False, 0, 100), "response_high_pct": ("อัตราตอบที่เชื่อถือได้มาก", False, 0, 100), "verify_n": ("จำนวนมื้อทดลองที่ต้องปกติ", True, 1, 20), "exposure_trials": ("จำนวนมื้อทดลองสูงสุดเมื่อเด็กไม่คุ้น", True, 1, 30), "exposure_gap_days": ("ระยะห่างของมื้อทดลองเมื่อเด็กไม่คุ้น", True, 1, 20), "portion_floor_pct": ("ปริมาณตักขั้นต่ำ", False, 0, 100), "grade_alert_pct": ("เกณฑ์เหลือสูงทั้งชั้น", False, 1, 100), "broth_points_normal": ("จำนวนจุดวัดแกงวันปกติ", True, 1, 3), "broth_points_audit": ("จำนวนจุดวัดแกงวันหาสาเหตุ", True, 1, 3), "qc_tolerance_pct": ("เกณฑ์ QC", False, 0.1, 10), "stable_band_g": ("ช่วงน้ำหนักนิ่ง", False, 0.5, 1000), "acceptance_window_days": ("ช่วงวันของ Menu Acceptance", True, 1, 730), } def clean_settings(body) -> dict: """Check and normalise a settings patch before anything is saved; one bad value rejects the whole patch.""" if not isinstance(body, dict): fail(400, "การตั้งค่าไม่ถูกต้อง") patch = {} for key, value in body.items(): if key == "enrolled" or key not in DEFAULT_SETTINGS: # enrolled is derived from the grade head counts continue if key in SETTING_RULES: name, whole, lo, hi = SETTING_RULES[key] v = number(value, name, lo, hi) if whole and not v.is_integer(): fail(400, f"{name}ต้องเป็นจำนวนเต็ม") patch[key] = int(v) if whole else v elif key == "school_name": name = str(value or "").strip() if not name or len(name) > 120: fail(400, "ใส่ชื่อโรงเรียน ไม่เกิน 120 ตัวอักษร") patch[key] = name elif key == "grades": grades = [g for g in ALL_GRADES if isinstance(value, list) and g in value] if not grades: fail(400, "เลือกอย่างน้อย 1 ชั้น") patch[key] = grades elif key in ("grade_students", "grade_portion"): if not isinstance(value, dict): fail(400, "การตั้งค่ารายชั้นไม่ถูกต้อง") if key == "grade_students": counts = {g: number(v, "จำนวนนักเรียน", 0, 2000) for g, v in value.items() if g in ALL_GRADES} if any(not v.is_integer() for v in counts.values()): fail(400, "จำนวนนักเรียนต้องเป็นจำนวนเต็ม") patch[key] = {g: int(v) for g, v in counts.items()} else: patch[key] = {g: round(number(v, "สัดส่วนที่ตัก", 0.2, 2), 2) for g, v in value.items() if g in ALL_GRADES} elif key == "qc_refs": # An empty list would let every channel "pass" QC with no check at all. if not isinstance(value, list) or not 1 <= len(value) <= 4: fail(400, "ตุ้ม QC ต้องมี 1–4 ค่า") refs = [number(v, "ตุ้มมาตรฐาน", 1, 200000) for v in value] if len(set(refs)) != len(refs): fail(400, "ตุ้ม QC ต้องไม่ซ้ำกัน") patch[key] = refs elif key == "return_bins": if value not in ("two", "five"): fail(400, "เลือกจุดคืนจานแบบ 2 ถัง หรือ 5 ถัง") om = open_meal() if om and value != settings()["return_bins"]: fail(409, f"รอบ {GRADE_TH.get(om['grade'], om['grade'])} ยังไม่จบ จบรอบก่อนเปลี่ยนจุดคืนจาน") patch[key] = value merged = {**settings(), **patch} if merged["response_low_pct"] > merged["response_high_pct"]: fail(400, "อัตราตอบขั้นต่ำต้องไม่มากกว่าอัตราตอบที่เชื่อถือได้มาก") if merged["exposure_trials"] < merged["verify_n"]: fail(400, "จำนวนมื้อทดลองสูงสุดเมื่อเด็กไม่คุ้น ต้องไม่น้อยกว่าจำนวนมื้อทดลองที่ต้องปกติ") return patch def post_settings(q, body): patch = clean_settings(body) save_settings(patch) devices.set_stable_band(settings()["stable_band_g"]) log_event("settings_changed", **patch) bump() return {"ok": True, "settings": settings()} def safe_backup(reason: str) -> str | None: """A checked copy of the database (server/backup.py); never stops the action that asked for it.""" if not backup.enabled(): return None try: return backup.make(reason)["name"] except Exception as e: # noqa: BLE001 — a full disk must not stop lunch print(f" Backup failed ({reason}): {e}", flush=True) return None def post_reset(q, body): if data_mode() == "real": fail(403, "ฐานข้อมูลนี้เป็นข้อมูลจริงของโรงเรียน ล้างหรือโหลดข้อมูลเดโมทับไม่ได้") preset = body.get("preset") if body.get("preset") in ("ready", "full", "verified") else "ready" safe_backup("before-reset") seed(preset) for c in devices.CHANNELS: devices.sim_set(c, value_g=0) devices.clear_tare(c) bump() return {"ok": True} # ----- sign-in: one PIN per role, required once the school runs on real data ----- # Which school screens each role opens (page file -> roles), and where a role lands after signing in. With real data # the server holds every screen and every read behind a signed-in role; in the demo the role is picked with one tap on # /start and the screens send other roles away themselves (public/js/core.js signIn). Product pages stay open. SCREENS = { "index.html": ("admin", "viewer", "kitchen"), "kitchen.html": ("admin", "kitchen"), "recipe.html": ("admin", "kitchen"), "opinions.html": ("admin", "kitchen", "teacher"), "planner.html": ("admin", "kitchen"), "sim.html": ("admin",), "demo.html": ("admin",), } HOME = {"admin": "/", "viewer": "/", "kitchen": "/kitchen", "teacher": "/opinions"} OPEN_READS = ("/api/auth/me", "/api/live") # live scale readings carry no school records READ_ROLES = {"/api/report": ("admin", "viewer")} # reads only some roles may make (the rest: any signed-in role) # Who may change what once data_mode is "real". The ESP32 boards post readings without a PIN. With demo data nothing # needs a PIN, so the online demo and rehearsals stay one tap away. NEED = { "/api/menu/save": "admin", "/api/menu/delete": "admin", "/api/recipe/save": "admin", "/api/action/schedule": "admin", "/api/action/reuse": "admin", "/api/planner/save": "admin", "/api/settings": "admin", "/api/demo/reset": "admin", "/api/auth/pins": "admin", "/api/meal/open": "kitchen", "/api/meal/context": "kitchen", "/api/meal/capture": "kitchen", "/api/meal/undo": "kitchen", "/api/meal/broth": "kitchen", "/api/meal/close": "kitchen", "/api/meal/cancel": "kitchen", "/api/scale/tare": "kitchen", "/api/audit/save": "kitchen", "/api/qc/zero": "kitchen", "/api/qc/read": "kitchen", "/api/opinion": "teacher", "/api/opinion/undo": "teacher", } SIM_ONLY = ("/api/sim", "/api/sim/votes") # the simulator writes fake readings: demo data only def pin_required() -> bool: with LOCK: # also called from the request threads before a handler takes the lock return data_mode() == "real" def get_auth_me(q, body, role=None): return {"required": pin_required(), "role": role, "role_th": auth.ROLE_TH.get(role), "roles": auth.ROLE_TH, "home": HOME.get(role)} def post_auth_pins(q, body): """Admin sets new PINs ({role: pin}); every changed role is signed out everywhere.""" pins = {r: str(body[r]).strip() for r in auth.ROLES if body.get(r) not in (None, "")} if not pins: fail(400, "ใส่ PIN ใหม่อย่างน้อย 1 บทบาท") try: auth.set_pins(pins) except ValueError as e: fail(400, str(e)) log_event("pins_changed", roles=sorted(pins)) return {"ok": True, "changed": sorted(pins)} ROUTES = { ("GET", "/api/auth/me"): get_auth_me, ("POST", "/api/auth/pins"): post_auth_pins, ("GET", "/api/state"): get_state, ("GET", "/api/live"): get_live, ("GET", "/api/menus"): get_menus, ("GET", "/api/menu"): get_menu, ("POST", "/api/menu/save"): post_menu_save, ("POST", "/api/menu/delete"): post_menu_delete, ("POST", "/api/recipe/save"): post_recipe_save, ("GET", "/api/patterns"): get_patterns, ("GET", "/api/issues"): get_issues, ("GET", "/api/report"): get_report, ("GET", "/api/action"): get_action, ("POST", "/api/action/schedule"): post_schedule, ("POST", "/api/action/reuse"): post_reuse, ("GET", "/api/planner"): get_planner, ("POST", "/api/planner/save"): post_planner_save, ("POST", "/api/meal/open"): post_open, ("POST", "/api/meal/context"): post_context, ("POST", "/api/meal/capture"): post_capture, ("POST", "/api/meal/undo"): post_undo, ("POST", "/api/meal/broth"): post_broth, ("POST", "/api/meal/close"): post_close, ("POST", "/api/meal/cancel"): post_cancel, ("POST", "/api/scale/tare"): post_tare, ("GET", "/api/audits"): get_audits, ("POST", "/api/audit/save"): post_audit, ("GET", "/api/opinions"): get_opinions, ("POST", "/api/opinion"): post_opinion, ("POST", "/api/opinion/undo"): post_opinion_undo, ("GET", "/api/vote/status"): vote_status, ("POST", "/api/vote"): post_vote, ("POST", "/api/sim/votes"): post_sim_votes, ("POST", "/api/qc/zero"): post_qc_zero, ("POST", "/api/qc/read"): post_qc_read, ("GET", "/api/qc"): get_qc, ("POST", "/api/reading"): post_reading, ("POST", "/api/sim"): post_sim, ("POST", "/api/settings"): post_settings, ("POST", "/api/demo/reset"): post_reset, } # ---------------------------------------------------------------- http plumbing def lan_urls() -> list[str]: try: ips = socket.gethostbyname_ex(socket.gethostname())[2] except OSError: ips = [] return [f"http://{ip}:{PORT}" for ip in ips if not ip.startswith("127.")] class Handler(BaseHTTPRequestHandler): server_version = "EatBack/3" def log_message(self, fmt, *args): # keep the console for startup info and errors pass def _send(self, status: int, payload: bytes, ctype: str, cookie: str | None = None) -> None: self.send_response(status) self.send_header("Content-Type", ctype) if cookie: self.send_header("Set-Cookie", cookie) self.send_header("Content-Length", str(len(payload))) self.send_header("Cache-Control", "no-cache") self.end_headers() self.wfile.write(payload) def _json(self, status: int, obj, cookie: str | None = None) -> None: self._send(status, json.dumps(obj, ensure_ascii=False, default=str).encode("utf-8"), "application/json; charset=utf-8", cookie) def _body(self) -> dict: length = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(length) if length else b"" try: return json.loads(raw) if raw else {} except json.JSONDecodeError: fail(400, "invalid JSON") def do_GET(self): self._dispatch("GET") def do_POST(self): self._dispatch("POST") def _token(self) -> str | None: jar = SimpleCookie(self.headers.get("Cookie") or "") return jar[auth.COOKIE].value if auth.COOKIE in jar else None def _auth(self, method: str, path: str, body: dict) -> bool: """Sign-in routes, and the PIN check in front of every change. True when the request was answered here.""" token = self._token() role = auth.session_role(token) if path == "/api/auth/me": self._json(200, get_auth_me({}, {}, role)) return True if path == "/api/auth/login" and method == "POST": wanted = body.get("role") if wanted is not None and wanted not in auth.ROLES: self._json(400, {"error": "ไม่รู้จักบทบาทนี้"}) return True if not pin_required(): # demo data: pick a role with one tap, so the demo shows each role's own screens got = wanted or "admin" else: try: got = auth.check_pin(str(body.get("pin") or ""), self.client_address[0]) except PermissionError as e: self._json(429, {"error": f"ใส่ PIN ผิดหลายครั้ง รอ {e.args[0]} วินาทีแล้วลองใหม่"}) return True if not got: self._json(401, {"error": "PIN ไม่ถูกต้อง"}) return True if wanted and not auth.allowed(got, wanted): self._json(403, {"error": f"PIN นี้ไม่ใช่ของ{auth.ROLE_TH[wanted]}"}) # never say whose it is return True new = auth.new_session(got) auth.end_session(token) with LOCK: log_event("signed_in", role=got) cookie = f"{auth.COOKIE}={new}; Path=/; HttpOnly; SameSite=Lax; Max-Age={auth.SESSION_S}" self._json(200, {**get_auth_me({}, {}, got), "ok": True}, cookie) return True if path == "/api/auth/logout" and method == "POST": auth.end_session(token) self._json(200, {"ok": True, **get_auth_me({}, {}, None)}, f"{auth.COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0") return True if not pin_required(): return False if method == "GET": if not role and path.startswith("/api/") and path not in OPEN_READS: self._json(401, {"error": "เข้าใช้ด้วย PIN ของบทบาทก่อน", "signin": True}) return True if path in READ_ROLES and not any(auth.allowed(role, r) for r in READ_ROLES[path]): self._json(403, {"error": "บทบาทนี้ไม่ได้ดูรายงานนี้"}) return True return False if path in SIM_ONLY: self._json(403, {"error": "ใช้ข้อมูลจริงอยู่ ปิดเครื่องจำลองไว้ เพื่อไม่ให้ค่าจำลองปนข้อมูลโรงเรียน"}) return True need = NEED.get(path) if need and not auth.allowed(role, need): self._json(401 if not role else 403, { "error": f"ต้องใส่ PIN ของ{auth.ROLE_TH[need]}ก่อนบันทึก" + ("" if not role else f" (ตอนนี้เข้าใช้เป็น{auth.ROLE_TH[role]})"), "need": need, "need_th": auth.ROLE_TH[need], "role": role}) return True return False def _dispatch(self, method: str) -> None: url = urlparse(self.path) if url.path == "/api/stream": return self._stream() body = {} if url.path.startswith("/api/"): try: body = self._body() if method == "POST" else {} except HttpError as e: return self._json(e.status, {"error": str(e)}) if self._auth(method, url.path, body): return handler = ROUTES.get((method, url.path)) if not handler: if method == "GET" and not url.path.startswith("/api/"): return self._static(url.path) return self._json(404, {"error": "not found"}) try: with LOCK: out = handler(parse_qs(url.query), body) self._json(200, out) except HttpError as e: self._json(e.status, {"error": str(e)}) except Exception as e: # noqa: BLE001 — report, never crash the server mid-demo import traceback traceback.print_exc() self._json(500, {"error": str(e)}) def _redirect(self, location: str) -> None: self.send_response(302) self.send_header("Location", location) self.send_header("Content-Length", "0") self.send_header("Cache-Control", "no-cache") self.end_headers() def _static(self, path: str) -> None: file = (PUBLIC / (PAGES.get(path) or path.lstrip("/"))).resolve() if PUBLIC.resolve() not in file.parents or not file.is_file(): return self._send(404, b"Not found", "text/plain") rel = file.relative_to(PUBLIC.resolve()).as_posix() # "/./kitchen.html" is still the kitchen screen # Real data: a school screen opens only for a signed-in role it belongs to; other roles go to their own. if rel in SCREENS and pin_required(): role = auth.session_role(self._token()) if not role: return self._redirect("/start?next=" + quote(self.path, safe="")) if role not in SCREENS[rel]: return self._redirect(HOME[role]) ctype = {".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".html": "text/html; charset=utf-8", ".woff2": "font/woff2", ".svg": "image/svg+xml"}.get( file.suffix, mimetypes.guess_type(file.name)[0] or "application/octet-stream") self._send(200, file.read_bytes(), ctype) def _stream(self) -> None: self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Cache-Control", "no-cache") self.send_header("Connection", "keep-alive") self.end_headers() with LOCK: # the stream runs on its own thread lockout = settings()["vote_lockout_s"] try: while True: data = {"version": state["version"], "scales": devices.snapshot(), "voice": {"enabled": state["voice_enabled"], "meal_id": state["voice_meal"], "locked_s": round(devices.voice_locked(lockout), 1)}} self.wfile.write(f"data: {json.dumps(data)}\n\n".encode()) self.wfile.flush() time.sleep(0.3) except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError, OSError): return def startup() -> tuple[bool, bool]: """Load the demo data on a first run or after the bundled menu base changed, never over real records. Returns (real data mode, demo data outdated).""" with LOCK: stored = one("SELECT value FROM settings WHERE key = 'seed_version'") outdated = not one("SELECT COUNT(*) AS n FROM menus")["n"] or (stored or {}).get("value") != str(SEED_VERSION) real = data_mode() == "real" devices.set_simulator(not real) # real data: scales without an ESP32 read as offline, not as simulated weights if outdated and not real: seed("ready") devices.set_stable_band(settings()["stable_band_g"]) bump() return real, outdated def main() -> None: real, outdated = startup() saved = safe_backup("start") fresh_pins = auth.ensure_pins() if real else None server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) server.daemon_threads = True print("\n EatBack running (Python)") if real: print(" Data mode REAL — every screen needs a role PIN; demo resets are refused" + (" (bundled demo data changed; this database was kept)" if outdated else "")) if fresh_pins: print(" New PINs (shown once: write them down, then change them in Settings)") for role, pin in fresh_pins.items(): print(f" {role:<8} {pin}") # role key, not the Thai name: a cp1252 console can't print Thai if saved: print(f" Backup {backup.BACKUP_DIR / saved} (one after every round; python server/backup.py list)") print(f" Dashboard http://localhost:{PORT}") for u in lan_urls(): print(f" LAN {u} (every phone starts at {u}/start" + ("" if real else f" · simulator: {u}/sim") + ")") print(" ESP32 POST /api/reading · kids' opinions page /opinions\n", flush=True) try: server.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()
"""EatBack local server — Python standard library only.
One laptop = server + database + dashboard. ESP32 boards post weights and voice-box presses over
the phone hotspot's Wi-Fi; the dashboard, kitchen phone and simulator are served from /public.
No scales at all? Every weight can also be typed in from the kitchen screen.
Run: python server/app.py (or double-click run.cmd)
"""
from __future__ import annotations
import json
import math
import mimetypes
import os
import re
import socket
import sys
import time
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, quote, urlparse
sys.path.insert(0, str(Path(__file__).resolve().parent))
import auth # noqa: E402
import backup # noqa: E402
import devices # noqa: E402
import logic # noqa: E402
import planning # noqa: E402
from db import ALL_GRADES, DEFAULT_SETTINGS, LOCK, ROOT, data_mode, log_event, many, one, run, save_settings, settings, transaction # noqa: E402
from seed import SEED_VERSION, seed # noqa: E402
from util import meal_id_for, now_iso, rnd, today # noqa: E402
PORT = int(os.environ.get("PORT", "5184"))
PUBLIC = ROOT / "public"
PAGES = {"/": "index.html", "/kitchen": "kitchen.html", "/sim": "sim.html", "/recipe": "recipe.html", "/planner": "planner.html",
"/opinions": "opinions.html", "/flow-3d": "flow-3d.html", "/scales-3d": "scales-3d.html", "/start": "start.html"}
GRADE_TH = {"K1": "อ.1", "K2": "อ.2", "K3": "อ.3", "P1": "ป.1", "P2": "ป.2", "P3": "ป.3", "P4": "ป.4", "P5": "ป.5", "P6": "ป.6"}
class HttpError(Exception):
def __init__(self, status: int, message: str):
super().__init__(message)
self.status = status
def fail(status: int, message: str):
raise HttpError(status, message)
# ---------------------------------------------------------------- change notification
state = {"version": 1, "voice_enabled": False, "voice_meal": None}
_matrix = {"key": None, "value": None}
def bump() -> None:
state["version"] += 1
m = open_meal()
state["voice_enabled"] = bool(m and m["investigation"])
state["voice_meal"] = m["id"] if m else None
def matrix() -> dict:
"""Grade x menu picture, rebuilt only when the data changed (every change bumps the version)."""
key = (state["version"], today())
if _matrix["key"] != key:
_matrix.update(key=key, value=logic.grade_matrix())
return _matrix["value"]
def open_meal() -> dict | None:
return one("SELECT * FROM meals WHERE status = 'open' LIMIT 1")
def stable_reading(channel: str) -> dict:
r = devices.reading(channel)
if not r["online"]:
fail(409, "ไม่มีสัญญาณจากเครื่องชั่ง ถ้าไม่มีเครื่องชั่ง เลือก “พิมพ์เอง”")
if not r["stable"]:
fail(409, "น้ำหนักยังไม่นิ่ง รอสักครู่แล้วกดใหม่")
return r
def unique_meal_id(day: str, grade: str) -> str:
base = meal_id = meal_id_for(day, grade)
i = 2
while one("SELECT 1 FROM meals WHERE id = ?", meal_id):
meal_id = f"{base}-{i}"
i += 1
return meal_id
def flag(value) -> int:
return 1 if value in (True, 1, "1", "true", "on") else 0
def number(value, name: str, minimum: float = 0, maximum: float | None = None) -> float:
if isinstance(value, bool): # JSON true/false would otherwise pass as 1/0