mirror of
https://github.com/Sea-Haven-Industries/meal-order-manager.git
synced 2026-10-07 16:18:54 +00:00
Compare commits
8 commits
11c7e14ce3
...
502e15792e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
502e15792e | ||
| 2f88a4a315 | |||
|
|
a9dcf28d09 | ||
| e319e4a0d3 | |||
| cf8ad2baea | |||
| d05de42104 | |||
| a7b27befc5 | |||
| 57a6412811 |
8 changed files with 125 additions and 508 deletions
8
.github/workflows/ci.yml
vendored
8
.github/workflows/ci.yml
vendored
|
|
@ -7,7 +7,7 @@ permissions:
|
|||
contents: read
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
lint:
|
||||
uses: Sea-Haven-Industries/.github/.github/workflows/ci-python-sam.yaml@0170a57c0d99b542cfafd1f3e1d369c32643f486 # v1.0.2
|
||||
with:
|
||||
run-tests: false
|
||||
|
|
@ -16,11 +16,9 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.x
|
||||
with:
|
||||
persist-credentials: false
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.x
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
|
|
|
|||
|
|
@ -97,9 +97,9 @@ def generate_form(
|
|||
return template.render(
|
||||
config=form_config,
|
||||
config_json=_json_for_script(form_config),
|
||||
css=(TEMPLATES_DIR / "form.css").read_text(encoding="utf-8"),
|
||||
form_js=(TEMPLATES_DIR / "form.js").read_text(encoding="utf-8"),
|
||||
admin_js=(TEMPLATES_DIR / "admin.js").read_text(encoding="utf-8"),
|
||||
css=(TEMPLATES_DIR / "form.css").read_text(),
|
||||
form_js=(TEMPLATES_DIR / "form.js").read_text(),
|
||||
admin_js=(TEMPLATES_DIR / "admin.js").read_text(),
|
||||
week=week,
|
||||
scraped_at=scraped_at,
|
||||
deadline=deadline,
|
||||
|
|
|
|||
|
|
@ -4,13 +4,11 @@ const ADMIN_URL = window.ADMIN_URL;
|
|||
const ADMIN_PDF_URL = window.ADMIN_PDF_URL;
|
||||
const MEALS = window.MEALS;
|
||||
const WEEK = window.WEEK;
|
||||
const ADMIN_REQUEST_TIMEOUT_MS = 10000;
|
||||
|
||||
let currentAdminWeek = '';
|
||||
let editingOrder = null;
|
||||
let editQuantities = {};
|
||||
let lastAdminData = null;
|
||||
let latestAdminRequest = 0;
|
||||
|
||||
function adminHeaders() {
|
||||
const h = {};
|
||||
|
|
@ -19,22 +17,8 @@ function adminHeaders() {
|
|||
return h;
|
||||
}
|
||||
|
||||
function adminFetch(url, options = {}) {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(() => controller.abort(), ADMIN_REQUEST_TIMEOUT_MS);
|
||||
return fetch(url, { ...options, signal: controller.signal })
|
||||
.finally(() => clearTimeout(timeout));
|
||||
}
|
||||
|
||||
function setAdminActionDisabled(action, disabled) {
|
||||
document.querySelectorAll('[data-admin-action="' + action + '"]').forEach(btn => {
|
||||
btn.disabled = disabled;
|
||||
});
|
||||
}
|
||||
|
||||
function loadWeekOrders(week) {
|
||||
if (!week) return;
|
||||
const requestId = ++latestAdminRequest;
|
||||
currentAdminWeek = week;
|
||||
editingOrder = null;
|
||||
editQuantities = {};
|
||||
|
|
@ -43,20 +27,11 @@ function loadWeekOrders(week) {
|
|||
document.getElementById('admin-empty').classList.add('is-hidden');
|
||||
document.getElementById('admin-stats').textContent = '';
|
||||
|
||||
adminFetch(ADMIN_URL + '?week=' + encodeURIComponent(week), { headers: adminHeaders() })
|
||||
.then(r => {
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
return r.json();
|
||||
})
|
||||
.then(data => {
|
||||
if (requestId === latestAdminRequest && week === currentAdminWeek) {
|
||||
renderAdminTable(data);
|
||||
}
|
||||
})
|
||||
fetch(ADMIN_URL + '?week=' + encodeURIComponent(week), { headers: adminHeaders() })
|
||||
.then(r => r.json())
|
||||
.then(data => renderAdminTable(data))
|
||||
.catch(() => {
|
||||
if (requestId === latestAdminRequest && week === currentAdminWeek) {
|
||||
tbody.innerHTML = '<tr><td colspan="5" class="admin-error">Failed to load orders.</td></tr>';
|
||||
}
|
||||
tbody.innerHTML = '<tr><td colspan="5" class="admin-error">Failed to load orders.</td></tr>';
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -106,9 +81,8 @@ function buildAddItemSelect(availableMeals) {
|
|||
|
||||
availableMeals.forEach(m => {
|
||||
const opt = document.createElement('option');
|
||||
const price = m.price || 0;
|
||||
opt.value = m.name;
|
||||
opt.textContent = m.name + ' ($' + price.toFixed(2) + ')';
|
||||
opt.textContent = m.name + ' ($' + m.price.toFixed(2) + ')';
|
||||
select.appendChild(opt);
|
||||
});
|
||||
|
||||
|
|
@ -141,10 +115,10 @@ function buildEditActions(email) {
|
|||
return wrap;
|
||||
}
|
||||
|
||||
function buildViewActions(email, name) {
|
||||
function buildViewActions(idx, email, name) {
|
||||
const wrap = document.createElement('div');
|
||||
wrap.className = 'admin-actions';
|
||||
const editBtn = buildActionButton('Edit', 'start-edit', { email });
|
||||
const editBtn = buildActionButton('Edit', 'start-edit', { index: String(idx), email });
|
||||
editBtn.className = 'btn btn-sm btn-edit';
|
||||
const deleteBtn = buildActionButton('Delete', 'delete', { email, name });
|
||||
deleteBtn.className = 'btn btn-sm btn-delete';
|
||||
|
|
@ -216,7 +190,7 @@ function renderAdminTable(data) {
|
|||
MEALS.forEach(m => { menuPrices[m.name] = m.price; });
|
||||
const newTotal = editNames.reduce((sum, name) => {
|
||||
const price = menuPrices[name] || 0;
|
||||
return sum + window.FormUtils.employeePrice(price) * (editQuantities[name] || 0);
|
||||
return sum + price * (editQuantities[name] || 0);
|
||||
}, 0);
|
||||
totalHtml = '$' + newTotal.toFixed(2);
|
||||
tr.appendChild(empTd);
|
||||
|
|
@ -255,7 +229,7 @@ function renderAdminTable(data) {
|
|||
if (isEditing) {
|
||||
actionsTd.appendChild(buildEditActions(order.employee_email));
|
||||
} else {
|
||||
actionsTd.appendChild(buildViewActions(order.employee_email, order.employee_name));
|
||||
actionsTd.appendChild(buildViewActions(idx, order.employee_email, order.employee_name));
|
||||
}
|
||||
|
||||
tr.appendChild(totalTd);
|
||||
|
|
@ -270,7 +244,7 @@ function renderAdminTable(data) {
|
|||
const t1 = document.createElement('td');
|
||||
t1.textContent = 'Total';
|
||||
const t2 = document.createElement('td');
|
||||
t2.textContent = mealCount + (mealCount === 1 ? ' meal' : ' meals');
|
||||
t2.textContent = mealCount + ' meals';
|
||||
const t3 = document.createElement('td');
|
||||
t3.className = 'total-cell';
|
||||
t3.textContent = '$' + data.grand_total.toFixed(2);
|
||||
|
|
@ -293,8 +267,7 @@ function downloadOrderList() {
|
|||
const names = Object.keys(totals).sort((a, b) => a.localeCompare(b));
|
||||
const esc = v => {
|
||||
const s = String(v);
|
||||
const safe = /^[=+\-@\t\r]/.test(s) ? "'" + s : s;
|
||||
return /[",\n]/.test(safe) ? '"' + safe.replace(/"/g, '""') + '"' : safe;
|
||||
return /[",\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
|
||||
};
|
||||
const rows = [['Item', 'Quantity']].concat(names.map(n => [n, totals[n]]));
|
||||
const csv = rows.map(r => r.map(esc).join(',')).join('\r\n');
|
||||
|
|
@ -315,7 +288,7 @@ function downloadSummaryPdf() {
|
|||
const btn = document.getElementById('admin-pdf-btn');
|
||||
if (btn) btn.disabled = true;
|
||||
window.FormUtils.clearStatus('admin');
|
||||
adminFetch(ADMIN_PDF_URL + '?week=' + encodeURIComponent(week), { headers: adminHeaders() })
|
||||
fetch(ADMIN_PDF_URL + '?week=' + encodeURIComponent(week), { headers: adminHeaders() })
|
||||
.then(r => r.json().then(data => ({ ok: r.ok, status: r.status, data })))
|
||||
.then(({ ok, status, data }) => {
|
||||
if (ok && data.url) {
|
||||
|
|
@ -349,17 +322,10 @@ function downloadSummaryPdf() {
|
|||
.finally(() => { if (btn) btn.disabled = false; });
|
||||
}
|
||||
|
||||
function adminStartEdit(email) {
|
||||
window.FormUtils.clearStatus('admin');
|
||||
const requestedWeek = currentAdminWeek;
|
||||
setAdminActionDisabled('start-edit', true);
|
||||
adminFetch(ADMIN_URL + '?week=' + encodeURIComponent(requestedWeek), { headers: adminHeaders() })
|
||||
.then(r => {
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
return r.json();
|
||||
})
|
||||
function adminStartEdit(idx, email) {
|
||||
fetch(ADMIN_URL + '?week=' + encodeURIComponent(currentAdminWeek), { headers: adminHeaders() })
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (currentAdminWeek !== requestedWeek) return;
|
||||
lastAdminData = data;
|
||||
const order = data.orders.find(o => o.employee_email === email);
|
||||
if (!order) return;
|
||||
|
|
@ -367,14 +333,7 @@ function adminStartEdit(email) {
|
|||
editQuantities = {};
|
||||
order.items.forEach(i => { editQuantities[i.name] = i.quantity; });
|
||||
renderAdminTable(data);
|
||||
})
|
||||
.catch(() => {
|
||||
window.FormUtils.showStatus('Failed to load this order for editing.', {
|
||||
tone: 'error',
|
||||
scope: 'admin',
|
||||
});
|
||||
})
|
||||
.finally(() => setAdminActionDisabled('start-edit', false));
|
||||
});
|
||||
}
|
||||
|
||||
function adminCancelEdit() {
|
||||
|
|
@ -407,8 +366,7 @@ function adminSaveEdit(email) {
|
|||
return;
|
||||
}
|
||||
window.FormUtils.clearStatus('admin');
|
||||
setAdminActionDisabled('save-edit', true);
|
||||
adminFetch(ADMIN_URL, {
|
||||
fetch(ADMIN_URL, {
|
||||
method: 'PUT',
|
||||
headers: { ...adminHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ week: currentAdminWeek, email, items }),
|
||||
|
|
@ -420,8 +378,7 @@ function adminSaveEdit(email) {
|
|||
tone: 'error',
|
||||
scope: 'admin',
|
||||
});
|
||||
})
|
||||
.finally(() => setAdminActionDisabled('save-edit', false));
|
||||
});
|
||||
}
|
||||
|
||||
function adminDeleteOrder(email, name) {
|
||||
|
|
@ -429,8 +386,7 @@ function adminDeleteOrder(email, name) {
|
|||
// confirm() retained deliberately for destructive delete guard.
|
||||
if (!confirm('Delete order for ' + label + '?')) return;
|
||||
window.FormUtils.clearStatus('admin');
|
||||
setAdminActionDisabled('delete', true);
|
||||
adminFetch(ADMIN_URL + '?week=' + encodeURIComponent(currentAdminWeek) + '&email=' + encodeURIComponent(email), {
|
||||
fetch(ADMIN_URL + '?week=' + encodeURIComponent(currentAdminWeek) + '&email=' + encodeURIComponent(email), {
|
||||
method: 'DELETE',
|
||||
headers: adminHeaders(),
|
||||
})
|
||||
|
|
@ -441,8 +397,7 @@ function adminDeleteOrder(email, name) {
|
|||
tone: 'error',
|
||||
scope: 'admin',
|
||||
});
|
||||
})
|
||||
.finally(() => setAdminActionDisabled('delete', false));
|
||||
});
|
||||
}
|
||||
|
||||
function handleAdminPanelClick(e) {
|
||||
|
|
@ -450,7 +405,7 @@ function handleAdminPanelClick(e) {
|
|||
if (btn) {
|
||||
const action = btn.dataset.adminAction;
|
||||
if (action === 'start-edit') {
|
||||
adminStartEdit(btn.dataset.email);
|
||||
adminStartEdit(parseInt(btn.dataset.index, 10), btn.dataset.email);
|
||||
} else if (action === 'delete') {
|
||||
adminDeleteOrder(btn.dataset.email, btn.dataset.name || '');
|
||||
} else if (action === 'save-edit') {
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@
|
|||
--radius-card: 12px;
|
||||
--radius-control: 8px;
|
||||
--shadow-card: 0 1px 3px rgba(0,0,0,0.08);
|
||||
--sticky-footer-height: 80px;
|
||||
}
|
||||
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
|
@ -15,7 +14,7 @@ body {
|
|||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: #f5f5f7;
|
||||
color: #1d1d1f;
|
||||
padding-bottom: calc(var(--sticky-footer-height) + env(safe-area-inset-bottom, 0px));
|
||||
padding-bottom: calc(80px + env(safe-area-inset-bottom, 0px));
|
||||
}
|
||||
|
||||
.is-hidden { display: none !important; }
|
||||
|
|
@ -76,7 +75,7 @@ header p { font-size: 0.85rem; opacity: 0.8; }
|
|||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.user-bar { display: flex; align-items: center; gap: 12px; }
|
||||
.user-info-row { display: flex; align-items: center; gap: 12px; }
|
||||
|
||||
.user-avatar {
|
||||
width: 40px;
|
||||
|
|
@ -88,13 +87,9 @@ header p { font-size: 0.85rem; opacity: 0.8; }
|
|||
|
||||
.user-avatar:not(.is-hidden) { display: block; }
|
||||
|
||||
.user-meta { flex: 1; min-width: 0; }
|
||||
.user-meta { flex: 1; }
|
||||
.user-name { font-weight: 600; font-size: 0.95rem; }
|
||||
.user-email {
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-muted);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.user-email { font-size: 0.85rem; color: var(--color-muted); }
|
||||
.count-display { font-size: 0.8rem; color: var(--color-muted); margin-left: 8px; }
|
||||
.g-signin-wrap { display: flex; justify-content: center; }
|
||||
.admin-muted { font-size: 0.8rem; color: #9ca3af; }
|
||||
|
|
@ -217,7 +212,6 @@ header p { font-size: 0.85rem; opacity: 0.8; }
|
|||
background: #fff;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px));
|
||||
min-height: calc(var(--sticky-footer-height) + env(safe-area-inset-bottom, 0px));
|
||||
box-shadow: 0 -2px 8px rgba(0,0,0,0.1);
|
||||
z-index: 100;
|
||||
}
|
||||
|
|
@ -366,16 +360,10 @@ header p { font-size: 0.85rem; opacity: 0.8; }
|
|||
font-size: 1rem;
|
||||
}
|
||||
|
||||
@media (max-width: 479px) {
|
||||
.user-bar { flex-wrap: wrap; }
|
||||
.user-meta { flex-basis: calc(100% - 52px); }
|
||||
.user-bar #admin-btn { margin-left: 52px; }
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.meal-card {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
grid-template-columns: 80px minmax(0, 1fr);
|
||||
align-items: start;
|
||||
}
|
||||
.qty-control {
|
||||
|
|
@ -539,7 +527,7 @@ header p { font-size: 0.85rem; opacity: 0.8; }
|
|||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.admin-toolbar .back-btn { margin: 0; padding: 8px 16px; font-size: 0.85rem; }
|
||||
.admin-toolbar .back-btn { margin: 0; padding: 8px 16px; font-size: 0.85rem; margin-top: 0; }
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.admin-toolbar { width: 100%; }
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@
|
|||
{% if config.authMode == 'google' %}
|
||||
<div class="employee-info">
|
||||
<div id="user-info">
|
||||
<div class="user-bar">
|
||||
<div class="user-info-row">
|
||||
<img id="user-avatar" class="user-avatar is-hidden" alt="">
|
||||
<div class="user-meta">
|
||||
<div id="user-name" class="user-name"></div>
|
||||
|
|
@ -70,7 +70,7 @@
|
|||
</div>
|
||||
{% endif %}
|
||||
|
||||
<input type="text" class="search-bar" id="search" placeholder="Search meals..." aria-label="Search meals">
|
||||
<input type="text" class="search-bar" id="search" placeholder="Search meals...">
|
||||
|
||||
<div class="filters" id="filters"></div>
|
||||
|
||||
|
|
|
|||
|
|
@ -26,13 +26,20 @@ let adminWeeks = [];
|
|||
let googleCredential = null;
|
||||
let googleUser = null;
|
||||
let reopenAtMs = null;
|
||||
let countdownTimer = null;
|
||||
let mealsListDelegationBound = false;
|
||||
|
||||
const GOOGLE_AUTH_MAX_ATTEMPTS = 200;
|
||||
|
||||
window.googleCredential = null;
|
||||
|
||||
function escapeHtml(str) {
|
||||
if (!str) return '';
|
||||
return String(str)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function employeePrice(retail) {
|
||||
if (!retail) return 0;
|
||||
const bulkPrice = Math.round(retail * (1 - BULK_DISCOUNT / 100) * 100 + 1e-8) / 100;
|
||||
|
|
@ -65,7 +72,7 @@ function showStatus(message, options) {
|
|||
}
|
||||
}
|
||||
|
||||
window.FormUtils = { employeePrice, showStatus, clearStatus };
|
||||
window.FormUtils = { escapeHtml, employeePrice, showStatus, clearStatus };
|
||||
|
||||
function syncGoogleCredential() {
|
||||
window.googleCredential = googleCredential;
|
||||
|
|
@ -79,17 +86,11 @@ function buildItems() {
|
|||
}));
|
||||
}
|
||||
|
||||
function waitForGoogleAuth(attempt = 0) {
|
||||
function waitForGoogleAuth() {
|
||||
if (typeof google !== 'undefined' && google.accounts && google.accounts.id) {
|
||||
initGoogleAuth();
|
||||
} else if (attempt < GOOGLE_AUTH_MAX_ATTEMPTS) {
|
||||
setTimeout(() => waitForGoogleAuth(attempt + 1), 50);
|
||||
} else {
|
||||
const signIn = document.getElementById('g-signin-btn');
|
||||
if (signIn) {
|
||||
signIn.textContent = 'Google sign-in failed to load. Refresh the page to try again.';
|
||||
}
|
||||
console.error('Google Identity Services failed to load.');
|
||||
setTimeout(waitForGoogleAuth, 50);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -127,9 +128,7 @@ function handleCredentialResponse(response) {
|
|||
|
||||
updateTotal();
|
||||
checkDuplicateOrder();
|
||||
checkAdmin().then(() => {
|
||||
if (formClosed && !isAdmin) showClosedOverlay();
|
||||
});
|
||||
checkAdmin();
|
||||
}
|
||||
|
||||
function signOut() {
|
||||
|
|
@ -322,17 +321,13 @@ function updateMealCardQty(index) {
|
|||
const qty = quantities[index] || 0;
|
||||
card.classList.toggle('selected', qty > 0);
|
||||
const qtyInput = card.querySelector('.qty');
|
||||
if (qtyInput && qtyInput !== document.activeElement) qtyInput.value = qty;
|
||||
}
|
||||
|
||||
function setQtyState(index, value) {
|
||||
const next = Math.max(0, parseInt(value, 10) || 0);
|
||||
if (next === 0) delete quantities[index];
|
||||
else quantities[index] = next;
|
||||
if (qtyInput) qtyInput.value = qty;
|
||||
}
|
||||
|
||||
function setQty(index, value) {
|
||||
setQtyState(index, value);
|
||||
const next = Math.max(0, parseInt(value, 10) || 0);
|
||||
if (next === 0) delete quantities[index];
|
||||
else quantities[index] = next;
|
||||
updateMealCardQty(index);
|
||||
updateTotal();
|
||||
}
|
||||
|
|
@ -355,21 +350,21 @@ function bindMealsListDelegation() {
|
|||
const delta = parseInt(btn.dataset.qtyDelta, 10);
|
||||
changeQty(index, delta);
|
||||
});
|
||||
list.addEventListener('change', (e) => {
|
||||
const input = e.target.closest('.qty');
|
||||
if (!input) return;
|
||||
const card = input.closest('[data-meal-index]');
|
||||
if (!card) return;
|
||||
const index = parseInt(card.dataset.mealIndex, 10);
|
||||
setQty(index, input.value);
|
||||
});
|
||||
list.addEventListener('input', (e) => {
|
||||
const input = e.target.closest('.qty');
|
||||
if (!input) return;
|
||||
const card = input.closest('[data-meal-index]');
|
||||
if (!card) return;
|
||||
const index = parseInt(card.dataset.mealIndex, 10);
|
||||
setQtyState(index, input.value);
|
||||
updateTotal();
|
||||
});
|
||||
list.addEventListener('focusout', (e) => {
|
||||
const input = e.target.closest('.qty');
|
||||
if (!input) return;
|
||||
const card = input.closest('[data-meal-index]');
|
||||
if (!card) return;
|
||||
updateMealCardQty(parseInt(card.dataset.mealIndex, 10));
|
||||
setQty(index, input.value);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -483,27 +478,21 @@ function populateEmpSelect(select, employees) {
|
|||
}
|
||||
|
||||
async function loadRoster() {
|
||||
let employees = ROSTER;
|
||||
const select = document.getElementById('emp-name');
|
||||
try {
|
||||
const res = await fetch(ROSTER_URL);
|
||||
const data = await res.json();
|
||||
const candidate = data.employees;
|
||||
if (Array.isArray(candidate) && candidate.every(e => typeof e.name === 'string' && typeof e.email === 'string')) {
|
||||
employees = candidate;
|
||||
} else {
|
||||
employees = ROSTER;
|
||||
}
|
||||
} catch (e) {}
|
||||
|
||||
const select = document.getElementById('emp-name');
|
||||
populateEmpSelect(select, employees);
|
||||
populateEmpSelect(select, data.employees || ROSTER);
|
||||
} catch (e) {
|
||||
populateEmpSelect(select, ROSTER);
|
||||
}
|
||||
}
|
||||
|
||||
function showClosedOverlay() {
|
||||
const overlay = document.getElementById('closed-overlay');
|
||||
overlay.classList.add('is-visible');
|
||||
overlay.style.display = 'flex';
|
||||
document.querySelectorAll('.qty-control button, .qty-control .qty').forEach(el => { el.disabled = true; });
|
||||
document.querySelectorAll('.qty-control button').forEach(b => { b.disabled = true; });
|
||||
const submitBtn = document.getElementById('submit-btn');
|
||||
if (submitBtn) submitBtn.disabled = true;
|
||||
if (formStatusData) startCountdown(formStatusData);
|
||||
|
|
@ -533,10 +522,10 @@ function adminBypassClosed() {
|
|||
}
|
||||
|
||||
function checkAdmin() {
|
||||
if (!ADMIN_URL) return Promise.resolve();
|
||||
if (!ADMIN_URL) return;
|
||||
const headers = {};
|
||||
if (googleCredential) headers['Authorization'] = 'Bearer ' + googleCredential;
|
||||
return fetch(ADMIN_URL, { headers })
|
||||
fetch(ADMIN_URL, { headers })
|
||||
.then(r => r.ok ? r.json() : null)
|
||||
.then(data => {
|
||||
if (data && data.weeks) {
|
||||
|
|
@ -618,8 +607,7 @@ function getEasternOffsetMs(date) {
|
|||
function startCountdown(data) {
|
||||
if (data && data.reopen_at) reopenAtMs = data.reopen_at * 1000;
|
||||
updateCountdown();
|
||||
if (countdownTimer !== null) clearInterval(countdownTimer);
|
||||
countdownTimer = setInterval(updateCountdown, 1000);
|
||||
setInterval(updateCountdown, 1000);
|
||||
}
|
||||
|
||||
function updateCountdown() {
|
||||
|
|
@ -660,7 +648,8 @@ async function checkFormStatus() {
|
|||
formStatusData = data;
|
||||
if (isAdmin) {
|
||||
adminBypassClosed();
|
||||
} else if (CONFIG.authMode !== 'google' || googleCredential) {
|
||||
} else if (CONFIG.authMode === 'google') {
|
||||
} else {
|
||||
showClosedOverlay();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
12
tests/fixtures/menu.json
vendored
12
tests/fixtures/menu.json
vendored
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"scraped_at": "2026-07-27T12:00:00+00:00",
|
||||
"meal_count": 5,
|
||||
"meal_count": 4,
|
||||
"meals": [
|
||||
{
|
||||
"name": "Chicken Bowl",
|
||||
|
|
@ -45,16 +45,6 @@
|
|||
"dietary_tags": [],
|
||||
"image_url": "",
|
||||
"is_new": false
|
||||
},
|
||||
{
|
||||
"name": "<!--<script>alert(1)</script>-->",
|
||||
"price": 9.0,
|
||||
"calories": "300",
|
||||
"protein": "10g",
|
||||
"description": "Hostile script comment",
|
||||
"dietary_tags": [],
|
||||
"image_url": "",
|
||||
"is_new": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -2,7 +2,6 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
|
@ -67,50 +66,6 @@ def _render(*, google: bool = False, api_key: str = "test-key") -> str:
|
|||
)
|
||||
|
||||
|
||||
def _google_credential() -> str:
|
||||
payload = json.dumps(
|
||||
{
|
||||
"name": "Test Admin",
|
||||
"email": "test-admin@example.com",
|
||||
"picture": (
|
||||
"data:image/svg+xml,"
|
||||
"<svg xmlns='http://www.w3.org/2000/svg' width='40' height='40'/>"
|
||||
),
|
||||
}
|
||||
).encode()
|
||||
encoded = base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
||||
return f"e30.{encoded}.signature"
|
||||
|
||||
|
||||
def _mock_form_routes(page):
|
||||
page.route(
|
||||
"**/api/form-status/**",
|
||||
lambda route: route.fulfill(
|
||||
status=200,
|
||||
content_type="application/json",
|
||||
body='{"status":"open"}',
|
||||
),
|
||||
)
|
||||
page.route(
|
||||
"**/api/roster**",
|
||||
lambda route: route.fulfill(
|
||||
status=200,
|
||||
content_type="application/json",
|
||||
body=json.dumps(
|
||||
{"employees": [{"name": "Ada Lovelace", "email": "ada@example.com"}]}
|
||||
),
|
||||
),
|
||||
)
|
||||
page.route(
|
||||
"**/api/admin/orders",
|
||||
lambda route: route.fulfill(
|
||||
status=403,
|
||||
content_type="application/json",
|
||||
body='{"error":"Forbidden"}',
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class TestGenerateFormStructural:
|
||||
def test_local_and_google_render(self):
|
||||
local = _render(google=False)
|
||||
|
|
@ -169,26 +124,6 @@ class TestGenerateFormStructural:
|
|||
local = _render(google=False)
|
||||
assert "<script src=" not in local
|
||||
|
||||
def test_mobile_viewport_and_safe_area_clearance_are_preserved(self):
|
||||
html = _render()
|
||||
css = (SERVER_DIR / "templates" / "form.css").read_text()
|
||||
assert (
|
||||
'content="width=device-width, initial-scale=1.0, viewport-fit=cover"'
|
||||
in html
|
||||
)
|
||||
assert "--sticky-footer-height: 80px;" in css
|
||||
assert (
|
||||
"padding-bottom: calc(var(--sticky-footer-height) + "
|
||||
"env(safe-area-inset-bottom, 0px));"
|
||||
) in css
|
||||
assert (
|
||||
"padding: 12px 16px calc(12px + env(safe-area-inset-bottom, 0px));"
|
||||
) in css
|
||||
assert (
|
||||
"min-height: calc(var(--sticky-footer-height) + "
|
||||
"env(safe-area-inset-bottom, 0px));"
|
||||
) in css
|
||||
|
||||
def test_script_order_form_then_admin(self):
|
||||
html = _render()
|
||||
form_pos = html.index("FORM_JS_MARKER")
|
||||
|
|
@ -203,6 +138,7 @@ class TestGenerateFormStructural:
|
|||
def test_no_onclick_admin_data_embedding(self):
|
||||
html = _render(google=True)
|
||||
assert 'onclick="admin' not in html
|
||||
assert 'onclick="admin' not in html
|
||||
# Static markup must not interpolate runtime data into onclick
|
||||
assert not re.search(r'onclick="[^"]*\$\{', html)
|
||||
|
||||
|
|
@ -214,6 +150,7 @@ class TestGenerateFormStructural:
|
|||
blob = cfg_match.group(1)
|
||||
# Literal </script> inside the CONFIG script would terminate early.
|
||||
assert "</script>" not in blob
|
||||
assert "<\\/script><script>alert(1)<\\/script>" in blob
|
||||
# Parsed JSON still contains the hostile meal name.
|
||||
cfg = json.loads(blob)
|
||||
assert any(
|
||||
|
|
@ -226,7 +163,6 @@ class TestGenerateFormStructural:
|
|||
assert "Luis' Lomo Saltado" in names
|
||||
assert 'Meal with "quotes"' in names
|
||||
assert "</script><script>alert(1)</script>" in names
|
||||
assert "<!--<script>alert(1)</script>-->" in names
|
||||
|
||||
def test_meal_card_template_and_qty_input(self):
|
||||
html = _render()
|
||||
|
|
@ -272,10 +208,14 @@ class TestGenerateFormStructural:
|
|||
|
||||
|
||||
class TestGenerateFormPlaywright:
|
||||
@pytest.fixture
|
||||
@pytest.fixture(scope="class")
|
||||
def browser_page(self, tmp_path_factory):
|
||||
sync_api = pytest.importorskip("playwright.sync_api")
|
||||
sync_playwright = sync_api.sync_playwright
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError as exc: # pragma: no cover
|
||||
raise RuntimeError(
|
||||
"playwright package is required; install requirements.txt"
|
||||
) from exc
|
||||
|
||||
html = _render(google=False, api_key="")
|
||||
# Stub status/roster so the page does not hang on network; roster fallback
|
||||
|
|
@ -291,127 +231,33 @@ class TestGenerateFormPlaywright:
|
|||
"Chromium is required for form Playwright tests. "
|
||||
"Run: playwright install --with-deps chromium"
|
||||
) from exc
|
||||
try:
|
||||
page = browser.new_page()
|
||||
_mock_form_routes(page)
|
||||
page.goto(out.as_uri())
|
||||
page.wait_for_selector('[data-meal-index="0"]')
|
||||
yield page
|
||||
finally:
|
||||
browser.close()
|
||||
|
||||
@pytest.mark.parametrize("width", [320, 375, 480])
|
||||
@pytest.mark.parametrize("google", [False, True], ids=["local", "google"])
|
||||
def test_sticky_footer_fits_narrow_viewports(self, tmp_path, width, google):
|
||||
sync_api = pytest.importorskip("playwright.sync_api")
|
||||
sync_playwright = sync_api.sync_playwright
|
||||
|
||||
html_path = tmp_path / f"order-form-{'google' if google else 'local'}.html"
|
||||
html_path.write_text(_render(google=google, api_key=""))
|
||||
|
||||
with sync_playwright() as p:
|
||||
try:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
"Chromium is required for form Playwright tests. "
|
||||
"Run: playwright install --with-deps chromium"
|
||||
) from exc
|
||||
try:
|
||||
page = browser.new_page(viewport={"width": width, "height": 800})
|
||||
page.add_init_script(
|
||||
"""window.google = {
|
||||
accounts: {
|
||||
id: {
|
||||
initialize() {},
|
||||
renderButton() {},
|
||||
disableAutoSelect() {},
|
||||
},
|
||||
},
|
||||
};"""
|
||||
)
|
||||
page.route(
|
||||
"https://accounts.google.com/gsi/client",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
_mock_form_routes(page)
|
||||
|
||||
page.goto(html_path.as_uri(), wait_until="domcontentloaded")
|
||||
page.wait_for_selector('[data-meal-index="0"]', state="attached")
|
||||
if google:
|
||||
page.evaluate(
|
||||
"(credential) => handleCredentialResponse({ credential })",
|
||||
_google_credential(),
|
||||
)
|
||||
page.wait_for_selector('[data-meal-index="0"]', state="visible")
|
||||
|
||||
first_increment = page.locator(
|
||||
'[data-meal-index="0"] [data-qty-delta="1"]'
|
||||
)
|
||||
first_increment.click()
|
||||
first_increment.click()
|
||||
page.wait_for_function(
|
||||
"() => document.getElementById('count-display').textContent === "
|
||||
"'2 meals'"
|
||||
)
|
||||
page.evaluate("() => document.fonts.ready")
|
||||
|
||||
total = page.locator("#total-display")
|
||||
count = page.locator("#count-display")
|
||||
submit = page.locator("#submit-btn")
|
||||
assert total.inner_text() == "$10.80"
|
||||
assert count.inner_text() == "2 meals"
|
||||
assert total.is_visible()
|
||||
assert count.is_visible()
|
||||
assert submit.is_visible()
|
||||
assert submit.is_enabled()
|
||||
submit.focus()
|
||||
assert submit.evaluate(
|
||||
"(element) => element === document.activeElement"
|
||||
)
|
||||
|
||||
page.evaluate(
|
||||
"() => window.scrollTo(0, document.documentElement.scrollHeight)"
|
||||
)
|
||||
layout = page.evaluate(
|
||||
"""() => {
|
||||
const rect = (selector) => {
|
||||
const box = document.querySelector(selector)
|
||||
.getBoundingClientRect();
|
||||
return {
|
||||
left: box.left,
|
||||
right: box.right,
|
||||
top: box.top,
|
||||
bottom: box.bottom,
|
||||
};
|
||||
};
|
||||
const footer = document.querySelector('#sticky-footer');
|
||||
return {
|
||||
clientWidth: document.documentElement.clientWidth,
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
viewportHeight: window.innerHeight,
|
||||
footer: {
|
||||
...rect('#sticky-footer'),
|
||||
position: getComputedStyle(footer).position,
|
||||
},
|
||||
total: rect('#total-display'),
|
||||
count: rect('#count-display'),
|
||||
submit: rect('#submit-btn'),
|
||||
lastCard: rect('#meals-list .meal-card:last-child'),
|
||||
};
|
||||
}"""
|
||||
)
|
||||
|
||||
assert layout["scrollWidth"] == layout["clientWidth"]
|
||||
for selector in ("footer", "total", "count", "submit"):
|
||||
assert layout[selector]["left"] >= 0
|
||||
assert layout[selector]["right"] <= layout["clientWidth"]
|
||||
assert layout["footer"]["position"] == "fixed"
|
||||
assert layout["footer"]["top"] >= 0
|
||||
assert layout["footer"]["bottom"] <= layout["viewportHeight"]
|
||||
assert layout["lastCard"]["bottom"] <= layout["footer"]["top"]
|
||||
finally:
|
||||
browser.close()
|
||||
page = browser.new_page()
|
||||
page.route(
|
||||
"**/api/form-status/**",
|
||||
lambda route: route.fulfill(
|
||||
status=200,
|
||||
content_type="application/json",
|
||||
body='{"status":"open"}',
|
||||
),
|
||||
)
|
||||
page.route(
|
||||
"**/api/roster**",
|
||||
lambda route: route.fulfill(
|
||||
status=200,
|
||||
content_type="application/json",
|
||||
body=json.dumps(
|
||||
{
|
||||
"employees": [
|
||||
{"name": "Ada Lovelace", "email": "ada@example.com"}
|
||||
]
|
||||
}
|
||||
),
|
||||
),
|
||||
)
|
||||
page.goto(out.as_uri())
|
||||
page.wait_for_selector('[data-meal-index="0"]')
|
||||
yield page
|
||||
browser.close()
|
||||
|
||||
def test_admin_bundle_loads(self, browser_page):
|
||||
assert browser_page.evaluate("typeof window.loadWeekOrders") == "function"
|
||||
|
|
@ -560,176 +406,27 @@ class TestGenerateFormPlaywright:
|
|||
# Reset first card via type-in
|
||||
qty = page.locator('[data-meal-index="0"] .qty')
|
||||
qty.fill("-3")
|
||||
qty.blur()
|
||||
qty.dispatch_event("change")
|
||||
page.wait_for_function(
|
||||
"() => document.querySelector('[data-meal-index=\"0\"] .qty').value === '0'"
|
||||
)
|
||||
assert qty.input_value() == "0"
|
||||
# Total may still include other meals from prior test if class-scoped page
|
||||
# is shared — set all known cards to 0 then set one meal to 2 via type-in.
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
document.querySelectorAll('[data-meal-index] .qty').forEach((input) => {
|
||||
input.value = '0';
|
||||
input.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
});
|
||||
}"""
|
||||
)
|
||||
page.wait_for_function(
|
||||
"() => document.getElementById('count-display').textContent === '0 meals'"
|
||||
)
|
||||
qty.fill("2")
|
||||
qty.blur()
|
||||
qty.dispatch_event("change")
|
||||
page.wait_for_function(
|
||||
"() => document.getElementById('count-display').textContent === '2 meals'"
|
||||
)
|
||||
assert page.locator("#total-display").inner_text() == "$10.80"
|
||||
|
||||
@pytest.mark.parametrize("width", [320, 375, 479])
|
||||
def test_local_roster_has_no_horizontal_overflow(self, browser_page, width):
|
||||
page = browser_page
|
||||
page.set_viewport_size({"width": width, "height": 800})
|
||||
dimensions = page.evaluate(
|
||||
"""() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
clientWidth: document.documentElement.clientWidth,
|
||||
})"""
|
||||
)
|
||||
assert dimensions["scrollWidth"] == dimensions["clientWidth"]
|
||||
|
||||
|
||||
class TestGenerateFormGooglePlaywright:
|
||||
@pytest.fixture(scope="class")
|
||||
@classmethod
|
||||
def signed_in_admin_page(cls, tmp_path_factory):
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError as exc: # pragma: no cover
|
||||
raise RuntimeError(
|
||||
"playwright package is required; install requirements.txt"
|
||||
) from exc
|
||||
|
||||
out = tmp_path_factory.mktemp("google-form") / "order-form.html"
|
||||
out.write_text(_render(google=True, api_key=""))
|
||||
|
||||
with sync_playwright() as p:
|
||||
try:
|
||||
browser = p.chromium.launch(headless=True)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
"Chromium is required for form Playwright tests. "
|
||||
"Run: playwright install --with-deps chromium"
|
||||
) from exc
|
||||
try:
|
||||
page = browser.new_page()
|
||||
page.add_init_script(
|
||||
"""window.google = {
|
||||
accounts: {
|
||||
id: {
|
||||
initialize() {},
|
||||
renderButton() {},
|
||||
disableAutoSelect() {},
|
||||
},
|
||||
},
|
||||
};"""
|
||||
)
|
||||
page.route(
|
||||
"https://accounts.google.com/gsi/client",
|
||||
lambda route: route.abort(),
|
||||
)
|
||||
|
||||
def handle_api(route):
|
||||
if "/api/form-status/" in route.request.url:
|
||||
route.fulfill(
|
||||
status=200,
|
||||
content_type="application/json",
|
||||
body='{"status":"open"}',
|
||||
)
|
||||
elif "/api/admin/orders" in route.request.url:
|
||||
route.fulfill(
|
||||
status=200,
|
||||
content_type="application/json",
|
||||
body='{"weeks":["2026-W30"]}',
|
||||
)
|
||||
else:
|
||||
route.fulfill(
|
||||
status=404,
|
||||
content_type="application/json",
|
||||
body="{}",
|
||||
)
|
||||
|
||||
page.route("https://api.example.com/**", handle_api)
|
||||
page.goto(out.as_uri(), wait_until="domcontentloaded")
|
||||
page.evaluate(
|
||||
"(credential) => handleCredentialResponse({ credential })",
|
||||
_google_credential(),
|
||||
)
|
||||
page.locator("#admin-btn").wait_for(state="visible")
|
||||
yield page
|
||||
finally:
|
||||
browser.close()
|
||||
|
||||
@pytest.mark.parametrize("width", [320, 375])
|
||||
def test_signed_in_admin_user_bar_fits_phone_width(
|
||||
self, signed_in_admin_page, width
|
||||
):
|
||||
page = signed_in_admin_page
|
||||
page.set_viewport_size({"width": width, "height": 800})
|
||||
|
||||
for selector in (
|
||||
"#user-avatar",
|
||||
"#user-name",
|
||||
"#user-email",
|
||||
"#admin-btn",
|
||||
"#sign-out-btn",
|
||||
):
|
||||
locator = page.locator(selector)
|
||||
assert locator.is_visible()
|
||||
bounds = locator.evaluate(
|
||||
"""element => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
return {
|
||||
left: rect.left,
|
||||
top: rect.top,
|
||||
right: rect.right,
|
||||
bottom: rect.bottom,
|
||||
viewportWidth: window.innerWidth,
|
||||
viewportHeight: window.innerHeight,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
assert bounds["left"] >= 0
|
||||
assert bounds["top"] >= 0
|
||||
assert bounds["right"] <= bounds["viewportWidth"]
|
||||
assert bounds["bottom"] <= bounds["viewportHeight"]
|
||||
|
||||
for selector in ("#user-name", "#user-email"):
|
||||
assert page.locator(selector).evaluate(
|
||||
"""element =>
|
||||
element.scrollWidth <= element.clientWidth &&
|
||||
element.scrollHeight <= element.clientHeight"""
|
||||
)
|
||||
assert page.locator("#admin-btn").is_enabled()
|
||||
assert page.locator("#sign-out-btn").is_enabled()
|
||||
|
||||
dimensions = page.evaluate(
|
||||
"""() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
clientWidth: document.documentElement.clientWidth,
|
||||
})"""
|
||||
)
|
||||
assert dimensions["scrollWidth"] == dimensions["clientWidth"]
|
||||
|
||||
def test_user_bar_stays_single_row_at_480(self, signed_in_admin_page):
|
||||
page = signed_in_admin_page
|
||||
page.set_viewport_size({"width": 480, "height": 800})
|
||||
assert (
|
||||
page.locator(".user-bar").evaluate(
|
||||
"(element) => getComputedStyle(element).flexWrap"
|
||||
)
|
||||
== "nowrap"
|
||||
)
|
||||
dimensions = page.evaluate(
|
||||
"""() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
clientWidth: document.documentElement.clientWidth,
|
||||
})"""
|
||||
)
|
||||
assert dimensions["scrollWidth"] == dimensions["clientWidth"]
|
||||
|
||||
def test_user_bar_wraps_below_shared_mobile_breakpoint(self, signed_in_admin_page):
|
||||
page = signed_in_admin_page
|
||||
page.set_viewport_size({"width": 479, "height": 800})
|
||||
assert (
|
||||
page.locator(".user-bar").evaluate(
|
||||
"(element) => getComputedStyle(element).flexWrap"
|
||||
)
|
||||
== "wrap"
|
||||
)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue