`;
const cat = categoryDivs[p.category] ? p.category : "food";
categoryDivs[cat].appendChild(div);
});
}
function updateCount(code, delta) {
counts[code] = (counts[code] || 0) + delta;
if (counts[code] < 0) counts[code] = 0;
currentOrder[code] = counts[code];
const el = document.getElementById("p-" + code);
if (el) el.innerText = counts[code];
updateCurrentTotal();
}
function updateCurrentTotal() {
let total = 0;
products.forEach(p => total += (currentOrder[p.code] || 0) * p.price);
document.getElementById("current-total").innerText =
"Totale ordine: €" + total.toFixed(2);
}
async function toggleDetails() {
const details = document.getElementById("order-details");
if (details.style.display === "block") { details.style.display = "none"; return; }
const res = await fetch(API.totali, { credentials: 'same-origin' });
const data = await res.json(); // es: {"brioche_vuota":2, "caffe":10}
const entries = Object.entries(data || {})
.map(([id, qty]) => [normalizeKey(id), Number(qty) || 0, String(id)])
.filter(([, qty]) => qty > 0)
.sort((a, b) => b[1] - a[1]);
let html = "";
const missing = [];
entries.forEach(([code, qty, original]) => {
const p = productByCode[code];
if (!p) missing.push({ originalId: original, normalized: code });
const name = p ? p.name : original;
html += `
${escapeHtml(name)}: ${qty}
`;
});
if (missing.length) {
console.warn("ID senza match nel listino (ordini -> listino):", missing);
}
details.innerHTML = html || "Nessun ordine
";
details.style.display = "block";
}
async function confirmOrder() {
let total = 0;
let hasItems = false;
products.forEach(p => {
const q = currentOrder[p.code] || 0;
if (q > 0) hasItems = true;
total += q * p.price;
});
if (!hasItems) return alert("Nessun prodotto");
await fetch(API.ordini, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
credentials: 'same-origin',
body: JSON.stringify({ dettaglio: currentOrder, totale: total })
});
products.forEach(p => {
counts[p.code] = 0;
currentOrder[p.code] = 0;
const el = document.getElementById("p-" + p.code);
if (el) el.innerText = "0";
});
updateCurrentTotal();
await loadSummaryFromOrdini();
alert("Ordine confermato e salvato!");
}
function cancelOrder() {
products.forEach(p => {
counts[p.code] = 0;
currentOrder[p.code] = 0;
const el = document.getElementById("p-" + p.code);
if (el) el.innerText = "0";
});
updateCurrentTotal();
}
function exportOrders() {
window.location = API.export;
}
(async function init(){
setDebug("Caricamento…");
try {
await loadSummaryFromOrdini();
await loadProductsFromListino();
setDebug("");
} catch (e) {
console.error(e);
setDebug("Errore caricamento. Controlla console (F12).");
}
})();