// 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') => `
${esc(m?.icon || '🍽️')}
`;
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('แต่ละชั้นกินแยกรอบ เลือกชั้นที่กำลังจะมากิน', 'Each grade eats in its own round. Pick the grade coming in now.')}
${gradePicker()}
${food(m, 'md')}
${esc(menuName(m))}${plan ? (plan.origin === 'trial' ? T(`มื้อทดลองของ ${gradeShort(g)}`, `Trial meal for ${gradeShort(g)}`) : T('ตามแผนวันนี้', "Today's plan")) : T('ไม่ได้อยู่ในแผน', 'Not in the plan')}
${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(`วางหม้อ${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')}
${T('เมนูแกง: วัดทัพพี', 'Curry: measure a ladle')}
${T('ตักแกง 1 ทัพพี ชั่งทั้งหมด แล้วกรองน้ำออกชั่งเนื้ออีกครั้ง ใช้เครื่องชั่งครัวธรรมดาได้', 'Weigh one full ladle, strain it, then weigh the solids. Any kitchen scale works.')}
${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.')}
${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`)}
${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('ที่มาข้อมูล · ยังไม่ผ่านการตรวจสอบ', '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.')}
${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')}