Files
zibo-dashboard/public/userarea/assets/js/worksheets-linked-modals.js
T

523 lines
23 KiB
JavaScript

(function () {
function escapeHtml(str) {
return String(str || "")
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
function valueOrDash(v) {
return v === null || v === undefined || String(v).trim() === ""
? "—"
: escapeHtml(v);
}
function renderReadonlyField(label, value) {
return `
<div class="readonly-label">${escapeHtml(label)}</div>
<div class="readonly-value">${valueOrDash(value)}</div>
`;
}
window.loadMatriceWorksheets = function (idmatrice, matriceNome, endpoint) {
endpoint = endpoint || "ajax/worksheet-linked-data.php";
$("#wl_idmatrice").val(idmatrice);
$("#wl_matrice_name").html(
`<span class="worksheet-chip"><i class="fa-solid fa-layer-group"></i>${escapeHtml(matriceNome || "")}</span>`,
);
$("#worksheetsListContainer").html(
'<div class="text-muted">Caricamento fogli di lavoro...</div>',
);
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(
'<div class="text-danger">Errore nel caricamento dei fogli</div>',
);
return;
}
const rows = data.worksheets || [];
if (!rows.length) {
$("#worksheetsListContainer").html(
'<div class="text-muted">Nessun foglio di lavoro collegato a questo profilo</div>',
);
return;
}
let html = `
<div class="table-responsive">
<table class="table table-striped align-middle worksheet-list-table">
<thead>
<tr>
<th style="width:110px;">Foglio</th>
<th style="width:100px;">Rev.</th>
<th style="width:110px;">Stato</th>
<th style="width:140px;">Data foglio</th>
<th>Cliente</th>
<th>Codice profilo</th>
<th style="width:110px;">Mescole</th>
<th style="width:230px;">Azioni</th>
</tr>
</thead>
<tbody>
`;
rows.forEach((r) => {
const statusBadge =
r.worksheet_status === "inactive"
? `<span class="worksheet-badge-status-inactive">Inattivo</span>`
: `<span class="worksheet-badge-status-active">Attivo</span>`;
html += `
<tr>
<td><span class="worksheet-badge-fl">${escapeHtml(r.worksheet_number_label || "—")}</span></td>
<td><span class="worksheet-badge-rev">${escapeHtml(r.revision_label || "0")}</span></td>
<td>${statusBadge}</td>
<td>${escapeHtml(r.worksheet_date_it || "—")}</td>
<td title="${escapeHtml(r.customer_name || "")}">${escapeHtml(r.customer_name || "—")}</td>
<td>${escapeHtml(r.profile_type_code || "—")}</td>
<td>${escapeHtml(String(r.mix_count || 0))}</td>
<td class="text-nowrap">
<button type="button"
class="btn btn-view-worksheet open-worksheet-detail"
data-id="${r.id}"
data-endpoint="${escapeHtml(endpoint)}">
<i class="fa-solid fa-eye me-1"></i>Apri dettaglio
</button>
<a class="worksheet-open-link ms-1"
href="manage-worksheet.php?id=${r.id}"
target="_blank">
<i class="fa-solid fa-arrow-up-right-from-square"></i>Apri pagina
</a>
</td>
</tr>
`;
});
html += `
</tbody>
</table>
</div>
`;
$("#worksheetsListContainer").html(html);
})
.catch(() => {
$("#worksheetsListContainer").html(
'<div class="text-danger">Errore nel caricamento dei fogli</div>',
);
});
};
let wsDisegniList = [];
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 showWorksheetDisegno(index) {
const f = wsDisegniList[index];
if (!f) return;
$(".ws-disegno-item").removeClass("active");
$(`.ws-disegno-item[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 = `<iframe src="${escapeHtml(path)}#zoom=page-width"></iframe>`;
} else if (wsIsImage(ext)) {
viewer = `<div class="img-wrap"><img src="${escapeHtml(path)}" alt="${escapeHtml(name)}"></div>`;
} else {
viewer = `<div class="h-100 d-flex justify-content-center align-items-center text-muted">Anteprima non disponibile per questo formato: usa "Apri in nuova scheda"</div>`;
}
$("#wsDisegnoToolbar").html(`
<div>
<div class="fw-bold">${escapeHtml(name)}</div>
${f.description ? `<div class="small text-muted">${escapeHtml(f.description)}</div>` : ""}
</div>
<a href="${escapeHtml(path)}" target="_blank" class="worksheet-open-link">
<i class="fa-solid fa-arrow-up-right-from-square"></i> Apri in nuova scheda
</a>
`);
$("#wsDisegnoViewer").html(viewer);
}
function loadWorksheetDisegni(idmatrice) {
wsDisegniList = [];
const $c = $("#wsDisegniContainer");
if (!idmatrice) {
$("#wsDisegniCount").text("0");
$c.html(
'<div class="text-muted">Nessun profilo collegato a questo foglio.</div>',
);
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",
);
wsDisegniList = (data.attachments || []).filter(
(a) => parseInt(a.is_disegno, 10) === 1,
);
$("#wsDisegniCount").text(wsDisegniList.length);
if (!wsDisegniList.length) {
$c.html(
'<div class="text-muted p-3">Nessun disegno tecnico per questo profilo. ' +
"Si possono segnare dalla gestione matrici (graffetta → pulsante compasso).</div>",
);
return;
}
let listHtml = "";
if (wsDisegniList.length > 1) {
listHtml =
'<div class="ws-disegni-list">' +
wsDisegniList
.map(
(f, i) =>
`<button type="button" class="ws-disegno-item" data-index="${i}">📐 ${escapeHtml(f.file_name || "Disegno " + (i + 1))}</button>`,
)
.join("") +
"</div>";
}
$c.html(`
${listHtml}
<div class="ws-disegno-toolbar" id="wsDisegnoToolbar"></div>
<div class="ws-disegno-viewer" id="wsDisegnoViewer"></div>
`);
// Se l'utente ha già aperto il tab mentre caricava, mostro subito il primo
if ($('.ws-tab[data-tab="disegni"]').hasClass("active")) {
showWorksheetDisegno(0);
}
})
.catch((err) => {
$("#wsDisegniCount").text("!");
$c.html(
'<div class="text-danger">Errore nel caricamento dei disegni: ' +
escapeHtml(err.message || "") +
"</div>",
);
});
}
window.loadWorksheetDetail = function (worksheetId, endpoint) {
endpoint = endpoint || "ajax/worksheet-linked-data.php";
$("#worksheetDetailContainer").html(
'<div class="text-muted">Caricamento dettaglio foglio...</div>',
);
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 worksheets:", data);
$("#worksheetsListContainer").html(
'<div class="text-danger">Errore nel caricamento dei fogli: ' +
escapeHtml(
data.message || "nessun dettaglio restituito",
) +
"</div>",
);
return;
}
const ws = data.worksheet || {};
const mixRows = data.mix_rows || [];
let mixHtml = `<div class="text-muted">Nessuna mescola associata</div>`;
if (mixRows.length) {
mixHtml = `
<div class="table-responsive">
<table class="table table-striped align-middle mix-readonly-table">
<thead>
<tr>
<th style="width:80px;">Pos</th>
<th>Mescola</th>
<th style="width:120px;">Peso g/m</th>
<th style="width:140px;">Densità</th>
<th style="width:150px;">Durezza</th>
<th style="width:130px;">Lubr.</th>
<th>Note lubr.</th>
</tr>
</thead>
<tbody>
`;
mixRows.forEach((r) => {
const nomeMescola = r.mescola_uscita
? `${escapeHtml(r.mescola_nome || "—")} <div class="small text-muted">${escapeHtml(r.mescola_uscita)}</div>`
: escapeHtml(r.mescola_nome || "—");
mixHtml += `
<tr>
<td>${escapeHtml(String(r.mix_position || ""))}</td>
<td>${nomeMescola}</td>
<td>${valueOrDash(r.mix_weight_g_m)}</td>
<td>${valueOrDash(r.required_density)}</td>
<td>${valueOrDash(r.required_hardness_shore_a)}</td>
<td>${valueOrDash(r.lubrication_type)}</td>
<td>${valueOrDash(r.lubrication_notes)}</td>
</tr>
`;
});
mixHtml += `
</tbody>
</table>
</div>
`;
}
const headerHtml = `
<div class="worksheet-title-box mb-3">
<div class="d-flex justify-content-between align-items-start gap-3 flex-wrap">
<div>
<h4 class="mb-1">${escapeHtml(ws.worksheet_number_label || "—")} / Rev. ${escapeHtml(ws.revision_label || "0")}</h4>
<small>
Stato: ${escapeHtml(ws.worksheet_status_label || "Attivo")}
${ws.matrice_nome ? " • Profilo: " + escapeHtml(ws.matrice_nome) : ""}
${ws.matrice_cliente ? " • Cliente matrice: " + escapeHtml(ws.matrice_cliente) : ""}
</small>
</div>
<div>
<a href="manage-worksheet.php?id=${escapeHtml(String(ws.id || ""))}"
target="_blank"
class="worksheet-open-link">
<i class="fa-solid fa-arrow-up-right-from-square"></i>
Apri foglio completo
</a>
</div>
</div>
</div>
`;
const html = `
<div class="row g-3">
<div class="col-lg-6">
<div class="readonly-card">
<div class="readonly-card-header">Dati principali</div>
<div class="readonly-card-body">
<div class="readonly-grid">
${renderReadonlyField("Foglio", ws.worksheet_number_label)}
${renderReadonlyField("Revisione", ws.revision_label)}
${renderReadonlyField("Stato", ws.worksheet_status_label)}
${renderReadonlyField("Data foglio", ws.worksheet_date_it)}
${renderReadonlyField("Cliente override", ws.customer_name)}
${renderReadonlyField("Codice profilo", ws.profile_type_code)}
${renderReadonlyField("Marchiatura", ws.marking)}
${renderReadonlyField("Approvato da", ws.approved_by)}
${renderReadonlyField("Creato il", ws.created_at_it)}
${renderReadonlyField("Ultimo aggiornamento", ws.updated_at_it)}
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="readonly-card">
<div class="readonly-card-header">Controlli produzione</div>
<div class="readonly-card-body">
<div class="readonly-grid">
${renderReadonlyField("Taglio", ws.control_frequency_cut)}
${renderReadonlyField("Disegno", ws.control_frequency_drawing)}
${renderReadonlyField("Dima", ws.control_frequency_jig)}
${renderReadonlyField("Modalità dima", ws.control_mode_jig)}
</div>
<hr>
<div class="readonly-label mb-2">Impostazione misure controllo produzione</div>
<div class="readonly-value" style="white-space:pre-wrap;">${valueOrDash(ws.prod_control_measure_settings)}</div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="readonly-card">
<div class="readonly-card-header">Packaging / Confezionamento</div>
<div class="readonly-card-body">
<div class="readonly-grid">
${renderReadonlyField("Codice confezione", ws.requested_package_code)}
${renderReadonlyField("Metri per confezione", ws.meters_per_package)}
${renderReadonlyField("Tolleranza metri/conf.", ws.meters_per_package_tolerance)}
${renderReadonlyField("Scatola tipo", ws.box_type)}
${renderReadonlyField("Conf./pezzi per scatola", ws.packages_or_pieces_per_box)}
${renderReadonlyField("Metri per scatola", ws.meters_per_box)}
${renderReadonlyField("Bancale tipo", ws.pallet_type)}
${renderReadonlyField("Scatole/conf. per bancale", ws.boxes_or_packages_per_pallet)}
</div>
<hr>
<div class="readonly-label mb-2">Note metri / confezione</div>
<div class="readonly-value" style="white-space:pre-wrap;">${valueOrDash(ws.meters_per_package_notes)}</div>
</div>
</div>
</div>
<div class="col-lg-6">
<div class="readonly-card">
<div class="readonly-card-header">Velocità e note</div>
<div class="readonly-card-body">
<div class="readonly-grid">
${renderReadonlyField("Vel. prevista kg/h", ws.speed_expected_kg_h)}
${renderReadonlyField("Vel. effettiva kg/h", ws.speed_actual_kg_h)}
${renderReadonlyField("Vel. prevista m/h", ws.speed_expected_m_h)}
${renderReadonlyField("Vel. effettiva m/h", ws.speed_actual_m_h)}
</div>
<hr>
<div class="readonly-label mb-2">Note</div>
<div class="readonly-value" style="white-space:pre-wrap;">${valueOrDash(ws.notes)}</div>
</div>
</div>
</div>
<div class="col-12">
<div class="readonly-card">
<div class="readonly-card-header">Mescole associate al foglio</div>
<div class="readonly-card-body">
${mixHtml}
</div>
</div>
</div>
</div>
`;
const fullHtml = `
${headerHtml}
<div class="ws-tabs">
<button type="button" class="ws-tab active" data-tab="dati">
<i class="fa-solid fa-file-lines me-1"></i> Dati foglio
</button>
<button type="button" class="ws-tab" data-tab="disegni">
📐 Disegni tecnici <span class="ws-tab-count" id="wsDisegniCount">…</span>
</button>
</div>
<div class="ws-tab-pane active" data-pane="dati">
${html}
</div>
<div class="ws-tab-pane" data-pane="disegni">
<div id="wsDisegniContainer">
<div class="text-muted">Caricamento disegni tecnici...</div>
</div>
</div>
`;
$("#worksheetDetailContainer").html(fullHtml);
loadWorksheetDisegni(ws.idmatrice);
})
.catch((err) => {
console.error("Catch loadMatriceWorksheets:", err);
$("#worksheetsListContainer").html(
'<div class="text-danger">Errore nel caricamento dei fogli: ' +
escapeHtml(err.message || "errore JavaScript/fetch") +
"</div>",
);
});
};
$(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 PDF solo la prima volta che si apre il tab
if (
tab === "disegni" &&
wsDisegniList.length &&
$("#wsDisegnoViewer").is(":empty")
) {
showWorksheetDisegno(0);
}
});
$(document).on("click", ".ws-disegno-item", function () {
showWorksheetDisegno(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();
});
})();