Spaces:
Running
Running
File size: 20,507 Bytes
811afbe 9aaa92e 811afbe 9aaa92e 811afbe 9aaa92e 811afbe | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | // Manual controls for the live weight channels: the kitchen scale and the return-station bins (two, or the five
// sorted bins when the school uses them). ESP32 readings take over again on their next post.
import { api, live, kg, num, act, signIn, roleChip } from './core.js';
import { T, onLang, applyStatic, langToggle, FIVE_BINS, binName } from './i18n.js';
await signIn('sim');
onLang(() => location.reload());
document.getElementById('lang-slot').innerHTML = roleChip() + langToggle();
applyStatic();
const CHANNELS = {
kitchen: { no: '01', title: T('เครื่องชั่งในครัว', 'Kitchen scale'), location: T('ครัว · ESP32 A', 'Kitchen · ESP32 A'), purpose: T('ชั่งหม้อก่อนและหลังตัก เพื่อรู้ว่าตักไปเท่าไร', 'Weigh pots before and after serving') },
rice: { no: '02', title: T('ถังเศษข้าว', 'Rice leftovers bin'), location: T('จุดคืนจาน · ESP32 B ช่อง 1', 'Return station · ESP32 B ch 1'), purpose: T('ชั่งเศษข้าวที่เด็กเทคืน', 'Weighs the rice kids bring back') },
dish: { no: '03', title: T('ถังเศษกับข้าว', 'Main-dish leftovers bin'), location: T('จุดคืนจาน · ESP32 B ช่อง 2', 'Return station · ESP32 B ch 2'), purpose: T('ชั่งเศษกับข้าวบนตะแกรง', 'Weighs main-dish leftovers on the strainer') },
};
FIVE_BINS.forEach((k, i) => {
CHANNELS[k] = { no: String(i + 2).padStart(2, '0'), title: T(`ถัง${binName(k)}`, `${binName(k)} bin`),
location: T(`จุดคืนจาน 5 ถัง · ESP32 B ช่อง ${i + 1}`, `5-bin return station · ESP32 B ch ${i + 1}`),
purpose: T(`เด็กแยกทิ้ง${binName(k)}ลงถังนี้`, `Children sort ${binName(k).toLowerCase()} into this bin`) };
});
const QUICK = {
kitchen: [
[T('วางหม้อกับข้าว 3 กก.', 'Main-dish pot 3 kg'), { value_g: 3000 }],
[T('ตักออก 0.5 กก.', 'Serve 0.5 kg'), { delta_g: -500 }],
[T('ตักออก 2.5 กก.', 'Serve 2.5 kg'), { delta_g: -2500 }],
[T('วางหม้อข้าว 12 กก.', 'Rice pot 12 kg'), { value_g: 12000 }],
[T('ยกหม้อออก', 'Lift the pot off'), { value_g: 0 }],
[T('ตุ้ม 500 ก.', '500 g weight'), { value_g: 500.9 }],
[T('ตุ้ม 500 ก. (เครื่องเพี้ยน)', '500 g weight (off)'), { value_g: 508.5 }],
[T('เพิ่ม 120 ก.', 'Add 120 g'), { delta_g: 120 }],
[T('เพิ่ม 30 ก.', 'Add 30 g'), { delta_g: 30 }],
[T('ตุ้ม 2,000 ก.', '2,000 g weight'), { value_g: 2003 }],
],
rice: [
[T('เพิ่ม 50 ก.', 'Add 50 g'), { delta_g: 50 }],
[T('เพิ่ม 200 ก.', 'Add 200 g'), { delta_g: 200 }],
[T('ตุ้ม 500 ก.', '500 g weight'), { value_g: 500.4 }],
[T('เทถังทิ้ง', 'Empty the bin'), { value_g: 0 }],
[T('ตุ้ม 2,000 ก.', '2,000 g weight'), { value_g: 1998.6 }],
],
dish: [
[T('เพิ่ม 50 ก.', 'Add 50 g'), { delta_g: 50 }],
[T('เพิ่ม 200 ก.', 'Add 200 g'), { delta_g: 200 }],
[T('เพิ่ม 700 ก.', 'Add 700 g'), { delta_g: 700 }],
[T('ตุ้ม 500 ก.', '500 g weight'), { value_g: 499.6 }],
[T('เทถังทิ้ง', 'Empty the bin'), { value_g: 0 }],
[T('ตุ้ม 2,000 ก.', '2,000 g weight'), { value_g: 2001.2 }],
],
};
const PRIMARY = { kitchen: [0, 1, 2, 3, 4], rice: [0, 1, 3], dish: [0, 1, 2, 4] };
const EXTRA = { kitchen: [5, 9, 6, 7, 8], rice: [2, 4], dish: [3, 5] };
FIVE_BINS.forEach((k, i) => {
QUICK[k] = [
[T('เพิ่ม 20 ก.', 'Add 20 g'), { delta_g: 20 }],
[T('เพิ่ม 100 ก.', 'Add 100 g'), { delta_g: 100 }],
[T('ตุ้ม 500 ก.', '500 g weight'), { value_g: [500.2, 499.8, 500.6, 499.7, 500.3][i] }],
[T('เทถังทิ้ง', 'Empty the bin'), { value_g: 0 }],
[T('ตุ้ม 2,000 ก.', '2,000 g weight'), { value_g: [1999.4, 2000.8, 2001.6, 1998.9, 2000.5][i] }],
];
PRIMARY[k] = [0, 1, 3];
EXTRA[k] = [2, 4];
});
// ---------------------------------------------------------------- kids' opinions (tapped in the app by a teacher)
const REASONS = [['ate_all', T('กินหมด', 'Ate it all')], ['too_much', T('เยอะไป', 'Too much')], ['taste', T('รสชาติไม่ถูกปาก', "Didn't like the taste")], ['hard', T('แข็งหรือชิ้นใหญ่', 'Too hard or big')], ['unfamiliar', T('ไม่คุ้น ไม่เคยกิน', 'Never had it before')], ['no_time', T('กินไม่ทัน', 'Not enough time')]];
const BATCHES = {
demo: [T('ห้องเรียน 18 คนตอบ', '18 kids answer'), T('ส่วนใหญ่ตอบ “แข็งหรือชิ้นใหญ่”', 'Mostly “too hard or big”'), { ate_all: 5, too_much: 1, taste: 2, hard: 8, unfamiliar: 1, no_time: 1 }],
spread: [T('ห้องเรียน 10 คนตอบ', '10 kids answer'), T('คำตอบกระจาย', 'Mixed answers'), { ate_all: 3, too_much: 2, taste: 2, hard: 1, unfamiliar: 1, no_time: 1 }],
};
let voiceState = null;
document.getElementById('voice-buttons').innerHTML = REASONS.map(([key, label]) =>
`<button class="btn" type="button" data-vote="${key}">${label}<small>${T('เด็ก 1 คน', 'one child')}</small></button>`).join('');
document.getElementById('voice-batches').innerHTML = Object.entries(BATCHES).map(([key, [title, sub]]) =>
`<button class="btn" type="button" data-batch="${key}"><span>${title}<small>${sub}</small></span></button>`).join('');
function voiceFeedback(message, error = false) {
const el = document.getElementById('voice-feedback');
el.textContent = message;
el.classList.toggle('error', error);
}
function renderVoice() {
const on = voiceState?.enabled;
const chip = document.getElementById('voice-state');
chip.textContent = !voiceState ? T('กำลังเชื่อมต่อ', 'Connecting') : on ? T('รอบนี้เก็บข้อคิดเห็น', 'Collecting this round') : T('รอบนี้ไม่ต้องเก็บข้อคิดเห็น', 'Not needed this round');
chip.className = `chip ${on ? 'good' : ''}`;
document.querySelectorAll('[data-vote], [data-batch]').forEach((b) => { b.disabled = !on; });
}
document.body.addEventListener('click', async (event) => {
const v = event.target.closest('button[data-vote]');
if (v) {
try {
const r = await api('/api/opinion', { meal_id: voiceState.meal_id, button: v.dataset.vote });
voiceFeedback(T(`บันทึกแล้ว รอบนี้ได้ข้อคิดเห็น ${r.total} คน จาก ${r.students} คน${r.over ? ' เกินจำนวนเด็ก รอบนี้ใช้ไม่ได้' : ''}`, `Saved. ${r.total} of ${r.students} children have answered${r.over ? '. More answers than children, so this round will not count' : ''}`), r.over);
} catch (e) { voiceFeedback(e.message, true); }
return;
}
const b = event.target.closest('button[data-batch]');
if (b) {
const r = await act('/api/sim/votes', { counts: BATCHES[b.dataset.batch][2] });
if (r) voiceFeedback(T(`เพิ่มข้อคิดเห็น ${r.added} คนแล้ว`, `Added ${r.added} answers`));
}
});
const busy = new Set();
let scales = null;
let state = null;
let stateVersion = null;
let stateLoading = false;
let lastStateAttempt = 0;
let scenarioBusy = false;
function buttonsFor(channel, indices) {
return indices.map((i) => {
const [label, body] = QUICK[channel][i];
const kind = body.value_g === 0 ? 'reset' : 'quick';
return `<button class="btn sm" type="button" data-ch="${channel}" data-i="${i}" data-kind="${kind}">${label}</button>`;
}).join('');
}
// The bins on screen: an open round keeps the layout it started with, otherwise the school's setting.
let shown = ['kitchen', 'rice', 'dish'];
function binsInUse() {
const c = state?.current;
const five = c?.meal?.status === 'open' ? Object.keys(c.sorted_bins ?? {}).length > 0 : state?.settings?.return_bins === 'five';
return five ? FIVE_BINS : ['rice', 'dish'];
}
function renderGrid() {
shown = ['kitchen', ...binsInUse()];
document.getElementById('grid').innerHTML = shown.map((channel) => [channel, CHANNELS[channel]]).map(([channel, info]) => `
<section class="card sim-card" data-channel="${channel}" aria-labelledby="title-${channel}">
<div class="sim-card-head">
<span class="sim-card-no" aria-hidden="true">${info.no}</span>
<div><h2 class="sim-card-title" id="title-${channel}">${info.title}</h2><div class="sim-card-location">${info.location}</div></div>
</div>
<p class="sim-card-purpose">${info.purpose}</p>
<div class="sim-reading">
<span class="sim-reading-label">${T("น้ำหนักตอนนี้", "Live weight")}</span>
<output class="scale-val" id="val-${channel}">—<span class="unit">${T("ก.", "g")}</span></output>
<div class="sim-reading-meta"><span class="chip" id="src-${channel}">${T("กำลังเชื่อมต่อ", "Connecting")}</span><span class="sim-stability" id="stable-${channel}">${T("รอข้อมูล…", "Waiting…")}</span></div>
</div>
<p class="sim-source-hint" id="source-hint-${channel}">${T("กำลังเชื่อมต่อ…", "Connecting…")}</p>
<div class="sim-quick-section">
<h3 class="sim-section-title">${T("ปุ่มลัด", "Quick values")}</h3>
<p class="sim-section-hint">${T("กดแล้วส่งค่าทันที", "Sends immediately")}</p>
<div class="sim-actions">${buttonsFor(channel, PRIMARY[channel])}</div>
<details class="sim-extra">
<summary>${T("ตุ้มตรวจเครื่องและค่าอื่น", "Reference weights & more")}</summary>
<div class="sim-actions">${buttonsFor(channel, EXTRA[channel])}</div>
</details>
</div>
<div class="sim-custom">
<form data-set-form="${channel}" novalidate>
<label for="in-${channel}">${T("ตั้งน้ำหนักเอง (กรัม)", "Set a weight (g)")}</label>
<div class="sim-setrow">
<input type="number" id="in-${channel}" min="0" step="0.1" inputmode="decimal" placeholder="${T("เช่น 1250", "e.g. 1250")}" aria-describedby="help-${channel} feedback-${channel}" required>
<button class="btn primary" type="submit">${T("ตั้งค่า", "Set")}</button>
</div>
<p class="sim-input-help" id="help-${channel}">${T("ใส่น้ำหนักรวม ไม่ใช่ค่าที่จะเพิ่ม", "Enter the total weight, not an amount to add")}</p>
<p class="sim-input-feedback" id="feedback-${channel}" role="status" aria-live="polite"></p>
</form>
</div>
</section>`).join('');
}
renderGrid();
function feedback(channel, message, style = '') {
const el = document.getElementById(`feedback-${channel}`);
el.textContent = message;
el.className = `sim-input-feedback ${style}`.trim();
}
function setBusy(channel, value) {
if (value) busy.add(channel); else busy.delete(channel);
document.querySelectorAll(`[data-channel="${channel}"] button`).forEach((button) => { button.disabled = value; });
document.getElementById(`in-${channel}`).disabled = value;
}
async function sendWeight(channel, body) {
if (!CHANNELS[channel] || busy.has(channel) || scenarioBusy) return;
const liveEsp32 = scales?.[channel]?.source === 'esp32' && scales[channel].online;
setBusy(channel, true);
feedback(channel, T('กำลังส่งค่า…', 'Sending…'), 'pending');
try {
const result = await act('/api/sim', { channel, ...body });
if (!result) { feedback(channel, T('ส่งค่าไม่สำเร็จ ลองอีกครั้ง', "Couldn't send. Try again."), 'error'); return; }
document.getElementById(`in-${channel}`).value = '';
feedback(channel, T(`ตั้งเป็น ${num(result.value_g, 1)} ก. แล้ว รอให้นิ่งก่อนบันทึก${liveEsp32 ? ' (ESP32 ยังส่งค่าอยู่ อาจทับค่านี้)' : ''}`, `Set to ${num(result.value_g, 1)} g. Wait for it to settle.${liveEsp32 ? ' The ESP32 is still sending and may override this.' : ''}`));
} finally {
setBusy(channel, false);
}
}
document.body.addEventListener('click', async (event) => {
const quick = event.target.closest('button[data-ch]');
if (quick) {
const channel = quick.dataset.ch;
const item = QUICK[channel]?.[Number(quick.dataset.i)];
if (item) await sendWeight(channel, item[1]);
return;
}
const scenario = event.target.closest('button[data-scenario]');
if (scenario) await runScenario(scenario.dataset.scenario);
});
document.body.addEventListener('submit', async (event) => {
const form = event.target.closest('form[data-set-form]');
if (!form) return;
event.preventDefault();
const channel = form.dataset.setForm;
const input = document.getElementById(`in-${channel}`);
const raw = input.value.trim();
const value = Number(raw);
if (raw === '' || !Number.isFinite(value) || value < 0 || !input.validity.valid) {
input.setAttribute('aria-invalid', 'true');
feedback(channel, T('กรอกน้ำหนักตั้งแต่ 0 กรัมขึ้นไป', 'Enter 0 g or more'), 'error');
input.focus();
return;
}
input.removeAttribute('aria-invalid');
await sendWeight(channel, { value_g: value });
});
document.body.addEventListener('input', (event) => {
if (!event.target.matches('input[id^="in-"]')) return;
event.target.removeAttribute('aria-invalid');
const channel = event.target.id.slice(3);
if (!busy.has(channel)) feedback(channel, '');
});
function scenarioFeedback(message, error = false) {
const el = document.getElementById('scenario-feedback');
el.textContent = message;
el.classList.toggle('error', error);
}
// Fill the return bins relative to their starting weights for the open meal. With five sorted bins the side dish
// is shared out the way children tend to leave it: mostly vegetables when a lot comes back.
const DISH_SHARE = { high: { veg: 0.7, protein: 0.22, fat: 0.08 }, normal: { veg: 0.55, protein: 0.35, fat: 0.1 } };
const BONE_SHARE = 0.03; // simulated bones and inedible bits, as a share of the main dish served
async function runScenario(kind) {
const current = state?.current;
const rates = { high: [15, 28], normal: [13, 14] }[kind];
const bins = shown.filter((c) => c !== 'kitchen');
if (!rates || scenarioBusy || bins.some((c) => busy.has(c))) return;
if (current?.meal?.status !== 'open' || !(current.metrics?.served_g > 0)) {
scenarioFeedback(T('เริ่มมื้อและชั่งหม้อก่อน', 'Start a meal and weigh a pot first'), true);
return;
}
const [ricePct, dishPct] = rates;
const riceWaste = (current.metrics.rice_served_g * ricePct) / 100;
const dishWaste = (current.metrics.dish_served_g * dishPct) / 100;
const sorted = current.sorted_bins ?? {};
const targets = bins.length === 5
? Object.fromEntries(FIVE_BINS.map((k) => [k, (sorted[k]?.start_g ?? 0)
+ (k === 'starch' ? riceWaste : k === 'bone' ? current.metrics.dish_served_g * BONE_SHARE : dishWaste * DISH_SHARE[kind][k])]))
: { rice: (current.meal.return_rice_start ?? 0) + riceWaste, dish: (current.meal.return_dish_start ?? 0) + dishWaste };
scenarioBusy = true;
renderScenarios();
bins.forEach((c) => setBusy(c, true));
scenarioFeedback(T('กำลังตั้งน้ำหนักถังเศษ…', 'Setting the bins…'));
try {
for (const [channel, value] of Object.entries(targets)) {
if (!await act('/api/sim', { channel, value_g: value })) { scenarioFeedback(T(`ตั้ง${CHANNELS[channel].title}ไม่สำเร็จ`, `Couldn't set the ${CHANNELS[channel].title}`), true); return; }
}
scenarioFeedback(T(`ตั้งแล้ว ข้าวเหลือ ${ricePct}% กับข้าวเหลือ ${dishPct}% รอให้นิ่งก่อนจบมื้อ`, `Done. Rice ${ricePct}% left, main dish ${dishPct}% left. Wait before ending the meal.`));
} finally {
scenarioBusy = false;
bins.forEach((c) => setBusy(c, false));
renderScenarios();
}
}
function renderScenarios() {
const current = state?.current;
const open = current?.meal?.status === 'open' && current.metrics?.served_g > 0;
document.getElementById('scenario-note').textContent = open
? T(`ตักไปแล้ว ${kg(current.metrics.served_g)} กก. เลือกว่าจะให้เหลือแบบไหน`, `${kg(current.metrics.served_g)} kg served. Choose how much comes back.`)
: T('เริ่มมื้อและชั่งหม้อในหน้าครัวก่อน', 'Start a meal and weigh a pot on the kitchen screen first');
document.getElementById('scenarios').innerHTML = `
<button class="btn" type="button" data-scenario="high" ${open && !scenarioBusy ? '' : 'disabled'}><span>${T("เหลือเยอะ", "High leftovers")}<small>${T("ข้าว 15% กับข้าว 28%", "Rice 15%, main dish 28%")}</small></span></button>
<button class="btn" type="button" data-scenario="normal" ${open && !scenarioBusy ? '' : 'disabled'}><span>${T("เหลือปกติ", "Normal leftovers")}<small>${T("ข้าว 13% กับข้าว 14%", "Rice 13%, main dish 14%")}</small></span></button>`;
}
function refreshState(version) {
if (stateLoading || (state && stateVersion === version) || (stateVersion === version && Date.now() - lastStateAttempt < 5000)) return;
stateVersion = version;
lastStateAttempt = Date.now();
stateLoading = true;
api('/api/state').then((next) => {
state = next;
if (['kitchen', ...binsInUse()].join() !== shown.join()) renderGrid();
renderScenarios();
}).catch(() => {
document.getElementById('scenario-note').textContent = T('โหลดไม่สำเร็จ กำลังลองใหม่…', 'Loading failed, retrying…');
}).finally(() => { stateLoading = false; });
}
renderScenarios();
live((tick) => {
if (!tick?.scales) return;
scales = tick.scales;
voiceState = tick.voice;
renderVoice();
refreshState(tick.version);
for (const channel of shown) {
const reading = scales[channel];
if (!reading || !document.getElementById(`val-${channel}`)) continue;
document.getElementById(`val-${channel}`).innerHTML = `${reading.online ? num(reading.raw, 1) : '—'}<span class="unit">${T('ก.', 'g')}</span>`;
const source = document.getElementById(`src-${channel}`);
source.textContent = reading.source === 'esp32' ? 'ESP32' : 'SIM';
source.className = `chip ${!reading.online ? 'crit' : reading.source === 'esp32' ? 'good' : 'warn'}`;
const stability = document.getElementById(`stable-${channel}`);
stability.textContent = !reading.online ? T('ไม่มีสัญญาณ', 'No signal') : reading.stable ? T('นิ่งแล้ว', 'Steady') : T('รอให้นิ่ง', 'Settling');
stability.className = `sim-stability ${!reading.online ? 'crit' : reading.stable ? '' : 'warn'}`;
document.getElementById(`source-hint-${channel}`).textContent = !reading.online
? T('เครื่องไม่มีสัญญาณ กดปุ่มด้านล่างเพื่อใช้ค่าจำลองแทน', 'No signal. Tap a button below to simulate instead.')
: reading.source === 'esp32'
? T('เครื่องจริงกำลังส่งค่า ถ้ากดค่าจำลอง ESP32 อาจทับค่าทันที', 'The real scale is sending. It may override simulated values.')
: T('กำลังใช้ค่าจำลอง รอให้นิ่งก่อนบันทึก', 'Using simulated values. Wait for them to settle.');
}
});
|