eatback / py /logic.py
kritpakin's picture
Roles, principal report, five bins, purchase order for the kitchen, print fix
9aaa92e verified
Raw History Blame Contribute Delete
72.3 kB
"""The EatBack loop: PLAN -> SERVE -> MEASURE -> repeated high? -> find the cause -> nutrition + budget gate -> trial -> measure again. Three layers of data, one gate: how much was left — kitchen scale + return station (every round) what was left — audit tray (monthly, or when the system asks) why it was left — kids' opinions, asked by a teacher and tapped in the app (1–3 days, when the system asks) can we use it — the menu base: nutrition + budget, all 4 food groups, never fewer vegetables Grades eat in separate rounds, so every rule runs per grade as if each grade were its own school: its own baseline, its own "3 in a row", its own investigation, trial and verification. Everything here is deterministic and explainable — no AI, no prediction. """ from __future__ import annotations import json from datetime import date import devices import nutrition from db import budget_tier, data_mode, many, one, portion, settings from util import add_days, add_school_days, local_iso, local_midnight_iso, mean, median, pct, rnd, today GROUPS = [ {"key": "starch", "th": "ข้าว/แป้ง", "icon": "🍚"}, {"key": "veg", "th": "ผัก", "icon": "🥬"}, {"key": "protein", "th": "โปรตีน", "icon": "🍗"}, {"key": "fruit", "th": "ผลไม้", "icon": "🍉"}, ] GROUP_TH = {g["key"]: g["th"] for g in GROUPS} # A closed round is evidence only on a normal day whose morning scale check passed. Baselines, streaks, menu history # and acceptance all use this one rule, so a round the trial check would refuse never shapes them either. COUNTED = "status = 'closed' AND context_absence = 0 AND context_event = 0 AND qc_ok = 1" DATA_NOTICE = { "code": "prototype_unverified", "status": "unverified", "message": "ข้อมูลเมนู สูตร ปริมาณสารอาหาร และต้นทุนยังไม่ได้ตรวจรับรองรายเมนู ตัวอย่างเดโมใช้เพื่อทดลองขั้นตอนเท่านั้น", "message_en": "Menu recipes, nutrient values and costs have no verified per-menu assessment. Demo examples simulate the workflow only.", "simulation_only": True, "ready_for_real_use": False, } def prototype_metadata() -> dict: return {"prototype": True, "simulation_only": True, "ready_for_real_use": False, "data_notice": dict(DATA_NOTICE)} def menu_provenance(menu: dict, recipe_origin: str | None = None) -> dict: origin = menu.get("data_origin") or "user" return {**menu, "nutrition_pass": 0, "nutrition_status": "unverified", "simulation_only": True, "ready_for_real_use": False, "energy": nutrition.full_portion(menu), "data_provenance": {"origin": origin, "nutrition": {"status": "unverified", "origin": origin, "source": menu.get("nutrition_source") or "", "source_url": menu.get("nutrition_source_url") or "", "checked_at": menu.get("nutrition_checked_at") or "", "scope": menu.get("nutrition_scope") or ""}, "recipe": {"status": "unverified", "origin": recipe_origin or "missing"}, "cost": {"status": "unverified", "origin": origin}}} def nutrition_check() -> dict: return {"key": "nutrition", "label": "Nutrition", "pass": False, "status": "unverified", "approved": False, "blocking": False, "simulation_only": True, "detail": "ยังไม่มีเอกสารประเมินโภชนาการรายเมนู ทดลองขั้นตอนด้วยข้อมูลตัวอย่างเท่านั้น", "detail_en": "No per-menu nutrition assessment is available. This option simulates the workflow only."} REASONS = { "ate_all": "กินหมด", "too_much": "เยอะไป", "taste": "รสชาติไม่ถูกปาก", "hard": "แข็งหรือชิ้นใหญ่", "unfamiliar": "ไม่คุ้น ไม่เคยกิน", "no_time": "กินไม่ทัน", } # What the kids said most -> what the system proposes. Every option still has to pass the gate. SOLUTIONS = { "too_much": {"title": "ทบทวนปริมาณตักต่อคนให้เหมาะกับช่วงวัย", "change": "ตักข้าวและกับข้าวตามปริมาณของช่วงวัยที่ตั้งไว้ ไม่ต่ำกว่านั้น และให้เติมได้ โดยผักต่อคนคงเดิม", "swap": False}, "taste": {"title": "ปรับสูตรและการปรุงรส", "change": "ปรับรสและกลิ่นให้เข้ากับเด็ก โดยไม่เพิ่มโซเดียมและน้ำตาลเกินสูตรเดิม", "swap": False}, "hard": {"title": "หั่นเล็กลง ทำให้นุ่มขึ้น หรือเปลี่ยนวิธีปรุง", "change": "หั่นชิ้นเล็กลงและปรุงให้นุ่มขึ้นในเมนูเดิม", "swap": True}, "unfamiliar": {"title": "เสิร์ฟซ้ำเป็นระยะ หรือจับคู่กับเมนูที่เด็กคุ้น", "change": "เสิร์ฟซ้ำเว้นระยะหลายครั้ง และจับคู่กับของที่เด็กคุ้น", "swap": False}, "no_time": {"title": "ทบทวนเวลาพักกลางวัน ไม่ต้องแก้สูตร", "change": "เพิ่มเวลากินหรือลดคิวรอรับอาหาร สูตรอาหารคงเดิม", "swap": False}, } # ---------------------------------------------------------------- context def context(grade: str | None = None) -> dict: """Everything the rules need for one grade (grade=None: whole-school views only).""" s = settings() recipe_origins = {r["menu_id"]: r["data_origin"] for r in many("SELECT menu_id, data_origin FROM recipes")} menus = {m["id"]: menu_provenance(m, recipe_origins.get(m["id"])) for m in many("SELECT * FROM menus")} counted_n = one(f"SELECT COUNT(*) AS n FROM meals WHERE grade = ? AND {COUNTED}", grade)["n"] if grade else 0 return { "s": s, "menus": menus, "budget": budget_tier(s["enrolled"]), "grade": grade, "portion": portion(s, grade), "counted_n": counted_n, "learning": bool(grade) and counted_n < s["learning_min_meals"], "_base": {}, "_window": None, "_sorts": {}, "_changes": None, } def completeness(menu: dict) -> dict: """A lunch should bring all four: rice/starch, protein, vegetables and fruit.""" missing = [g["key"] for g in GROUPS if not (menu.get(f"{g['key']}_g") or 0) > 0] return {"complete": not missing, "missing": missing} # ---------------------------------------------------------------- measures def dish_served_eff(meal: dict, menu: dict) -> float: """Dish served, as edible solids: solids only for curry/soup (the return strainer only keeps solids), and less the bones and other inedible parts the five-bin station weighed back, which were never food to eat or leave.""" ds = meal.get("dish_served_g") or 0 if menu["has_broth"] and meal.get("solid_ratio") is not None: # a ratio of 0 means no solids, not "use the gross" ds *= meal["solid_ratio"] return max(0.0, ds - (meal.get("bone_g") or 0)) def judged_pct(meal: dict, menu: dict, rice_w=None, dish_w=None) -> float | None: """The waste % a menu is judged on: the dish for rice + side dish menus, everything for one-dish meals.""" rw = meal.get("rice_waste_g") if rice_w is None else rice_w dw = meal.get("dish_waste_g") if dish_w is None else dish_w ds = dish_served_eff(meal, menu) if menu["category"] == "one_dish": return pct((rw or 0) + (dw or 0), (meal.get("rice_served_g") or 0) + ds) return pct(dw, ds) def metrics(meal: dict, menu: dict, live: dict | None = None, leftovers: dict | None = None) -> dict: """`leftovers` (from leftover_mix) splits per-child intake by what children left; screens that show intake pass it.""" rs = meal.get("rice_served_g") or 0 ds = meal.get("dish_served_g") or 0 ds_eff = dish_served_eff(meal, menu) rw = live["rice_waste_g"] if live else meal.get("rice_waste_g") or 0 dw = live["dish_waste_g"] if live else meal.get("dish_waste_g") or 0 served_eff = rs + ds_eff waste = rw + dw total = pct(waste, served_eff) students = meal.get("students") or 0 return { "rice_served_g": rs, "dish_served_g": ds, "dish_served_eff_g": ds_eff, "served_g": rs + ds, "served_eff_g": served_eff, "solid_ratio": meal.get("solid_ratio"), "rice_waste_g": rw, "dish_waste_g": dw, "waste_g": waste, "bone_g": meal.get("bone_g"), "rice_pct": pct(rw, rs), "dish_pct": pct(dw, ds_eff), "total_pct": total, "judged_pct": judged_pct(meal, menu, rw, dw), "per_student_g": waste / students if students and served_eff else None, # Menu Acceptance: share of measured food served that was eaten; not a nutrition assessment. "acceptance_pct": (100 - total) if total is not None else None, "money_lost_thb": menu["cost_thb"] * portion(settings(), meal.get("grade")) * students * total / 100 if total is not None and students else None, # Energy and servings per child (กรมอนามัย household units), once the leftovers are final. "nutrition": nutrition.eaten(meal, menu, ds_eff, leftovers, portion(settings(), meal.get("grade"))) if meal.get("status") == "closed" else None, } def sorted_bins_for(meal_id: str) -> dict: """A five-bin round's bins: {bin: {"start_g", "waste_g"}}; empty for a two-bin or typed-in round.""" return {r["bin"]: {"start_g": r["start_g"], "waste_g": r["waste_g"]} for r in many("SELECT bin, start_g, waste_g FROM sorted_bins WHERE meal_id = ?", meal_id)} def live_waste(meal: dict, scales: dict) -> dict | None: """Leftovers so far for an open round read from the bins (None when they are typed in at the end). Five bins: rice is the starch bin, the side dish is vegetables + meat + skin and fat; bones are shown on their own.""" if meal["bins_manual"]: return None bins = sorted_bins_for(meal["id"]) if bins: got = {b: max(0.0, scales[b]["raw"] - v["start_g"]) for b, v in bins.items()} return {"rice_waste_g": got.get("starch", 0.0), "dish_waste_g": got.get("veg", 0.0) + got.get("protein", 0.0) + got.get("fat", 0.0), "bins": got} return { "rice_waste_g": max(0.0, scales["rice"]["raw"] - (meal["return_rice_start"] or 0)), "dish_waste_g": max(0.0, scales["dish"]["raw"] - (meal["return_dish_start"] or 0)), } # ---------------------------------------------------------------- baseline + status def _window(ctx: dict) -> list[dict]: """Counted closed rounds of this grade inside the baseline window (loaded once per request).""" if ctx["_window"] is None: since = add_days(today(), -ctx["s"]["baseline_window_days"]) ctx["_window"] = many(f"SELECT * FROM meals WHERE {COUNTED} AND grade = ? AND date >= ?", ctx["grade"], since) return ctx["_window"] def baseline_for(menu_id: str, ctx: dict) -> dict: """Median judged waste of OTHER menus of the same type (rice + side dish / one-dish) for this grade.""" if menu_id in ctx["_base"]: return ctx["_base"][menu_id] s, menus = ctx["s"], ctx["menus"] menu = menus[menu_id] vals = [v for r in _window(ctx) if r["menu_id"] != menu_id and r["menu_id"] in menus and menus[r["menu_id"]]["category"] == menu["category"] for v in [judged_pct(r, menus[r["menu_id"]])] if v is not None] ok = len(vals) >= s["baseline_min_meals"] b = median(vals) if ok else None out = { "pct": rnd(b), "n": len(vals), "ok": ok, "category": menu["category"], "high_above": rnd(b + s["high_margin_pts"]) if ok else None, } ctx["_base"][menu_id] = out return out def status_of(value: float | None, base: dict, ctx: dict) -> str: if ctx["learning"]: return "learning" if value is None: return "none" if not base["ok"]: return "nobase" return "high" if value > base["high_above"] else "normal" # ---------------------------------------------------------------- pattern def menu_pattern(menu_id: str, ctx: dict) -> dict: menu = ctx["menus"][menu_id] base = baseline_for(menu_id, ctx) serves = [] for m in many("SELECT * FROM meals WHERE menu_id = ? AND grade = ? AND status = 'closed' ORDER BY date, closed_at", menu_id, ctx["grade"]): v = judged_pct(m, menu) qc_failed = m["qc_ok"] != 1 excluded = bool(m["context_absence"] or m["context_event"]) or qc_failed serves.append({ "id": m["id"], "date": m["date"], "origin": m["origin"], "students": m["students"], "judged_pct": rnd(v), "rice_pct": rnd(pct(m["rice_waste_g"], m["rice_served_g"])), "excluded": excluded, "qc_failed": qc_failed, "context_absence": m["context_absence"], "context_event": m["context_event"], "investigation": m["investigation"], "trial": m["action_id"] is not None, "status": "excluded" if excluded else status_of(v, base, ctx), }) counted = [x for x in serves if not x["excluded"]] streak = 0 for x in reversed(counted): if x["status"] != "high": break streak += 1 n = ctx["s"]["repeat_n"] if ctx["learning"]: flag = "learning" elif not serves: flag = "no_data" elif not base["ok"]: flag = "nobase" elif streak >= n: flag = "repeated_high" elif streak: flag = "high" else: flag = "normal" last = counted[-n:] action = latest_action(menu_id, ctx["grade"]) return { "menu_id": menu_id, "grade": ctx["grade"], "baseline": base, "serves": serves, "last": last, "flag": flag, "consecutive_high": streak, "repeat_n": n, "avg_last_pct": rnd(mean([x["judged_pct"] for x in last if x["judged_pct"] is not None])), "action": action_summary(action, ctx) if action else None, } # ---------------------------------------------------------------- investigation (what + why) def latest_action(menu_id: str, grade: str | None) -> dict | None: return one("SELECT * FROM actions WHERE menu_id = ? AND grade = ? ORDER BY id DESC LIMIT 1", menu_id, grade) def needs_investigation(menu_id: str, ctx: dict) -> bool: """Ask for the kids' opinions + a 4-compartment sort on this grade's next serve once a menu is repeatedly high.""" if menu_pattern(menu_id, ctx)["flag"] != "repeated_high": return False a = latest_action(menu_id, ctx["grade"]) return a is None or a["status"] == "not_verified" def replaceable_action(menu_id: str, grade: str) -> dict | None: """The latest decision, if its trial has not been served yet (so it can still be changed).""" a = latest_action(menu_id, grade) if a and a["status"] == "testing" and not one("SELECT 1 FROM meals WHERE action_id = ? AND status IN ('open', 'closed')", a["id"]): return a return None def evidence_meals(menu_id: str, grade: str, ignore_action: int | None = None) -> list[dict]: """Investigation rounds of this menu and grade not already used by a live or verified decision.""" used = set() for a in many("SELECT id, evidence_meals FROM actions WHERE menu_id = ? AND grade = ? AND status IN ('testing', 'verified')", menu_id, grade): if a["id"] != ignore_action: used.update(json.loads(a["evidence_meals"])) rows = many( "SELECT * FROM meals WHERE menu_id = ? AND grade = ? AND investigation = 1 AND status IN ('open', 'closed') ORDER BY date, opened_at", menu_id, grade, ) return [r for r in rows if r["id"] not in used] def voice_summary(meals: list[dict], ctx: dict) -> dict: s = ctx["s"] per_meal, totals = [], {k: 0 for k in REASONS} responses = students = 0 for m in meals: counts = {k: 0 for k in REASONS} for r in many("SELECT button, COUNT(*) AS n FROM votes WHERE meal_id = ? GROUP BY button", m["id"]): counts[r["button"]] = r["n"] total = sum(counts.values()) invalid = bool(m["students"]) and total > m["students"] per_meal.append({"meal_id": m["id"], "date": m["date"], "students": m["students"], "total": total, "invalid": invalid, "counts": counts, "status": m["status"]}) if not invalid: responses += total students += m["students"] or 0 for k, v in counts.items(): totals[k] += v rate = pct(responses, students) if rate is None: level = None elif rate < s["response_low_pct"]: level = "low" elif rate <= s["response_high_pct"]: level = "medium" else: level = "high" reason_total = sum(v for k, v in totals.items() if k != "ate_all") ranked = sorted(((k, v) for k, v in totals.items() if k != "ate_all" and v > 0), key=lambda kv: -kv[1]) top = None if ranked and (len(ranked) == 1 or ranked[0][1] > ranked[1][1]): top = {"key": ranked[0][0], "th": REASONS[ranked[0][0]], "n": ranked[0][1], "share": rnd(pct(ranked[0][1], reason_total))} return { "meals": per_meal, "counts": totals, "responses": responses, "students": students, "rate": rnd(rate), "level": level, "reason_total": reason_total, "top": top, "tie": bool(ranked) and top is None, "low_pct": s["response_low_pct"], "high_pct": s["response_high_pct"], "any_invalid": any(p["invalid"] for p in per_meal), } def _group_finding(meal: dict, ctx: dict, waste: dict, covers: int) -> dict: """Each food group's leftovers as a share of what was planned for `covers` children; the top group is the one at or above the flag share. A group with no weight (None) was not weighed and gets no rate.""" menu = ctx["menus"][meal["menu_id"]] s = ctx["s"] factor = portion(s, meal["grade"]) rates = [] for g in GROUPS: planned = menu[f"{g['key']}_g"] * factor * covers w = waste.get(g["key"]) rates.append({**g, "waste_g": w, "planned_g": planned, "rate": rnd(pct(w, planned)) if w is not None else None}) ranked = sorted((r for r in rates if r["rate"] is not None), key=lambda r: -r["rate"]) top = ranked[0] if ranked and ranked[0]["rate"] >= s["audit_flag_pct"] else None return {"meal_id": meal["id"], "date": meal["date"], "grade": meal["grade"], "covers": covers, "students": meal["students"], "rates": rates, "top": top, "flag_pct": s["audit_flag_pct"], "menu_id": meal["menu_id"]} def audit_finding(a: dict, ctx: dict) -> dict: """A 4-compartment sort (two-bin schools): part of the round's leftovers sorted on a tray and typed in.""" meal = one("SELECT * FROM meals WHERE id = ?", a["meal_id"]) waste = {k: a[f"{k}_g"] for k in ("starch", "veg", "protein", "fruit")} return {**_group_finding(meal, ctx, waste, a["covers"]), "source": "tray", "audit_id": a["id"], "ts": a["ts"], "consistency": audit_consistency(a, meal, ctx["s"])} def bins_finding(meal: dict, ctx: dict) -> dict | None: """What came back by food group from a closed round's five sorted bins, read like a 4-compartment sort. The bins hold every child's leftovers, so they replace the tray: skin and fat count with the meat, and fruit is not weighed (it goes in the general bin), so it has no rate. None when the round has no complete bins.""" bins = {b: v["waste_g"] for b, v in sorted_bins_for(meal["id"]).items()} if meal.get("status") != "closed" or set(bins) != set(devices.FIVE_BINS) or any(v is None for v in bins.values()): return None waste = {"starch": bins["starch"], "veg": bins["veg"], "protein": bins["protein"] + bins["fat"], "fruit": None} return {**_group_finding(meal, ctx, waste, meal["students"] or 0), "source": "bins", "audit_id": None, "ts": meal.get("closed_at") or local_iso(meal["date"], "12:00"), "consistency": None, "fat_g": bins["fat"], "bone_g": bins["bone"]} def latest_finding(menu_id: str, grade: str, ctx: dict) -> dict | None: """The newest leftovers-by-group for a menu in a grade: a round's five bins or a 4-compartment sort.""" found = [] m = one("""SELECT * FROM meals ml WHERE menu_id = ? AND grade = ? AND status = 'closed' AND (SELECT COUNT(*) FROM sorted_bins sb WHERE sb.meal_id = ml.id AND sb.waste_g IS NOT NULL) = 5 ORDER BY COALESCE(closed_at, date) DESC LIMIT 1""", menu_id, grade) if m and (f := bins_finding(m, ctx)): found.append(f) a = one("""SELECT a.* FROM audits a JOIN meals ml ON ml.id = a.meal_id WHERE ml.menu_id = ? AND ml.grade = ? ORDER BY a.ts DESC, a.id DESC LIMIT 1""", menu_id, grade) if a: found.append(audit_finding(a, ctx)) return max(found, key=lambda f: f["ts"] or "") if found else None def sort_finding(meal: dict, ctx: dict) -> dict | None: """A round's leftovers by food group: its own five bins, else its latest 4-compartment sort.""" found = bins_finding(meal, ctx) if found: return found row = one("SELECT * FROM audits WHERE meal_id = ? ORDER BY id DESC LIMIT 1", meal["id"]) return audit_finding(row, ctx) if row else None def audit_consistency(a: dict, meal: dict, s: dict) -> dict | None: """Reliability: audit total (fruit goes to the unweighed bin) vs what the return station weighed.""" if meal["status"] != "closed": return None daily = (meal["rice_waste_g"] or 0) + (meal["dish_waste_g"] or 0) scale = (meal["students"] or a["covers"]) / a["covers"] if a["covers"] else 1 audit_total = (a["starch_g"] + a["veg_g"] + a["protein_g"]) * scale diff = abs(audit_total - daily) / daily * 100 if daily > 0 else None return { "daily_g": daily, "audit_g": rnd(audit_total, 0), "diff_pct": rnd(diff), "limit_pct": s["audit_consistency_pct"], "ok": diff is not None and diff <= s["audit_consistency_pct"], } def _served_at(meal: dict) -> str: """When a round was served, as a UTC timestamp comparable with event and action times.""" return meal["opened_at"] or local_iso(meal["date"], "11:00") def _menu_changes(ctx: dict) -> dict: """When each menu's portions, recipe or cooking changed: menu and recipe saves for every grade, and the start of each 'adjust' trial (same menu, new way of cooking) for its grade. Loaded once per request.""" if ctx["_changes"] is None: changes: dict = {} for e in many("SELECT ts, detail FROM events WHERE type IN ('menu_saved', 'recipe_saved')"): try: menu_id = json.loads(e["detail"]).get("menu_id") except (ValueError, AttributeError): continue changes.setdefault((menu_id, None), []).append(e["ts"]) for a in many("SELECT trial_menu_id, grade, created_at FROM actions WHERE kind = 'adjust'"): changes.setdefault((a["trial_menu_id"], a["grade"]), []).append(a["created_at"]) ctx["_changes"] = changes return ctx["_changes"] def leftover_mix(meal: dict, ctx: dict) -> dict | None: """What a closed round's leftovers were made of, so per-child intake splits what came back by what children actually left instead of by the recipe. First the round's own five sorted bins (source "bins"); then the round's own 4-compartment sort; then the latest sort of the same menu in the same grade, as long as that menu's portions, recipe and cooking did not change between the two rounds (source "sort"). A sort that disagrees with the bins is not used. None: intake stays on the recipe split.""" menu = ctx["menus"].get(meal["menu_id"]) if meal.get("status") != "closed" or not menu: return None groups = ("starch", "veg", "protein") if menu["category"] == "one_dish" else ("veg", "protein") bins = {b: v["waste_g"] for b, v in sorted_bins_for(meal["id"]).items()} if set(bins) == set(devices.FIVE_BINS) and all(v is not None for v in bins.values()): # Skin and visible fat came off the meat, so they count with the meat group. mix = {"starch_g": bins["starch"], "veg_g": bins["veg"], "protein_g": bins["protein"] + bins["fat"]} if sum(mix[f"{g}_g"] for g in groups) > 0: return {**mix, "source": "bins", "meal_id": meal["id"], "date": meal["date"], "own": True} key = (meal["menu_id"], meal["grade"]) if key not in ctx["_sorts"]: ctx["_sorts"][key] = many( """SELECT a.id, a.meal_id, a.covers, a.starch_g, a.veg_g, a.protein_g, a.fruit_g, ml.date, ml.opened_at, ml.status, ml.students, ml.rice_waste_g, ml.dish_waste_g FROM audits a JOIN meals ml ON ml.id = a.meal_id WHERE ml.menu_id = ? AND ml.grade = ? ORDER BY COALESCE(ml.opened_at, ml.date) DESC, a.id DESC""", *key) sorts = ctx["_sorts"][key] changes = _menu_changes(ctx).get((meal["menu_id"], None), []) + _menu_changes(ctx).get(key, []) here = _served_at(meal) for a in [r for r in sorts if r["meal_id"] == meal["id"]] + [r for r in sorts if r["meal_id"] != meal["id"]]: own = a["meal_id"] == meal["id"] if not own: lo, hi = sorted((here, _served_at(a))) if any(lo < c <= hi for c in changes): continue consistency = audit_consistency(a, a, ctx["s"]) # the row carries the sorted round's bins if sum(a[f"{g}_g"] for g in groups) <= 0 or not (consistency and consistency["ok"]): continue return {"starch_g": a["starch_g"], "veg_g": a["veg_g"], "protein_g": a["protein_g"], "source": "sort", "audit_id": a["id"], "meal_id": a["meal_id"], "date": a["date"], "own": own} return None def synthesis_for_meal(meal: dict, ctx: dict) -> dict: """The evidence picture a round belongs to — including the one a decision was already based on.""" used_by = next((a["id"] for a in many("SELECT id, evidence_meals FROM actions WHERE menu_id = ? AND grade = ?", meal["menu_id"], meal["grade"]) if meal["id"] in json.loads(a["evidence_meals"])), None) return cause_synthesis(meal["menu_id"], ctx, used_by) def cause_synthesis(menu_id: str, ctx: dict, ignore_action: int | None = None) -> dict: ev = evidence_meals(menu_id, ctx["grade"], ignore_action) voice = voice_summary(ev, ctx) # What came back: the newest of the rounds' five bins and their 4-compartment sorts. found = [f for f in (bins_finding(m, ctx) for m in ev) if f] if ev: marks = ",".join("?" * len(ev)) audit_row = one(f"SELECT * FROM audits WHERE meal_id IN ({marks}) ORDER BY ts DESC, id DESC LIMIT 1", *[m["id"] for m in ev]) if audit_row: found.append(audit_finding(audit_row, ctx)) audit = max(found, key=lambda f: f["ts"] or "") if found else None blockers, codes = [], [] # codes let the screens word each blocker in Thai or English if not ev: blockers.append("ยังไม่มีข้อคิดเห็นจากเด็ก มื้อหน้าที่มีเมนูนี้ ครูจะถามเด็กแล้วกดบันทึกในแอป") codes.append({"code": "no_evidence"}) else: if audit is None: blockers.append("ยังไม่ได้แยกเศษ 4 ช่อง") codes.append({"code": "need_audit"}) if voice["level"] in (None, "low"): blockers.append(f"ถามเด็กได้ {voice['rate'] if voice['rate'] is not None else 0}% ต้องได้อย่างน้อย {voice['low_pct']}% ถามต่ออีก 1–3 วัน") codes.append({"code": "low_voice", "rate": voice["rate"] or 0, "need": voice["low_pct"]}) elif voice["top"] is None: blockers.append("คำตอบยังกระจาย ไม่มีเหตุผลไหนเด่น") codes.append({"code": "no_top"}) return { "evidence_meals": [m["id"] for m in ev], "voice": voice, "audit": audit, "what": audit["top"] if audit else None, "why": voice["top"], "ready": not blockers, "blockers": blockers, "blocker_codes": codes, } # ---------------------------------------------------------------- gate: nutrition + budget def menu_history(menu_id: str, ctx: dict) -> dict: """How much of this menu comes back: for the context grade, or across all grades when there is none.""" menu = ctx["menus"][menu_id] sql = f"SELECT * FROM meals WHERE menu_id = ? AND {COUNTED}" rows = many(sql + " AND grade = ?", menu_id, ctx["grade"]) if ctx["grade"] else many(sql, menu_id) vals = [v for m in rows for v in [judged_pct(m, menu)] if v is not None] return {"n": len(vals), "avg": rnd(mean(vals))} def options(menu_id: str, synth: dict, ctx: dict) -> dict: P = ctx["menus"][menu_id] limit = ctx["budget"]["limit"] reason = synth["why"]["key"] if synth["why"] else None sol = SOLUTIONS.get(reason) if not sol: return {"solution": None, "options": [], "rejected": [], **prototype_metadata()} group = synth["what"]["key"] if synth["what"] else "veg" budget_ok = P["cost_thb"] <= limit adjust = { "key": "adjust", "kind": "adjust", "menu": P, "title": sol["title"], "change": sol["change"], **prototype_metadata(), "checks": [ nutrition_check(), {"key": "veg", "label": "ไม่ลดผัก", "detail": f"ผัก {P['veg_g']:g} g ต่อคนเท่าเดิม", "pass": True, "value": P["veg_g"], "ref": P["veg_g"]}, {"key": "budget", "label": "Budget", "detail": f"{P['cost_thb']:g} {'≤' if budget_ok else '>'} {limit} บาท/คน", "pass": budget_ok, "value": P["cost_thb"], "ref": limit}, ], } s = ctx["s"] if reason == "too_much": # checked on every trial serve, so the rule is listed here rather than passed up front adjust["checks"].append({"key": "portion_floor", "label": "ไม่ตักต่ำกว่าปริมาณตามวัย", "pass": None, "blocking": False, "detail": f"มื้อทดลองนับเมื่อตักได้อย่างน้อย {s['portion_floor_pct']:g}% ของปริมาณตามวัยที่ตั้งไว้", "value": s["portion_floor_pct"], "portion": ctx["portion"]}) elif reason == "unfamiliar": adjust["checks"].append({"key": "exposure", "label": "เสิร์ฟซ้ำก่อนตัดสิน", "pass": None, "blocking": False, "detail": f"ทดลองได้ถึง {s['exposure_trials']} มื้อ เว้น {s['exposure_gap_days']} วันเรียน", "value": s["exposure_trials"], "gap": s["exposure_gap_days"], "verify_n": s["verify_n"]}) adjust["eligible"] = all(c["pass"] is not False or c.get("blocking") is False for c in adjust["checks"]) out, rejected = [adjust], [] if sol["swap"]: base = baseline_for(menu_id, ctx) keep = f"{group}_g" other = "veg_g" if group == "protein" else "protein_g" rows = [] for C in ctx["menus"].values(): if C["id"] == menu_id or C["category"] != P["category"]: continue h = menu_history(C["id"], ctx) keep_ok = C[keep] >= P[keep] veg_ok = C["veg_g"] >= P["veg_g"] other_ok = C[other] >= P[other] * 0.9 b_ok = C["cost_thb"] <= limit comp = completeness(C) checks = [ {"key": "keep", "label": f"{GROUP_TH[group]}ไม่ลดลง", "detail": f"{C[keep]:g} g {'≥' if keep_ok else '<'} {P[keep]:g} g", "pass": keep_ok, "group": group, "value": C[keep], "ref": P[keep]}, ] if group != "veg": checks.append({"key": "veg", "label": "ไม่ลดผัก", "detail": f"{C['veg_g']:g} g {'≥' if veg_ok else '<'} {P['veg_g']:g} g", "pass": veg_ok, "value": C["veg_g"], "ref": P["veg_g"]}) checks += [ {"key": "complete", "label": "ครบ 4 อย่าง", "detail": "ข้าว โปรตีน ผัก ผลไม้ครบ" if comp["complete"] else "ขาด " + " ".join(GROUP_TH[k] for k in comp["missing"]), "pass": comp["complete"], "missing": comp["missing"]}, {"key": "format", "label": "เปลี่ยนวิธีปรุง", "detail": f"{P['prep_th']} → {C['prep_th']}" if C["prep"] != P["prep"] else f"วิธีเดิม ({C['prep_th']})", "pass": C["prep"] != P["prep"], "from_th": P["prep_th"], "from_en": P["prep_en"], "to_th": C["prep_th"], "to_en": C["prep_en"]}, nutrition_check(), {"key": "other_group", "label": f"{GROUP_TH[other[:-2]]}ตามแผน", "detail": f"{GROUP_TH[other[:-2]]} {C[other]:g} g {'≥' if other_ok else '<'} 90% ของเดิม (ค่าที่กรอกในแผน)", "pass": other_ok, "other": other[:-2], "value": C[other], "ref": round(P[other] * 0.9, 1)}, {"key": "budget", "label": "Budget", "detail": f"{C['cost_thb']:g} {'≤' if b_ok else '>'} {limit} บาท/คน", "pass": b_ok, "value": C["cost_thb"], "ref": limit}, {"key": "acceptance", "label": "เด็กเคยกินได้ดี", "detail": f"เหลือเฉลี่ย {h['avg']}% ({h['n']} ครั้ง)" if h["n"] else "ยังไม่เคยเสิร์ฟ", "pass": (h["avg"] <= base["high_above"]) if h["n"] and base["ok"] else None, "avg": h["avg"], "n": h["n"]}, ] fail = next((c for c in checks if c["pass"] is False and c.get("blocking") is not False), None) rows.append({ "key": f"swap:{C['id']}", "kind": "swap", "menu": C, "title": f"เปลี่ยนเป็น {C['name_th']}", "change": f"เปลี่ยนวิธีปรุงเป็น{C['prep_th']} โดย{'ผัก' if group == 'veg' else GROUP_TH[group] + 'และผัก'}ไม่ลดลง", "checks": checks, "history": h, **prototype_metadata(), "eligible": fail is None, "reason": f"{fail['label']}: {fail['detail']}" if fail else None, "fail_key": fail["key"] if fail else None, }) ok = sorted((r for r in rows if r["eligible"]), key=lambda r: (0 if r["history"]["n"] else 1, r["history"]["avg"] or 0, r["menu"]["cost_thb"])) out += ok rejected = [r for r in rows if not r["eligible"]] return {"solution": {**sol, "reason": reason, "reason_th": REASONS[reason]}, "options": out, "rejected": rejected, **prototype_metadata()} # ---------------------------------------------------------------- trials + verification def portion_check(meal: dict, menu: dict, s: dict) -> dict | None: """Served per child against the grade's planned portion (menu grams x grade portion). Rice + main dish menus check the rice and the dish solids separately, one-dish meals the whole plate. Fruit is not weighed.""" students = meal.get("students") or 0 if not students: return None factor = portion(s, meal["grade"]) dish_plan = (menu["veg_g"] + menu["protein_g"]) * factor rice_got = (meal.get("rice_served_g") or 0) / students dish_got = dish_served_eff(meal, menu) / students if menu["category"] == "one_dish": parts = [("plate", rice_got + dish_got, menu["starch_g"] * factor + dish_plan)] else: parts = [("rice", rice_got, menu["starch_g"] * factor), ("dish", dish_got, dish_plan)] rows = [{"part": k, "per_child_g": rnd(got, 0), "plan_g": rnd(plan, 0), "pct": rnd(pct(got, plan))} for k, got, plan in parts if plan > 0] floor = s["portion_floor_pct"] return {"ok": all(r["pct"] >= floor for r in rows), "floor_pct": floor, "parts": rows} def action_summary(a: dict, ctx: dict) -> dict: s = ctx["s"] trials = [] for m in many("SELECT * FROM meals WHERE action_id = ? ORDER BY date, rowid", a["id"]): entry = {"id": m["id"], "date": m["date"], "status": m["status"], "judged_pct": None, "result": None, "portion": None} if m["status"] == "closed": menu = ctx["menus"][m["menu_id"]] v = judged_pct(m, menu) served = portion_check(m, menu, s) if a["cause"] == "too_much" else None if m["context_absence"] or m["context_event"]: result = "excluded" # unusual day: counts neither for nor against the fix elif not m["qc_ok"]: result = "qc_failed" # the scales were not checked or were off that morning: the number is not trusted elif served and not served["ok"]: result = "under_portion" # less came back because less was served: not evidence the fix worked else: st = status_of(v, baseline_for(m["menu_id"], ctx), ctx) result = "good" if st == "normal" else "high" if st == "high" else st entry.update(judged_pct=rnd(v), result=result, portion=served) trials.append(entry) good = sum(1 for t in trials if t["result"] == "good") exposure = a["cause"] == "unfamiliar" menu = ctx["menus"].get(a["trial_menu_id"]) source = one("SELECT grade FROM actions WHERE id = ?", a["source_action_id"]) if a.get("source_action_id") else None return { **a, "evidence_meals": json.loads(a["evidence_meals"]), "trials": trials, "good": good, "counted": sum(1 for t in trials if t["result"] in ("good", "high")), "exposure": exposure, "max_trials": s["exposure_trials"] if exposure else None, "gap_days": s["exposure_gap_days"] if exposure else 1, "portion_floor_pct": s["portion_floor_pct"] if a["cause"] == "too_much" else None, "verify_n": s["verify_n"], "trial_menu_name": menu["name_th"] if menu else a["trial_menu_id"], "cause_th": REASONS.get(a["cause"]), "finding_th": GROUP_TH.get(a["finding"]), "source_grade": source["grade"] if source else None, **prototype_metadata(), } def reuse_targets(source: dict) -> dict: """Recheck each grade's own evidence and gate; success elsewhere is only a trial proposal.""" targets = [] for grade in settings()["grades"]: if grade == source["grade"]: continue target = {"grade": grade, "eligible": False} existing = one("SELECT * FROM actions WHERE source_action_id = ? AND grade = ?", source["id"], grade) active = latest_action(source["menu_id"], grade) if existing: trial = one("SELECT id, date FROM meals WHERE action_id = ? ORDER BY date DESC, rowid DESC LIMIT 1", existing["id"]) target.update(existing_action_id=existing["id"], status=existing["status"], meal_id=trial["id"] if trial else None, date=trial["date"] if trial else None) code, th, en = "already_reused", "ส่งไปทดลองกับชั้นนี้แล้ว", "This class already has a trial from this fix." elif active and active["status"] in ("testing", "verified"): target.update(existing_action_id=active["id"], status=active["status"]) code, th, en = "active_action", "ชั้นนี้มีวิธีแก้ที่กำลังทดลองหรือผ่านเกณฑ์การกินแล้ว", "This class already has a fix being tested or one that met the acceptance target." else: ctx = context(grade) pattern = menu_pattern(source["menu_id"], ctx) synth = cause_synthesis(source["menu_id"], ctx) if pattern["flag"] != "repeated_high": code, th, en = "no_repeated_high", "ยังไม่พบเมนูนี้เหลือเยอะต่อเนื่องในชั้นนี้", "This menu has no repeated high waste in this class." elif not synth["ready"]: code, th, en = "insufficient_evidence", synth["blockers"][0], "Collect this class's opinions and the 4-compartment sort first." elif synth["why"]["key"] != source["cause"]: code, th, en = "cause_mismatch", "เด็กชั้นนี้ให้เหตุผลต่างกัน ควรเลือกวิธีแก้จากข้อมูลของชั้นนี้", "This class reports a different cause; choose its fix from its own evidence." else: opt = next((o for o in options(source["menu_id"], synth, ctx)["options"] if o["key"] == source["option_key"] and o["eligible"] and o["menu"]["id"] == source["trial_menu_id"]), None) if not opt: code, th, en = "option_ineligible", "วิธีนี้ไม่ผ่านเกณฑ์ของชั้นนี้ในข้อมูลปัจจุบัน", "This fix does not pass this class's current checks." else: target.update(eligible=True, date=next_trial_date(today(), grade)) code, th, en = "ready", "พร้อมเริ่มทดลองและวัดผลแยกชั้น", "Ready for a separate trial and measurement." target.update(reason_code=code, reason=th, reason_en=en) targets.append(target) return {"source_action_id": source["id"], "source_grade": source["grade"], "targets": targets, **prototype_metadata()} def next_trial_date(after: str, grade: str, gap: int = 1) -> str: """First free school day at least `gap` school days after `after` (and after today).""" day = add_school_days(max(after, today()), gap) while one("SELECT 1 FROM meals WHERE grade = ? AND date = ?", grade, day): day = add_school_days(day, 1) return day # ---------------------------------------------------------------- QC def qc_today(ctx: dict) -> dict: """This morning's reference-weight checks for the kitchen scale and the bins of the school's return station.""" since = local_midnight_iso(today()) channels = ("kitchen",) + devices.return_bins(ctx["s"]["return_bins"]) out = {} for c in channels: checks = [] for ref in ctx["s"]["qc_refs"]: checks.append(one( "SELECT * FROM qc_checks WHERE channel = ? AND reference_g = ? AND ts >= ? ORDER BY id DESC LIMIT 1", c, ref, since, )) # No reference weights configured means nothing was checked, which is never a pass. out[c] = {"pass": bool(checks) and all(r and r["pass"] for r in checks), "checks": checks, "done": sum(1 for r in checks if r)} return {**out, "all_ok": all(out[c]["pass"] for c in channels), "refs": ctx["s"]["qc_refs"], "channels": list(channels)} # ---------------------------------------------------------------- kitchen def pots_for(meal_id: str) -> list[dict]: pots, open_ = [], {"rice": None, "dish": None} for w in many("SELECT * FROM weighings WHERE meal_id = ? ORDER BY id", meal_id): if w["phase"] == "before": p = {"pot": w["pot"], "n": sum(1 for x in pots if x["pot"] == w["pot"]) + 1, "before_g": w["raw_g"], "after_g": None, "served_g": None, "manual": w["source"] == "manual"} pots.append(p) open_[w["pot"]] = p elif open_[w["pot"]]: p = open_[w["pot"]] p["after_g"] = w["raw_g"] p["served_g"] = max(0.0, p["before_g"] - w["raw_g"]) p["manual"] = p["manual"] or w["source"] == "manual" open_[w["pot"]] = None return pots def served_from_pots(pots: list[dict]) -> dict: total = lambda k: sum(p["served_g"] for p in pots if p["pot"] == k and p["served_g"] is not None) return {"rice_served_g": total("rice"), "dish_served_g": total("dish")} def broth_for(meal_id: str) -> dict: samples = many("SELECT * FROM broth_samples WHERE meal_id = ? ORDER BY id", meal_id) ratios = [s["solid_g"] / s["ladle_g"] for s in samples if s["ladle_g"] > 0] return {"samples": samples, "ratio": rnd(mean(ratios), 3) if ratios else None} def broth_required(meal: dict, ctx: dict) -> int: s = ctx["s"] return s["broth_points_audit"] if meal.get("investigation") else s["broth_points_normal"] def current_meal(grade: str) -> dict | None: d = today() return ( one("SELECT * FROM meals WHERE status = 'open' AND grade = ? ORDER BY opened_at DESC LIMIT 1", grade) or one("SELECT * FROM meals WHERE status = 'closed' AND origin <> 'seed' AND date = ? AND grade = ? ORDER BY closed_at DESC LIMIT 1", d, grade) or one("""SELECT * FROM meals WHERE status = 'planned' AND grade = ? AND (origin <> 'weekly' OR date >= ?) ORDER BY CASE WHEN date = ? THEN 0 ELSE 1 END, date, rowid LIMIT 1""", grade, d, d) or one("SELECT * FROM meals WHERE status = 'closed' AND grade = ? ORDER BY date DESC, closed_at DESC LIMIT 1", grade) ) def school_acceptance(ctx: dict) -> dict: """Menu Acceptance over the window (share of measured food eaten, not a health or nutrition score): for the context grade, or the whole school.""" since = add_days(today(), -ctx["s"]["acceptance_window_days"]) sql = f"SELECT * FROM meals WHERE {COUNTED} AND date >= ?" rows = many(sql + " AND grade = ?", since, ctx["grade"]) if ctx["grade"] else many(sql, since) served = eaten = 0.0 n = 0 for m in rows: menu = ctx["menus"][m["menu_id"]] mm = metrics(m, menu) if mm["served_eff_g"] > 0: served += mm["served_eff_g"] eaten += max(0.0, mm["served_eff_g"] - mm["waste_g"]) n += 1 return {"pct": rnd(pct(eaten, served)), "meals": n, "days": ctx["s"]["acceptance_window_days"], "label": "Menu Acceptance", "scope": "all_menus", "nutrition_assessed": False} def open_round() -> dict | None: return one("SELECT * FROM meals WHERE status = 'open' LIMIT 1") def rounds_today(s: dict) -> list[dict]: """Each grade's round today, for the kitchen's grade picker and the whole-school view.""" d = today() out = [] for g in s["grades"]: m = one("""SELECT id, menu_id, status, origin, investigation, action_id, students FROM meals WHERE grade = ? AND date = ? ORDER BY CASE status WHEN 'open' THEN 0 WHEN 'closed' THEN 1 ELSE 2 END, rowid LIMIT 1""", g, d) out.append({"grade": g, "meal": m}) return out def _shared(ctx: dict, scales: dict) -> dict: s = ctx["s"] om = open_round() return { "today": today(), "settings": s, "budget": ctx["budget"], "scales": scales, "qc": qc_today(ctx), "data_mode": data_mode(), **prototype_metadata(), "open_round": {"id": om["id"], "grade": om["grade"], "menu_id": om["menu_id"], "investigation": om["investigation"]} if om else None, "rounds_today": rounds_today(s), "voice_box": {"enabled": bool(om and om["investigation"]), "meal_id": om["id"] if om else None, "locked_s": round(devices.voice_locked(s["vote_lockout_s"]), 1)}, "reasons": REASONS, "groups": GROUPS, } def build_state(grade: str | None, extra: dict | None = None) -> dict: """grade=None: the whole-school view (every grade's round today). Otherwise the full loop for one grade.""" ctx = context(grade) scales = devices.snapshot() out = _shared(ctx, scales) out["grade"] = grade if grade is None: out["overview"] = overview(ctx, scales) out["acceptance"] = school_acceptance(ctx) return {**out, **(extra or {})} meal = current_meal(grade) current = None if meal: menu = ctx["menus"][meal["menu_id"]] pots = pots_for(meal["id"]) broth = broth_for(meal["id"]) live = None if meal["status"] == "open": live = live_waste(meal, scales) m = metrics({**meal, **served_from_pots(pots), "solid_ratio": broth["ratio"], "bone_g": ((live or {}).get("bins") or {}).get("bone")}, menu, live or {"rice_waste_g": 0, "dish_waste_g": 0}) else: m = metrics(meal, menu, leftovers=leftover_mix(meal, ctx)) pattern = menu_pattern(meal["menu_id"], ctx) will_investigate = meal["status"] == "planned" and not meal["action_id"] and needs_investigation(meal["menu_id"], ctx) synth = synthesis_for_meal(meal, ctx) if (meal["investigation"] or pattern["flag"] == "repeated_high") else None current = { "meal": meal, "menu": menu, "pots": pots, "broth": broth, "broth_required": broth_required(meal, ctx) if menu["has_broth"] else 0, "live": live, "metrics": m, "pattern": pattern, "baseline": pattern["baseline"], "judged_status": "excluded" if meal["context_absence"] or meal["context_event"] else "qc_failed" if meal["status"] == "closed" and meal["qc_ok"] != 1 else status_of(m["judged_pct"], pattern["baseline"], ctx), "audit": sort_finding(meal, ctx), "sorted_bins": sorted_bins_for(meal["id"]), "votes": voice_summary([meal], ctx) if meal["investigation"] else None, "synthesis": synth, "will_investigate": will_investigate, "action": action_summary(one("SELECT * FROM actions WHERE id = ?", meal["action_id"]), ctx) if meal["action_id"] else None, "nutrition": m["nutrition"] or nutrition.planned(menu, grade, ctx["portion"], ladled_history(ctx)), } nxt = one( """SELECT ml.*, mn.name_th, mn.name_en, mn.prep_th, mn.prep_en, mn.icon, a.menu_id AS from_menu_id, fm.name_th AS from_menu_name, fm.name_en AS from_menu_name_en, a.kind AS action_kind, a.change_th AS action_change FROM meals ml JOIN menus mn ON mn.id = ml.menu_id LEFT JOIN actions a ON a.id = ml.action_id LEFT JOIN menus fm ON fm.id = a.menu_id WHERE ml.status = 'planned' AND ml.grade = ? AND ml.id <> ? AND (ml.origin <> 'weekly' OR ml.date >= ?) ORDER BY ml.date LIMIT 1""", grade, meal["id"] if meal else "", today(), ) return { **out, "learning": {"active": ctx["learning"], "counted": ctx["counted_n"], "needed": ctx["s"]["learning_min_meals"]}, "acceptance": school_acceptance(ctx), "current": current, "next": nxt, "portion": ctx["portion"], "recent_nutrition": recent_nutrition(ctx), **(extra or {}), } def ladled_history(ctx: dict, n: int = 10) -> dict | None: """How much of the plan this grade's rounds actually got ladled, by food group, over its last counted rounds: the measured shortfall a kitchen cooks extra for.""" rounds = [] for r in many(f"SELECT * FROM meals WHERE grade = ? AND {COUNTED} ORDER BY date DESC, rowid DESC LIMIT ?", ctx["grade"], n): menu = ctx["menus"].get(r["menu_id"]) if menu: rounds.append((r, menu, dish_served_eff(r, menu), portion(ctx["s"], r["grade"]))) return nutrition.ladled_share(rounds) def recent_nutrition(ctx: dict, n: int = 5) -> list[dict]: """Energy and servings per child for the grade's last closed rounds, one row per day.""" rows = [] for r in many("SELECT * FROM meals WHERE grade = ? AND status = 'closed' ORDER BY date DESC, rowid DESC LIMIT ?", ctx["grade"], n): menu = ctx["menus"].get(r["menu_id"]) nu = nutrition.eaten(r, menu, dish_served_eff(r, menu), leftover_mix(r, ctx), portion(ctx["s"], r["grade"])) if menu else None if not nu: continue units = {g["key"]: g["units"] for g in nu["groups"]} rows.append({"date": r["date"], "menu_id": menu["id"], "name_th": menu["name_th"], "name_en": menu["name_en"], "icon": menu["icon"], "students": r["students"], "kcal": nu["kcal"], "pct_day": nu["pct_day"], **units, "carb_g": nu["carb_g"], "protein_g": nu["protein_g"], "fat_g": nu["fat_g"], "split": nu["leftover_split"]["by"], "counted": bool(r["qc_ok"] == 1 and not r["context_absence"] and not r["context_event"])}) return rows # ---------------------------------------------------------------- whole school: every grade side by side def overview(ctx_all: dict, scales: dict) -> dict: """Today's round for each grade plus the day's totals.""" s = ctx_all["s"] rounds, menu_count = [], {} tot = {"students": 0, "served_eff_g": 0.0, "waste_g": 0.0, "money_lost_thb": 0.0, "done": 0, "open": 0, "planned": 0} for r in rounds_today(s): g = r["grade"] entry = {"grade": g, "students_default": s["grade_students"].get(g), "portion": portion(s, g), "meal": None, "menu": None, "metrics": None, "judged_status": None, "will_investigate": False, "baseline": None} if r["meal"]: ctx = context(g) meal = one("SELECT * FROM meals WHERE id = ?", r["meal"]["id"]) menu = ctx["menus"][meal["menu_id"]] menu_count[menu["id"]] = menu_count.get(menu["id"], 0) + 1 entry.update(meal=meal, menu=menu, learning=ctx["learning"]) base = baseline_for(menu["id"], ctx) entry["baseline"] = base if meal["status"] == "planned": tot["planned"] += 1 entry["will_investigate"] = not meal["action_id"] and needs_investigation(menu["id"], ctx) else: if meal["status"] == "open": tot["open"] += 1 pots = pots_for(meal["id"]) broth = broth_for(meal["id"]) live = live_waste(meal, scales) mm = metrics({**meal, **served_from_pots(pots), "solid_ratio": broth["ratio"], "bone_g": ((live or {}).get("bins") or {}).get("bone")}, menu, live or {"rice_waste_g": 0, "dish_waste_g": 0}) entry["live"] = live is not None else: tot["done"] += 1 mm = metrics(meal, menu, leftovers=leftover_mix(meal, ctx)) tot["students"] += meal["students"] or 0 tot["served_eff_g"] += mm["served_eff_g"] tot["waste_g"] += mm["waste_g"] tot["money_lost_thb"] += mm["money_lost_thb"] or 0 entry["metrics"] = mm excluded = meal["context_absence"] or meal["context_event"] or (meal["status"] == "closed" and meal["qc_ok"] != 1) entry["judged_status"] = "excluded" if excluded else status_of(mm["judged_pct"], base, ctx) rounds.append(entry) main_menu = max(menu_count, key=menu_count.get) if menu_count else None tot["acceptance_pct"] = rnd(100 - pct(tot["waste_g"], tot["served_eff_g"])) if tot["served_eff_g"] > 0 else None return {"rounds": rounds, "totals": tot, "menu": ctx_all["menus"].get(main_menu) if main_menu else None} def grade_alert(ctx: dict) -> dict | None: """The grade leaves a lot of every menu: its median over all counted rounds is above the whole-grade limit. Menu baselines are relative to the grade's other menus, so only this flag sees a grade-wide problem (portions too big for the age, too little time to eat, snacks before lunch).""" s = ctx["s"] if ctx["learning"]: return None vals = [v for r in _window(ctx) if r["menu_id"] in ctx["menus"] for v in [judged_pct(r, ctx["menus"][r["menu_id"]])] if v is not None] if len(vals) < s["baseline_min_meals"]: return None med = median(vals) return {"median_pct": rnd(med), "limit_pct": s["grade_alert_pct"], "n": len(vals)} if med > s["grade_alert_pct"] else None def grade_matrix() -> dict: """Every grade x menu: flag, recent leftovers and the running decision. Drives the heatmap, the fix list and the grade dots.""" s = settings() cells = {} summary = {} for g in s["grades"]: ctx = context(g) row = {} needs = testing = verified = watch = 0 for mid in sorted(ctx["menus"]): p = menu_pattern(mid, ctx) a = p["action"] row[mid] = { "flag": p["flag"], "avg": p["avg_last_pct"], "last": [x["judged_pct"] for x in p["last"]], "last_status": [x["status"] for x in p["last"]], "n": len([x for x in p["serves"] if not x["excluded"]]), "consecutive_high": p["consecutive_high"], "baseline": p["baseline"], "action": {k: a[k] for k in ("id", "status", "kind", "trial_menu_id", "good", "verify_n", "cause", "finding", "option_key", "source_action_id", "source_grade", "simulation_only", "ready_for_real_use", "exposure", "counted", "max_trials")} if a else None, } live_action = a and a["status"] in ("testing", "verified") if p["flag"] == "repeated_high" and not live_action: needs += 1 elif p["flag"] == "high" and not live_action: watch += 1 if a and a["status"] == "testing": testing += 1 if a and a["status"] == "verified": verified += 1 cells[g] = row summary[g] = {"needs_fix": needs, "watch": watch, "testing": testing, "verified": verified, "learning": ctx["learning"], "counted": ctx["counted_n"], "acceptance": school_acceptance(ctx), "grade_alert": grade_alert(ctx)} return {"grades": s["grades"], "cells": cells, "summary": summary, "repeat_n": s["repeat_n"], "margin": s["high_margin_pts"], **prototype_metadata()} def issues(matrix: dict) -> list[dict]: """The whole-school to-do list: which grade has which menu to look at, and how far along it is.""" out = [] stage_rank = {"decide": 0, "ask": 1, "not_verified": 2, "testing": 3, "watch": 4, "verified": 5} for g in matrix["grades"]: ctx = None for mid, c in matrix["cells"][g].items(): a = c["action"] if a and a["status"] in ("testing", "verified"): stage = a["status"] elif c["flag"] == "repeated_high": ctx = ctx or context(g) ra = replaceable_action(mid, g) synth = cause_synthesis(mid, ctx, ra["id"] if ra else None) stage = "decide" if synth["ready"] else "ask" c = {**c, "blocker": synth["blocker_codes"][0] if synth["blocker_codes"] else None, "why": synth["why"]["key"] if synth["why"] else None, "what": synth["what"]["key"] if synth["what"] else None} if a and a["status"] == "not_verified" and not synth["ready"]: stage = "not_verified" elif c["flag"] == "high": stage = "watch" else: continue out.append({"grade": g, "menu_id": mid, "stage": stage, **c}) out.sort(key=lambda x: (stage_rank[x["stage"]], matrix["grades"].index(x["grade"]), x["menu_id"])) return out def audit_meals(ctx: dict) -> dict: """For the audit page: rounds asking for an audit, and the audit history.""" # Two bins: investigation rounds always need one; any other round served today can take the routine monthly # audit. Five bins weigh every group in every round, so nothing waits for the tray. g = ctx["grade"] five = ctx["s"]["return_bins"] == "five" wanted = [] if five else many( f"""SELECT ml.* FROM meals ml WHERE ml.status IN ('open', 'closed') AND (ml.investigation = 1 OR ml.date = ?) {'AND ml.grade = ?' if g else ''} AND NOT EXISTS (SELECT 1 FROM audits a WHERE a.meal_id = ml.id) ORDER BY ml.investigation DESC, ml.date DESC, ml.opened_at DESC LIMIT 20""", today(), *([g] if g else []), ) hist_rows = many( f"SELECT a.* FROM audits a JOIN meals ml ON ml.id = a.meal_id {'WHERE ml.grade = ?' if g else ''} ORDER BY a.ts DESC, a.id DESC LIMIT 20", *([g] if g else []), ) history = [audit_finding(a, ctx) for a in hist_rows] for h in history: h["menu_name"] = ctx["menus"][h["menu_id"]]["name_th"] return { "pending": [{**m, "menu_name": ctx["menus"][m["menu_id"]]["name_th"], "menu": ctx["menus"][m["menu_id"]]} for m in wanted], "history": history, "bins_replace_sort": five, } # ---------------------------------------------------------------- menu library + recipes def recipe_for(menu_id: str) -> dict | None: r = one("SELECT * FROM recipes WHERE menu_id = ?", menu_id) if not r: return None return {**r, "ingredients": json.loads(r["ingredients"]), "steps": json.loads(r["steps"]), "steps_en": json.loads(r["steps_en"] or "[]"), "data_provenance": {"origin": r.get("data_origin") or "user", "status": "unverified"}, **prototype_metadata()} def menu_table(ctx: dict) -> list[dict]: rows = [] has_recipe = {r["menu_id"] for r in many("SELECT menu_id FROM recipes")} served = {r["menu_id"]: r["n"] for r in many("SELECT menu_id, COUNT(*) AS n FROM meals WHERE status = 'closed' GROUP BY menu_id")} for m in sorted(ctx["menus"].values(), key=lambda x: x["id"]): rows.append({**m, "budget_pass": m["cost_thb"] <= ctx["budget"]["limit"], "history": menu_history(m["id"], ctx), **completeness(m), "has_recipe": m["id"] in has_recipe, "served_n": served.get(m["id"], 0)}) return rows def menu_detail(menu_id: str, matrix: dict) -> dict: s = settings() ctx = context(None) menu = ctx["menus"][menu_id] per_grade = [] for g in s["grades"]: c = matrix["cells"].get(g, {}).get(menu_id) h = menu_history(menu_id, {**ctx, "grade": g}) per_grade.append({"grade": g, "portion": portion(s, g), "students": s["grade_students"].get(g, 0), "n": h["n"], "avg": h["avg"], "flag": c["flag"] if c else None, "action": c["action"] if c else None}) return { "menu": {**menu, **completeness(menu), "budget_pass": menu["cost_thb"] <= ctx["budget"]["limit"]}, "recipe": recipe_for(menu_id), "grades": per_grade, "history": menu_history(menu_id, ctx), "served_n": one("SELECT COUNT(*) AS n FROM meals WHERE menu_id = ? AND status IN ('open', 'closed')", menu_id)["n"], "budget": ctx["budget"], "settings": s, **prototype_metadata(), } # ---------------------------------------------------------------- the principal's monthly report SCHOOL_DAYS_PER_YEAR = 200 # a Thai school year, used only for the yearly projection def _month_bounds(month: str) -> tuple[str, str, str]: """First day of the month, first day of the next one, and the previous month ("YYYY-MM").""" y, m = (int(x) for x in month.split("-")) nxt = f"{y + 1:04d}-01-01" if m == 12 else f"{y:04d}-{m + 1:02d}-01" prev = f"{y - 1:04d}-12" if m == 1 else f"{y:04d}-{m - 1:02d}" return f"{y:04d}-{m:02d}-01", nxt, prev def _report_rounds(month: str, ctxs: dict, s: dict, limit: float) -> list[dict]: """Every closed round of the month with what it cost, what the lunch subsidy paid for it, what came back and what each child ate (the same numbers as the round's own screens).""" start, end, _ = _month_bounds(month) rows = [] for meal in many("SELECT * FROM meals WHERE status = 'closed' AND date >= ? AND date < ? ORDER BY date, grade", start, end): g = meal["grade"] if g not in ctxs: ctxs[g] = context(g) menu = ctxs[g]["menus"].get(meal["menu_id"]) if not menu: continue m = metrics(meal, menu, leftovers=leftover_mix(meal, ctxs[g])) students = meal["students"] or 0 rows.append({ "meal": meal, "menu": menu, "m": m, "nu": m["nutrition"], "students": students, "counted": meal["qc_ok"] == 1 and not meal["context_absence"] and not meal["context_event"], "cost": menu["cost_thb"] * portion(s, g) * students, "budget": limit * students, "lost": m["money_lost_thb"] or 0, "bins": bool(sorted_bins_for(meal["id"])), }) return rows def _report_summary(rows: list[dict]) -> dict: """Totals for a set of rounds. Money counts every round; what was eaten counts only rounds whose scales passed the morning check on an ordinary day, like every other number the school decides on.""" counted = [r for r in rows if r["counted"]] served = sum(r["m"]["served_eff_g"] for r in counted) waste = sum(r["m"]["waste_g"] for r in counted) ate = [r for r in counted if r["nu"] and r["students"]] kids = sum(r["students"] for r in ate) def avg(get): return rnd(sum(get(r) * r["students"] for r in ate) / kids, 1) if kids else None groups = {} for key in ("starch", "protein", "veg"): pairs = [(r, next((g for g in r["nu"]["groups"] if g["key"] == key), None)) for r in ate] pairs = [(r, g) for r, g in pairs if g and g.get("lunch")] n = sum(r["students"] for r, _ in pairs) def share(status, pairs=pairs, n=n): return rnd(pct(sum(r["students"] for r, g in pairs if g["lunch"]["status"] == status), n)) if n else None groups[key] = {"units": rnd(sum(g["units"] * r["students"] for r, g in pairs) / n, 1) if n else None, "meets_pct": share("meets"), "minimum_pct": share("minimum"), "below_pct": share("below")} cost, budget, lost = (sum(r[k] for r in rows) for k in ("cost", "budget", "lost")) return { "rounds": len(rows), "counted": len(counted), "counted_pct": rnd(pct(len(counted), len(rows))) if rows else None, "days": len({r["meal"]["date"] for r in rows}), "child_meals": sum(r["students"] for r in rows), "acceptance_pct": rnd(100 - pct(waste, served)) if served else None, "cost_thb": round(cost), "budget_thb": round(budget), "lost_thb": round(lost), "cost_pct_of_budget": rnd(pct(cost, budget)) if budget else None, "lost_pct_of_budget": rnd(pct(lost, budget)) if budget else None, "kcal": avg(lambda r: r["nu"]["kcal"]), "protein_g": avg(lambda r: r["nu"]["protein_g"]), "groups": groups, "bins_pct": rnd(pct(sum(1 for r in rows if r["bins"]), len(rows))) if rows else None, } def _fix_row(x: dict, ctxs: dict) -> dict: """A menu problem for the report: the grade, the menu, where it stands, and a tried fix's before and after.""" out = {k: x.get(k) for k in ("grade", "menu_id", "stage", "avg", "why", "what", "consecutive_high")} if x["grade"] not in ctxs: ctxs[x["grade"]] = context(x["grade"]) menus = ctxs[x["grade"]]["menus"] out["menu"] = {k: menus.get(x["menu_id"], {}).get(k) for k in ("name_th", "name_en", "icon")} a = x.get("action") if a: row = one("SELECT before_pct, change_th, trial_menu_id FROM actions WHERE id = ?", a["id"]) or {} trials = [judged_pct(t, menus[t["menu_id"]]) for t in many("SELECT * FROM meals WHERE action_id = ? AND status = 'closed'", a["id"]) if t["menu_id"] in menus] trials = [t for t in trials if t is not None] trial_menu = menus.get(row.get("trial_menu_id")) or {} out["action"] = {"status": a["status"], "change_th": row.get("change_th"), "before_pct": rnd(row.get("before_pct")), "after_pct": rnd(mean(trials)) if trials else None, "trials": len(trials), "trial_menu": {k: trial_menu.get(k) for k in ("name_th", "name_en", "icon")}} return out def monthly_report(month: str | None, open_issues: list[dict]) -> dict: """What the principal needs once a month: what the children ate against the lunch standard, what lunch cost against the government subsidy and how much of it came back as leftovers, which menus need a decision and which fixes worked, and how far the numbers can be trusted.""" s = settings() budget = budget_tier(s["enrolled"]) month = month or today()[:7] _, _, prev_month = _month_bounds(month) ctxs: dict = {} rows = _report_rounds(month, ctxs, s, budget["limit"]) school = _report_summary(rows) prev = _report_summary(_report_rounds(prev_month, ctxs, s, budget["limit"])) grades = [] for g in s["grades"]: t = nutrition.lunch_target(g) grades.append({"grade": g, "students": s["grade_students"].get(g), "target": {"servings": t["servings"], "kcal": t["kcal"], "protein_g": t["protein_g"], "label_th": t["label_th"], "label_en": t["label_en"]}, **_report_summary([r for r in rows if r["meal"]["grade"] == g])}) weeks: dict[str, list] = {} for r in rows: weeks.setdefault(add_days(r["meal"]["date"], -date.fromisoformat(r["meal"]["date"]).weekday()), []).append(r) week_rows = [] for w, rs in sorted(weeks.items()): sm = _report_summary(rs) week_rows.append({"week": w, "rounds": sm["rounds"], "acceptance_pct": sm["acceptance_pct"], "lost_thb": sm["lost_thb"], "kcal": sm["kcal"], "veg_units": sm["groups"]["veg"]["units"], "veg_meets_pct": sm["groups"]["veg"]["meets_pct"]}) fixes = {stage: [_fix_row(x, ctxs) for x in open_issues if x.get("stage") in stages] for stage, stages in (("decide", ("decide", "not_verified")), ("ask", ("ask",)), ("testing", ("testing",)), ("verified", ("verified",)))} asked = [r for r in rows if r["meal"]["investigation"]] answers = sum(one("SELECT COUNT(*) AS n FROM votes WHERE meal_id = ?", r["meal"]["id"])["n"] for r in asked) asked_kids = sum(r["students"] for r in asked) lost_day = school["lost_thb"] / school["days"] if school["days"] else None return { "month": month, "prev_month": prev_month, "today": today(), "data_mode": data_mode(), "months": [r["m"] for r in many("SELECT DISTINCT substr(date, 1, 7) AS m FROM meals WHERE status = 'closed' ORDER BY m")], "school_name": s["school_name"], "enrolled": s["enrolled"], "budget": budget, "school": school, "prev": prev, "grades": grades, "weeks": week_rows, "fixes": fixes, "watch": sum(1 for x in open_issues if x.get("stage") == "watch"), "voice": {"rounds": len(asked), "answers": answers, "students": asked_kids, "rate": rnd(pct(answers, asked_kids)) if asked_kids else None}, "projection": {"school_days": SCHOOL_DAYS_PER_YEAR, "lost_per_day_thb": round(lost_day) if lost_day is not None else None, "lost_year_thb": round(lost_day * SCHOOL_DAYS_PER_YEAR) if lost_day is not None else None}, **prototype_metadata(), }
"""The EatBack loop: PLAN -> SERVE -> MEASURE -> repeated high? -> find the cause -> nutrition + budget gate -> trial -> measure again.
Three layers of data, one gate:
how much was left — kitchen scale + return station (every round)
what was left — audit tray (monthly, or when the system asks)
why it was left — kids' opinions, asked by a teacher and tapped in the app (1–3 days, when the system asks)
can we use it — the menu base: nutrition + budget, all 4 food groups, never fewer vegetables
Grades eat in separate rounds, so every rule runs per grade as if each grade were its own school:
its own baseline, its own "3 in a row", its own investigation, trial and verification.
Everything here is deterministic and explainable — no AI, no prediction.
"""
from __future__ import annotations
import json
from datetime import date
import devices
import nutrition
from db import budget_tier, data_mode, many, one, portion, settings
from util import add_days, add_school_days, local_iso, local_midnight_iso, mean, median, pct, rnd, today
GROUPS = [
{"key": "starch", "th": "ข้าว/แป้ง", "icon": "🍚"},
{"key": "veg", "th": "ผัก", "icon": "🥬"},
{"key": "protein", "th": "โปรตีน", "icon": "🍗"},
{"key": "fruit", "th": "ผลไม้", "icon": "🍉"},
]
GROUP_TH = {g["key"]: g["th"] for g in GROUPS}
# A closed round is evidence only on a normal day whose morning scale check passed. Baselines, streaks, menu history
# and acceptance all use this one rule, so a round the trial check would refuse never shapes them either.
COUNTED = "status = 'closed' AND context_absence = 0 AND context_event = 0 AND qc_ok = 1"
DATA_NOTICE = {
"code": "prototype_unverified", "status": "unverified",
"message": "ข้อมูลเมนู สูตร ปริมาณสารอาหาร และต้นทุนยังไม่ได้ตรวจรับรองรายเมนู ตัวอย่างเดโมใช้เพื่อทดลองขั้นตอนเท่านั้น",
"message_en": "Menu recipes, nutrient values and costs have no verified per-menu assessment. Demo examples simulate the workflow only.",
"simulation_only": True, "ready_for_real_use": False,
}
def prototype_metadata() -> dict:
return {"prototype": True, "simulation_only": True, "ready_for_real_use": False, "data_notice": dict(DATA_NOTICE)}
def menu_provenance(menu: dict, recipe_origin: str | None = None) -> dict:
origin = menu.get("data_origin") or "user"
return {**menu, "nutrition_pass": 0, "nutrition_status": "unverified", "simulation_only": True, "ready_for_real_use": False,
"energy": nutrition.full_portion(menu),
"data_provenance": {"origin": origin,
"nutrition": {"status": "unverified", "origin": origin, "source": menu.get("nutrition_source") or "",
"source_url": menu.get("nutrition_source_url") or "", "checked_at": menu.get("nutrition_checked_at") or "",
"scope": menu.get("nutrition_scope") or ""},
"recipe": {"status": "unverified", "origin": recipe_origin or "missing"},
"cost": {"status": "unverified", "origin": origin}}}
def nutrition_check() -> dict:
return {"key": "nutrition", "label": "Nutrition", "pass": False, "status": "unverified", "approved": False,
"blocking": False, "simulation_only": True,
"detail": "ยังไม่มีเอกสารประเมินโภชนาการรายเมนู ทดลองขั้นตอนด้วยข้อมูลตัวอย่างเท่านั้น",
"detail_en": "No per-menu nutrition assessment is available. This option simulates the workflow only."}
REASONS = {
"ate_all": "กินหมด",
"too_much": "เยอะไป",
"taste": "รสชาติไม่ถูกปาก",
"hard": "แข็งหรือชิ้นใหญ่",
"unfamiliar": "ไม่คุ้น ไม่เคยกิน",
"no_time": "กินไม่ทัน",
}
# What the kids said most -> what the system proposes. Every option still has to pass the gate.
SOLUTIONS = {
"too_much": {"title": "ทบทวนปริมาณตักต่อคนให้เหมาะกับช่วงวัย",
"change": "ตักข้าวและกับข้าวตามปริมาณของช่วงวัยที่ตั้งไว้ ไม่ต่ำกว่านั้น และให้เติมได้ โดยผักต่อคนคงเดิม", "swap": False},
"taste": {"title": "ปรับสูตรและการปรุงรส",
"change": "ปรับรสและกลิ่นให้เข้ากับเด็ก โดยไม่เพิ่มโซเดียมและน้ำตาลเกินสูตรเดิม", "swap": False},
"hard": {"title": "หั่นเล็กลง ทำให้นุ่มขึ้น หรือเปลี่ยนวิธีปรุง",
"change": "หั่นชิ้นเล็กลงและปรุงให้นุ่มขึ้นในเมนูเดิม", "swap": True},
"unfamiliar": {"title": "เสิร์ฟซ้ำเป็นระยะ หรือจับคู่กับเมนูที่เด็กคุ้น",
"change": "เสิร์ฟซ้ำเว้นระยะหลายครั้ง และจับคู่กับของที่เด็กคุ้น", "swap": False},
"no_time": {"title": "ทบทวนเวลาพักกลางวัน ไม่ต้องแก้สูตร",
"change": "เพิ่มเวลากินหรือลดคิวรอรับอาหาร สูตรอาหารคงเดิม", "swap": False},
}
# ---------------------------------------------------------------- context
def context(grade: str | None = None) -> dict:
"""Everything the rules need for one grade (grade=None: whole-school views only)."""
s = settings()
recipe_origins = {r["menu_id"]: r["data_origin"] for r in many("SELECT menu_id, data_origin FROM recipes")}
menus = {m["id"]: menu_provenance(m, recipe_origins.get(m["id"])) for m in many("SELECT * FROM menus")}
counted_n = one(f"SELECT COUNT(*) AS n FROM meals WHERE grade = ? AND {COUNTED}", grade)["n"] if grade else 0
return {
"s": s, "menus": menus, "budget": budget_tier(s["enrolled"]), "grade": grade, "portion": portion(s, grade),
"counted_n": counted_n, "learning": bool(grade) and counted_n < s["learning_min_meals"], "_base": {}, "_window": None,