Spaces:
Running
Running
Download js/planner.js from eatbackhackathon2026/eatback: direct link, hf CLI and curl.
- Browser
- Download file 34.7 kB
-
https://huggingface.co/spaces/eatbackhackathon2026/eatback/resolve/main/js/planner.js
- Command line
-
hf download hf://spaces/eatbackhackathon2026/eatback/js/planner.js
-
curl -L -o planner.js https://huggingface.co/spaces/eatbackhackathon2026/eatback/resolve/main/js/planner.js
34.7 kB
| import { api, esc, LOGO, WORDMARK, toast, signIn, roleChip, isAdmin, printPage, printIfAsked } from './core.js'; | |
| import { T, onLang, langToggle, num, menuName, gradeName, gradeShort, date as displayDate, longDate, unitLabel, ingredientName, recipeSteps, recipeTips, errorText } from './i18n.js'; | |
| const params = new URLSearchParams(location.search); | |
| const localYmd = (d = new Date()) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; | |
| const dateObj = (s) => new Date(`${s}T12:00:00`); | |
| const addDays = (s, days) => { const d = dateObj(s); d.setDate(d.getDate() + days); return localYmd(d); }; | |
| const monday = (s) => { const d = dateObj(s); return addDays(s, -((d.getDay() + 6) % 7)); }; | |
| const today = localYmd(); | |
| const initialWeek = new Date().getDay() % 6 === 0 ? addDays(monday(today), 7) : monday(today); | |
| const key = (day, grade) => `${day}:${grade}`; | |
| let data = null, shopping = null, busy = false, loadVersion = 0; | |
| const state = { week: /^\d{4}-\d{2}-\d{2}$/.test(params.get('week') || '') ? params.get('week') : initialWeek, grades: [], view: 'plan', recipes: true, draft: new Map(), expanded: new Set() }; | |
| function chosenGrades() { return data.settings.grades.filter((g) => state.grades.includes(g)); } | |
| function cellMeals(day, grade) { return data.meals.filter((m) => m.date === day && m.grade === grade); } | |
| function editable(day, grade) { return day >= today && cellMeals(day, grade).every((m) => m.editable); } | |
| function original(day, grade) { | |
| const m = cellMeals(day, grade)[0]; | |
| return { date: day, grade, menu_id: m?.menu_id || null, students: m?.students ?? data.settings.grade_students[grade] ?? 1 }; | |
| } | |
| function cell(day, grade) { return state.draft.get(key(day, grade)) || original(day, grade); } | |
| function changeCell(day, grade, patch) { | |
| if (!editable(day, grade)) return; | |
| const orig = original(day, grade), next = { ...cell(day, grade), ...patch }; | |
| if (next.menu_id === orig.menu_id && next.students === orig.students) state.draft.delete(key(day, grade)); | |
| else state.draft.set(key(day, grade), next); | |
| shopping = null; | |
| document.body.classList.remove('can-print'); | |
| } | |
| function menu(id) { return data.menus.find((m) => m.id === id); } | |
| function options(selected, placeholder) { return `<option value="">${esc(placeholder)}</option>${data.menus.map((m) => `<option value="${esc(m.id)}"${m.id === selected ? ' selected' : ''}>${esc(menuName(m))}${!m.has_recipe ? T(' · ยังไม่มีสูตร', ' · no recipe') : ''}</option>`).join('')}`; } | |
| function range(week = data.week, end = data.end) { return `${displayDate(week)} – ${displayDate(end)} ${dateObj(week).getFullYear() + T(543, 0)}`; } | |
| function scopeLabel() { return chosenGrades().length === data.settings.grades.length ? T('ทั้งโรงเรียน', 'Whole school') : chosenGrades().map(gradeShort).join(', '); } | |
| function mealStatus(m) { return m.status === 'closed' ? T('จบมื้อแล้ว', 'Completed') : m.status === 'open' ? T('กำลังกิน', 'In progress') : m.origin === 'trial' || m.action_id ? T('จองทดลองแก้', 'Reserved trial') : T('วางแผนแล้ว', 'Planned'); } | |
| function provenanceNote(cssClass = 'sheet-warning', m = null, recipe = null) { | |
| const recipeOrigin = recipe?.data_origin || m?.data_provenance?.recipe?.origin; | |
| const costOrigin = m?.data_provenance?.cost?.origin; | |
| const recipeLabel = recipeOrigin === 'user' ? T('สูตรและปริมาณวัตถุดิบ: ผู้ใช้กรอก ยังไม่ตรวจสอบ', 'Recipe and ingredient amounts: user-entered, unverified') : T('สูตรและปริมาณวัตถุดิบตั้งต้น: ประมาณการ DEMO', 'Seed recipe and ingredient amounts: DEMO estimates'); | |
| const costLabel = costOrigin === 'user' ? T('ต้นทุน: ผู้ใช้กรอก ยังไม่ตรวจสอบ', 'Cost: user-entered, unverified') : T('ต้นทุนตั้งต้น: ประมาณการ DEMO', 'Seed cost: DEMO estimate'); | |
| return `<div class="${cssClass}"><span><b>${T('ที่มาข้อมูล · ยังไม่ผ่านการตรวจสอบ', 'Data source · unverified')}</b><br>${recipeLabel} · ${costLabel}<br>${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.')}</span></div>`; | |
| } | |
| function syncUrl() { | |
| const query = new URLSearchParams({ week: state.week }); | |
| if (chosenGrades().length !== data.settings.grades.length) query.set('grades', chosenGrades().join(',')); | |
| history.replaceState(null, '', `/planner.html?${query}`); | |
| } | |
| async function load(week) { | |
| const version = ++loadVersion; | |
| busy = true; | |
| if (data) render(); | |
| try { | |
| const result = await api(`/api/planner?week=${encodeURIComponent(week)}`); | |
| if (version !== loadVersion) return; | |
| data = result; state.week = result.week; shopping = null; state.draft.clear(); state.expanded.clear(); | |
| if (!state.grades.length) state.grades = (params.get('grades') || params.get('grade') || '').split(',').filter((g) => data.settings.grades.includes(g)); | |
| state.grades = state.grades.filter((g) => data.settings.grades.includes(g)); | |
| if (!state.grades.length) state.grades = [...data.settings.grades]; | |
| state.view = isAdmin() ? 'plan' : 'shopping'; syncUrl(); | |
| } catch (e) { | |
| if (data) toast(errorText(e.message), true); | |
| else document.getElementById('main').innerHTML = `<div class="empty"><h1>${T('โหลดแผนไม่สำเร็จ', 'Could not load the plan')}</h1><p>${esc(errorText(e.message))}</p><button class="btn primary" id="retry">${T('ลองอีกครั้ง', 'Try again')}</button></div>`; | |
| } finally { if (version === loadVersion) { busy = false; if (data) render(); else document.getElementById('retry')?.addEventListener('click', () => load(week)); } } | |
| // Only the coordinator plans; the kitchen gets the saved week's purchase order and recipes straight away. | |
| if (version === loadVersion && data && !isAdmin()) await openShopping(); | |
| } | |
| function renderHeader() { | |
| document.title = `${isAdmin() ? T('วางเมนูรายสัปดาห์', 'Weekly meal planner') : T('ใบสั่งซื้อประจำสัปดาห์', 'Weekly purchase order')} · EatBack`; | |
| const header = document.getElementById('header'); header.className = 'app-header planner-header'; | |
| header.innerHTML = `<div class="hdr-row"><a class="brand" href="${isAdmin() ? '/' : '/kitchen.html'}">${LOGO}<div><div class="brand-name">${WORDMARK}</div><div class="brand-sub">${esc(data.settings.school_name)}</div></div></a><nav class="nav" aria-label="${T('เมนูหลัก', 'Main navigation')}">${isAdmin() ? `<a href="/">${T('ภาพรวม', 'Overview')}</a><a href="/#/menus">${T('เมนูและสูตร', 'Menus & recipes')}</a><a class="active" href="/planner.html" aria-current="page">${T('วางเมนูรายสัปดาห์', 'Weekly planner')}</a>` : `<a class="active" href="/planner.html" aria-current="page">${T('ใบสั่งซื้อประจำสัปดาห์', 'Weekly purchase order')}</a>`}</nav><div class="header-right"><a class="btn ghost sm" href="/kitchen.html">${T('เข้าครัว', 'Kitchen')} ↗</a>${roleChip()}${langToggle()}</div></div>`; | |
| } | |
| function render() { | |
| renderHeader(); | |
| const grades = chosenGrades(), dirty = state.draft.size; | |
| document.body.classList.toggle('can-print', state.view === 'shopping' && !!shopping && !dirty && shopping.shopping.meal_count > 0); | |
| document.body.classList.toggle('hide-recipes', !state.recipes); | |
| const main = document.getElementById('main'); main.className = 'planner-main'; | |
| main.innerHTML = `<section class="planner-hero"><div><p class="eyebrow">${T('จากแผนมื้อกลางวัน สู่ครัวโรงเรียน', 'FROM WEEKLY MENUS TO THE SCHOOL KITCHEN')}</p>${isAdmin() ? `<h1>${T('วางเมนูทั้งสัปดาห์', 'Plan lunches for the week')}</h1><p class="sub">${T('เลือกเมนูวันจันทร์–ศุกร์ ปรับจำนวนเด็กแยกชั้น แล้วรวมวัตถุดิบเป็นใบสั่งซื้อและสูตรสำหรับครัวในครั้งเดียว', 'Plan Monday to Friday, adjust head counts by grade, then bring the shopping list and scaled recipes together for your kitchen.')}</p>` | |
| : `<h1>${T('ใบสั่งซื้อและสูตรประจำสัปดาห์', "This week's purchase order and recipes")}</h1><p class="sub">${T('จากแผนที่ผู้ดูแลบันทึกไว้ รวมวัตถุดิบตามจำนวนเด็กของแต่ละชั้น เลือกสัปดาห์หรือชั้นแล้วพิมพ์ได้เลย แก้แผนได้ที่ผู้ดูแล', 'From the plan the coordinator saved, with ingredients for each grade’s head count. Pick a week or grades and print; the coordinator edits the plan.')}</p>`}</div><div class="hero-stamp"><strong>5</strong><span>${T('วันเรียน วางแผนได้ในหน้าเดียว', 'school days, one plan')}</span></div></section> | |
| <section class="card flat planner-controls"><div class="planner-toolbar"><div class="week-controls"><button class="btn" id="prev-week" aria-label="${T('สัปดาห์ก่อน', 'Previous week')}"${busy ? ' disabled' : ''}>←</button><label class="field">${T('สัปดาห์ของวันที่', 'Week containing')}<input type="date" id="week" value="${state.week}"${busy ? ' disabled' : ''}></label><button class="btn" id="next-week" aria-label="${T('สัปดาห์ถัดไป', 'Next week')}"${busy ? ' disabled' : ''}>→</button></div><div class="planner-tabs" role="group" aria-label="${T('มุมมองแผน', 'Plan view')}">${isAdmin() ? `<button id="view-plan" aria-pressed="${state.view === 'plan'}"${busy ? ' disabled' : ''}>${T('1. วางเมนู', '1. Plan meals')}</button>` : ''}<button id="view-shopping" aria-pressed="${state.view === 'shopping'}"${busy ? ' disabled' : ''}>${(isAdmin() ? T('2. ใบสั่งซื้อและสูตร', '2. Shopping & recipes') : T('ใบสั่งซื้อและสูตร', 'Shopping & recipes'))}</button></div></div><div class="planner-scope"><span class="scope-label">${T('เลือกชั้น', 'Grades')}</span><button class="gchip${grades.length === data.settings.grades.length ? ' on' : ''}" id="all-grades" aria-pressed="${grades.length === data.settings.grades.length}"${busy ? ' disabled' : ''}>${T('ทุกชั้น', 'All grades')}</button>${data.settings.grades.map((g) => `<button class="gchip${grades.includes(g) ? ' on' : ''}" data-grade="${g}" aria-pressed="${grades.includes(g)}"${busy ? ' disabled' : ''}>${gradeShort(g)}</button>`).join('')}<span class="spacer"></span><span class="small ink2">${range()}</span></div></section> | |
| ${state.view === 'plan' ? `${provenanceNote('planner-note warn')}${renderPlan()}` : renderShopping()} | |
| <p class="print-unavailable">${T('บันทึกแผนและเปิดแท็บ “ใบสั่งซื้อและสูตร” ก่อนพิมพ์', 'Save your plan and open “Shopping & recipes” before printing.')}</p>`; | |
| bind(); | |
| } | |
| function renderPlan() { | |
| const grades = chosenGrades(); | |
| return `<div class="planner-editor"><div class="planner-note"><span aria-hidden="true">↳</span><span>${T('เลือกเมนูในแต่ละวันเพื่อใช้กับชั้นที่เลือกทั้งหมด กด “ปรับแยกรายชั้น” เพื่อเปลี่ยนเมนูหรือจำนวนเด็กเฉพาะชั้น มื้อทดลองและมื้อที่เริ่มแล้วจะคงไว้', 'Choose a daily menu for every selected grade. Open “Adjust by grade” to change an individual menu or head count. Reserved trials and started meals are kept.')}</span></div><div class="week-grid">${data.dates.map((day, index) => { | |
| const cells = grades.map((g) => cell(day, g)), filled = cells.filter((c) => c.menu_id), unique = [...new Set(filled.map((c) => c.menu_id))], m = unique.length === 1 ? menu(unique[0]) : null; | |
| const canEdit = grades.some((g) => editable(day, g)); | |
| return `<article class="day-card"><div class="day-head"><div><h2>${T(['จันทร์', 'อังคาร', 'พุธ', 'พฤหัสบดี', 'ศุกร์'][index], ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'][index])}</h2><small>${displayDate(day)}</small></div><span class="day-number">${day.slice(-2)}</span></div><div class="day-content"><div class="day-menu-icon" aria-hidden="true">${esc(m?.icon || (filled.length ? '🍱' : '🥣'))}</div><p class="day-menu-name">${m ? esc(menuName(m)) : filled.length ? T('หลายเมนู แยกตามชั้น', 'Different menus by grade') : T('วันนี้กินอะไรดี', 'What’s for lunch?')}</p><p class="day-progress">${num(filled.length)} / ${num(grades.length)} ${T('ชั้นมีเมนูแล้ว', 'grades planned')} · ${num(filled.reduce((sum, c) => sum + (Number(c.students) || 0), 0))} ${T('คน', 'students')}</p><label class="field">${T('ใช้เมนูนี้กับชั้นที่เลือก', 'Menu for selected grades')}<select class="bulk-select" data-day-menu="${day}"${!canEdit || busy ? ' disabled' : ''}>${options('', canEdit ? T('เลือกเมนูของวันนี้…', 'Choose a daily menu…') : T('ดูแผนย้อนหลัง', 'Past meals'))}</select></label><details class="day-grades" data-details="${day}"${state.expanded.has(day) ? ' open' : ''}><summary>${T('ปรับแยกรายชั้น / จำนวนเด็ก', 'Adjust by grade / head count')}</summary>${grades.map((g) => renderGradeCell(day, g)).join('')}</details></div></article>`; | |
| }).join('')}</div></div><div class="planner-savebar"><p><b>${state.draft.size ? T(`แก้ไข ${num(state.draft.size)} มื้อ ยังไม่บันทึก`, `${num(state.draft.size)} unsaved meal changes`) : T('แผนที่บันทึกไว้พร้อมใช้งาน', 'Your saved plan is ready')}</b><small>${T('จำนวนวัตถุดิบคิดจากจำนวนเด็ก × สัดส่วนตักของแต่ละชั้น', 'Ingredient amounts use head count × each grade’s portion size')}</small></p>${state.draft.size ? `<button class="btn ghost" id="discard"${busy ? ' disabled' : ''}>${T('ยกเลิกการแก้', 'Discard changes')}</button>` : ''}<button class="btn primary" id="save"${busy || !state.draft.size ? ' disabled' : ''}>${busy ? T('กำลังบันทึก…', 'Saving…') : T('บันทึกแผนทั้งสัปดาห์', 'Save weekly plan')}</button><button class="btn" id="save-preview"${busy ? ' disabled' : ''}>${state.draft.size ? T('บันทึกและดูใบสั่งซื้อ', 'Save & view shopping') : T('ดูใบสั่งซื้อ', 'View shopping')} →</button></div>`; | |
| } | |
| function renderGradeCell(day, grade) { | |
| const c = cell(day, grade), rows = cellMeals(day, grade), canEdit = editable(day, grade), dirty = state.draft.has(key(day, grade)); | |
| return `<div class="grade-plan"><div class="grade-plan-top"><b>${gradeShort(grade)}${dirty ? ' •' : ''}</b><label class="grade-headcount"><span class="sr-only">${gradeName(grade)} ${displayDate(day)} ${T('จำนวนนักเรียน', 'students')}</span><input type="number" min="1" max="2000" step="1" inputmode="numeric" value="${esc(c.students)}" data-count-day="${day}" data-count-grade="${grade}"${!canEdit || busy ? ' disabled' : ''}><span>${T('คน', 'kids')}</span></label></div>${canEdit ? `<select aria-label="${gradeName(grade)} ${displayDate(day)} ${T('เมนู', 'menu')}" data-cell-day="${day}" data-cell-grade="${grade}"${busy ? ' disabled' : ''}>${options(c.menu_id, T('ยังไม่วางเมนู / ล้างเมนู', 'No menu / clear menu'))}</select>` : `<div class="locked-menu">${rows.length ? rows.map((m) => esc(menuName(m.menu || menu(m.menu_id)))).join('<br>') : T('ไม่มีมื้อที่บันทึกไว้', 'No recorded meal')}</div>`}${!canEdit && rows.length ? `<span class="chip ${rows.some((m) => m.origin === 'trial') ? 'warn' : ''}">🔒 ${[...new Set(rows.map(mealStatus))].join(' · ')}</span>` : ''}</div>`; | |
| } | |
| function quantity(qty, unit, roundCount = false) { | |
| if (qty == null || qty === '' || !Number.isFinite(Number(qty))) return { label: T('ระบุเพิ่ม', 'Specify'), unit: unitLabel(unit || '') }; | |
| let value = Number(qty), u = unit; | |
| if ((u === 'ก.' || u === 'กรัม') && value >= 1000) { value /= 1000; u = 'กก.'; } | |
| else if (u === 'มล.' && value >= 1000) { value /= 1000; u = 'ลิตร'; } | |
| if (roundCount && ['ฟอง', 'ผล', 'ชิ้น', 'หลอด', 'ห่อ'].includes(u)) value = Math.ceil(value - 1e-9); | |
| return { label: num(value, Number.isInteger(value) ? 0 : value < 1 ? 3 : 2), unit: unitLabel(u || '') }; | |
| } | |
| function renderShopping() { | |
| if (!shopping) return `<div class="planner-note" role="status">${busy ? T('กำลังรวมวัตถุดิบ…', 'Building your shopping list…') : T('ยังไม่มีใบสั่งซื้อ กด “ใบสั่งซื้อและสูตร” เพื่อลองอีกครั้ง', 'No shopping list loaded. Open “Shopping & recipes” to retry.')}</div>`; | |
| const report = shopping.shopping, meals = shopping.meals, hasMeals = report.meal_count > 0; | |
| if (!hasMeals) return `<div class="empty"><h2>${T('เริ่มจากเมนูมื้อแรกของสัปดาห์', 'Start with the first lunch of the week')}</h2><p class="ink2">${T('ยังไม่มีเมนูของชั้นที่เลือกในสัปดาห์นี้ วางเมนูและบันทึกแล้วระบบจะรวมวัตถุดิบให้', 'There are no meals for the selected grades this week. Save a plan to build your ingredient list.')}</p>${isAdmin() ? `<button class="btn primary" id="empty-plan">${T('กลับไปวางเมนู', 'Plan meals')}</button>` : `<p class="ink2">${T('ผู้ดูแลยังไม่ได้วางแผนของสัปดาห์นี้ ลองเลือกสัปดาห์อื่น', 'The coordinator has not planned this week yet; try another week.')}</p>`}</div>`; | |
| const plannedOnly = meals.filter((m) => m.status === 'planned').length === meals.length; | |
| return `<div class="print-actions"><div><b>${T('ร่างรายการสำหรับครัว · ตรวจสอบก่อนใช้จริง', 'Kitchen draft · review before real use')}</b><p class="small ink2">${T('รวมวัตถุดิบจากแผนที่บันทึกไว้ของชั้นที่เลือก', 'Ingredients from the saved plan for your selected grades')}</p></div><div class="row wrap"><label><input type="checkbox" id="include-recipes"${state.recipes ? ' checked' : ''}>${T('แนบสูตรทั้งสัปดาห์', 'Include weekly recipes')}</label><button class="btn primary" id="print">${T('พิมพ์ใบสั่งซื้อ', 'Print shopping list')} ↗</button></div></div><article class="purchase-sheet"><div class="purchase-brand">${LOGO}${WORDMARK}<div class="school-info">${esc(data.settings.school_name)}<br>${T('จัดทำวันที่', 'Prepared')} ${longDate(localYmd())}</div></div><div class="purchase-title"><h2>${T('ใบสั่งซื้อวัตถุดิบรายสัปดาห์', 'Weekly ingredient order')}</h2><p>${range()} · ${esc(scopeLabel())}</p></div><div class="purchase-stats"><div><strong>${num(report.meal_count)}</strong><span>${T('มื้อแยกชั้น', 'grade meals')}</span></div><div><strong>${num(report.student_servings)}</strong><span>${T('ที่เสิร์ฟตลอดสัปดาห์', 'student servings this week')}</span></div><div><strong>${num(report.ingredients.length)}</strong><span>${T('รายการวัตถุดิบ', 'ingredient entries')}</span></div></div> | |
| ${provenanceNote()} | |
| ${!plannedOnly ? `<div class="sheet-warning">${T('สัปดาห์นี้มีมื้อที่เริ่มหรือจบแล้ว ใบนี้รวมทุกมื้อที่บันทึกในสัปดาห์ของชั้นที่เลือก โปรดตรวจรายการที่ซื้อแล้วก่อนสั่งเพิ่ม', 'This week includes started or completed meals. This list includes every recorded meal for the selected grades; check what has already been purchased before ordering.')}</div>` : ''} | |
| ${report.warnings.length ? `<div class="sheet-warning"><b>${T('มีข้อมูลต้องเติมก่อนสั่งซื้อ', 'Details to complete before ordering')}</b><ul>${report.warnings.map((w) => `<li>${esc(T(w.message, w.message_en || w.message))}</li>`).join('')}</ul></div>` : ''} | |
| <h3>${T('วัตถุดิบรวมทั้งสัปดาห์', 'Combined ingredients')}</h3><table class="purchase-table"><thead><tr><th class="tick"><span class="sr-only">${T('เช็ก', 'Check')}</span></th><th>${T('วัตถุดิบ', 'Ingredient')}</th><th class="qty">${T('จำนวน', 'Amount')}</th><th class="unit">${T('หน่วย', 'Unit')}</th><th class="notes">${T('รับจริง / หมายเหตุ', 'Received / notes')}</th></tr></thead><tbody>${report.ingredients.map((i) => { const q = quantity(i.qty, i.unit, true); return `<tr><td class="tick"><span></span></td><td>${esc(ingredientName(i))}${i.incomplete ? `<br><small>${T('ยังมีส่วนที่ไม่ระบุปริมาณ', 'Some quantities are missing')}</small>` : ''}</td><td class="qty">${q.label}${i.incomplete && i.qty != null ? '+' : ''}</td><td class="unit">${esc(q.unit)}</td><td class="notes"></td></tr>`; }).join('')}</tbody></table> | |
| <h3>${T('แผนเมนูที่ใช้คำนวณ', 'Meals included in this order')}</h3><table class="purchase-table"><thead><tr><th>${T('วัน', 'Day')}</th><th>${T('เมนู / ชั้น', 'Menu / grades')}</th><th class="qty">${T('คน', 'Students')}</th></tr></thead><tbody>${scheduleRows(meals)}</tbody></table><p class="sheet-foot">${T('คิดปริมาณจากจำนวนเด็กและสัดส่วนตักตามวัยที่ตั้งไว้ รวมวัตถุดิบชื่อเดียวกันเมื่อแปลงหน่วยได้ ของนับเป็นชิ้นปัดขึ้นหลังรวมทั้งสัปดาห์ ปริมาณนี้ยังไม่หักสต็อกคงเหลือ', 'Amounts use each grade’s head count and configured portion size. Matching ingredients are combined when their units are compatible. Counted items round up after the weekly total. Existing stock has not been deducted.')}</p><div class="sheet-signatures"><span>${T('ผู้จัดทำ', 'Prepared by')} ____________________</span><span>${T('ผู้ตรวจรับ / วันที่', 'Received by / date')} ____________________</span></div> | |
| <section class="weekly-recipes">${report.recipes.map(renderRecipe).join('')}</section></article>`; | |
| } | |
| function scheduleRows(meals) { | |
| const rows = new Map(); | |
| for (const m of meals) { const k = `${m.date}:${m.menu_id}:${m.status}:${m.origin === 'trial' ? 'trial' : ''}`; if (!rows.has(k)) rows.set(k, { ...m, entries: [] }); rows.get(k).entries.push(m); } | |
| return [...rows.values()].sort((a, b) => a.date.localeCompare(b.date)).map((r) => `<tr><td>${displayDate(r.date, true)}</td><td><b>${esc(menuName(r.menu || menu(r.menu_id)))}</b><div class="days">${r.entries.map((m) => `${gradeShort(m.grade)} (${num(m.students)})`).join(' · ')}</div>${r.status !== 'planned' || r.origin === 'trial' ? `<span class="status">${mealStatus(r)}</span>` : ''}</td><td class="qty">${num(r.entries.reduce((sum, m) => sum + Number(m.students), 0))}</td></tr>`).join(''); | |
| } | |
| function renderRecipe(item) { | |
| const r = item.recipe, m = item.menu, dates = [...new Set(item.meals.map((row) => row.date))]; | |
| return `<article class="weekly-recipe">${provenanceNote('sheet-warning', m, r)}<div class="weekly-recipe-head"><span class="day-menu-icon" aria-hidden="true">${esc(m.icon || '🍽️')}</span><div><h3>${esc(menuName(m))}</h3><p>${T('สูตรรวมสำหรับสัปดาห์', 'Weekly recipe total')} ${range()}</p></div></div><div class="recipe-meta">${T('รวม', 'Total')} ${num(item.students)} ${T('ที่เสิร์ฟ', 'student servings')} · ${T('ใช้วัตถุดิบเท่ากับ', 'Equal to')} ${num(item.portion_servings, 2)} ${T('ที่เต็ม', 'full portions')}${r ? ` · ${T('สูตรตั้งต้น', 'Base recipe')} ${num(r.servings)} × ${num(item.factor, 3)}` : ''}<br>${T('ใช้วันที่', 'Scheduled')} ${dates.map((d) => displayDate(d, true)).join(' · ')}<br>${T('แยกมื้อ', 'By meal')}: ${item.meals.map((row) => `${displayDate(row.date)} ${gradeShort(row.grade)} ${num(row.students)} ${T('คน', 'students')}`).join(' · ')}</div>${r ? `<div class="weekly-recipe-grid"><div><h4>${T('วัตถุดิบรวมของเมนูนี้', 'Weekly ingredients for this menu')}</h4><table class="purchase-table"><tbody>${r.ingredients.map((i) => { const q = quantity(i.qty == null || i.qty === '' ? null : Number(i.qty) * item.factor, i.unit, true); return `<tr><td>${esc(ingredientName(i))}</td><td class="qty">${q.label}</td><td class="unit">${esc(q.unit)}</td></tr>`; }).join('')}</tbody></table></div><div><h4>${T('วิธีทำ', 'Method')}</h4><ol>${(recipeSteps(r) || []).map((step) => `<li>${esc(step)}</li>`).join('')}</ol>${recipeTips(r) ? `<p class="recipe-tip">${esc(recipeTips(r))}</p>` : ''}</div></div><p class="sheet-foot">${T('สูตรนี้เป็นยอดรวมทั้งสัปดาห์ ให้แบ่งเตรียมตามวันและจำนวนเด็กแต่ละมื้อ ของนับเป็นชิ้นปัดขึ้นต่อเมนู จึงอาจต่างจากยอดรวมในใบสั่งซื้อเล็กน้อย', 'This is the weekly total for this recipe. Prepare each lunch according to its day and head count. Counted items round up per menu, so totals may differ slightly from the combined order.')}</p>` : `<div class="sheet-warning">${T('เมนูนี้ยังไม่มีสูตร จึงยังไม่รวมวัตถุดิบในใบสั่งซื้อ', 'This menu has no recipe, so its ingredients are not included in the order.')}</div>`}</article>`; | |
| } | |
| async function save(showShopping = false) { | |
| if (busy) return; | |
| const entries = [...state.draft.values()]; | |
| if (entries.some((e) => !Number.isInteger(e.students) || e.students < 1 || e.students > 2000)) { toast(T('จำนวนนักเรียนต้องเป็นจำนวนเต็ม 1–2,000 คน', 'Head counts must be whole numbers from 1 to 2,000.'), true); return; } | |
| if (entries.length) { | |
| busy = true; render(); | |
| try { data = await api('/api/planner/save', { week: state.week, entries }); state.draft.clear(); shopping = null; toast(T('บันทึกแผนทั้งสัปดาห์แล้ว', 'Weekly plan saved')); } | |
| catch (e) { toast(errorText(e.message), true); busy = false; render(); return; } | |
| busy = false; render(); | |
| } | |
| if (showShopping) await openShopping(); | |
| } | |
| async function openShopping() { | |
| if (busy) return; | |
| if (state.draft.size) { await save(true); return; } | |
| busy = true; state.view = 'shopping'; shopping = null; render(); | |
| try { shopping = await api(`/api/planner?week=${encodeURIComponent(state.week)}&grades=${encodeURIComponent(chosenGrades().join(','))}`); } | |
| catch (e) { toast(errorText(e.message), true); } | |
| finally { busy = false; render(); } | |
| } | |
| function switchWeek(week) { | |
| if (busy || !/^\d{4}-\d{2}-\d{2}$/.test(week) || !Number.isFinite(dateObj(week).getTime())) return; | |
| if (state.draft.size && !confirm(T('มีแผนที่ยังไม่บันทึก ต้องการละทิ้งการแก้ไขและเปลี่ยนสัปดาห์หรือไม่', 'Discard your unsaved changes and switch weeks?'))) { render(); return; } | |
| load(week); | |
| } | |
| function bind() { | |
| document.getElementById('week').addEventListener('change', (e) => switchWeek(e.target.value)); | |
| document.getElementById('prev-week').addEventListener('click', () => switchWeek(addDays(state.week, -7))); | |
| document.getElementById('next-week').addEventListener('click', () => switchWeek(addDays(state.week, 7))); | |
| document.getElementById('view-plan')?.addEventListener('click', () => { state.view = 'plan'; render(); }); | |
| document.getElementById('view-shopping').addEventListener('click', openShopping); | |
| document.getElementById('all-grades').addEventListener('click', () => { state.grades = [...data.settings.grades]; scopeChanged(); }); | |
| document.querySelectorAll('[data-grade]').forEach((el) => el.addEventListener('click', () => { | |
| const g = el.dataset.grade; | |
| if (state.grades.length === data.settings.grades.length) state.grades = [g]; | |
| else if (state.grades.includes(g)) { if (state.grades.length === 1) return; state.grades = state.grades.filter((x) => x !== g); } | |
| else state.grades.push(g); | |
| scopeChanged(); | |
| })); | |
| document.querySelectorAll('[data-day-menu]').forEach((el) => el.addEventListener('change', () => { if (!el.value) return; chosenGrades().forEach((g) => changeCell(el.dataset.dayMenu, g, { menu_id: el.value })); render(); })); | |
| document.querySelectorAll('[data-cell-day]').forEach((el) => el.addEventListener('change', () => { changeCell(el.dataset.cellDay, el.dataset.cellGrade, { menu_id: el.value || null }); render(); })); | |
| document.querySelectorAll('[data-count-day]').forEach((el) => { | |
| el.addEventListener('input', () => { | |
| changeCell(el.dataset.countDay, el.dataset.countGrade, { students: el.value === '' ? '' : Number(el.value) }); | |
| document.getElementById('save').disabled = busy || !state.draft.size; | |
| document.querySelector('.planner-savebar b').textContent = state.draft.size ? T(`แก้ไข ${num(state.draft.size)} มื้อ ยังไม่บันทึก`, `${num(state.draft.size)} unsaved meal changes`) : T('แผนที่บันทึกไว้พร้อมใช้งาน', 'Your saved plan is ready'); | |
| document.getElementById('save-preview').textContent = `${state.draft.size ? T('บันทึกและดูใบสั่งซื้อ', 'Save & view shopping') : T('ดูใบสั่งซื้อ', 'View shopping')} →`; | |
| if (state.draft.size && !document.getElementById('discard')) { | |
| const discard = document.createElement('button'); discard.className = 'btn ghost'; discard.id = 'discard'; discard.textContent = T('ยกเลิกการแก้', 'Discard changes'); | |
| discard.addEventListener('click', () => { state.draft.clear(); render(); }); | |
| document.querySelector('.planner-savebar').insertBefore(discard, document.getElementById('save')); | |
| } else if (!state.draft.size) document.getElementById('discard')?.remove(); | |
| }); | |
| }); | |
| document.querySelectorAll('[data-details]').forEach((el) => el.addEventListener('toggle', () => { if (!el.isConnected) return; if (el.open) state.expanded.add(el.dataset.details); else state.expanded.delete(el.dataset.details); })); | |
| document.getElementById('save')?.addEventListener('click', () => save()); | |
| document.getElementById('save-preview')?.addEventListener('click', () => save(true)); | |
| document.getElementById('discard')?.addEventListener('click', () => { state.draft.clear(); render(); }); | |
| document.getElementById('empty-plan')?.addEventListener('click', () => { state.view = 'plan'; render(); }); | |
| document.getElementById('include-recipes')?.addEventListener('change', (e) => { state.recipes = e.target.checked; document.body.classList.toggle('hide-recipes', !state.recipes); }); | |
| document.getElementById('print')?.addEventListener('click', printPage); | |
| } | |
| function scopeChanged() { shopping = null; syncUrl(); if (state.view === 'shopping') openShopping(); else render(); } | |
| window.addEventListener('beforeunload', (e) => { if (state.draft.size) { e.preventDefault(); e.returnValue = ''; } }); | |
| onLang(() => { if (data) render(); }); | |
| await signIn('planner'); | |
| await load(state.week); | |
| if (new URLSearchParams(location.search).get('print') === '1') { // opened by printPage from a framed page | |
| if (state.view !== 'shopping') await openShopping(); | |
| printIfAsked(); | |
| } | |