eatback / py /db.py
kritpakin's picture
Five sorted bins as the main story, role PINs, start page, kitchen stages
811afbe verified
Raw History Blame Contribute Delete
17.8 kB
"""SQLite storage (Python standard library only — nothing to pip install).
Weights are stored in grams everywhere; the UI converts to kg for display."""
from __future__ import annotations
import json
import os
import sqlite3
import threading
from contextlib import contextmanager
from pathlib import Path
from util import now_iso
ROOT = Path(__file__).resolve().parent.parent
DATA_DIR = ROOT / "data"
DATA_DIR.mkdir(exist_ok=True)
DB_PATH = Path(os.environ.get("EATBACK_DB") or DATA_DIR / "eatback.sqlite3") # override for tests
# One connection shared by the request threads; LOCK serialises every access.
LOCK = threading.RLock()
conn = sqlite3.connect(DB_PATH, check_same_thread=False, isolation_level=None)
conn.row_factory = sqlite3.Row
SCHEMA = """
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
-- Sample menu base. Phase 2: replaced by the Thai School Lunch menu base.
CREATE TABLE IF NOT EXISTS menus (
id TEXT PRIMARY KEY,
name_th TEXT NOT NULL,
name_en TEXT NOT NULL,
category TEXT NOT NULL, -- rice_side (ข้าว + กับข้าว) | one_dish (อาหารจานเดียว)
prep TEXT NOT NULL, -- preparation format key
prep_th TEXT NOT NULL,
prep_en TEXT NOT NULL DEFAULT '',
icon TEXT NOT NULL DEFAULT '',
has_broth INTEGER NOT NULL, -- curry/soup: dish is strained at the return station
starch_g REAL NOT NULL, -- planned grams per student (grade 4–6 portion), by food group
veg_g REAL NOT NULL,
protein_g REAL NOT NULL,
fruit_g REAL NOT NULL,
fruit_name TEXT NOT NULL DEFAULT '', -- the fruit served with this menu
kcal REAL NOT NULL,
cost_thb REAL NOT NULL, -- ingredient cost per student
nutrition_pass INTEGER NOT NULL DEFAULT 0, -- legacy field; this prototype cannot certify nutrition
nutrition_status TEXT NOT NULL DEFAULT 'unverified',
nutrition_source TEXT NOT NULL DEFAULT '',
nutrition_source_url TEXT NOT NULL DEFAULT '',
nutrition_checked_at TEXT NOT NULL DEFAULT '',
nutrition_scope TEXT NOT NULL DEFAULT '',
data_origin TEXT NOT NULL DEFAULT 'user'
);
-- How to cook a menu. Quantities make `servings` grade 4–6 portions; screens scale them to the day's head count.
CREATE TABLE IF NOT EXISTS recipes (
menu_id TEXT PRIMARY KEY,
servings INTEGER NOT NULL,
ingredients TEXT NOT NULL, -- JSON [{name, name_en, qty, unit}]
steps TEXT NOT NULL, -- JSON [str]
steps_en TEXT NOT NULL DEFAULT '[]',
tips TEXT NOT NULL DEFAULT '',
tips_en TEXT NOT NULL DEFAULT '',
updated_at TEXT NOT NULL,
data_origin TEXT NOT NULL DEFAULT 'user'
);
-- One lunch round for one grade. Grades eat in separate rounds, so every number is per grade.
-- status: planned -> open -> closed
CREATE TABLE IF NOT EXISTS meals (
id TEXT PRIMARY KEY, -- e.g. 260926-P1
date TEXT NOT NULL,
menu_id TEXT NOT NULL,
grade TEXT NOT NULL DEFAULT '', -- K1–K3, P1–P6
students INTEGER,
planned_students INTEGER, -- weekly plan headcount, retained when attendance changes at serving
seating TEXT, -- unused since grades (kept for old databases)
bins_manual INTEGER NOT NULL DEFAULT 0, -- leftovers typed in at the end instead of read from the bins
status TEXT NOT NULL,
origin TEXT NOT NULL, -- seed | live | trial
action_id INTEGER, -- set when this meal tests an improvement
investigation INTEGER NOT NULL DEFAULT 0, -- voice buttons + audit requested
context_absence INTEGER NOT NULL DEFAULT 0, -- unusual absence that day
context_event INTEGER NOT NULL DEFAULT 0, -- special activity that day
return_rice_start REAL,
return_dish_start REAL,
rice_served_g REAL,
dish_served_g REAL, -- pot difference (gross, includes broth)
solid_ratio REAL, -- broth menus: solids / ladle, from broth samples
rice_waste_g REAL,
dish_waste_g REAL,
bone_g REAL, -- five-bin station: bones and other inedible parts back from the dish (NULL: not weighed)
qc_ok INTEGER,
opened_at TEXT,
closed_at TEXT
);
-- Every kitchen-scale capture (pot before / after serving). Append-only.
CREATE TABLE IF NOT EXISTS weighings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
meal_id TEXT NOT NULL,
pot TEXT NOT NULL, -- rice | dish
phase TEXT NOT NULL, -- before | after
raw_g REAL NOT NULL,
source TEXT NOT NULL, -- esp32 | sim | manual
ts TEXT NOT NULL
);
-- Curry/soup: one standard ladle weighed before and after straining.
CREATE TABLE IF NOT EXISTS broth_samples (
id INTEGER PRIMARY KEY AUTOINCREMENT,
meal_id TEXT NOT NULL,
point TEXT NOT NULL, -- start | middle | end
ladle_g REAL NOT NULL,
solid_g REAL NOT NULL,
ts TEXT NOT NULL
);
-- Audit tray: the meal's combined leftovers split into 4 food groups, weighed on any scale and typed in.
CREATE TABLE IF NOT EXISTS audits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
meal_id TEXT NOT NULL,
covers INTEGER NOT NULL, -- students whose leftovers went into the tray
starch_g REAL NOT NULL,
veg_g REAL NOT NULL,
protein_g REAL NOT NULL,
fruit_g REAL NOT NULL,
source TEXT NOT NULL,
ts TEXT NOT NULL
);
-- Five-bin return station (settings return_bins = 'five'): children sort their tray into five weighed bins, four
-- food groups and one for bones and other inedible parts. One row per bin per round: the reading when the round
-- opened, and what came back when it closed (NULL until then, or when the leftovers were typed in instead).
-- meals.rice_waste_g / dish_waste_g still hold starch and veg + protein + fat, so every two-bin rule keeps working;
-- meals.bone_g holds the bone bin, which comes off what the dish served instead of counting as leftovers.
CREATE TABLE IF NOT EXISTS sorted_bins (
meal_id TEXT NOT NULL,
bin TEXT NOT NULL, -- starch | veg | protein | fat | bone
start_g REAL NOT NULL,
waste_g REAL,
PRIMARY KEY (meal_id, bin)
);
-- Kids' voice box: one row per accepted button press. No names, no IDs.
CREATE TABLE IF NOT EXISTS votes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
meal_id TEXT NOT NULL,
button TEXT NOT NULL, -- ate_all | too_much | taste | hard | unfamiliar | no_time
source TEXT NOT NULL, -- esp32 | sim
ts TEXT NOT NULL
);
-- IMPROVE decisions. status: testing -> verified | not_verified
CREATE TABLE IF NOT EXISTS actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
menu_id TEXT NOT NULL, -- the menu with repeated high waste
grade TEXT NOT NULL DEFAULT '', -- the grade it was found in; the trial runs for that grade
evidence_meals TEXT NOT NULL, -- JSON list of investigation meal ids used for the decision
audit_id INTEGER,
finding TEXT, -- food group the audit flagged
cause TEXT, -- top voice-box reason
option_key TEXT NOT NULL, -- adjust | swap:<menu id>
kind TEXT NOT NULL, -- adjust | swap
trial_menu_id TEXT NOT NULL,
change_th TEXT NOT NULL,
status TEXT NOT NULL,
before_pct REAL,
source_action_id INTEGER, -- verified decision reused as a new, independently measured trial
created_at TEXT NOT NULL
);
-- Scale verification with reference weights.
CREATE TABLE IF NOT EXISTS qc_checks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel TEXT NOT NULL,
reference_g REAL NOT NULL,
reading_g REAL NOT NULL,
deviation_pct REAL NOT NULL,
tolerance_pct REAL NOT NULL,
pass INTEGER NOT NULL,
source TEXT NOT NULL,
ts TEXT NOT NULL
);
-- Audit trail of everything that changes data.
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL,
type TEXT NOT NULL,
detail TEXT NOT NULL
);
"""
def migrate() -> None:
"""Create missing tables, columns and indexes. Runs at start and again after a backup is restored."""
# WAL needs shared memory, which the in-browser build (Pyodide) does not have.
conn.executescript(SCHEMA.replace("PRAGMA journal_mode = WAL;", "") if os.environ.get("EATBACK_BROWSER") else SCHEMA)
# Older databases get the newer columns in place (the seed version bump then reloads the demo data).
for _table, _col, _decl in (
("menus", "prep_en", "TEXT NOT NULL DEFAULT ''"), ("menus", "icon", "TEXT NOT NULL DEFAULT ''"),
("menus", "fruit_name", "TEXT NOT NULL DEFAULT ''"), ("meals", "grade", "TEXT NOT NULL DEFAULT ''"),
("meals", "bins_manual", "INTEGER NOT NULL DEFAULT 0"), ("actions", "grade", "TEXT NOT NULL DEFAULT ''"),
("actions", "source_action_id", "INTEGER"),
("meals", "planned_students", "INTEGER"), ("meals", "bone_g", "REAL"),
("menus", "nutrition_status", "TEXT NOT NULL DEFAULT 'unverified'"),
("menus", "nutrition_source", "TEXT NOT NULL DEFAULT ''"),
("menus", "nutrition_source_url", "TEXT NOT NULL DEFAULT ''"),
("menus", "nutrition_checked_at", "TEXT NOT NULL DEFAULT ''"),
("menus", "nutrition_scope", "TEXT NOT NULL DEFAULT ''"),
("menus", "data_origin", "TEXT NOT NULL DEFAULT 'user'"),
("recipes", "data_origin", "TEXT NOT NULL DEFAULT 'user'"),
):
if _col not in {r[1] for r in conn.execute(f"PRAGMA table_info({_table})").fetchall()}:
conn.execute(f"ALTER TABLE {_table} ADD COLUMN {_col} {_decl}")
if _col == "data_origin":
# Identify the old bundled samples, then retain user edits recorded in the audit log.
_id_col = "id" if _table == "menus" else "menu_id"
_event_kind = "menu_saved" if _table == "menus" else "recipe_saved"
_edited = set()
for _event in conn.execute("SELECT detail FROM events WHERE type = ?", (_event_kind,)):
try:
_edited.add(json.loads(_event[0]).get("menu_id"))
except (ValueError, AttributeError):
pass
for _i in range(1, 15):
_menu_id = f"M{_i:02d}"
if _menu_id not in _edited:
conn.execute(f"UPDATE {_table} SET data_origin = 'demo' WHERE {_id_col} = ?", (_menu_id,))
conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS action_reuse_once ON actions(source_action_id, grade) WHERE source_action_id IS NOT NULL")
for _sql in (
"CREATE INDEX IF NOT EXISTS meals_grade_status ON meals(grade, status, date)",
"CREATE INDEX IF NOT EXISTS meals_menu_grade ON meals(menu_id, grade)",
"CREATE INDEX IF NOT EXISTS meals_action ON meals(action_id)",
"CREATE INDEX IF NOT EXISTS weighings_meal ON weighings(meal_id)",
"CREATE INDEX IF NOT EXISTS broth_meal ON broth_samples(meal_id)",
"CREATE INDEX IF NOT EXISTS audits_meal ON audits(meal_id)",
"CREATE INDEX IF NOT EXISTS votes_meal ON votes(meal_id)",
"CREATE INDEX IF NOT EXISTS qc_channel_ts ON qc_checks(channel, reference_g, ts)",
):
conn.execute(_sql)
# No per-menu assessment documents have been imported. Historical demo checkboxes were not evidence.
conn.execute("UPDATE menus SET nutrition_pass = 0, nutrition_status = 'unverified'")
with LOCK:
migrate()
def one(sql: str, *params) -> dict | None:
row = conn.execute(sql, params).fetchone()
return dict(row) if row else None
def many(sql: str, *params) -> list[dict]:
return [dict(r) for r in conn.execute(sql, params).fetchall()]
def run(sql: str, *params) -> sqlite3.Cursor:
return conn.execute(sql, params)
@contextmanager
def transaction():
conn.execute("BEGIN IMMEDIATE")
try:
yield
except BaseException:
conn.execute("ROLLBACK")
raise
conn.execute("COMMIT")
ALL_GRADES = ("K1", "K2", "K3", "P1", "P2", "P3", "P4", "P5", "P6")
DEFAULT_SETTINGS = {
"school_name": "โรงเรียนบ้านหนองตัวอย่าง",
"enrolled": 182, # sum of grade_students; decides the government lunch budget tier
"grades": list(ALL_GRADES), # grades this school teaches, each eats in its own round
"grade_students": {"K1": 18, "K2": 20, "K3": 20, "P1": 24, "P2": 22, "P3": 20, "P4": 20, "P5": 19, "P6": 19},
# Portion per student compared with grade 4–6 (team starting values, the school sets its own).
"grade_portion": {"K1": 0.6, "K2": 0.6, "K3": 0.7, "P1": 0.8, "P2": 0.8, "P3": 0.9, "P4": 1.0, "P5": 1.0, "P6": 1.0},
"high_margin_pts": 8, # high waste = more than the baseline + 8 points
"repeat_n": 3, # repeated high waste = N high serves in a row
"learning_min_meals": 15, # no judgements until this many counted meals exist
"baseline_window_days": 60,
"baseline_min_meals": 5, # other meals of the same menu type needed for a baseline
"audit_flag_pct": 20, # a food group is flagged when >= 20% of what was served comes back
"audit_consistency_pct": 10, # audit total vs daily bins may differ by at most 10%
"vote_lockout_s": 2.5, # voice box locks after each press
"response_low_pct": 30, # < 30% responses: not enough to name a cause
"response_high_pct": 60, # 30–60% medium confidence, > 60% full
"verify_n": 2, # an improvement is verified after N good trial serves
# Kids said "unfamiliar": acceptance of a new food usually needs several exposures, so early high serves
# do not end the trial. It ends after this many counted serves, spaced this many school days apart.
"exposure_trials": 8,
"exposure_gap_days": 3,
# Kids said "too much": a trial only counts when each child was still served at least this share of the
# grade's planned portion (menu grams x grade portion), so leftovers cannot fall just because less was served.
"portion_floor_pct": 90,
# Whole-grade alert: the grade's median leftovers over every menu is above this. Per-menu baselines are
# relative, so a grade that leaves a lot of everything would otherwise never be flagged.
"grade_alert_pct": 30,
"broth_points_normal": 2, # curry ladle samples: start + end
"broth_points_audit": 3, # start + middle + end on investigation days
"qc_refs": [500, 2000], # reference weights checked every morning
"qc_tolerance_pct": 1.0,
"stable_band_g": 10, # reading is stable when it moves less than this over 1.2 s
# Return station: "five" bins the children sort into (starch, veg, protein, fat, bone), weighed by ESP32 B or
# typed in from any scale; or "two" bins (rice, dish) with the 4-compartment tray on cause-finding rounds.
"return_bins": "five",
"acceptance_window_days": 30,
}
def settings() -> dict:
s = json.loads(json.dumps(DEFAULT_SETTINGS)) # deep copy: the grade maps are nested
for r in many("SELECT key, value FROM settings"):
if r["key"] in s:
s[r["key"]] = json.loads(r["value"])
s["grades"] = [g for g in ALL_GRADES if g in s["grades"]] or list(ALL_GRADES)
s["enrolled"] = sum(int(s["grade_students"].get(g) or 0) for g in s["grades"]) or s["enrolled"]
return s
def portion(s: dict, grade: str | None) -> float:
"""Portion factor for a grade (1.0 = grade 4–6 portion)."""
return float(s["grade_portion"].get(grade, 1.0)) if grade else 1.0
def save_settings(patch: dict) -> None:
for k, v in patch.items():
if k in DEFAULT_SETTINGS:
run(
"INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
k, json.dumps(v, ensure_ascii=False),
)
def _meta(key: str) -> str | None:
row = one("SELECT value FROM settings WHERE key = ?", key)
return row["value"] if row else None
def _set_meta(key: str, value: str) -> None:
run("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", key, value)
def data_mode() -> str:
"""'demo' (sample data, may be reset) or 'real' (the school's own records: never reset or re-seeded).
Kept outside DEFAULT_SETTINGS so the settings form cannot change it."""
return "real" if _meta("data_mode") == "real" else "demo"
def set_data_mode(mode: str) -> None:
_set_meta("data_mode", mode)
_set_meta("data_mode_since", now_iso())
def data_mode_info() -> dict:
return {"mode": data_mode(), "since": _meta("data_mode_since"), "last_reseed": json.loads(_meta("last_reseed") or "null")}
def budget_tier(enrolled: int) -> dict:
"""Thai government lunch subsidy by school size (Cabinet resolution 8 Nov 2022, still in force for FY2569)."""
if enrolled <= 40:
return {"limit": 36, "label": "โรงเรียน 1–40 คน"}
if enrolled <= 100:
return {"limit": 27, "label": "โรงเรียน 41–100 คน"}
if enrolled <= 120:
return {"limit": 24, "label": "โรงเรียน 101–120 คน"}
return {"limit": 22, "label": "โรงเรียน 121 คนขึ้นไป"}
def log_event(kind: str, **detail) -> None:
run("INSERT INTO events (ts, type, detail) VALUES (?, ?, ?)", now_iso(), kind, json.dumps(detail, ensure_ascii=False))