"""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: