eatback / js /start.js
kritpakin's picture
Roles, principal report, five bins, purchase order for the kitchen, print fix
9aaa92e verified
Raw History Blame Contribute Delete
10.8 kB
// Start page: sign in as one role and go to that role's own screens. Each card says what the role sees.
// With real school data a role signs in with its PIN; in the demo one tap picks the role, so the demo shows the same
// separation. A role that opens another role's screen is sent back to its own (core.js signIn, server/app.py SCREENS).
import { api, live, esc, toast, askPin, LOGO, WORDMARK, HOME, ROLE_ICON, SCREENS, roleName, screenOf } from './core.js';
import { T, onLang, langToggle, num, menuName, gradeName, gradeShort } from './i18n.js';
const $app = document.getElementById('app');
const next = new URLSearchParams(location.search).get('next');
let me = null;
let S = null;
let issues = [];
let menus = {};
let version = -1;
async function refresh() {
try {
me = await api('/api/auth/me');
// Real data: the day's tasks are school records, so they show only once a role has signed in.
S = null;
if (!me.required || me.role) {
let list;
[S, { issues }, { menus: list }] = await Promise.all([api('/api/state?grade=all'), api('/api/issues'), api('/api/menus')]);
menus = Object.fromEntries(list.map((m) => [m.id, m]));
}
render();
} catch (e) {
$app.innerHTML = `<div class="card"><h2>${T('โหลดไม่สำเร็จ', "Couldn't load")}</h2><p class="small">${esc(e.message)}</p></div>`;
}
}
live((t) => { if (t.version !== version) { version = t.version; refresh(); } });
onLang(render);
// Where to go after signing in: the page the person was sent here from, if this role may open it, else the role's home.
const target = (role) => {
const screen = next ? screenOf(next) : null;
return next && (!screen || SCREENS[screen].includes(role)) ? next : HOME[role];
};
const ROLES = {
kitchen: {
th: 'มือถือในครัว', en: 'Phone in the kitchen',
sees: [['หน้าครัว: เปิดรอบ ชั่งหม้อ ชั่ง 5 ถัง จบรอบ', 'Kitchen screen: rounds, pots, the 5 bins'], ['สูตรอาหาร และใบสั่งซื้อประจำสัปดาห์ (พิมพ์ได้)', 'Recipes and the weekly purchase order (printable)'], ['ตรวจเครื่องชั่งเช้า', 'Morning scale check'], ['กดข้อคิดเห็นแทนครูได้', "Can tap the kids' answers for a teacher"]],
},
teacher: {
th: 'มือถือหรือแท็บเล็ต', en: 'Phone or tablet',
sees: [['หน้าครู: ถามเด็กแล้วกด 1 ใน 6 ข้อ', 'Teacher screen: ask each child, tap one of six answers'], ['ไม่เห็นตัวเลขเศษหรือการตัดสินใจของโรงเรียน', "Does not see the school's leftovers or decisions"]],
},
admin: {
th: 'โน้ตบุ๊ก', en: 'Laptop',
sees: [['ทุกหน้า: ภาพรวม แนวโน้ม สิ่งที่ควรปรับ รายงานผู้บริหาร', 'Everything: overview, trends, fixes, the principal report'], ['เลือกวิธีแก้และเริ่มทดลอง', 'Picks the fix and starts the trial'], ['เมนู สูตร แผนรายสัปดาห์และใบสั่งซื้อ', 'Menus, recipes, the weekly plan and purchase order'], ['ตั้งค่าโรงเรียนและ PIN', 'School settings and PINs']],
},
viewer: {
th: 'ดูอย่างเดียว', en: 'Read only',
sees: [['รายงานประจำเดือน: เด็กได้รับอะไร งบประมาณ เศษคิดเป็นเงิน เมนูที่ต้องตัดสินใจ', 'Monthly report: what children got, budget, leftovers in money, decisions'], ['ภาพรวมทุกชั้น แนวโน้มเมนู สิ่งที่ควรปรับ', 'Every grade, menu trends, fixes'], ['แก้ข้อมูลหรือตัดสินใจแทนไม่ได้', "Can't change data or decide"]],
},
};
// Today's job for each role, from the school's rounds and decisions (only once the data may be read).
function todo() {
if (!S) return {};
const rounds = S.overview?.rounds ?? [];
const withMeal = rounds.filter((r) => r.meal);
const done = withMeal.filter((r) => r.meal.status === 'closed').length;
const open = withMeal.find((r) => r.meal.status === 'open');
const ask = rounds.filter((r) => r.will_investigate || (r.meal?.investigation && r.meal.status !== 'closed'));
const decide = issues.filter((x) => x.stage === 'decide' || x.stage === 'not_verified');
const testing = issues.filter((x) => x.stage === 'testing');
const acc = S.overview?.totals?.acceptance_pct;
const menuOf = (r) => (r.menu ? esc(menuName(r.menu)) : '');
return {
kitchen: [open ? T(`กำลังเสิร์ฟ ${gradeName(open.grade)} · ชั่งหม้อและจบรอบให้ครบ`, `Serving ${gradeName(open.grade)} · weigh the pots and end the round`)
: !S.qc.all_ok ? T('เริ่มจากตรวจเครื่องชั่งเช้านี้', "Start with this morning's scale check")
: done < withMeal.length ? T(`เริ่มรอบถัดไป · เหลือ ${withMeal.length - done} ชั้น`, `Start the next round · ${withMeal.length - done} grades to go`)
: T('วันนี้ทุกชั้นจบรอบแล้ว', 'Every grade is done today'),
T(`รอบวันนี้ จบแล้ว ${num(done)} จาก ${num(withMeal.length)} ชั้น`, `Rounds today: ${num(done)} of ${num(withMeal.length)} done`)],
teacher: [ask.length ? T(`วันนี้ต้องถามเด็ก ${ask.length} ชั้น`, `Ask the children in ${ask.length} grade${ask.length > 1 ? 's' : ''} today`) : T('วันนี้ไม่มีชั้นที่ต้องถามเด็ก', 'No grade needs asking today'),
ask.map((r) => `${gradeShort(r.grade)} · ${menuOf(r)}`).join(' · ')],
admin: [decide.length ? T(`รอตัดสินใจ ${decide.length} เรื่อง`, `${decide.length} decision${decide.length > 1 ? 's' : ''} waiting`) : T('ยังไม่มีเรื่องที่รอตัดสินใจ', 'No decision waiting'),
decide.slice(0, 3).map((x) => `${gradeShort(x.grade)} · ${menus[x.menu_id] ? esc(menuName(menus[x.menu_id])) : esc(x.menu_id)}`).join(' · ')],
viewer: [acc == null ? T('ยังไม่มีรอบที่จบวันนี้', 'No round finished yet today') : T(`วันนี้อาหารที่ไม่กลับมาเป็นเศษ ${Math.round(acc)}%`, `Today ${Math.round(acc)}% of the food did not come back`),
T(`กำลังทดลองแก้ ${testing.length} เมนู · ผ่านเกณฑ์การกินแล้ว ${issues.filter((x) => x.stage === 'verified').length}`, `${testing.length} fixes on trial · ${issues.filter((x) => x.stage === 'verified').length} met the eating goal`)],
};
}
function render() {
if (!me) return;
document.title = `EatBack · ${T('เข้าใช้', 'Sign in')}`;
const jobs = todo();
const mine = me.role;
const mode = me.required
? `<span class="chip crit">${T('ข้อมูลจริงของโรงเรียน · เลือกบทบาทแล้วใส่ PIN', 'Real school data · pick your role and enter its PIN')}</span>`
: `<span class="chip">${T('ข้อมูลเดโม · เลือกบทบาทเพื่อดูหน้าจอของบทบาทนั้น ไม่ต้องใช้ PIN', 'Demo data · pick a role to see its screens, no PIN')}</span>`;
const who = mine
? `<span class="chip brand">${ROLE_ICON[mine]} ${T(`เข้าใช้เป็น${roleName(mine)}`, `Signed in: ${roleName(mine)}`)}</span>
<button class="btn sm ghost" data-do="logout">${T('ออกจากระบบ', 'Sign out')}</button>` : '';
const card = (role) => {
const r = ROLES[role];
const [job, detail] = jobs[role] ?? [];
const button = role === mine
? `<a class="btn primary" href="${esc(target(role))}">${T('ไปหน้าของฉัน', 'Go to my screens')} →</a>`
: `<button class="btn${mine ? '' : ' primary'}" data-role="${role}">${mine ? T(`สลับเป็น${roleName(role)}`, `Switch to ${roleName(role)}`) : T(`เข้าใช้เป็น${roleName(role)}`, `Sign in as ${roleName(role)}`)}${me.required ? ' 🔒' : ''}</button>`;
return `<section class="role${role === mine ? ' mine' : ''}" data-card="${role}">
<div class="role-head"><div class="food c1" aria-hidden="true">${ROLE_ICON[role]}</div><div><h2>${roleName(role)}</h2><small>${T(r.th, r.en)}</small></div></div>
${job ? `<div class="todo">${job}</div>${detail ? `<div class="small muted">${detail}</div>` : ''}` : ''}
<div class="sees"><span class="small muted">${T('เห็นหน้า', 'Sees')}</span><ul>${r.sees.map(([th, en]) => `<li>${T(th, en)}</li>`).join('')}</ul></div>
<div class="actions">${button}</div>
</section>`;
};
$app.innerHTML = `<header class="st-top">${LOGO}<div style="flex:1;min-width:0"><h1>${WORDMARK} <span class="st-title">${T('เข้าใช้', 'Sign in')}</span></h1>
<div class="small muted">${esc(S?.settings.school_name ?? '')}</div></div>${langToggle()}</header>
<div class="st-mode">${mode} ${who}${next && !mine ? ` <span class="chip warn">${T('หน้าที่เปิดต้องเข้าใช้ด้วยบทบาทก่อน', 'That screen needs a signed-in role first')}</span>` : ''}</div>
<div class="roles">${['kitchen', 'teacher', 'admin', 'viewer'].map(card).join('')}</div>`;
}
async function enter(role) {
if (me.required) {
if (!await askPin({ need: role, need_th: roleName(role) })) return;
} else {
await api('/api/auth/login', { role });
}
me = await api('/api/auth/me');
location.href = target(me.role);
}
$app.addEventListener('click', async (e) => {
if (e.target.closest('[data-do="logout"]')) {
await api('/api/auth/logout', {});
toast(T('ออกจากระบบแล้ว', 'Signed out'));
await refresh();
return;
}
const b = e.target.closest('[data-role]');
if (b) {
b.disabled = true;
try { await enter(b.dataset.role); } catch (err) { toast(err.message, true); } finally { b.disabled = false; }
}
});
refresh();