// 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') => ``; 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 = `${T('ไปตรวจเครื่องชั่ง', 'Check the scales')} ↗`; return trial ? `
${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}
` : `
${T('เช้านี้ยังตรวจเครื่องชั่งไม่ผ่านครบ ตัวเลขวันนี้อาจคลาดเคลื่อน', "The scales haven't passed this morning's check, so today's numbers may be off.")} ${link}
`; } 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 = `

${T('โหลดไม่สำเร็จ', "Couldn't load")}

${esc(e.message)}

`; $('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 = `
${LOGO}

${WORDMARK} ${T('หน้าครัว', 'Kitchen')}

${esc(S.settings.school_name)}
${roleChip()}${langToggle()}
${badges()}
—${T('กก.', 'kg')}

${isAdmin() ? `${T('เปิดหน้าภาพรวม', 'Open the dashboard')} ↗` : `${T('ตรวจเครื่องชั่งเช้านี้', "This morning's scale check")} ↗ · ${T('ใบสั่งซื้อประจำสัปดาห์', "This week's purchase order")} ↗`}

`; } // 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' ? `${T('ข้อมูลจริง', 'Real data')}` : `${T('ข้อมูลเดโม', 'Demo data')}`; const scale = mode === 'manual' ? `✍️ ${T('ตาชั่งธรรมดา พิมพ์เอง', 'Any scale, typed in')}` : !live ? `⚖️ ${T('ยังไม่มีสัญญาณเครื่องชั่ง', 'No scale signal yet')}` : k.source === 'esp32' ? `⚖️ ${T('เครื่องชั่ง IoT', 'IoT scale')}` : `⚖️ ${T('ค่าจำลอง ยังไม่ได้ต่อเครื่องชั่ง', 'Simulated, no scale connected')}`; const qc = S.qc?.all_ok ? `${T('ตรวจเครื่องชั่งเช้านี้แล้ว', 'Scales checked this morning')}` : `${T('ยังไม่ตรวจเครื่องชั่งเช้านี้ รอบจะไม่ถูกนับ', "Scales not checked: rounds won't count")}`; 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 `
${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 ``; }).join('')}
`; } 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 ? `
${food(c.menu, 'sm')}
${esc(menuName(c.menu))}
${gradeName(g)} · ${T('จบรอบแล้ว', 'Round finished')}
${T('ตักเสิร์ฟ', 'Served')}${kg(c.metrics.served_g)} ${T('กก.', 'kg')}
${T('เหลือกลับมา', 'Came back')}${kg(c.metrics.waste_g)} ${T('กก.', 'kg')}
${T('วันนี้มีอะไรผิดปกติไหม', 'Anything unusual today?')}
${c.audit?.source === 'bins' ? `
${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')}
` : c.audit ? `
${T('บันทึกการแยกเศษ 4 ช่องแล้ว', '4-compartment sort recorded')}
` : ''} ${nextGrade ? `` : ''}
` : ''; const opts = menus.map((x) => ``).join(''); return `${last}

${T('เริ่มรอบกิน', 'Start a round')}

${T('แต่ละชั้นกินแยกรอบ เลือกชั้นที่กำลังจะมากิน', 'Each grade eats in its own round. Pick the grade coming in now.')}

${gradePicker()} ${willAsk ? `
${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'}.`)}
` : ''} ${m?.has_broth ? `
${T('เมนูแกง ระหว่างตักต้องวัดทัพพี 2 ครั้ง', 'Curry menu: measure a ladle twice while serving.')}
` : ''}

${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)`)}

${T('วันนี้มีอะไรผิดปกติไหม', 'Anything unusual today?')}
${T('ถ้าติ๊ก รอบนี้จะไม่ถูกนำไปเทียบ', "If ticked, this round isn't used for comparisons.")}
${qcHint(plan?.origin === 'trial')}
`; } // ---------------------------------------------------------------- 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) => `
${potName(p.pot)} ${T('หม้อ', 'pot')} ${p.n}${p.manual ? ` ${T('พิมพ์เอง', 'typed')}` : ''}${kg(p.before_g)} → ${p.after_g == null ? T('รอชั่งหลังตัก', 'waiting') : kg(p.after_g)} ${T('กก.', 'kg')}
${p.served_g == null ? '…' : `${kg(p.served_g)} ${T('กก.', 'kg')}`}
`).join('') : `

${T('ยังไม่ได้ชั่ง', 'Nothing weighed yet')}

`; const manualBox = (label) => ``; const step = active ? `
2
${T('ตักเสร็จแล้ว ชั่งหม้อใบเดิมอีกครั้ง', 'Done serving? Weigh the same pot again')}
${manual ? T(`ก่อนตักหนัก ${kg(active.before_g)} กก.`, `It weighed ${kg(active.before_g)} kg before`) : `${T('ตักไปแล้วประมาณ', 'Served so far about')} — ${T('กก.', 'kg')}`}
${manual ? `${manualBox(T('น้ำหนักหม้อหลังตัก', 'Pot weight after serving'))}` : ``}` : `
1
${T(`วางหม้อ${potName(pot)}ที่ทำเสร็จบนตาชั่ง`, `Put the ${potName(pot).toLowerCase()} pot on the scale`)}
${manual ? T('อ่านตัวเลขบนตาชั่งแล้วพิมพ์ลงช่อง', 'Read the scale and type the number') : T('รอให้ตัวเลขนิ่งแล้วกด', 'Wait for the number to settle, then tap')}
${manual ? `${manualBox(T('น้ำหนักหม้อก่อนตัก', 'Pot weight before serving'))}` : ``}`; 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 ? `

${T('เมนูแกง: วัดทัพพี', 'Curry: measure a ladle')}

${T('ตักแกง 1 ทัพพี ชั่งทั้งหมด แล้วกรองน้ำออกชั่งเนื้ออีกครั้ง ใช้เครื่องชั่งครัวธรรมดาได้', 'Weigh one full ladle, strain it, then weigh the solids. Any kitchen scale works.')}

${brothPoints.map((p) => `
${T(...POINT[p])}${byPoint[p] ? ` ✓ ${T('เนื้อ', 'solids')} ${Math.round((byPoint[p].solid_g / byPoint[p].ladle_g) * 100)}%` : ''}
`).join('')}
` : ''; const five = returnBins(S.settings).length === 5; const liveBins = roundBins(); const kgBox = (id, label, value) => ``; const bins = manualBins() ? `

${T('ของเหลือที่จุดคืนจาน', 'Leftovers at the return station')}

${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.')}

${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)}`}
` : `

${T('ของเหลือที่จุดคืนจาน', 'Leftovers at the return station')}

${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.')}

${liveBins.map((k) => `
${binIcon(k)} ${binName(k)}— ${T('กก.', 'kg')}
`).join('')}
`; 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) => `
${n}${T(th, en)}${note}${body}
`; 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'), `
${['rice', 'dish'].map((k) => ``).join('')}
${other ? `
${T(`หม้อ${potName(other.pot)}ยังไม่ได้ชั่งหลังตัก`, `The ${potName(other.pot).toLowerCase()} pot still needs its after-weight`)}
` : ''}
${step}

${T('ชั่งแล้ว', 'Weighed')}

${potList}
${T('ข้าวที่ตัก', 'Rice served')}${kg(c.metrics.rice_served_g)} ${T('กก.', 'kg')}
${T('กับข้าวที่ตัก', 'Main dish served')}${kg(c.metrics.dish_served_g)} ${T('กก.', 'kg')}
${c.pots.length ? `` : ''}
${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`), `

${T('ครูกดในหน้าครู ครัวไม่ต้องทำ ถ้าไม่มีครู ครัวกดแทนได้ที่นี่', "Teachers tap on the teacher page; the kitchen does nothing. With no teacher around, the kitchen can tap here.")} ${T('เปิดหน้าครู', 'Teacher page')} ↗

${opinionPanel(c)}`) : `
2${T('ระหว่างรับประทาน: เด็กกินตามปกติ รอบนี้ไม่ต้องถามเด็ก', "While eating: the children eat as usual; this round doesn't ask them")}
`; 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}

${T('จบรอบ', 'End the round')}

`); return `
${food(c.menu)}
${esc(menuName(c.menu))}
${gradeName(c.meal.grade)} · ${T(`${num(c.meal.students)} คน`, `${num(c.meal.students)} students`)}
${T('กำลังเสิร์ฟ', 'Serving')}
${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 `

${T('กำลังโหลดสูตร…', 'Loading the recipe…')}

`; } const D = recipe.data; if (!D) return `

${T('โหลดสูตรไม่สำเร็จ', "Couldn't load the recipe")}

`; 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 `
${food(m)}
${esc(menuName(m))}
${T(`ทั้งโรงเรียน ${num(all.students)} คน ใช้วัตถุดิบเท่ากับ ${num(all.portions)} ที่เต็ม`, `Whole school: ${num(all.students)} students = ${num(all.portions)} full portions`)}
${r ? `🖨️ ${T('พิมพ์สูตรทั้งโรงเรียน', 'Print for the whole school')}` : ''}
${T('ที่มาข้อมูล · ยังไม่ผ่านการตรวจสอบ', 'Data source · unverified')}
${recipeLabel} · ${costLabel}
${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.')}
${r ? `

${T('วัตถุดิบประมาณการ (ทั้งโรงเรียน)', 'Estimated ingredients (whole school)')}

${r.ingredients.map((i) => { const s = scaleQty(i.qty, i.unit, scaleFor); return ``; }).join('')}
${esc(ingredientName(i))}${s.q == null ? '' : num(s.q, s.dp)}${esc(unitLabel(s.unit))}

${T('วิธีทำ', 'Method')}

    ${recipeSteps(r).map((x) => `
  1. ${esc(x)}
  2. `).join('')}
${recipeTips(r) ? `
💡${esc(recipeTips(r))}
` : ''}
` : `

${T('ยังไม่มีสูตร', 'No recipe yet')}

${T('เพิ่มสูตรได้ในหน้าภาพรวม เมนู “เมนูและสูตร”', 'Add one on the dashboard under “Menus & recipes”.')}

`}

${T('ปริมาณต่อคนตามค่าที่ตั้ง', 'Configured amount per student')}

${D.settings.grades.map((g) => { const f = D.settings.grade_portion[g] ?? 1; return `${['starch', 'protein', 'veg', 'fruit'].map((k) => ``).join('')}`; }).join('')}
${T('ชั้น', 'Grade')}🍚🍗🥦🍉
${gradeShort(g)}${Math.round(m[`${k}_g`] * f)}

${T('หน่วยเป็นกรัม', 'Grams')}${fruitName(m) ? ` · ${T('ผลไม้', 'Fruit')}: ${esc(fruitName(m))}` : ''} · ${T(`${gradeShort(form.grade)} วันนี้ ${num(one.students)} คน`, `${gradeShort(form.grade)} today: ${num(one.students)}`)}

`; } // ---------------------------------------------------------------- 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 `
💬 ${T('ข้อคิดเห็นจากเด็ก', "Kids' opinions")} ${T('เปิดหน้าครู', 'Teacher page')} ↗

${T('ครูถามเด็กทีละคนว่าวันนี้กินเมนูนี้เป็นอย่างไร แล้วกดข้อที่เด็กตอบ 1 ครั้งต่อ 1 คน', 'Ask each child how this menu was today, then tap their answer. One tap per child.')}

${REASON_ORDER.map((k) => ``).join('')}
${T(`บันทึกแล้ว ${num(total)} จาก ${num(c.meal.students)} คน`, `${num(total)} of ${num(c.meal.students)} children recorded`)}
${total > (c.meal.students || 0) ? `
${T('บันทึกเกินจำนวนเด็ก รอบนี้จะไม่ถูกนำไปใช้ กดยกเลิกครั้งล่าสุดเพื่อแก้', 'More answers than children. This round will not be used until you undo the extra taps.')}
` : ''}
`; } 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 `

🧺 ${T('แยกเศษ 4 ช่อง ก่อนชั่งเศษ', 'Sort into 4 compartments before weighing')}

${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.')}

${saved ? `
✓ ${T('บันทึกแล้ว', 'Saved')}: ${saved.top ? `${group(saved.top.key)} ${Math.round(saved.top.rate)}%` : T('ไม่มีกลุ่มเด่น', 'nothing stands out')} · ${T('แก้ได้โดยกดบันทึกใหม่', 'save again to correct it')}
` : ''} ${mode === 'scale' ? `
${T('เครื่องชั่งในครัว (หักภาชนะแล้ว)', 'Kitchen scale (after tare)')}: — ${T('กก.', 'kg')}
` : ''} ${GROUP_ORDER.map((k) => `
${mode === 'scale' ? `` : ''}
`).join('')}
`; } // ---------------------------------------------------------------- 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();