// Shared helpers for the dashboard, kitchen and simulator pages. import { errorText, T } from './i18n.js'; export { kg, kgAuto, pct, num } from './i18n.js'; export async function api(path, body, retried = false) { const res = await fetch(path, body === undefined ? { cache: 'no-store' } : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); const data = await res.json().catch(() => ({})); if (!res.ok) { // Real school data: reading needs a signed-in role (the sign-in ran out: back to /start), and a change needs the // PIN of the role that does it (ask once, sign in, try again). if (res.status === 401 && data.signin) { location.replace(startUrl()); return new Promise(() => {}); } if ((res.status === 401 || res.status === 403) && data.need && !retried && await askPin(data)) return api(path, body, true); throw Object.assign(new Error(data.error || `HTTP ${res.status}`), { status: res.status }); } return data; } // The PIN box: resolves true once signed in with a role that covers `need`, false when the person cancels. export function askPin({ need, need_th: needTh, error } = {}) { return new Promise((resolve) => { let dlg = document.getElementById('pin-dialog'); if (!dlg) { dlg = document.createElement('dialog'); dlg.id = 'pin-dialog'; document.body.appendChild(dlg); } dlg.innerHTML = `

${T(`ใส่ PIN ${needTh ?? ''}`, `Enter the ${needTh ?? ''} PIN`)}

${esc(error || T('โรงเรียนใช้ข้อมูลจริงอยู่ การบันทึกต้องใช้ PIN ของบทบาทนั้น', 'This school runs on real data: saving needs the PIN of that role.'))}

`; const input = dlg.querySelector('#pin-input'); const err = dlg.querySelector('.pin-err'); const done = (ok) => { dlg.close(); resolve(ok); }; dlg.querySelector('[data-pin="cancel"]').addEventListener('click', () => done(false)); dlg.addEventListener('cancel', (e) => { e.preventDefault(); done(false); }, { once: true }); dlg.querySelector('form').addEventListener('submit', async (e) => { e.preventDefault(); if (!/^\d{4,8}$/.test(input.value)) { err.textContent = T('PIN เป็นตัวเลข 4–8 หลัก', 'A PIN is 4–8 digits'); return; } const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ pin: input.value, role: need }) }); const data = await res.json().catch(() => ({})); if (res.ok) { window.dispatchEvent(new CustomEvent('eatback:role', { detail: data })); done(true); return; } err.textContent = data.error || T('เข้าใช้ไม่สำเร็จ', 'Could not sign in'); input.select(); }); dlg.showModal(); input.focus(); }); } // ---------------------------------------------------------------- who is using this screen // Each school screen belongs to some roles (server/app.py SCREENS). With real school data the server enforces it; in // the demo the role is picked with one tap on /start. A role that opens another role's screen goes to its own. export const SCREENS = { dashboard: ['admin', 'viewer', 'kitchen'], kitchen: ['admin', 'kitchen'], recipe: ['admin', 'kitchen'], opinions: ['admin', 'kitchen', 'teacher'], planner: ['admin', 'kitchen'], sim: ['admin'], demo: ['admin'], }; export const HOME = { admin: '/#/today?g=all', viewer: '/#/report', kitchen: '/kitchen.html', teacher: '/opinions.html' }; export const ROLE_ICON = { admin: '📋', kitchen: '🍲', teacher: '🧒', viewer: '🏫' }; export const roleName = (r) => T(...({ admin: ['ผู้ดูแล', 'Coordinator'], kitchen: ['แม่ครัว', 'Kitchen'], teacher: ['ครูประจำชั้น', 'Class teacher'], viewer: ['ผู้บริหาร', 'Principal'] }[r] ?? [r, r])); export let me = null; export const can = (screen) => !!me?.role && (SCREENS[screen] ?? []).includes(me.role); // The school screen a link opens ('/kitchen.html', '/kitchen.html?grade=P1', '/#/fix' -> 'kitchen', 'dashboard'), or null // for the product pages anyone may read. export function screenOf(href) { const name = String(href).replace(/^\//, '').split(/[?#.]/)[0]; return { '': 'dashboard', index: 'dashboard', kitchen: 'kitchen', recipe: 'recipe', opinions: 'opinions', planner: 'planner', sim: 'sim', demo: 'demo' }[name] ?? null; } export const isAdmin = () => me?.role === 'admin'; function startUrl() { return `/start.html?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`; } // Call first on every school screen: resolves with the signed-in role, or leaves for /start or the role's own screen. export async function signIn(screen) { me = await api('/api/auth/me'); if (!me.role) location.replace(startUrl()); else if (!can(screen)) location.replace(HOME[me.role]); else return me; return new Promise(() => {}); } // Who is signed in, next to the language switch: tap it to switch role or sign out. export function roleChip() { if (!me?.role) return ''; return `${ROLE_ICON[me.role]} ${esc(roleName(me.role))} `; } // Print this page. Inside a frame (the Hugging Face Space page, an app preview) the browser may ignore print(), so the // page opens in a tab of its own with ?print=1 and prints itself there once its content is ready. export function printPage() { let framed = true; try { framed = window.top !== window.self; } catch { /* a cross-origin parent: framed */ } if (!framed) { window.print(); return; } const u = new URL(location.href); u.searchParams.set('print', '1'); window.open(u.href, '_blank', 'noopener'); } // Call once the page has rendered: prints when opened by printPage, then drops ?print=1 so a reload doesn't print again. export function printIfAsked() { const u = new URL(location.href); if (u.searchParams.get('print') !== '1') return false; u.searchParams.delete('print'); history.replaceState(null, '', u.pathname + u.search + u.hash); setTimeout(() => window.print(), 300); return true; } // Live scale readings + a data version that bumps on every change. // On the local network this is a Server-Sent Events stream. Public tunnels and hosting proxies // often buffer SSE, so from anywhere else the page polls a small payload once a second instead. // Only a page on screen listens: a browser opens at most 6 connections to one server, and streams // left open by hidden tabs or by pages kept for the back button would leave none for the next page, // which then hangs on "loading". A page shown again catches up from the version in the first tick. const LOCAL = /^(localhost|127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|\[?::1\]?$)|\.local$/; export function live(onTick) { let timer; if (!LOCAL.test(location.hostname)) { let busy = false; const poll = async () => { clearTimeout(timer); if (busy || document.hidden) return; busy = true; try { onTick(await api('/api/live')); } catch { /* keep trying while the link reconnects */ } busy = false; timer = setTimeout(poll, 1000); }; document.addEventListener('visibilitychange', poll); window.addEventListener('pageshow', (e) => { if (e.persisted) poll(); }); window.addEventListener('pagehide', () => clearTimeout(timer)); poll(); return; } let es = null; const stop = () => { clearTimeout(timer); es?.close(); es = null; }; const connect = () => { clearTimeout(timer); if (es || document.hidden) return; es = new EventSource('/api/stream'); es.onmessage = (e) => onTick(JSON.parse(e.data)); es.onerror = () => { stop(); timer = setTimeout(connect, 1500); }; }; document.addEventListener('visibilitychange', () => (document.hidden ? stop() : connect())); window.addEventListener('pageshow', (e) => { if (e.persisted) connect(); }); window.addEventListener('pagehide', stop); connect(); } // ---------------------------------------------------------------- recipes: scale a quantity to the day's head count const COUNT_UNITS = ['ฟอง', 'ผล', 'ชิ้น', 'หลอด', 'ห่อ']; export function scaleQty(qty, unit, factor) { if (qty == null || qty === '') return { q: null, unit, dp: 0 }; let v = Number(qty) * factor; let u = unit; if ((u === 'ก.' || u === 'กรัม') && v >= 1000) { v /= 1000; u = 'กก.'; } else if (u === 'มล.' && v >= 1000) { v /= 1000; u = 'ลิตร'; } if (u === 'กก.' || u === 'ลิตร') return { q: Math.round(v * 100) / 100, unit: u, dp: 2 }; if (COUNT_UNITS.includes(u)) return { q: Math.ceil(v - 1e-9), unit: u, dp: 0 }; if (v >= 100) return { q: Math.round(v / 5) * 5, unit: u, dp: 0 }; if (v >= 10) return { q: Math.round(v), unit: u, dp: 0 }; return { q: Math.round(v * 10) / 10, unit: u, dp: v % 1 ? 1 : 0 }; } // Standard (grade 4–6) portions for a group of students: each grade eats its own portion size. export function portionsFor(settings, target, students) { const grades = target === 'all' ? settings.grades : [target]; const heads = grades.reduce((a, g) => a + (Number(settings.grade_students[g]) || 0), 0); const std = grades.reduce((a, g) => a + (Number(settings.grade_students[g]) || 0) * (Number(settings.grade_portion[g]) || 1), 0); const n = students ?? heads; return { students: n, portions: heads ? (std / heads) * n : n }; } export const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); let toastTimer; export function toast(msg, isErr = false) { let el = document.getElementById('toast'); if (!el) { el = document.createElement('div'); el.id = 'toast'; el.setAttribute('role', 'status'); el.setAttribute('aria-live', 'polite'); document.body.appendChild(el); } el.textContent = msg; el.className = `show${isErr ? ' err' : ''}`; clearTimeout(toastTimer); toastTimer = setTimeout(() => { el.className = ''; }, isErr ? 4200 : 2600); } // Run a POST and toast any error in the current language. Returns the result or null. export async function act(path, body, okMsg) { try { const r = await api(path, body ?? {}); if (okMsg) toast(okMsg); return r; } catch (e) { toast(errorText(e.message) || T('ทำรายการไม่สำเร็จ', 'Something went wrong'), true); return null; } } // Brand mark: a school lunch tray (rice, vegetables, protein, data) inside a green-to-orange feedback loop. export const MARK = ``; export const LOGO = MARK; export const WORDMARK = 'EatBack';