Spaces:
Running
Running
Download js/kitchen.js from eatbackhackathon2026/eatback: direct link, hf CLI and curl.
- Browser
- Download file 57.2 kB
-
https://huggingface.co/spaces/eatbackhackathon2026/eatback/resolve/main/js/kitchen.js
- Command line
-
hf download hf://spaces/eatbackhackathon2026/eatback/js/kitchen.js
-
curl -L -o kitchen.js https://huggingface.co/spaces/eatbackhackathon2026/eatback/resolve/main/js/kitchen.js
57.2 kB
| // Kitchen phone screen: pick the grade, start its round, weigh pots (scale or typed in), measure curry ladles, | |
| // record the kids' opinions on cause-finding rounds, weigh the five return bins (or type them in from any scale), | |
| // end the round, and read the recipe scaled to the head count. A two-bin school sorts a cause-finding round's | |
| // leftovers into 4 compartments instead. | |
| import { api, live, esc, toast, act, LOGO, WORDMARK, scaleQty, portionsFor, signIn, isAdmin, roleChip } from './core.js'; | |
| import { | |
| T, onLang, langToggle, num, kg, pct, menuName, group, groupIcon, GROUP_ORDER, gradeName, gradeShort, | |
| unitLabel, ingredientName, recipeSteps, recipeTips, fruitName, reason, REASON_ORDER, REASON_ICON, | |
| FIVE_BINS, returnBins, binName, binIcon, | |
| } from './i18n.js'; | |
| await signIn('kitchen'); | |
| const $app = document.getElementById('app'); | |
| const $ = (id) => document.getElementById(id); | |
| const POINT = { start: ['ตอนเริ่มตัก', 'Start'], middle: ['กลางรอบ', 'Middle'], end: ['ตอนท้าย', 'End'] }; | |
| const store = { | |
| get: (k, d) => { try { return localStorage.getItem(k) ?? d; } catch { return d; } }, | |
| set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* ignore */ } }, | |
| }; | |
| const urlGrade = new URLSearchParams(location.search).get('grade'); | |
| const form = { grade: urlGrade || store.get('eatback.kitchenGrade', null), menu: null, students: null, absence: false, event: false, audit: {}, weight: '', rice: '', dish: '', bins: {} }; | |
| let S = null; | |
| let menus = []; | |
| let recipe = { id: null, data: null }; | |
| let scales = null; | |
| let version = -1; | |
| let tab = 'meal'; | |
| let pot = 'dish'; | |
| let mode = store.get('eatback.inputMode', 'scale') === 'manual' ? 'manual' : 'scale'; | |
| let lastLiveAt = 0; | |
| let busy = false; | |
| // Round stages the cook opened or closed by hand, so a live refresh keeps them that way ("meal id:stage" -> open). | |
| const stageOpen = {}; | |
| const fresh = () => lastLiveAt > 0 && Date.now() - lastLiveAt < 3000; | |
| const ch = (k) => scales?.[k] ?? S?.scales?.[k] ?? null; | |
| const validCount = (v) => String(v ?? '').trim() !== '' && Number.isSafeInteger(Number(v)) && Number(v) > 0; | |
| const kgValue = (v) => { const n = Number(String(v ?? '').replace(',', '.').trim()); return String(v ?? '').trim() !== '' && Number.isFinite(n) && n >= 0 ? n : null; }; | |
| const potName = (k) => (k === 'rice' ? T('ข้าว', 'Rice') : T('กับข้าว', 'Main dish')); | |
| const food = (m, size = 'md') => `<div class="food ${size} c${(Number(String(m?.id ?? '').replace(/\D/g, '')) % 4) + 1}" aria-hidden="true">${esc(m?.icon || '🍽️')}</div>`; | |
| const inProgress = (k = pot) => S?.current?.pots.find((p) => p.pot === k && p.after_g == null); | |
| // Cause-finding round still open: the kids' opinions (and, with two bins, the 4-compartment sort) are recorded in it. | |
| const asking = () => { const c = S?.current; return c && c.meal.status === 'open' && c.meal.investigation ? c : null; }; | |
| const roundOf = (g) => S?.rounds_today?.find((r) => r.grade === g)?.meal ?? null; | |
| const manualBins = () => mode === 'manual' || !!S?.current?.meal.bins_manual; | |
| // The school's return station has the five sorted bins (the setting cannot change while a round is open). They show | |
| // what came back by food group in every round, so only a two-bin school sorts a cause-finding round on the tray. | |
| const fiveBins = () => returnBins(S?.settings).length === 5; | |
| const needsTray = (c) => !!c?.meal.investigation && !fiveBins(); | |
| // The return-station bins in use: an open round keeps the layout it started with, otherwise the school's setting. | |
| const sortedRound = () => S?.current?.meal.status === 'open' && Object.keys(S.current.sorted_bins ?? {}).length > 0; | |
| const roundBins = () => (S?.current?.meal.status === 'open' ? (sortedRound() ? FIVE_BINS : ['rice', 'dish']) : returnBins(S?.settings)); | |
| const binStart = (k) => (sortedRound() ? S.current.sorted_bins[k]?.start_g : S?.current?.meal[`return_${k}_start`]) ?? 0; | |
| const availablePlans = () => [S?.current?.meal, S?.next].filter((m) => m?.status === 'planned' && (m.origin !== 'weekly' || m.date === S.today)); | |
| function setText(id, v) { const el = $(id); if (el && el.textContent !== v) el.textContent = v; } | |
| function setHint(id, text, tone = '') { | |
| const el = $(id); | |
| if (!el) return; | |
| const cls = `hint${tone ? ` ${tone}` : ''}`; | |
| if (el.textContent !== text) el.textContent = text; | |
| if (el.className !== cls) el.className = cls; | |
| } | |
| // Scales not checked (or failed) this morning: the round is still recorded, but a trial round won't count toward a fix. | |
| function qcHint(trial) { | |
| if (S.qc?.all_ok) return ''; | |
| const link = `<a href="/#/qc" target="_blank" rel="noopener">${T('ไปตรวจเครื่องชั่ง', 'Check the scales')} ↗</a>`; | |
| return trial | |
| ? `<div class="hint crit">${T('เช้านี้ยังตรวจเครื่องชั่งไม่ผ่านครบ รอบทดลองนี้จะไม่ถูกนับในการยืนยันผลแก้เมนู ควรตรวจก่อนเริ่มรอบ', "The scales haven't passed this morning's check. This trial round won't count toward confirming the fix. Check them before starting.")} ${link}</div>` | |
| : `<div class="hint warn">${T('เช้านี้ยังตรวจเครื่องชั่งไม่ผ่านครบ ตัวเลขวันนี้อาจคลาดเคลื่อน', "The scales haven't passed this morning's check, so today's numbers may be off.")} ${link}</div>`; | |
| } | |
| function binsIssue() { | |
| if (!fresh()) return [T('กำลังเชื่อมต่อเครื่องชั่ง', 'Connecting to the scales'), 'warn']; | |
| const bins = roundBins(); | |
| const off = bins.filter((k) => !ch(k)?.online); | |
| if (off.length) return [T(`${off.map(binName).join(' · ')} ไม่มีสัญญาณ ถ้าไม่มีเครื่องชั่ง กด “พิมพ์เอง” ด้านบน`, `No signal from: ${off.map(binName).join(' · ')}. No scales? Tap “Type it in” above.`), 'crit']; | |
| if (bins.some((k) => !ch(k)?.stable)) return [T('รอให้ถังเศษนิ่งสักครู่', 'Waiting for the bins to settle'), 'warn']; | |
| return null; | |
| } | |
| // ---------------------------------------------------------------- data | |
| function pickGrade(s) { | |
| const grades = s.settings.grades; | |
| if (form.grade && grades.includes(form.grade)) return form.grade; | |
| const next = s.rounds_today.find((r) => !r.meal || r.meal.status !== 'closed'); | |
| return next?.grade ?? grades[0]; | |
| } | |
| async function refresh() { | |
| try { | |
| let state = await api(`/api/state${form.grade ? `?grade=${encodeURIComponent(form.grade)}` : '?grade=all'}`).catch(() => api('/api/state?grade=all')); | |
| const g = state.open_round?.grade ?? pickGrade(state); | |
| if (g !== state.grade) state = await api(`/api/state?grade=${encodeURIComponent(g)}`); | |
| if (form.grade !== g) { form.grade = g; form.menu = null; form.students = null; } | |
| store.set('eatback.kitchenGrade', g); | |
| S = state; | |
| if (!menus.length) menus = (await api('/api/menus')).menus; | |
| if (!$('body')) shell(); | |
| renderBody(); | |
| } catch (e) { | |
| $app.innerHTML = `<div class="kc"><h2>${T('โหลดไม่สำเร็จ', "Couldn't load")}</h2><p class="sub">${esc(e.message)}</p><button class="btn primary big-btn" id="retry">${T('ลองใหม่', 'Try again')}</button></div>`; | |
| $('retry').addEventListener('click', refresh); | |
| } | |
| } | |
| async function loadRecipe(id) { | |
| if (!id || recipe.id === id) return; | |
| recipe = { id, data: null }; | |
| try { recipe.data = await api(`/api/menu?id=${encodeURIComponent(id)}`); } catch { recipe.data = null; } | |
| if (tab === 'recipe') renderBody(); | |
| } | |
| live((t) => { | |
| scales = t.scales; | |
| lastLiveAt = Date.now(); | |
| if (t.version !== version) { version = t.version; menus = []; recipe.id = null; refresh(); } | |
| tick(); | |
| }); | |
| setInterval(tick, 1000); | |
| onLang(() => { if (S) { shell(); renderBody(); } }); | |
| // ---------------------------------------------------------------- layout | |
| function shell() { | |
| document.title = `EatBack · ${T('หน้าครัว', 'Kitchen')}`; | |
| $app.innerHTML = ` | |
| <header class="k-top">${LOGO}<div style="flex:1 1 170px;min-width:0"><h1>${WORDMARK} <span class="k-title">${T('หน้าครัว', 'Kitchen')}</span></h1><div class="school">${esc(S.settings.school_name)}</div></div><div class="who">${roleChip()}${langToggle()}</div></header> | |
| <div class="mode" role="radiogroup" aria-label="${T('วิธีใส่น้ำหนัก', 'How weights are entered')}"> | |
| <button role="radio" data-mode="scale" aria-checked="${mode === 'scale'}">⚖️ ${T('เครื่องชั่ง', 'Scale')}<small>${T('อ่านค่าอัตโนมัติ', 'Reads automatically')}</small></button> | |
| <button role="radio" data-mode="manual" aria-checked="${mode === 'manual'}">✍️ ${T('พิมพ์เอง', 'Type it in')}<small>${T('ใช้ตาชั่งอะไรก็ได้', 'Any scale works')}</small></button> | |
| </div> | |
| <div class="k-badges" id="k-badges">${badges()}</div> | |
| <section class="scale-card" aria-live="polite" ${mode === 'manual' ? 'hidden' : ''}> | |
| <div class="lbl"><span id="s-label"></span></div> | |
| <div class="w"><span id="s-val">—</span><small>${T('กก.', 'kg')}</small></div> | |
| <div class="st"><span class="dot" id="s-dot"></span><span id="s-state"></span><span id="s-src"></span></div> | |
| </section> | |
| <div class="seg" role="tablist"> | |
| <button role="tab" data-tab="meal" class="${tab === 'meal' ? 'on' : ''}" aria-selected="${tab === 'meal'}">🍽️ ${T('รอบกิน', 'Rounds')}</button> | |
| <button role="tab" data-tab="recipe" class="${tab === 'recipe' ? 'on' : ''}" aria-selected="${tab === 'recipe'}">📖 ${T('สูตร', 'Recipe')}</button> | |
| </div> | |
| <div id="body"></div> | |
| <p class="small muted" style="text-align:center;margin-top:18px">${isAdmin() | |
| ? `<a href="/#/today?g=${esc(form.grade ?? 'all')}" target="_blank" rel="noopener">${T('เปิดหน้าภาพรวม', 'Open the dashboard')} ↗</a>` | |
| : `<a href="/#/qc" target="_blank" rel="noopener">${T('ตรวจเครื่องชั่งเช้านี้', "This morning's scale check")} ↗</a> · <a href="/planner.html" target="_blank" rel="noopener">${T('ใบสั่งซื้อประจำสัปดาห์', "This week's purchase order")} ↗</a>`}</p>`; | |
| } | |
| // What the numbers on this screen are: demo or real data, which scale, and whether this morning's check passed. | |
| // A steady reading can be saved either way; a round only counts once the check has passed. | |
| function badges() { | |
| const k = ch('kitchen'); | |
| const live = fresh() && k?.online; | |
| const data = S.data_mode === 'real' ? `<span class="chip crit">${T('ข้อมูลจริง', 'Real data')}</span>` : `<span class="chip">${T('ข้อมูลเดโม', 'Demo data')}</span>`; | |
| const scale = mode === 'manual' ? `<span class="chip">✍️ ${T('ตาชั่งธรรมดา พิมพ์เอง', 'Any scale, typed in')}</span>` | |
| : !live ? `<span class="chip warn">⚖️ ${T('ยังไม่มีสัญญาณเครื่องชั่ง', 'No scale signal yet')}</span>` | |
| : k.source === 'esp32' ? `<span class="chip good">⚖️ ${T('เครื่องชั่ง IoT', 'IoT scale')}</span>` | |
| : `<span class="chip warn">⚖️ ${T('ค่าจำลอง ยังไม่ได้ต่อเครื่องชั่ง', 'Simulated, no scale connected')}</span>`; | |
| const qc = S.qc?.all_ok ? `<span class="chip good">${T('ตรวจเครื่องชั่งเช้านี้แล้ว', 'Scales checked this morning')}</span>` | |
| : `<span class="chip warn">${T('ยังไม่ตรวจเครื่องชั่งเช้านี้ รอบจะไม่ถูกนับ', "Scales not checked: rounds won't count")}</span>`; | |
| return `${data}${scale}${qc}`; | |
| } | |
| function renderBody() { | |
| const open = S.current?.meal.status === 'open'; | |
| const html = tab === 'recipe' ? recipeView() : open ? openView(S.current) : startView(); | |
| const focus = document.activeElement?.id; | |
| $('body').innerHTML = html; | |
| if (focus && $(focus) && /^(f-|a-|b-|m-)/.test(focus)) $(focus).focus(); | |
| tick(); | |
| } | |
| // ---------------------------------------------------------------- start a round | |
| function gradePicker() { | |
| return `<div class="grades" role="radiogroup" aria-label="${T('เลือกชั้น', 'Choose the grade')}">${S.settings.grades.map((g) => { | |
| const m = roundOf(g); | |
| const st = !m ? '' : m.status === 'closed' ? `✓ ${T('กินแล้ว', 'done')}` : m.status === 'open' ? `● ${T('กำลังกิน', 'eating')}` : m.investigation ? T('ข้อคิดเห็น', 'opinions') : ''; | |
| return `<button role="radio" data-grade="${g}" aria-checked="${form.grade === g}" class="${m?.status === 'closed' ? 'done' : ''}"><b>${gradeShort(g)}</b><small>${st || `${num(S.settings.grade_students[g])} ${T('คน', '')}`}</small></button>`; | |
| }).join('')}</div>`; | |
| } | |
| function startView() { | |
| const c = S.current; | |
| const g = form.grade; | |
| const planned = availablePlans(); | |
| const dayMenu = S.rounds_today.map((r) => r.meal?.menu_id).find(Boolean); | |
| form.menu ??= planned[0]?.menu_id ?? dayMenu ?? menus[0]?.id; | |
| form.students ??= planned.find((x) => x.menu_id === form.menu)?.students ?? S.settings.grade_students[g] ?? ''; | |
| const plannedIds = new Set(planned.map((m) => m.menu_id)); | |
| const m = menus.find((x) => x.id === form.menu); | |
| const plan = planned.find((x) => x.menu_id === form.menu); | |
| const willAsk = c?.meal.status === 'planned' && c.will_investigate && c.meal.menu_id === form.menu; | |
| const done = c?.meal.status === 'closed' && c.meal.origin !== 'seed' && c.meal.date === S.today; | |
| const nextGrade = S.rounds_today.find((r) => r.grade !== g && (!r.meal || r.meal.status === 'planned'))?.grade; | |
| const last = done ? ` | |
| <section class="kc"> | |
| <div class="row">${food(c.menu, 'sm')}<div style="flex:1"><b>${esc(menuName(c.menu))}</b><div class="small muted">${gradeName(g)} · ${T('จบรอบแล้ว', 'Round finished')}</div></div></div> | |
| <div class="two"><div><small>${T('ตักเสิร์ฟ', 'Served')}</small><span class="v">${kg(c.metrics.served_g)}</span> ${T('กก.', 'kg')}</div><div><small>${T('เหลือกลับมา', 'Came back')}</small><span class="v">${kg(c.metrics.waste_g)}</span> ${T('กก.', 'kg')}</div></div> | |
| <fieldset><legend>${T('วันนี้มีอะไรผิดปกติไหม', 'Anything unusual today?')}</legend> | |
| <label class="check-line"><input type="checkbox" id="c-absence" ${c.meal.context_absence ? 'checked' : ''}> ${T('นักเรียนขาดเยอะผิดปกติ', 'Many students absent')}</label> | |
| <label class="check-line"><input type="checkbox" id="c-event" ${c.meal.context_event ? 'checked' : ''}> ${T('มีกิจกรรมพิเศษ', 'Special event')}</label></fieldset> | |
| ${c.audit?.source === 'bins' ? `<div class="hint ${c.audit.top ? 'warn' : 'good'}">${c.audit.top ? T(`5 ถัง: ${group(c.audit.top.key)}เหลือ ${Math.round(c.audit.top.rate)}% ของที่ตั้งใจเสิร์ฟ`, `5 bins: ${Math.round(c.audit.top.rate)}% of the ${group(c.audit.top.key).toLowerCase()} came back`) : T('5 ถัง: ไม่มีกลุ่มอาหารไหนเหลือเด่น', '5 bins: no food group stands out')}</div>` | |
| : c.audit ? `<div class="hint good">${T('บันทึกการแยกเศษ 4 ช่องแล้ว', '4-compartment sort recorded')}</div>` : ''} | |
| ${nextGrade ? `<button class="btn big-btn" data-grade="${nextGrade}">${T(`เริ่มรอบถัดไป: ${gradeName(nextGrade)}`, `Next round: ${gradeName(nextGrade)}`)} →</button>` : ''} | |
| </section>` : ''; | |
| const opts = menus.map((x) => `<option value="${x.id}"${x.id === form.menu ? ' selected' : ''}>${plannedIds.has(x.id) ? '★ ' : ''}${esc(menuName(x))}</option>`).join(''); | |
| return `${last} | |
| <section class="kc"> | |
| <h2>${T('เริ่มรอบกิน', 'Start a round')}</h2> | |
| <p class="sub">${T('แต่ละชั้นกินแยกรอบ เลือกชั้นที่กำลังจะมากิน', 'Each grade eats in its own round. Pick the grade coming in now.')}</p> | |
| ${gradePicker()} | |
| <div class="menu-pick">${food(m, 'md')}<div><b>${esc(menuName(m))}</b><span class="small muted">${plan ? (plan.origin === 'trial' ? T(`มื้อทดลองของ ${gradeShort(g)}`, `Trial meal for ${gradeShort(g)}`) : T('ตามแผนวันนี้', "Today's plan")) : T('ไม่ได้อยู่ในแผน', 'Not in the plan')}</span></div> | |
| <button class="btn sm" data-tab="recipe" style="margin-left:auto">📖 ${T('สูตร', 'Recipe')}</button></div> | |
| <label class="field">${T('เมนู', 'Menu')}<select id="f-menu">${opts}</select></label> | |
| ${willAsk ? `<div class="hint crit">${T(`รอบนี้เก็บข้อคิดเห็นจากเด็ก: ${gradeShort(g)} เหลือเมนูนี้เยอะ 3 ครั้งติด ครูถามเด็กแล้วกดข้อคิดเห็นในแอป ${fiveBins() ? 'ส่วนเหลืออะไรดูจาก 5 ถังได้เลย ไม่ต้องแยกถาดเพิ่ม' : 'และก่อนชั่งเศษให้แยกเศษ 4 ช่อง'}`, `This round collects the kids' opinions: ${gradeShort(g)} left a lot of this menu three times in a row. A teacher asks the kids and taps their answers in the app${fiveBins() ? '; the 5 bins already show what came back' : ', and the leftovers are sorted into 4 compartments before weighing'}.`)}</div>` : ''} | |
| ${m?.has_broth ? `<div class="hint">${T('เมนูแกง ระหว่างตักต้องวัดทัพพี 2 ครั้ง', 'Curry menu: measure a ladle twice while serving.')}</div>` : ''} | |
| <label class="field">${T(`นักเรียน ${gradeShort(g)} ที่มากิน`, `${gradeShort(g)} students eating`)}<input id="f-students" type="number" inputmode="numeric" min="1" step="1" value="${esc(form.students)}"></label> | |
| <p class="small muted" style="margin-top:6px">${T(`ชั้นนี้ตักคนละ ${Math.round((S.settings.grade_portion[g] ?? 1) * 100)}% ของปริมาณเต็ม (ค่าที่ตั้งไว้ ยังไม่ใช่เกณฑ์โภชนาการที่ยืนยันแล้ว)`, `Configured portion: ${Math.round((S.settings.grade_portion[g] ?? 1) * 100)}% of a full portion (a setting, not a verified nutrition standard)`)}</p> | |
| <fieldset><legend>${T('วันนี้มีอะไรผิดปกติไหม', 'Anything unusual today?')}</legend> | |
| <label class="check-line"><input type="checkbox" id="f-absence" ${form.absence ? 'checked' : ''}> ${T('นักเรียนขาดเยอะผิดปกติ', 'Many students absent')}</label> | |
| <label class="check-line"><input type="checkbox" id="f-event" ${form.event ? 'checked' : ''}> ${T('มีกิจกรรมพิเศษ', 'Special event')}</label> | |
| <div class="small muted">${T('ถ้าติ๊ก รอบนี้จะไม่ถูกนำไปเทียบ', "If ticked, this round isn't used for comparisons.")}</div></fieldset> | |
| ${qcHint(plan?.origin === 'trial')} | |
| <div class="hint" id="open-hint"></div> | |
| <button class="btn primary big-btn" data-do="open">${T(`เริ่มรอบ ${gradeShort(g)}`, `Start ${gradeShort(g)}`)}</button> | |
| </section>`; | |
| } | |
| // ---------------------------------------------------------------- round in progress | |
| function openView(c) { | |
| const active = inProgress(); | |
| const other = inProgress(pot === 'rice' ? 'dish' : 'rice'); | |
| const manual = mode === 'manual'; | |
| const potList = c.pots.length ? c.pots.map((p) => `<div class="pot"><div><b style="font-family:var(--font)">${potName(p.pot)} ${T('หม้อ', 'pot')} ${p.n}${p.manual ? ` <span class="chip">${T('พิมพ์เอง', 'typed')}</span>` : ''}</b><small>${kg(p.before_g)} → ${p.after_g == null ? T('รอชั่งหลังตัก', 'waiting') : kg(p.after_g)} ${T('กก.', 'kg')}</small></div><b>${p.served_g == null ? '…' : `${kg(p.served_g)} ${T('กก.', 'kg')}`}</b></div>`).join('') : `<p class="sub">${T('ยังไม่ได้ชั่ง', 'Nothing weighed yet')}</p>`; | |
| const manualBox = (label) => `<label class="field big-input">${label}<span class="unit-wrap"><input id="m-weight" type="text" inputmode="decimal" autocomplete="off" placeholder="0.00" value="${esc(form.weight)}"><span>${T('กก.', 'kg')}</span></span></label>`; | |
| const step = active | |
| ? `<div class="step"><span class="n">2</span><div><b>${T('ตักเสร็จแล้ว ชั่งหม้อใบเดิมอีกครั้ง', 'Done serving? Weigh the same pot again')}</b><div class="sub">${manual ? T(`ก่อนตักหนัก ${kg(active.before_g)} กก.`, `It weighed ${kg(active.before_g)} kg before`) : `${T('ตักไปแล้วประมาณ', 'Served so far about')} <b id="pour">—</b> ${T('กก.', 'kg')}`}</div></div></div> | |
| ${manual ? `${manualBox(T('น้ำหนักหม้อหลังตัก', 'Pot weight after serving'))}<button class="btn primary big-btn" data-do="after">${T('บันทึกหลังตัก', 'Save after serving')}</button>` | |
| : `<button class="btn primary big-btn" data-do="after" data-stable>${T('ชั่งหลังตัก', 'Weigh after serving')}</button>`}` | |
| : `<div class="step"><span class="n">1</span><div><b>${T(`วางหม้อ${potName(pot)}ที่ทำเสร็จบนตาชั่ง`, `Put the ${potName(pot).toLowerCase()} pot on the scale`)}</b><div class="sub">${manual ? T('อ่านตัวเลขบนตาชั่งแล้วพิมพ์ลงช่อง', 'Read the scale and type the number') : T('รอให้ตัวเลขนิ่งแล้วกด', 'Wait for the number to settle, then tap')}</div></div></div> | |
| ${manual ? `${manualBox(T('น้ำหนักหม้อก่อนตัก', 'Pot weight before serving'))}<button class="btn primary big-btn" data-do="before">${T('บันทึกก่อนตัก', 'Save before serving')}</button>` | |
| : `<button class="btn primary big-btn" data-do="before" data-stable>${T('ชั่งก่อนตัก', 'Weigh before serving')}</button>`}`; | |
| const brothPoints = c.broth_required >= 3 ? ['start', 'middle', 'end'] : ['start', 'end']; | |
| const byPoint = Object.fromEntries(c.broth.samples.map((s) => [s.point, s])); | |
| const broth = c.menu.has_broth ? `<section class="kc"> | |
| <h2>${T('เมนูแกง: วัดทัพพี', 'Curry: measure a ladle')}</h2> | |
| <p class="sub">${T('ตักแกง 1 ทัพพี ชั่งทั้งหมด แล้วกรองน้ำออกชั่งเนื้ออีกครั้ง ใช้เครื่องชั่งครัวธรรมดาได้', 'Weigh one full ladle, strain it, then weigh the solids. Any kitchen scale works.')}</p> | |
| ${brothPoints.map((p) => `<div class="ladle"><div class="name">${T(...POINT[p])}${byPoint[p] ? ` <span class="chip good">✓ ${T('เนื้อ', 'solids')} ${Math.round((byPoint[p].solid_g / byPoint[p].ladle_g) * 100)}%</span>` : ''}</div> | |
| <label class="field">${T('ทั้งทัพพี (กรัม)', 'Full ladle (g)')}<input type="number" id="b-${p}-l" inputmode="numeric" min="1" value="${byPoint[p]?.ladle_g ?? ''}"></label> | |
| <label class="field">${T('เนื้อ (กรัม)', 'Solids (g)')}<input type="number" id="b-${p}-s" inputmode="numeric" min="0" value="${byPoint[p]?.solid_g ?? ''}"></label> | |
| <button class="btn" data-do="broth" data-point="${p}">${T('บันทึก', 'Save')}</button></div>`).join('')} | |
| </section>` : ''; | |
| const five = returnBins(S.settings).length === 5; | |
| const liveBins = roundBins(); | |
| const kgBox = (id, label, value) => `<label class="field">${label}<span class="unit-wrap"><input id="${id}" type="text" inputmode="decimal" autocomplete="off" placeholder="0.00" value="${esc(value ?? '')}"><span>${T('กก.', 'kg')}</span></span></label>`; | |
| const bins = manualBins() | |
| ? `<section class="kc"><h2>${T('ของเหลือที่จุดคืนจาน', 'Leftovers at the return station')}</h2> | |
| <p class="sub">${five | |
| ? T('เด็กเทน้ำแกงผ่านตะแกรง แล้วแยกลง 5 ถังตามรูป ผลไม้และเปลือกผลไม้ทิ้งถังขยะทั่วไป · พอจบรอบ ชั่งทีละถังด้วยตาชั่งอะไรก็ได้ หักน้ำหนักถังเปล่า แล้วพิมพ์ครบ 5 ช่อง (ถังว่างพิมพ์ 0)', 'Children pour curry liquid through the strainer, then sort into the 5 bins by picture; fruit and fruit peel go in the general bin · When the round is over, weigh each bin on any scale, minus the empty bin, and type all 5 (an empty bin is 0).') | |
| : T('พอเด็กกินเสร็จ ชั่งถังเศษทั้งสองใบ หักน้ำหนักถังเปล่า แล้วพิมพ์ลงช่อง ถังกระดูกและเปลือกไม่ต้องชั่ง', 'When the round is over, weigh both leftover bins, minus the empty bin, and type them in. The bones & peels bin is not weighed.')}</p> | |
| <div class="two">${five ? FIVE_BINS.map((k) => kgBox(`m-bin-${k}`, `${binIcon(k)} ${binName(k)}`, form.bins[k])).join('') | |
| : `${kgBox('m-rice', `🍚 ${T('เศษข้าว', 'Rice leftovers')}`, form.rice)}${kgBox('m-dish', `🍲 ${T('เศษกับข้าว', 'Main-dish leftovers')}`, form.dish)}`}</div></section>` | |
| : `<section class="kc"><h2>${T('ของเหลือที่จุดคืนจาน', 'Leftovers at the return station')}</h2><p class="sub">${liveBins.length === 5 | |
| ? T('เด็กเทน้ำแกงผ่านตะแกรงก่อน แล้วแยกลง 5 ถังตามรูป: ข้าว แป้ง · ผัก · เนื้อ ไข่ · หนัง มัน · กระดูกและส่วนกินไม่ได้ ผลไม้และเปลือกผลไม้ทิ้งถังขยะทั่วไป นับเฉพาะที่เพิ่มขึ้นตั้งแต่เริ่มรอบ', 'Children pour curry liquid through the strainer first, then sort into the 5 bins by picture: rice & starch · vegetables · meat & eggs · skin & fat · bones & inedible. Fruit and fruit peel go in the general bin. Only what was added since the round started counts.') | |
| : T('นับเฉพาะที่เพิ่มขึ้นตั้งแต่เริ่มรอบ ถังกระดูกและเปลือกไม่ชั่ง', 'Only what was added since the round started. The bones & peels bin is not weighed.')}</p> | |
| <div class="${liveBins.length === 5 ? 'bins5' : 'two'}">${liveBins.map((k) => `<div><small>${binIcon(k)} ${binName(k)}</small><span class="v" id="bin-${k}">—</span> ${T('กก.', 'kg')}</div>`).join('')}</div></section>`; | |
| const servedAny = c.pots.some((p) => p.served_g != null); | |
| const served = (k) => c.pots.some((p) => p.pot === k && p.served_g != null); | |
| // Serving is done once every pot this menu needs has its after-weight (a one-dish menu has no separate rice pot). | |
| const phase = active || other || !served('dish') || (c.menu.category !== 'one_dish' && !served('rice')) ? 'serve' : 'back'; | |
| const asked = c.votes?.meals?.[0]?.total ?? 0; | |
| const stage = (key, n, th, en, note, body) => `<details class="stage${phase === key ? ' now' : ''}" data-stage="${c.meal.id}:${key}" ${(stageOpen[`${c.meal.id}:${key}`] ?? phase === key) ? 'open' : ''}> | |
| <summary><span class="stage-n">${n}</span><span class="stage-t">${T(th, en)}</span><small>${note}</small></summary>${body}</details>`; | |
| const serveStage = stage('serve', 1, 'ก่อนเสิร์ฟ: ชั่งหม้อก่อนและหลังตัก', 'Before serving: weigh each pot before and after', | |
| servedAny ? T(`ตักแล้ว ${kg(c.metrics.served_g)} กก.`, `${kg(c.metrics.served_g)} kg served`) : T('ยังไม่ได้ชั่ง', 'Nothing weighed yet'), ` | |
| <div class="seg" role="tablist" aria-label="${T('ชั่งอะไร', 'What are you weighing')}"> | |
| ${['rice', 'dish'].map((k) => `<button role="tab" data-pot="${k}" class="${pot === k ? 'on' : ''}" aria-selected="${pot === k}">${k === 'rice' ? '🍚' : '🍲'} ${potName(k)}<small>${inProgress(k) ? T('รอชั่งหลังตัก', 'Waiting for after') : served(k) ? T('ชั่งแล้ว', 'Weighed') : T('ยังไม่ชั่ง', 'Not weighed yet')}</small></button>`).join('')} | |
| </div> | |
| ${other ? `<div class="hint warn">${T(`หม้อ${potName(other.pot)}ยังไม่ได้ชั่งหลังตัก`, `The ${potName(other.pot).toLowerCase()} pot still needs its after-weight`)}</div>` : ''} | |
| <section class="kc">${step}</section> | |
| <section class="kc"><h2>${T('ชั่งแล้ว', 'Weighed')}</h2>${potList} | |
| <div class="two"><div><small>${T('ข้าวที่ตัก', 'Rice served')}</small><span class="v">${kg(c.metrics.rice_served_g)}</span> ${T('กก.', 'kg')}</div><div><small>${T('กับข้าวที่ตัก', 'Main dish served')}</small><span class="v">${kg(c.metrics.dish_served_g)}</span> ${T('กก.', 'kg')}</div></div> | |
| ${c.pots.length ? `<button class="btn ghost block" style="margin-top:10px" data-do="undo">↶ ${T('ย้อนรายการล่าสุด', 'Undo last')}</button>` : ''}</section> | |
| ${broth}`); | |
| const eatStage = c.meal.investigation | |
| ? stage('eat', 2, 'ระหว่างรับประทาน: ครูถามเด็ก', 'While eating: the teacher asks the children', | |
| T(`ครูเก็บคำตอบแล้ว ${num(asked)} จาก ${num(c.meal.students)} คน`, `${num(asked)} of ${num(c.meal.students)} answered`), ` | |
| <p class="sub" style="margin:8px 0">${T('ครูกดในหน้าครู ครัวไม่ต้องทำ ถ้าไม่มีครู ครัวกดแทนได้ที่นี่', "Teachers tap on the teacher page; the kitchen does nothing. With no teacher around, the kitchen can tap here.")} | |
| <a href="/opinions.html" target="_blank" rel="noopener">${T('เปิดหน้าครู', 'Teacher page')} ↗</a></p> | |
| ${opinionPanel(c)}`) | |
| : `<div class="stage-line"><span class="stage-n">2</span>${T('ระหว่างรับประทาน: เด็กกินตามปกติ รอบนี้ไม่ต้องถามเด็ก', "While eating: the children eat as usual; this round doesn't ask them")}</div>`; | |
| const backStage = stage('back', 3, 'หลังคืนจาน: เศษ แล้วจบรอบ', 'After the trays come back: leftovers, then end the round', | |
| needsTray(c) ? T('รอบนี้แยกเศษ 4 ช่องก่อนชั่ง', 'This round sorts the leftovers first') | |
| : five ? T('เด็กแยกลง 5 ถัง แล้วจบรอบ', 'Children sort into the 5 bins, then end the round') : T('ชั่งถังเศษแล้วจบรอบ', 'Weigh the bins, then end the round'), ` | |
| ${needsTray(c) ? sortSection(c) : ''} | |
| ${bins} | |
| <section class="kc"><h2>${T('จบรอบ', 'End the round')}</h2> | |
| <div class="hint" id="close-hint"></div> | |
| <button class="btn primary big-btn" data-do="close">${T(`จบรอบ ${gradeShort(c.meal.grade)}`, `End ${gradeShort(c.meal.grade)}`)}</button> | |
| <button class="btn ghost block" style="margin-top:8px" data-do="cancel">${T('ยกเลิกรอบนี้', 'Cancel this round')}</button></section>`); | |
| return ` | |
| <section class="kc"><div class="row">${food(c.menu)}<div style="flex:1;min-width:0"><b style="font-size:17px">${esc(menuName(c.menu))}</b><div class="small muted">${gradeName(c.meal.grade)} · ${T(`${num(c.meal.students)} คน`, `${num(c.meal.students)} students`)}</div></div><span class="chip brand">${T('กำลังเสิร์ฟ', 'Serving')}</span></div></section> | |
| ${c.meal.action_id ? qcHint(true) : ''} | |
| ${serveStage}${eatStage}${backStage}`; | |
| } | |
| // ---------------------------------------------------------------- recipe | |
| function recipeView() { | |
| const id = S.current?.meal.status === 'open' ? S.current.menu.id : form.menu ?? S.current?.menu.id; | |
| if (recipe.id !== id) { loadRecipe(id); return `<section class="kc"><p class="sub">${T('กำลังโหลดสูตร…', 'Loading the recipe…')}</p></section>`; } | |
| const D = recipe.data; | |
| if (!D) return `<section class="kc"><h2>${T('โหลดสูตรไม่สำเร็จ', "Couldn't load the recipe")}</h2></section>`; | |
| const m = D.menu; | |
| const r = D.recipe; | |
| const recipeLabel = (r?.data_origin || m.data_provenance?.recipe?.origin) === 'user' ? T('สูตรและปริมาณวัตถุดิบ: ผู้ใช้กรอก ยังไม่ตรวจสอบ', 'Recipe and ingredient amounts: user-entered, unverified') : T('สูตรและปริมาณวัตถุดิบตั้งต้น: ประมาณการ DEMO', 'Seed recipe and ingredient amounts: DEMO estimates'); | |
| const costLabel = m.data_provenance?.cost?.origin === 'user' ? T('ต้นทุน: ผู้ใช้กรอก ยังไม่ตรวจสอบ', 'Cost: user-entered, unverified') : T('ต้นทุนตั้งต้น: ประมาณการ DEMO', 'Seed cost: DEMO estimate'); | |
| const all = portionsFor(D.settings, 'all'); | |
| const one = portionsFor(D.settings, form.grade); | |
| const scaleFor = r ? all.portions / r.servings : 1; | |
| return ` | |
| <section class="kc"><div class="row">${food(m)}<div style="flex:1;min-width:0"><b style="font-size:17px">${esc(menuName(m))}</b><div class="small muted">${T(`ทั้งโรงเรียน ${num(all.students)} คน ใช้วัตถุดิบเท่ากับ ${num(all.portions)} ที่เต็ม`, `Whole school: ${num(all.students)} students = ${num(all.portions)} full portions`)}</div></div></div> | |
| ${r ? `<a class="btn big-btn" href="/recipe.html?menu=${m.id}&for=all" target="_blank" rel="noopener">🖨️ ${T('พิมพ์สูตรทั้งโรงเรียน', 'Print for the whole school')}</a>` : ''}</section> | |
| <section class="kc"><div class="hint warn" style="margin-top:0"><b>${T('ที่มาข้อมูล · ยังไม่ผ่านการตรวจสอบ', 'Data source · unverified')}</b><br>${recipeLabel} · ${costLabel}<br>${T('ตัวเลขพลังงานและคุณค่าทางโภชนาการยังไม่ผ่านการตรวจสอบจากแหล่งภายนอก สูตรตั้งต้นไม่ได้มาจาก Thai School Lunch ตรวจสูตรและปริมาณก่อนนำไปใช้จริง', 'Energy and nutrition values have not been externally verified. Seed recipes were not imported from Thai School Lunch. Review the recipe and quantities before real use.')}</div></section> | |
| ${r ? `<section class="kc"><h2>${T('วัตถุดิบประมาณการ (ทั้งโรงเรียน)', 'Estimated ingredients (whole school)')}</h2> | |
| <table class="recipe-ing"><tbody>${r.ingredients.map((i) => { const s = scaleQty(i.qty, i.unit, scaleFor); return `<tr><td>${esc(ingredientName(i))}</td><td class="q">${s.q == null ? '' : num(s.q, s.dp)}</td><td class="u">${esc(unitLabel(s.unit))}</td></tr>`; }).join('')}</tbody></table></section> | |
| <section class="kc"><h2>${T('วิธีทำ', 'Method')}</h2><ol class="steps-list">${recipeSteps(r).map((x) => `<li>${esc(x)}</li>`).join('')}</ol> | |
| ${recipeTips(r) ? `<div class="tip"><span>💡</span><span>${esc(recipeTips(r))}</span></div>` : ''}</section>` : `<section class="kc"><h2>${T('ยังไม่มีสูตร', 'No recipe yet')}</h2><p class="sub">${T('เพิ่มสูตรได้ในหน้าภาพรวม เมนู “เมนูและสูตร”', 'Add one on the dashboard under “Menus & recipes”.')}</p></section>`} | |
| <section class="kc"><h2>${T('ปริมาณต่อคนตามค่าที่ตั้ง', 'Configured amount per student')}</h2> | |
| <table class="t"><thead><tr><th>${T('ชั้น', 'Grade')}</th><th class="r">🍚</th><th class="r">🍗</th><th class="r">🥦</th><th class="r">🍉</th></tr></thead><tbody> | |
| ${D.settings.grades.map((g) => { const f = D.settings.grade_portion[g] ?? 1; return `<tr${g === form.grade ? ' style="background:var(--brand-wash)"' : ''}><td><b>${gradeShort(g)}</b></td>${['starch', 'protein', 'veg', 'fruit'].map((k) => `<td class="r">${Math.round(m[`${k}_g`] * f)}</td>`).join('')}</tr>`; }).join('')} | |
| </tbody></table><p class="small muted" style="margin-top:8px">${T('หน่วยเป็นกรัม', 'Grams')}${fruitName(m) ? ` · ${T('ผลไม้', 'Fruit')}: ${esc(fruitName(m))}` : ''} · ${T(`${gradeShort(form.grade)} วันนี้ ${num(one.students)} คน`, `${gradeShort(form.grade)} today: ${num(one.students)}`)}</p></section>`; | |
| } | |
| // ---------------------------------------------------------------- kids' opinions + 4-compartment sort (cause-finding rounds) | |
| function opinionPanel(c) { | |
| const counts = c.votes?.meals?.[0]?.counts ?? {}; | |
| const total = c.votes?.meals?.[0]?.total ?? 0; | |
| return `<section class="kc opinions"> | |
| <div class="row"><b>💬 ${T('ข้อคิดเห็นจากเด็ก', "Kids' opinions")}</b><span class="spacer"></span> | |
| <a class="small" href="/opinions.html?meal=${encodeURIComponent(c.meal.id)}" target="_blank" rel="noopener">${T('เปิดหน้าครู', 'Teacher page')} ↗</a></div> | |
| <p class="sub">${T('ครูถามเด็กทีละคนว่าวันนี้กินเมนูนี้เป็นอย่างไร แล้วกดข้อที่เด็กตอบ 1 ครั้งต่อ 1 คน', 'Ask each child how this menu was today, then tap their answer. One tap per child.')}</p> | |
| <div class="op-grid">${REASON_ORDER.map((k) => `<button class="op-btn" type="button" data-opinion="${k}"><span class="i" aria-hidden="true">${REASON_ICON[k]}</span><span class="t">${reason(k)}</span><b>${num(counts[k] ?? 0)}</b></button>`).join('')}</div> | |
| <div class="row op-foot"><span>${T(`บันทึกแล้ว ${num(total)} จาก ${num(c.meal.students)} คน`, `${num(total)} of ${num(c.meal.students)} children recorded`)}</span><span class="spacer"></span> | |
| <button class="btn sm ghost" type="button" data-do="opinion-undo" ${total ? '' : 'disabled'}>↶ ${T('ยกเลิกครั้งล่าสุด', 'Undo last')}</button></div> | |
| ${total > (c.meal.students || 0) ? `<div class="hint crit">${T('บันทึกเกินจำนวนเด็ก รอบนี้จะไม่ถูกนำไปใช้ กดยกเลิกครั้งล่าสุดเพื่อแก้', 'More answers than children. This round will not be used until you undo the extra taps.')}</div>` : ''} | |
| </section>`; | |
| } | |
| function sortSection(c) { | |
| const saved = c.audit; | |
| if (form.audit.meal !== c.meal.id) { | |
| // A saved sort opens with its numbers, so it can be checked or corrected. | |
| form.audit = saved | |
| ? { meal: c.meal.id, covers: saved.covers, ...Object.fromEntries(saved.rates.map((r) => [r.key, Math.round(r.waste_g)])) } | |
| : { meal: c.meal.id, covers: c.meal.students }; | |
| } | |
| return `<section class="kc sort"> | |
| <h2>🧺 ${T('แยกเศษ 4 ช่อง ก่อนชั่งเศษ', 'Sort into 4 compartments before weighing')}</h2> | |
| <p class="sub">${T('พอเด็กคืนจานครบ เทเศษรวมของรอบนี้ลงถาด 4 ช่อง ชั่งทีละช่องแล้วกรอกเป็นกรัม จากนั้นจึงชั่งถังเศษและจบรอบ ใช้เครื่องชั่งตัวไหนก็ได้', 'When all trays are back, sort this round’s leftovers into the 4-compartment tray, weigh each compartment and enter grams. Then weigh the bins and end the round. Any scale works.')}</p> | |
| ${saved ? `<div class="hint good">✓ ${T('บันทึกแล้ว', 'Saved')}: ${saved.top ? `${group(saved.top.key)} ${Math.round(saved.top.rate)}%` : T('ไม่มีกลุ่มเด่น', 'nothing stands out')} · ${T('แก้ได้โดยกดบันทึกใหม่', 'save again to correct it')}</div>` : ''} | |
| ${mode === 'scale' ? `<div class="row sort-scale"><span class="small">${T('เครื่องชั่งในครัว (หักภาชนะแล้ว)', 'Kitchen scale (after tare)')}: <b id="sort-net">—</b> ${T('กก.', 'kg')}</span><span class="spacer"></span><button class="btn sm" id="tare" type="button">${T('หักภาชนะ', 'Tare')}</button></div>` : ''} | |
| <label class="field">${T('เศษรวมจากนักเรียน (คน)', 'Leftovers from (students)')}<input id="a-covers" type="number" inputmode="numeric" min="1" value="${esc(form.audit.covers ?? '')}"></label> | |
| ${GROUP_ORDER.map((k) => `<div class="audit-row"><label class="field">${groupIcon(k)} ${group(k)} (${T('กรัม', 'g')})<input id="a-${k}" type="number" inputmode="numeric" min="0" value="${esc(form.audit[k] ?? '')}"></label> | |
| ${mode === 'scale' ? `<button class="btn sm" data-fill="${k}" data-stable>${T('ใช้ค่าเครื่องชั่ง', 'Use scale')}</button>` : ''}</div>`).join('')} | |
| <div class="hint" id="audit-hint"></div> | |
| <button class="btn ${saved ? '' : 'primary'} big-btn" data-do="audit">${saved ? T('บันทึกใหม่', 'Save again') : T('บันทึกการแยกเศษ', 'Save the sort')}</button> | |
| </section>`; | |
| } | |
| // ---------------------------------------------------------------- live updates | |
| function tick() { | |
| const c = S?.current; | |
| if ($('s-val')) { | |
| const k = ch('kitchen'); | |
| const on = fresh() && k?.online; | |
| setText('s-label', T('เครื่องชั่งในครัว', 'Kitchen scale')); | |
| setText('s-val', on ? (k.raw / 1000).toFixed(3) : '—'); | |
| if ($('sort-net')) setText('sort-net', on ? (k.net / 1000).toFixed(3) : '—'); | |
| $('s-dot').className = `dot ${!on ? 'off' : k.stable ? 'on' : 'sim'}`; | |
| setText('s-state', !fresh() ? T('กำลังเชื่อมต่อ', 'Connecting') : !k?.online ? T('ไม่มีสัญญาณ · ไม่มีเครื่องชั่ง กด “พิมพ์เอง”', 'No signal · no scale? Tap “Type it in”') : k.stable ? T('นิ่งแล้ว กดบันทึกได้', 'Steady, ready to save') : T('รอให้นิ่ง', 'Settling')); | |
| setText('s-src', on ? (k.source === 'esp32' ? '· ESP32' : `· ${T('ค่าจำลอง', 'simulated')}`) : ''); | |
| const b = $('k-badges'); | |
| if (b) { const html = badges(); if (b.innerHTML !== html) b.innerHTML = html; } | |
| const tare = $('tare'); | |
| if (tare) tare.disabled = !(on && k.stable) || busy; | |
| document.querySelectorAll('[data-stable]').forEach((b) => { b.disabled = !(on && k.stable) || busy; }); | |
| const a = inProgress(); | |
| if ($('pour') && a) setText('pour', on ? kg(Math.max(0, a.before_g - k.raw)) : '—'); | |
| } | |
| const openBtn = document.querySelector('[data-do="open"]'); | |
| if (openBtn) { | |
| const issue = mode === 'manual' ? null : binsIssue(); | |
| const ok = validCount(form.students); | |
| const busyRound = S.open_round && S.open_round.grade !== form.grade; | |
| openBtn.disabled = busy || !ok || !!issue || !!busyRound; | |
| setHint('open-hint', busyRound ? T(`รอบ ${gradeShort(S.open_round.grade)} ยังไม่จบ`, `The ${gradeShort(S.open_round.grade)} round is still open`) | |
| : !ok ? T('กรอกจำนวนนักเรียน', 'Enter the number of students') | |
| : issue ? issue[0] : mode === 'manual' ? (fiveBins() ? T('โหมดพิมพ์เอง ชั่งถังเศษ 5 ใบด้วยตาชั่งธรรมดาแล้วพิมพ์ตอนจบรอบ', 'Type-in mode: weigh the 5 bins on any scale and type them in at the end') : T('โหมดพิมพ์เอง จะพิมพ์น้ำหนักเศษตอนจบรอบ', 'Type-in mode: leftovers are typed in at the end')) | |
| : roundBins().length === 5 ? T('ถังเศษทั้ง 5 ใบพร้อมแล้ว', 'All 5 leftover bins are ready') : T('ถังเศษทั้งสองใบพร้อมแล้ว', 'Both leftover bins are ready'), | |
| busyRound || !ok ? 'warn' : issue ? issue[1] : 'good'); | |
| } | |
| for (const key of roundBins()) { | |
| const r = ch(key); | |
| if ($(`bin-${key}`)) setText(`bin-${key}`, fresh() && r?.online ? kg(Math.max(0, r.raw - binStart(key))) : '—'); | |
| } | |
| const manualSave = document.querySelector('[data-do="before"]:not([data-stable]), [data-do="after"]:not([data-stable])'); | |
| if (manualSave) { | |
| // An emptied pot weighs 0 after serving; only the before-weight needs a pot on the scale (server: at least 50 g). | |
| const w = kgValue(form.weight); | |
| manualSave.disabled = busy || w == null || (manualSave.dataset.do === 'before' && Math.round(w * 1000) < 50); | |
| } | |
| const close = document.querySelector('[data-do="close"]'); | |
| if (close && c?.meal.status === 'open') { | |
| const pending = c.pots.filter((p) => p.after_g == null); | |
| const served = c.metrics.rice_served_g + c.metrics.dish_served_g; | |
| const brothLeft = c.menu.has_broth ? Math.max(0, c.broth_required - c.broth.samples.length) : 0; | |
| const typed = manualBins(); | |
| const unsorted = needsTray(c) && !c.audit; | |
| const missingBins = FIVE_BINS.filter((k) => kgValue(form.bins[k]) == null); | |
| const issue = !typed ? binsIssue() | |
| : fiveBins() ? (missingBins.length ? [T(`พิมพ์น้ำหนักถัง: ${missingBins.map(binName).join(' · ')}`, `Type in: ${missingBins.map(binName).join(' · ')}`), 'warn'] : null) | |
| : kgValue(form.rice) == null || kgValue(form.dish) == null ? [T('พิมพ์น้ำหนักเศษข้าวและเศษกับข้าว', 'Type in the rice and main-dish leftovers'), 'warn'] : null; | |
| let msg; | |
| if (pending.length) msg = [T('ยังมีหม้อที่ต้องชั่งหลังตัก', 'A pot still needs its after-weight'), 'warn']; | |
| else if (served <= 0) msg = [T('ชั่งหม้ออย่างน้อย 1 ใบก่อน', 'Weigh at least one pot first'), 'warn']; | |
| else if (brothLeft) msg = [T(`วัดทัพพีแกงอีก ${brothLeft} ครั้ง`, `Measure the curry ladle ${brothLeft} more time(s)`), 'warn']; | |
| else if (unsorted) msg = [T('แยกเศษ 4 ช่องแล้วกดบันทึกก่อนชั่งเศษ', 'Sort into 4 compartments and save before weighing the bins'), 'warn']; | |
| else msg = issue ?? [T('พร้อมจบรอบ', 'Ready to end the round'), 'good']; | |
| close.disabled = busy || !!pending.length || served <= 0 || !!brothLeft || unsorted || !!issue; | |
| setHint('close-hint', msg[0], msg[1]); | |
| } | |
| const save = document.querySelector('[data-do="audit"]'); | |
| if (save) { | |
| const missing = GROUP_ORDER.filter((g) => String(form.audit[g] ?? '').trim() === ''); | |
| const ok = validCount(form.audit.covers) && !missing.length; | |
| save.disabled = busy || !ok; | |
| setHint('audit-hint', !validCount(form.audit.covers) ? T('กรอกจำนวนนักเรียน', 'Enter the number of students') : missing.length ? T(`ยังไม่ได้กรอก: ${missing.map(group).join(', ')}`, `Still missing: ${missing.map(group).join(', ')}`) : T('ครบแล้ว กดบันทึกได้', 'All set'), ok ? 'good' : 'warn'); | |
| } | |
| } | |
| // ---------------------------------------------------------------- events | |
| document.addEventListener('input', (e) => { | |
| const id = e.target.id; | |
| if (id === 'f-students') form.students = e.target.value; | |
| if (id === 'a-covers') form.audit.covers = e.target.value; | |
| if (id === 'm-weight') form.weight = e.target.value; | |
| if (id === 'm-rice') form.rice = e.target.value; | |
| if (id === 'm-dish') form.dish = e.target.value; | |
| const bin = /^m-bin-(\w+)$/.exec(id); | |
| if (bin) form.bins[bin[1]] = e.target.value; | |
| const g = /^a-(starch|veg|protein|fruit)$/.exec(id); | |
| if (g) form.audit[g[1]] = e.target.value; | |
| tick(); | |
| }); | |
| document.addEventListener('change', async (e) => { | |
| const id = e.target.id; | |
| if (id === 'f-menu') { form.menu = e.target.value; form.students = null; renderBody(); } | |
| if (id === 'f-absence') form.absence = e.target.checked; | |
| if (id === 'f-event') form.event = e.target.checked; | |
| if (id === 'c-absence' || id === 'c-event') { | |
| await act('/api/meal/context', { meal_id: S.current.meal.id, context_absence: $('c-absence').checked, context_event: $('c-event').checked }, T('บันทึกแล้ว', 'Saved')); | |
| } | |
| }); | |
| document.addEventListener('click', async (e) => { | |
| const sum = e.target.closest('details[data-stage] > summary'); | |
| if (sum) { const d = sum.parentElement; stageOpen[d.dataset.stage] = !d.open; return; } | |
| const md = e.target.closest('[data-mode]'); | |
| if (md) { mode = md.dataset.mode; store.set('eatback.inputMode', mode); shell(); renderBody(); return; } | |
| const t = e.target.closest('[data-tab]'); | |
| if (t) { tab = t.dataset.tab; shell(); renderBody(); return; } | |
| const go = e.target.closest('[data-go]'); | |
| if (go) { tab = go.dataset.go; shell(); renderBody(); return; } | |
| const gr = e.target.closest('[data-grade]'); | |
| if (gr && !busy) { | |
| if (S.open_round) { toast(T(`รอบ ${gradeShort(S.open_round.grade)} ยังไม่จบ`, `The ${gradeShort(S.open_round.grade)} round is still open`), true); return; } | |
| Object.assign(form, { grade: gr.dataset.grade, menu: null, students: null, absence: false, event: false }); | |
| tab = 'meal'; | |
| await refresh(); | |
| shell(); renderBody(); | |
| return; | |
| } | |
| const p = e.target.closest('[data-pot]'); | |
| if (p) { pot = p.dataset.pot; form.weight = ''; renderBody(); return; } | |
| const fill = e.target.closest('[data-fill]'); | |
| if (fill && !fill.disabled) { | |
| const v = Math.max(0, Math.round(ch('kitchen').net)); | |
| form.audit[fill.dataset.fill] = v; | |
| $(`a-${fill.dataset.fill}`).value = v; | |
| tick(); | |
| return; | |
| } | |
| if (e.target.closest('#tare')) { | |
| if (confirm(T('วางภาชนะเปล่าบนเครื่องชั่งแล้วใช่ไหม', 'Is the empty container on the scale?'))) await act('/api/scale/tare', {}, T('หักภาชนะแล้ว', 'Tared')); | |
| return; | |
| } | |
| const op = e.target.closest('[data-opinion]'); | |
| if (op && !busy && asking()) { | |
| busy = true; | |
| try { | |
| const r = await act('/api/opinion', { meal_id: S.current.meal.id, button: op.dataset.opinion }); | |
| if (r) { toast(T(`บันทึก: ${reason(op.dataset.opinion)}`, `Saved: ${reason(op.dataset.opinion)}`)); await refresh(); } | |
| } finally { busy = false; tick(); } | |
| return; | |
| } | |
| const b = e.target.closest('[data-do]'); | |
| if (!b || b.disabled || busy) return; | |
| const what = b.dataset.do; | |
| if (what === 'undo' && !confirm(T('ย้อนรายการชั่งล่าสุดใช่ไหม', 'Undo the last weighing?'))) return; | |
| if (what === 'close' && !confirm(T('จบรอบและคำนวณของเหลือเลยไหม', 'End the round and calculate leftovers now?'))) return; | |
| if (what === 'cancel' && !confirm(T('ยกเลิกรอบนี้ใช่ไหม ข้อมูลที่ชั่งไว้จะหายไป', 'Cancel this round? Its weighings will be removed.'))) return; | |
| busy = true; | |
| tick(); | |
| try { | |
| let r = null; | |
| if (what === 'open') { | |
| const planned = availablePlans().find((m) => m.menu_id === form.menu && m.grade === form.grade); | |
| r = await act('/api/meal/open', { | |
| grade: form.grade, menu_id: form.menu, students: Number(form.students), meal_id: planned?.id, | |
| bins: mode === 'manual' ? 'manual' : 'scale', context_absence: form.absence, context_event: form.event, | |
| }); | |
| if (r) { toast(r.investigation ? T('เริ่มรอบแล้ว รอบนี้เก็บข้อคิดเห็นจากเด็ก', 'Round started. This round collects the kids’ opinions.') : T('เริ่มรอบแล้ว', 'Round started')); Object.assign(form, { menu: null, students: null, absence: false, event: false, weight: '', rice: '', dish: '' }); } | |
| } else if (what === 'before' || what === 'after') { | |
| const body = { pot, phase: what }; | |
| if (mode === 'manual') body.manual_g = Math.round(kgValue(form.weight) * 1000); | |
| r = await act('/api/meal/capture', body, what === 'before' ? T('บันทึกแล้ว ตักได้เลย', 'Saved. Start serving.') : T('บันทึกแล้ว', 'Saved')); | |
| if (r) form.weight = ''; | |
| } else if (what === 'broth') { | |
| const pt = b.dataset.point; | |
| r = await act('/api/meal/broth', { point: pt, ladle_g: Number($(`b-${pt}-l`).value), solid_g: Number($(`b-${pt}-s`).value) }, T('บันทึกทัพพีแล้ว', 'Ladle saved')); | |
| } else if (what === 'undo') { | |
| r = await act('/api/meal/undo', {}, T('ย้อนแล้ว', 'Undone')); | |
| } else if (what === 'close') { | |
| const grams = (v) => Math.round(kgValue(v) * 1000); | |
| const body = !manualBins() ? {} | |
| : fiveBins() ? { sorted_waste_g: Object.fromEntries(FIVE_BINS.map((k) => [k, grams(form.bins[k])])) } | |
| : { rice_waste_g: grams(form.rice), dish_waste_g: grams(form.dish) }; | |
| r = await act('/api/meal/close', body, T('จบรอบแล้ว', 'Round ended')); | |
| if (r) Object.assign(form, { rice: '', dish: '', bins: {} }); | |
| } else if (what === 'cancel') { | |
| r = await act('/api/meal/cancel', {}, T('ยกเลิกแล้ว', 'Cancelled')); | |
| } else if (what === 'opinion-undo') { | |
| r = await act('/api/opinion/undo', { meal_id: S.current.meal.id }); | |
| if (r) toast(T(`ยกเลิก “${reason(r.removed)}” แล้ว`, `Removed “${reason(r.removed)}”`)); | |
| } else if (what === 'audit') { | |
| const c = asking(); | |
| const body = { meal_id: c.meal.id, covers: Number(form.audit.covers) }; | |
| GROUP_ORDER.forEach((g) => { body[`${g}_g`] = Number(form.audit[g]); }); | |
| r = await act('/api/audit/save', body); | |
| if (r) toast(r.finding.top ? T(`บันทึกแล้ว ${group(r.finding.top.key)}เหลือเด่น`, `Saved. Most left: ${group(r.finding.top.key)}`) : T('บันทึกแล้ว', 'Saved')); | |
| } | |
| if (r) await refresh(); | |
| } finally { | |
| busy = false; | |
| tick(); | |
| } | |
| }); | |
| refresh(); | |