(function () { function escapeHtml(str) { return String(str === null || str === undefined ? "" : str) .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } function isEmpty(v) { return v === null || v === undefined || String(v).trim() === ""; } function valueOrDash(v) { return isEmpty(v) ? "—" : escapeHtml(v); } // Traduce il valore salvato (es. "every_2h") nell'etichetta del menu a tendina, // usando le etichette di ws_lookup_options restituite dall'endpoint. // Se l'etichetta non c'è, mostra il valore così com'è. function lookupLabel(lookups, category, value) { if (isEmpty(value)) return ""; const map = lookups && lookups[category]; if (map && map[String(value)] !== undefined) return map[String(value)]; return value; } // Campo in sola lettura: etichetta piccola sopra, valore in evidenza sotto function wsdField(label, value, extraClass) { const empty = isEmpty(value); return `
${escapeHtml(label)}
${valueOrDash(value)}
`; } // Blocco di testo lungo (note, misure di controllo) function wsdText(label, value, emptyText) { const empty = isEmpty(value); return `
${label ? `
${escapeHtml(label)}
` : ""}
${empty ? escapeHtml(emptyText || "—") : escapeHtml(value)}
`; } function wsdSection(theme, title, badge, body, colClass) { return `
${title} ${badge ? `${badge}` : ""}
${body}
`; } window.loadMatriceWorksheets = function (idmatrice, matriceNome, endpoint) { endpoint = endpoint || "ajax/worksheet-linked-data.php"; $("#wl_idmatrice").val(idmatrice); $("#wl_matrice_name").html( `${escapeHtml(matriceNome || "")}`, ); $("#worksheetsListContainer").html( '
Caricamento fogli di lavoro...
', ); fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "action=get_matrice_worksheets&idmatrice=" + encodeURIComponent(idmatrice), }) .then(async (r) => { const text = await r.text(); try { return JSON.parse(text); } catch (e) { console.error("Risposta non JSON worksheets:", text); throw new Error("Risposta non JSON, vedi console"); } }) .then((data) => { if (!data.success) { $("#worksheetsListContainer").html( '
Errore nel caricamento dei fogli
', ); return; } const rows = data.worksheets || []; if (!rows.length) { $("#worksheetsListContainer").html( '
Nessun foglio di lavoro collegato a questo profilo
', ); return; } let html = `
`; rows.forEach((r) => { const statusBadge = r.worksheet_status === "inactive" ? `Inattivo` : `Attivo`; html += ` `; }); html += `
Foglio Rev. Stato Data foglio Cliente Codice profilo Mescole Azioni
${escapeHtml(r.worksheet_number_label || "—")} ${escapeHtml(r.revision_label || "0")} ${statusBadge} ${escapeHtml(r.worksheet_date_it || "—")} ${escapeHtml(r.customer_name || "—")} ${escapeHtml(r.profile_type_code || "—")} ${escapeHtml(String(r.mix_count || 0))} Apri pagina
`; $("#worksheetsListContainer").html(html); }) .catch(() => { $("#worksheetsListContainer").html( '
Errore nel caricamento dei fogli
', ); }); }; // ================================================================ // Tab allegati della matrice: disegni tecnici, strumenti, cicli // ================================================================ const WS_ATT_KINDS = { disegni: { flag: "is_disegno", label: "Disegni tecnici", icon: "📐", itemLabel: "Disegno", empty: "Nessun disegno tecnico per questo profilo. " + "Si possono segnare dalla gestione matrici (graffetta → pulsante compasso).", }, strumenti: { flag: "is_strumento", label: "Strumenti di lavoro", icon: "🔧", itemLabel: "Strumento", empty: "Nessuno strumento di lavoro per questo profilo. " + "Si possono segnare dalla gestione matrici (graffetta → pulsante chiave inglese).", }, cicli: { flag: "is_ciclo", label: "Cicli di lavoro", icon: "🔁", itemLabel: "Ciclo", empty: "Nessun ciclo di lavoro per questo profilo. " + "Si possono segnare dalla gestione matrici (graffetta → pulsante frecce).", }, }; let wsAttLists = { disegni: [], strumenti: [], cicli: [] }; function wsFileExt(name) { const p = String(name || "").split("."); return p.length > 1 ? p.pop().toLowerCase() : ""; } function wsIsImage(ext) { return ["jpg", "jpeg", "png", "gif", "bmp", "webp"].includes(ext); } function showWorksheetAttachment(kind, index) { const list = wsAttLists[kind] || []; const f = list[index]; if (!f) return; $(`.ws-disegno-item[data-kind="${kind}"]`).removeClass("active"); $( `.ws-disegno-item[data-kind="${kind}"][data-index="${index}"]`, ).addClass("active"); const name = f.file_name || ""; const path = f.file_url || f.file_path || ""; const ext = wsFileExt(name); let viewer; if (ext === "pdf") { viewer = ``; } else if (wsIsImage(ext)) { viewer = `
${escapeHtml(name)}
`; } else { viewer = `
Anteprima non disponibile per questo formato: usa "Apri in nuova scheda"
`; } $(`#wsToolbar_${kind}`).html(`
${escapeHtml(name)}
${f.description ? `
${escapeHtml(f.description)}
` : ""}
Apri in nuova scheda `); $(`#wsViewer_${kind}`).html(viewer); } function renderWorksheetAttachmentKind(kind) { const cfg = WS_ATT_KINDS[kind]; const list = wsAttLists[kind]; const $c = $(`#wsContainer_${kind}`); $(`#wsCount_${kind}`).text(list.length); if (!list.length) { $c.html( `
${escapeHtml(cfg.empty)}
`, ); return; } let listHtml = ""; if (list.length > 1) { listHtml = '
' + list .map( (f, i) => ``, ) .join("") + "
"; } $c.html(` ${listHtml}
`); // Se l'utente ha già aperto il tab mentre caricava, mostro subito il primo if ($(`.ws-tab[data-tab="${kind}"]`).hasClass("active")) { showWorksheetAttachment(kind, 0); } } function loadWorksheetAttachments(idmatrice) { wsAttLists = { disegni: [], strumenti: [], cicli: [] }; const kinds = Object.keys(WS_ATT_KINDS); if (!idmatrice) { kinds.forEach((k) => { $(`#wsCount_${k}`).text("0"); $(`#wsContainer_${k}`).html( '
Nessun profilo collegato a questo foglio.
', ); }); return; } fetch("get_matrice_attachments.php?id=" + encodeURIComponent(idmatrice)) .then((r) => r.json()) .then((data) => { if (!data.success) throw new Error( data.message || "Errore caricamento allegati", ); const all = data.attachments || []; kinds.forEach((k) => { const flag = WS_ATT_KINDS[k].flag; wsAttLists[k] = all.filter( (a) => parseInt(a[flag], 10) === 1, ); renderWorksheetAttachmentKind(k); }); }) .catch((err) => { kinds.forEach((k) => { $(`#wsCount_${k}`).text("!"); $(`#wsContainer_${k}`).html( '
Errore nel caricamento degli allegati: ' + escapeHtml(err.message || "") + "
", ); }); }); } // ================================================================ // Dettaglio foglio di lavoro (sola lettura) // Rispecchia le sezioni di manage-worksheet.php: // 1 Dati principali · 2 Controlli · 3 Imballo · 4 Velocità · 5 Note · 6 Mescole // ================================================================ function renderWorksheetDetail(data) { const ws = data.worksheet || {}; const mixRows = data.mix_rows || []; const packageRows = data.package_rows || []; const lookups = data.lookups || {}; const isInactive = ws.worksheet_status === "inactive"; const statusLabel = ws.worksheet_status_label || (isInactive ? "Inattivo" : "Attivo"); const statusBadge = isInactive ? `${escapeHtml(statusLabel)}` : `${escapeHtml(statusLabel)}`; const cliente = ws.customer_name || ws.matrice_cliente || ""; // ---------- Intestazione ---------- const excelLink = ws.source_xlsx_path ? ` Excel di origine ` : ""; const headerHtml = `

${escapeHtml(ws.worksheet_number_label || "—")} / Rev. ${escapeHtml(ws.revision_label || "0")}

${ws.matrice_nome ? "Profilo: " + escapeHtml(ws.matrice_nome) : "Nessun profilo collegato"}
`; // ---------- Striscia riepilogo ---------- const summaryHtml = `
Stato
${statusBadge}
Cliente
${valueOrDash(cliente)}
Codice profilo
${valueOrDash(ws.profile_type_code)}
Data foglio
${valueOrDash(ws.worksheet_date_it)}
Mescole / Imballi
${mixRows.length} / ${packageRows.length}
`; // ---------- 1. Dati principali ---------- const sec1 = wsdSection( "blue", "1. Dati principali", "", `
${wsdField("Matrice / Profilo", ws.matrice_nome)} ${wsdField("Data foglio", ws.worksheet_date_it)} ${wsdField("Codice profilo", ws.profile_type_code)} ${wsdField("Cliente (override)", ws.customer_name)} ${wsdField("Marchiatura", lookupLabel(lookups, "marking", ws.marking))} ${wsdField("Visto / Approvazione", ws.approved_by)}
Creato il ${valueOrDash(ws.created_at_it)} · Ultimo aggiornamento ${valueOrDash(ws.updated_at_it)}
`, "col-lg-6", ); // ---------- 2. Controlli di produzione ---------- const sec2 = wsdSection( "green", "2. Controlli di produzione", "", `
${wsdField("Taglio", lookupLabel(lookups, "control_frequency_cut", ws.control_frequency_cut))} ${wsdField("Disegno", lookupLabel(lookups, "control_frequency_drawing", ws.control_frequency_drawing))} ${wsdField("Dima", lookupLabel(lookups, "control_frequency_jig", ws.control_frequency_jig))} ${wsdField("Modalità dima", lookupLabel(lookups, "control_mode_jig", ws.control_mode_jig))}
${wsdText("Impostazione misure controllo produzione", ws.prod_control_measure_settings, "Nessuna indicazione")} `, "col-lg-6", ); // ---------- 3. Imballo e confezionamento ---------- let packagesHtml = `
Nessun imballo associato
`; if (packageRows.length) { packagesHtml = `
${packageRows .map( (p) => ` `, ) .join("")}
Pos Categoria Imballo
${valueOrDash(p.package_position)} ${valueOrDash(p.package_category)}
${valueOrDash(p.package_name)}
${p.package_item_code ? `
${escapeHtml(p.package_item_code)}
` : ""}
`; } const sec3 = wsdSection( "orange", "3. Imballo e confezionamento", `${packageRows.length} imball${packageRows.length === 1 ? "o" : "i"}`, `
${packagesHtml}
${wsdField("Metri per confezione", ws.meters_per_package)} ${wsdField("Tolleranza metri/conf.", ws.meters_per_package_tolerance)} ${wsdField("Conf./pezzi per scatola", ws.packages_or_pieces_per_box)} ${wsdField("Metri per scatola", ws.meters_per_box)} ${wsdField("Scatole/conf. per bancale", ws.boxes_or_packages_per_pallet)}
${wsdText("Note metri/confezione", ws.meters_per_package_notes, "Nessuna nota")}
`, "col-12", ); // ---------- 4. Velocità di produzione ---------- const sec4 = wsdSection( "purple", "4. Velocità di produzione", "", `
PrevistaEffettiva
kg/h ${valueOrDash(ws.speed_expected_kg_h)} ${valueOrDash(ws.speed_actual_kg_h)}
m/h ${valueOrDash(ws.speed_expected_m_h)} ${valueOrDash(ws.speed_actual_m_h)}
`, "col-lg-6", ); // ---------- 5. Note finali ---------- const sec5 = wsdSection( "gray", "5. Note finali", "", wsdText("", ws.notes, "Nessuna nota"), "col-lg-6", ); // ---------- 6. Mescole ---------- let mixHtml = `
Nessuna mescola associata
`; if (mixRows.length) { mixHtml = `
${mixRows .map( (r) => ` `, ) .join("")}
Pos Mescola Peso g/m Sostegno g/m Densità Durezza (Sh A) Lubrificazione Note lubr.
${valueOrDash(r.mix_position)}
${valueOrDash(r.mescola_nome)}
${r.mescola_uscita ? `
${escapeHtml(r.mescola_uscita)}
` : ""}
${valueOrDash(r.mix_weight_g_m)} ${valueOrDash(r.support_weight_g_m)} ${valueOrDash(r.required_density)} ${valueOrDash(r.required_hardness_shore_a)} ${valueOrDash(lookupLabel(lookups, "lubrication_type", r.lubrication_type))} ${valueOrDash(r.lubrication_notes)}
`; } const sec6 = wsdSection( "cyan", "6. Mescole associate al foglio", `${mixRows.length} rig${mixRows.length === 1 ? "a" : "he"}`, mixHtml, "col-12", ); const datiHtml = ` ${summaryHtml}
${sec1} ${sec2} ${sec3} ${sec4} ${sec5} ${sec6}
`; // ---------- Tab allegati ---------- const attTabsHtml = Object.keys(WS_ATT_KINDS) .map((k) => { const c = WS_ATT_KINDS[k]; return ` `; }) .join(""); const attPanesHtml = Object.keys(WS_ATT_KINDS) .map((k) => { const c = WS_ATT_KINDS[k]; return `
Caricamento ${escapeHtml(c.label.toLowerCase())}...
`; }) .join(""); return ` ${headerHtml}
${attTabsHtml}
${datiHtml}
${attPanesHtml} `; } window.loadWorksheetDetail = function (worksheetId, endpoint) { endpoint = endpoint || "ajax/worksheet-linked-data.php"; const $box = $("#worksheetDetailContainer"); $box.html( '
Caricamento dettaglio foglio...
', ); fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "action=get_worksheet_detail&worksheet_id=" + encodeURIComponent(worksheetId), }) .then(async (r) => { const text = await r.text(); try { return JSON.parse(text); } catch (e) { console.error("Risposta non JSON worksheet detail:", text); throw new Error("Risposta non JSON, vedi console"); } }) .then((data) => { if (!data.success) { console.error("Errore dettaglio foglio:", data); $box.html( '
Errore nel caricamento del foglio: ' + escapeHtml( data.message || "nessun dettaglio restituito", ) + "
", ); return; } $box.html(renderWorksheetDetail(data)); loadWorksheetAttachments((data.worksheet || {}).idmatrice); }) .catch((err) => { console.error("Errore dettaglio foglio:", err); $box.html( '
Errore nel caricamento del foglio: ' + escapeHtml(err.message || "errore JavaScript/fetch") + "
", ); }); }; $(document).on("click", ".worksheets, .show-worksheets", function () { const idmatrice = $(this).data("id"); const nome = $(this).data("nome") || ""; const endpoint = $(this).data("endpoint") || "ajax/worksheet-linked-data.php"; loadMatriceWorksheets(idmatrice, nome, endpoint); new bootstrap.Modal( document.getElementById("worksheetsListModal"), ).show(); }); $(document).on("click", ".ws-tab", function () { const tab = $(this).data("tab"); $(".ws-tab").removeClass("active"); $(this).addClass("active"); $(".ws-tab-pane").removeClass("active"); $(`.ws-tab-pane[data-pane="${tab}"]`).addClass("active"); // Carico il file solo la prima volta che si apre il tab if ( WS_ATT_KINDS[tab] && (wsAttLists[tab] || []).length && $(`#wsViewer_${tab}`).is(":empty") ) { showWorksheetAttachment(tab, 0); } }); $(document).on("click", ".ws-disegno-item", function () { showWorksheetAttachment( $(this).data("kind"), parseInt($(this).data("index"), 10), ); }); $(document).on("click", ".open-worksheet-detail", function () { const worksheetId = $(this).data("id"); const endpoint = $(this).data("endpoint") || "ajax/worksheet-linked-data.php"; loadWorksheetDetail(worksheetId, endpoint); new bootstrap.Modal( document.getElementById("worksheetDetailModal"), ).show(); }); })();