eatback / js /core.js
kritpakin's picture
Pages free connections when hidden, real-data fix wording, kitchen purchase-order menu, School A/B five-bin wording
efb572d verified
Raw History Blame Contribute Delete
13.6 kB
// 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 = `<form class="pin-form" novalidate>
<h2>${T(`ใส่ PIN ${needTh ?? ''}`, `Enter the ${needTh ?? ''} PIN`)}</h2>
<p class="small ink2">${esc(error || T('โรงเรียนใช้ข้อมูลจริงอยู่ การบันทึกต้องใช้ PIN ของบทบาทนั้น', 'This school runs on real data: saving needs the PIN of that role.'))}</p>
<input id="pin-input" type="password" inputmode="numeric" autocomplete="off" maxlength="8" aria-label="PIN">
<p class="pin-err small" role="alert"></p>
<div class="pin-actions"><button type="button" class="btn ghost" data-pin="cancel">${T('ยกเลิก', 'Cancel')}</button>
<button type="submit" class="btn primary">${T('เข้าใช้', 'Sign in')}</button></div>
</form>`;
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 `<a class="role-chip" href="/start.html" title="${T('สลับบทบาทหรือออกจากระบบ', 'Switch role or sign out')}">${ROLE_ICON[me.role]} ${esc(roleName(me.role))} <span aria-hidden="true">⇄</span></a>`;
}
// 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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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 = `<svg class="brand-mark" viewBox="0 0 64 64" aria-hidden="true">
<path d="M7.6 41A25.5 25.5 0 0 1 45.5 9.2" fill="none" stroke="#41B649" stroke-width="5.6" stroke-linecap="round"/>
<path d="M21 57.2A25.5 25.5 0 0 0 55.2 23.5" fill="none" stroke="#F59E0B" stroke-width="5.6" stroke-linecap="round"/>
<path d="M48.2 22.6L57.8 13.6L60.6 26.4Z" fill="#F59E0B" stroke="#F59E0B" stroke-width="2" stroke-linejoin="round"/>
<g transform="rotate(-9 32 33)">
<rect x="11.5" y="16.5" width="41" height="33" rx="7.5" fill="#fff" stroke="#CBD5CF" stroke-width="2.2"/>
<rect x="15" y="20" width="16" height="12" rx="3.2" fill="#EDF2EE"/><rect x="33" y="20" width="16" height="12" rx="3.2" fill="#EDF2EE"/>
<rect x="15" y="34" width="16" height="12" rx="3.2" fill="#EDF2EE"/><rect x="33" y="34" width="16" height="12" rx="3.2" fill="#EDF2EE"/>
<ellipse cx="23" cy="26.4" rx="5.9" ry="3.9" fill="#fff" stroke="#E2E8E4" stroke-width=".6"/>
<circle cx="20.8" cy="25.8" r="1" fill="#41B649"/><circle cx="24.6" cy="25.1" r="1" fill="#41B649"/><circle cx="23.4" cy="28" r="1" fill="#41B649"/>
<rect x="39.2" y="26.4" width="2" height="3.8" rx=".9" fill="#86C96F"/>
<circle cx="37.9" cy="24.9" r="2.7" fill="#2E9E45"/><circle cx="41.3" cy="23.6" r="2.6" fill="#41B649"/><circle cx="40.4" cy="26.3" r="2.2" fill="#2E9E45"/>
<ellipse cx="45.4" cy="28.1" rx="2.5" ry="2" fill="#F59E0B"/>
<path d="M17.6 40.6C17.6 36.6 22 35.6 25.4 36.4C28.8 37.2 29.6 40.4 27.6 42.6C25.4 44.8 17.6 44.6 17.6 40.6Z" fill="#C8742F"/>
<path d="M20 39.2C21.8 38 24 37.8 26 38.6" stroke="#E6A461" stroke-width="1.2" fill="none" stroke-linecap="round"/>
<rect x="36.2" y="40.2" width="2.8" height="3.8" rx=".7" fill="#1E7B34"/><rect x="40" y="38" width="2.8" height="6" rx=".7" fill="#1E7B34"/><rect x="43.8" y="35.6" width="2.8" height="8.4" rx=".7" fill="#1E7B34"/>
</g>
</svg>`;
export const LOGO = MARK;
export const WORDMARK = '<span class="wordmark"><span class="w1">Eat</span><span class="w2">Back</span></span>';