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 `${data.menus.map((m) => ``).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 `
${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.')}
`; } 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 = `

${T('โหลดแผนไม่สำเร็จ', 'Could not load the plan')}

${esc(errorText(e.message))}

`; } 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 = `
${LOGO}
${WORDMARK}
${esc(data.settings.school_name)}
${T('เข้าครัว', 'Kitchen')} ↗${roleChip()}${langToggle()}
`; } 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 = `

${T('จากแผนมื้อกลางวัน สู่ครัวโรงเรียน', 'FROM WEEKLY MENUS TO THE SCHOOL KITCHEN')}

${isAdmin() ? `

${T('วางเมนูทั้งสัปดาห์', 'Plan lunches for the week')}

${T('เลือกเมนูวันจันทร์–ศุกร์ ปรับจำนวนเด็กแยกชั้น แล้วรวมวัตถุดิบเป็นใบสั่งซื้อและสูตรสำหรับครัวในครั้งเดียว', 'Plan Monday to Friday, adjust head counts by grade, then bring the shopping list and scaled recipes together for your kitchen.')}

` : `

${T('ใบสั่งซื้อและสูตรประจำสัปดาห์', "This week's purchase order and recipes")}

${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.')}

`}
5${T('วันเรียน วางแผนได้ในหน้าเดียว', 'school days, one plan')}
${isAdmin() ? `` : ''}
${T('เลือกชั้น', 'Grades')}${data.settings.grades.map((g) => ``).join('')}${range()}
${state.view === 'plan' ? `${provenanceNote('planner-note warn')}${renderPlan()}` : renderShopping()} `; bind(); } function renderPlan() { const grades = chosenGrades(); return `
${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.')}
${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 `

${T(['จันทร์', 'อังคาร', 'พุธ', 'พฤหัสบดี', 'ศุกร์'][index], ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'][index])}

${displayDate(day)}
${day.slice(-2)}

${m ? esc(menuName(m)) : filled.length ? T('หลายเมนู แยกตามชั้น', 'Different menus by grade') : T('วันนี้กินอะไรดี', 'What’s for lunch?')}

${num(filled.length)} / ${num(grades.length)} ${T('ชั้นมีเมนูแล้ว', 'grades planned')} · ${num(filled.reduce((sum, c) => sum + (Number(c.students) || 0), 0))} ${T('คน', 'students')}

${T('ปรับแยกรายชั้น / จำนวนเด็ก', 'Adjust by grade / head count')}${grades.map((g) => renderGradeCell(day, g)).join('')}
`; }).join('')}

${state.draft.size ? T(`แก้ไข ${num(state.draft.size)} มื้อ ยังไม่บันทึก`, `${num(state.draft.size)} unsaved meal changes`) : T('แผนที่บันทึกไว้พร้อมใช้งาน', 'Your saved plan is ready')}${T('จำนวนวัตถุดิบคิดจากจำนวนเด็ก × สัดส่วนตักของแต่ละชั้น', 'Ingredient amounts use head count × each grade’s portion size')}

${state.draft.size ? `` : ''}
`; } 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 `
${gradeShort(grade)}${dirty ? ' •' : ''}
${canEdit ? `` : `
${rows.length ? rows.map((m) => esc(menuName(m.menu || menu(m.menu_id)))).join('
') : T('ไม่มีมื้อที่บันทึกไว้', 'No recorded meal')}
`}${!canEdit && rows.length ? `🔒 ${[...new Set(rows.map(mealStatus))].join(' · ')}` : ''}
`; } 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 `
${busy ? T('กำลังรวมวัตถุดิบ…', 'Building your shopping list…') : T('ยังไม่มีใบสั่งซื้อ กด “ใบสั่งซื้อและสูตร” เพื่อลองอีกครั้ง', 'No shopping list loaded. Open “Shopping & recipes” to retry.')}
`; const report = shopping.shopping, meals = shopping.meals, hasMeals = report.meal_count > 0; if (!hasMeals) return `

${T('เริ่มจากเมนูมื้อแรกของสัปดาห์', 'Start with the first lunch of the week')}

${T('ยังไม่มีเมนูของชั้นที่เลือกในสัปดาห์นี้ วางเมนูและบันทึกแล้วระบบจะรวมวัตถุดิบให้', 'There are no meals for the selected grades this week. Save a plan to build your ingredient list.')}

${isAdmin() ? `` : `

${T('ผู้ดูแลยังไม่ได้วางแผนของสัปดาห์นี้ ลองเลือกสัปดาห์อื่น', 'The coordinator has not planned this week yet; try another week.')}

`}
`; const plannedOnly = meals.filter((m) => m.status === 'planned').length === meals.length; return `
${LOGO}${WORDMARK}
${esc(data.settings.school_name)}
${T('จัดทำวันที่', 'Prepared')} ${longDate(localYmd())}

${T('ใบสั่งซื้อวัตถุดิบรายสัปดาห์', 'Weekly ingredient order')}

${range()} · ${esc(scopeLabel())}

${num(report.meal_count)}${T('มื้อแยกชั้น', 'grade meals')}
${num(report.student_servings)}${T('ที่เสิร์ฟตลอดสัปดาห์', 'student servings this week')}
${num(report.ingredients.length)}${T('รายการวัตถุดิบ', 'ingredient entries')}
${provenanceNote()} ${!plannedOnly ? `
${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.')}
` : ''} ${report.warnings.length ? `
${T('มีข้อมูลต้องเติมก่อนสั่งซื้อ', 'Details to complete before ordering')}
` : ''}

${T('วัตถุดิบรวมทั้งสัปดาห์', 'Combined ingredients')}

${report.ingredients.map((i) => { const q = quantity(i.qty, i.unit, true); return ``; }).join('')}
${T('เช็ก', 'Check')}${T('วัตถุดิบ', 'Ingredient')}${T('จำนวน', 'Amount')}${T('หน่วย', 'Unit')}${T('รับจริง / หมายเหตุ', 'Received / notes')}
${esc(ingredientName(i))}${i.incomplete ? `
${T('ยังมีส่วนที่ไม่ระบุปริมาณ', 'Some quantities are missing')}` : ''}
${q.label}${i.incomplete && i.qty != null ? '+' : ''}${esc(q.unit)}

${T('แผนเมนูที่ใช้คำนวณ', 'Meals included in this order')}

${scheduleRows(meals)}
${T('วัน', 'Day')}${T('เมนู / ชั้น', 'Menu / grades')}${T('คน', 'Students')}

${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.')}

${T('ผู้จัดทำ', 'Prepared by')} ____________________${T('ผู้ตรวจรับ / วันที่', 'Received by / date')} ____________________
${report.recipes.map(renderRecipe).join('')}
`; } 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) => `${displayDate(r.date, true)}${esc(menuName(r.menu || menu(r.menu_id)))}
${r.entries.map((m) => `${gradeShort(m.grade)} (${num(m.students)})`).join(' · ')}
${r.status !== 'planned' || r.origin === 'trial' ? `${mealStatus(r)}` : ''}${num(r.entries.reduce((sum, m) => sum + Number(m.students), 0))}`).join(''); } function renderRecipe(item) { const r = item.recipe, m = item.menu, dates = [...new Set(item.meals.map((row) => row.date))]; return `
${provenanceNote('sheet-warning', m, r)}

${esc(menuName(m))}

${T('สูตรรวมสำหรับสัปดาห์', 'Weekly recipe total')} ${range()}

${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)}` : ''}
${T('ใช้วันที่', 'Scheduled')} ${dates.map((d) => displayDate(d, true)).join(' · ')}
${T('แยกมื้อ', 'By meal')}: ${item.meals.map((row) => `${displayDate(row.date)} ${gradeShort(row.grade)} ${num(row.students)} ${T('คน', 'students')}`).join(' · ')}
${r ? `

${T('วัตถุดิบรวมของเมนูนี้', 'Weekly ingredients for this menu')}

${r.ingredients.map((i) => { const q = quantity(i.qty == null || i.qty === '' ? null : Number(i.qty) * item.factor, i.unit, true); return ``; }).join('')}
${esc(ingredientName(i))}${q.label}${esc(q.unit)}

${T('วิธีทำ', 'Method')}

    ${(recipeSteps(r) || []).map((step) => `
  1. ${esc(step)}
  2. `).join('')}
${recipeTips(r) ? `

${esc(recipeTips(r))}

` : ''}

${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.')}

` : `
${T('เมนูนี้ยังไม่มีสูตร จึงยังไม่รวมวัตถุดิบในใบสั่งซื้อ', 'This menu has no recipe, so its ingredients are not included in the order.')}
`}
`; } 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(); }