2025-09-20 22:00:16 +02:00

1067 lines
40 KiB
JavaScript

$(document).ready(function () {
console.log("parts.js caricato correttamente");
// ===================
// GLOBAL STATE
// ===================
let photoData = {
naturalWidth: 0,
naturalHeight: 0,
displayWidth: 0,
displayHeight: 0,
scale: 1,
};
let photoAnnotations = {}; // Annotazioni per ogni foto
let partColors = {}; // Colori associati ai numeri delle parti
let selectedPartNumber = null; // Numero della parte selezionata
let unsavedChanges = false; // Flag per modifiche non salvate
// ===================
// VOICE RECOGNITION SETUP
// ===================
const SpeechRecognition =
window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition = null;
let isVoiceActive = false;
const magicWord = "salva"; // Parola magica per aggiungere nuova riga
if (SpeechRecognition) {
recognition = new SpeechRecognition();
recognition.lang = "it-IT";
recognition.continuous = true;
recognition.interimResults = false;
recognition.onresult = function (event) {
const transcript = event.results[
event.results.length - 1
][0].transcript
.trim()
.toLowerCase();
console.log("Transcript vocale:", transcript);
const $currentRow = $("#partsTableBody tr:last");
const $descriptionInput = $currentRow.find(".part-description");
if (transcript.includes(magicWord)) {
const cleanedTranscript = transcript
.replace(magicWord, "")
.trim();
if (cleanedTranscript) {
$descriptionInput.val(
(
$descriptionInput.val() +
" " +
cleanedTranscript
).trim(),
);
$descriptionInput.trigger("blur");
}
const maxPartNumber = Math.max(
...$("#partsTableBody tr")
.map(function () {
return (
parseInt($(this).find(".part-number").val()) ||
0
);
})
.get(),
);
addNewRow(maxPartNumber + 1);
const $newRow = $("#partsTableBody tr:last");
$newRow.find(".part-description").focus();
} else {
$descriptionInput.val(
($descriptionInput.val() + " " + transcript).trim(),
);
$descriptionInput.trigger("blur");
}
};
recognition.onerror = function (event) {
console.error("Errore riconoscimento vocale:", event.error);
if (event.error === "no-speech" || event.error === "aborted") {
if (isVoiceActive) recognition.start();
} else {
alert("Errore nel riconoscimento vocale: " + event.error);
toggleVoiceRecognition();
}
};
recognition.onend = function () {
if (isVoiceActive) recognition.start();
};
} else {
console.warn("Riconoscimento vocale non supportato dal browser.");
$("#toggleVoiceBtn").hide();
}
function toggleVoiceRecognition() {
if (!recognition) return;
isVoiceActive = !isVoiceActive;
const $btn = $("#toggleVoiceBtn");
if (isVoiceActive) {
$btn.addClass("btn-danger").html(
'<i class="fas fa-microphone-slash"></i> Stop Voce',
);
recognition.start();
$("#partsTableBody tr:last").find(".part-description").focus();
} else {
$btn.removeClass("btn-danger")
.addClass("btn-secondary")
.html('<i class="fas fa-microphone"></i> Voce');
recognition.stop();
}
}
$("#toggleVoiceBtn").on("click", toggleVoiceRecognition);
// ===================
// MODAL HANDLING
// ===================
$(".parts-btn").on("click", function () {
const iddatadb = $(this).data("iddatadb");
const idquotations = $(this).data("idquotations");
const rowIndex = $(this).data("row");
const importRef = $("table tbody tr")
.eq(rowIndex)
.find("td")
.eq(1)
.text();
const description =
$("table tbody tr").eq(rowIndex).find("td").eq(2).text() ||
"Sconosciuto";
$("#trfHeader").text(
`${iddatadb || idquotations} - ${importRef} - ${description}`,
);
$("#partsModal")
.data("iddatadb", iddatadb)
.data("idquotations", idquotations);
loadPhoto(iddatadb, idquotations);
loadExistingParts(iddatadb, idquotations);
const modal = new bootstrap.Modal(
document.getElementById("partsModal"),
);
modal.show();
});
$("#partsModal .close-btn, #partsModal").on("click", function (event) {
if (event.target === this) {
const modal = bootstrap.Modal.getInstance(
document.getElementById("partsModal"),
);
modal.hide();
}
});
$("#partsModal").on("hide.bs.modal", function (e) {
if (
unsavedChanges &&
!confirm("Hai modifiche non salvate. Vuoi davvero uscire?")
) {
e.preventDefault();
}
});
// ===================
// PHOTO LOADERS
// ===================
function loadPhoto(iddatadb, idquotations) {
const endpoint = idquotations
? "load_photo_quotation.php"
: "load_photo.php";
const data = idquotations
? { idquotations: idquotations }
: { iddatadb: iddatadb };
$.ajax({
url: endpoint,
method: "GET",
data: data,
success: function (response) {
if (response.success) {
if (response.photos && response.photos.length > 1) {
showPhotoSelector(response.photos);
} else if (
response.photos &&
response.photos.length === 1
) {
loadSinglePhoto(response.photos[0]);
} else {
$("#samplePhoto").attr("src", "");
alert("Nessuna foto trovata per questo elemento.");
}
} else {
alert(
response.message ||
"Errore nel caricamento della foto.",
);
}
},
error: function (xhr, status, error) {
alert(
`Errore nel caricamento della foto: ${error} (${xhr.status})`,
);
},
});
}
function showPhotoSelector(photos) {
const selectorContainer = $("#photoSelectorContainer");
selectorContainer.empty().show();
const selector = $(
'<select id="photoSelector" class="form-control"></select>',
);
photos.forEach((photo, index) => {
const photoName = photo.split("/").pop();
const option = $("<option></option>")
.val(photo)
.text(`Photo ${index + 1} - ${photoName}`);
selector.append(option);
});
selector.on("change", function () {
loadSinglePhoto($(this).val());
});
selectorContainer.append(selector);
if (photos.length > 0) {
selector.val(photos[0]);
loadSinglePhoto(photos[0]);
}
}
function loadSinglePhoto(photoPath) {
const img = $("#samplePhoto");
img.off("load").attr("src", photoPath);
img.on("load", function () {
const canvas = document.getElementById("photoCanvas");
const ctx = canvas.getContext("2d");
const naturalWidth = img[0].naturalWidth;
const naturalHeight = img[0].naturalHeight;
const parent = $(canvas).parent();
const maxW = parent.width();
const maxH = parent.height();
const scale = Math.min(maxW / naturalWidth, maxH / naturalHeight);
photoData = {
naturalWidth,
naturalHeight,
displayWidth: Math.max(1, Math.round(naturalWidth * scale)),
displayHeight: Math.max(1, Math.round(naturalHeight * scale)),
scale,
};
canvas.width = naturalWidth;
canvas.height = naturalHeight;
canvas.style.width = `${photoData.displayWidth}px`;
canvas.style.height = `${photoData.displayHeight}px`;
$("#markerContainer").css({
width: `${photoData.displayWidth}px`,
height: `${photoData.displayHeight}px`,
});
$("#descriptionList").css({
maxWidth: `${Math.max(200, Math.round(photoData.displayWidth * 0.35))}px`,
});
ctx.clearRect(0, 0, naturalWidth, naturalHeight);
ctx.drawImage(img[0], 0, 0, naturalWidth, naturalHeight);
updateMarkers();
updateDescriptions();
});
}
// ===================
// PARTS TABLE
// ===================
function addNewRow(nextPartNumber, isMix = false) {
const description = isMix ? "Mix" : "";
const defaultColor = isMix ? "#0000ff" : "#ff0000";
const newRow = `
<tr data-part-id="">
<td><input type="number" class="form-control form-control-sm part-number" value="${nextPartNumber || 1}" style="width: 80px;"></td>
<td><input type="text" class="form-control form-control-sm part-description" value="${description}" placeholder="Inserisci descrizione" style="width: 100%;"></td>
<td>
<button type="button" class="btn btn-success btn-sm add-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-plus fa-xs"></i></button>
<button type="button" class="btn btn-primary btn-sm add-mix-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;">M</button>
<button type="button" class="btn btn-danger btn-sm remove-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem; display: none;"><i class="fas fa-trash fa-xs"></i></button>
<span class="save-status text-success" style="display: none; margin-left: 5px;"><i class="fas fa-check fa-xs"></i></span>
<span class="save-loading text-warning" style="display: none; margin-left: 5px;"><i class="fas fa-spinner fa-spin fa-xs"></i></span>
</td>
</tr>`;
$("#partsTableBody").append(newRow);
updateRowButtons();
partColors[nextPartNumber || 1] = defaultColor;
markUnsaved();
}
function updateRowButtons() {
const rowCount = $("#partsTableBody tr").length;
$("#partsTableBody tr").each(function () {
$(this)
.find(".remove-row")
.toggle(rowCount > 1);
});
}
$(document).on("click", ".add-row", function (e) {
e.preventDefault();
const maxPartNumber = Math.max(
...$("#partsTableBody tr")
.map(function () {
return parseInt($(this).find(".part-number").val()) || 0;
})
.get(),
);
addNewRow(maxPartNumber + 1);
updatePartsList();
});
$(document).on("click", ".add-mix-row", function (e) {
e.preventDefault();
const maxPartNumber = Math.max(
...$("#partsTableBody tr")
.map(function () {
return parseInt($(this).find(".part-number").val()) || 0;
})
.get(),
);
addNewRow(maxPartNumber + 1, true);
updatePartsList();
});
$(document).on("click", ".remove-row", function (e) {
e.preventDefault();
const $row = $(this).closest("tr");
const partId = $row.data("part-id");
const partNumber = $row.find(".part-number").val();
const iddatadb = $("#partsModal").data("iddatadb");
const idquotations = $("#partsModal").data("idquotations");
const endpoint = idquotations
? "delete_part_quotation.php"
: "delete_part.php";
if (partId && partId !== "new") {
$.ajax({
url: endpoint,
method: "POST",
data: JSON.stringify({ part_id: partId }),
contentType: "application/json",
success: function (response) {
if (response.success) {
$row.remove();
delete partColors[partNumber];
updateRowButtons();
updatePartsList();
clearCanvasMarkers(false);
markUnsaved();
} else {
alert(`Errore nell'eliminazione: ${response.message}`);
}
},
error: function (xhr, status, error) {
alert(`Errore nell'eliminazione: ${error} (${xhr.status})`);
},
});
} else {
$row.remove();
delete partColors[partNumber];
updateRowButtons();
updatePartsList();
markUnsaved();
}
});
$(document).on("blur", ".part-description, .part-number", function () {
const $input = $(this);
const $row = $input.closest("tr");
const partNumber = $row.find(".part-number").val();
const partDescription = $row.find(".part-description").val().trim();
const $saveStatus = $row.find(".save-status");
const $saveLoading = $row.find(".save-loading");
const iddatadb = $("#partsModal").data("iddatadb");
const idquotations = $("#partsModal").data("idquotations");
const isMix = partDescription.startsWith("Mix") ? "Y" : "N";
const partId = $row.data("part-id") || null;
const endpoint = idquotations
? "save_parts_quotation.php"
: "save_parts.php";
const data = idquotations
? { idquotations: idquotations }
: { iddatadb: iddatadb };
if (partDescription && (iddatadb || idquotations)) {
$saveLoading.show();
$saveStatus.hide();
$.ajax({
url: endpoint,
method: "POST",
data: JSON.stringify({
...data,
parts: [
{
id: partId,
part_number: partNumber,
part_description: partDescription,
mix: isMix,
},
],
}),
contentType: "application/json",
success: function (response) {
$saveLoading.hide();
if (response.success) {
$saveStatus.show();
if (response.part_id) {
$row.attr("data-part-id", response.part_id).data(
"part-id",
response.part_id,
);
}
setTimeout(() => $saveStatus.hide(), 2000);
updatePartsList();
} else {
alert(`Errore nel salvataggio: ${response.message}`);
}
},
error: function (xhr, status, error) {
$saveLoading.hide();
alert(
`Errore nel salvataggio delle parti: ${error} (${xhr.status})`,
);
},
});
}
});
$(document).on("change", ".part-color", function () {
const partNumber = $(this).closest("li").data("part-number");
partColors[partNumber] = $(this).val();
updateMarkers();
markUnsaved();
});
function loadExistingParts(iddatadb, idquotations) {
const endpoint = idquotations
? "load_parts_quotation.php"
: "load_parts.php";
const data = idquotations
? { idquotations: idquotations }
: { iddatadb: iddatadb };
$.ajax({
url: endpoint,
method: "GET",
data: data,
success: function (response) {
$("#partsTableBody").empty();
if (response.success && response.parts.length > 0) {
response.parts.forEach((part) => {
const defaultColor = part.part_description.startsWith(
"Mix",
)
? "#0000ff"
: "#ff0000";
const newRow = `
<tr data-part-id="${part.id}">
<td><input type="number" class="form-control form-control-sm part-number" value="${part.part_number}" style="width: 80px;"></td>
<td><input type="text" class="form-control form-control-sm part-description" value="${part.part_description}" style="width: 100%;"></td>
<td>
<button type="button" class="btn btn-success btn-sm add-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-plus fa-xs"></i></button>
<button type="button" class="btn btn-primary btn-sm add-mix-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;">M</button>
<button type="button" class="btn btn-danger btn-sm remove-row" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-trash fa-xs"></i></button>
<span class="save-status text-success" style="display: none; margin-left: 5px;"><i class="fas fa-check fa-xs"></i></span>
<span class="save-loading text-warning" style="display: none; margin-left: 5px;"><i class="fas fa-spinner fa-spin fa-xs"></i></span>
</td>
</tr>`;
$("#partsTableBody").append(newRow);
partColors[part.part_number] = defaultColor;
});
} else {
addNewRow(1);
}
updateRowButtons();
updatePartsList();
},
error: function (xhr, status, error) {
alert(
`Errore nel caricamento delle parti: ${error} (${xhr.status})`,
);
addNewRow(1);
},
});
}
function updatePartsList() {
const showMixParts = $("#showMixParts").is(":checked");
$("#partsList").empty();
$("#partsTableBody tr").each(function () {
const partNumber = $(this).find(".part-number").val();
const partDescription = $(this).find(".part-description").val();
const partColor =
partColors[partNumber] ||
(partDescription.startsWith("Mix") ? "#0000ff" : "#ff0000");
if (
partNumber &&
partDescription &&
(showMixParts || !partDescription.startsWith("Mix"))
) {
const listItem = `
<li class="list-group-item" data-part-number="${partNumber}">
${partNumber} - ${partDescription}
<div style="display: flex; align-items: center;">
<button type="button" class="btn btn-success btn-sm add-to-mix-btn" style="padding: 0.1rem 0.3rem; font-size: 0.8rem;"><i class="fas fa-plus fa-xs"></i></button>
<input type="color" class="part-color" value="${partColor}" style="margin-left: 5px;">
</div>
</li>`;
$("#partsList").append(listItem);
}
});
updateMarkers();
}
function renumberParts() {
const $rows = $("#partsTableBody tr");
const iddatadb = $("#partsModal").data("iddatadb");
const idquotations = $("#partsModal").data("idquotations");
const endpoint = idquotations
? "renumber_parts_quotation.php"
: "renumber_parts.php";
const data = idquotations
? { idquotations: idquotations }
: { iddatadb: iddatadb };
let newPartColors = {};
let partsData = $rows
.map(function (index) {
const $row = $(this);
return {
partNumber: $row.find(".part-number").val(),
partDescription: $row.find(".part-description").val(),
partId: $row.data("part-id"),
};
})
.get();
partsData.forEach((part, index) => {
const newNumber = index + 1;
newPartColors[newNumber] = partColors[part.partNumber] || "#ff0000";
part.partNumber = newNumber;
});
$rows.each(function (index) {
$(this)
.find(".part-number")
.val(index + 1);
});
partColors = newPartColors;
const currentPhoto = $("#samplePhoto").attr("src");
if (photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto].markers.forEach((marker) => {
const newPartNumber = partsData.find(
(p) => p.partNumber == marker.partNumber,
)?.partNumber;
if (newPartNumber) {
marker.partNumber = newPartNumber;
marker.color = partColors[newPartNumber];
}
});
}
const partsToSave = partsData.map((part) => ({
id: part.partId || null,
part_number: part.partNumber,
part_description: part.partDescription,
mix: part.partDescription.startsWith("Mix") ? "Y" : "N",
}));
$.ajax({
url: endpoint,
method: "POST",
data: JSON.stringify({ ...data, parts: partsToSave }),
contentType: "application/json",
success: function (response) {
if (response.success) {
$rows.each(function (index) {
const $row = $(this);
const newPartId =
response.part_ids && response.part_ids[index]
? response.part_ids[index]
: $row.data("part-id");
if (newPartId) {
$row.attr("data-part-id", newPartId).data(
"part-id",
newPartId,
);
}
const $saveStatus = $row.find(".save-status");
const $saveLoading = $row.find(".save-loading");
$saveLoading.hide();
$saveStatus.show();
setTimeout(() => $saveStatus.hide(), 2000);
});
updatePartsList();
updateMarkers();
updateDescriptions();
markUnsaved();
} else {
alert(
`Errore nella rinumerazione delle parti: ${response.message}`,
);
}
},
error: function (xhr, status, error) {
alert(
`Errore nella rinumerazione delle parti: ${error} (${xhr.status})`,
);
},
});
}
$(document).on("click", ".add-to-mix-btn", function () {
const $listItem = $(this).closest("li");
const partDescription = $listItem.text().split(" - ")[1].trim();
const $mixRow = $("#partsTableBody tr")
.filter(function () {
return $(this)
.find(".part-description")
.val()
.startsWith("Mix");
})
.last();
if ($mixRow.length === 0) {
alert("Crea prima una riga Mix usando il pulsante 'M'.");
return;
}
const $descriptionInput = $mixRow.find(".part-description");
let currentDescription = $descriptionInput.val().trim();
if (currentDescription === "Mix") {
currentDescription = `Mix ${partDescription}`;
} else if (!currentDescription.includes(partDescription)) {
currentDescription += ` + ${partDescription}`;
} else {
return;
}
$descriptionInput.val(currentDescription);
$descriptionInput.trigger("blur");
updatePartsList();
});
$("#partsList").on("click", "li", function (e) {
if (
$(e.target).hasClass("add-to-mix-btn") ||
$(e.target).hasClass("part-color")
)
return;
selectedPartNumber = $(this).data("part-number");
$(this).addClass("active").siblings().removeClass("active");
});
$("#showMixParts").on("change", updatePartsList);
$("#renumberPartsBtn").on("click", renumberParts);
// ===================
// MARKERS & DESCRIPTIONS
// ===================
const canvas = document.getElementById("photoCanvas");
const ctx = canvas.getContext("2d");
$("#markerContainer").on("click", function (e) {
if (selectedPartNumber === null) return;
const rect = canvas.getBoundingClientRect();
const x = (e.clientX - rect.left) / photoData.scale;
const y = (e.clientY - rect.top) / photoData.scale;
const currentPhoto = $("#samplePhoto").attr("src");
if (!photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto] = {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
}
const partColor = partColors[selectedPartNumber] || "#ff0000";
const existingMarker = photoAnnotations[currentPhoto].markers.find(
(m) => m.partNumber == selectedPartNumber,
);
if (existingMarker) {
existingMarker.x = x;
existingMarker.y = y;
existingMarker.color = partColor;
} else {
photoAnnotations[currentPhoto].markers.push({
partNumber: selectedPartNumber,
x,
y,
color: partColor,
});
}
updateMarkers();
updateDescriptions();
markUnsaved();
selectedPartNumber = null;
$("#partsList li").removeClass("active");
});
function updateMarkers() {
const markerContainer = $("#markerContainer");
markerContainer.empty().css({
width: `${photoData.displayWidth}px`,
height: `${photoData.displayHeight}px`,
});
const currentPhoto = $("#samplePhoto").attr("src");
const annotations = photoAnnotations[currentPhoto] || {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
const showMixParts = $("#showMixParts").is(":checked");
annotations.markers.forEach((marker) => {
const partRow = $("#partsTableBody tr").filter(function () {
return $(this).find(".part-number").val() == marker.partNumber;
});
const partDescription = partRow.find(".part-description").val();
if (
!showMixParts &&
partDescription &&
partDescription.startsWith("Mix")
)
return;
const scaledX = marker.x * photoData.scale;
const scaledY = marker.y * photoData.scale;
const markerColor =
marker.color || partColors[marker.partNumber] || "#ff0000";
const $marker = $(
`<div class="draggable-marker" style="background: ${markerColor}; border: 1px solid ${markerColor}; color: #ffffff;">${marker.partNumber}</div>`,
).css({
left: scaledX - 8 + "px",
top: scaledY - 8 + "px",
});
markerContainer.append($marker);
makeDraggable($marker, marker);
});
}
function makeDraggable($element, item) {
let isDragging = false;
let startLeft = 0;
let startTop = 0;
let initialX = 0;
let initialY = 0;
$element.on("mousedown", function (e) {
e.preventDefault();
isDragging = true;
startLeft = parseFloat($element.css("left")) || 0;
startTop = parseFloat($element.css("top")) || 0;
initialX = e.clientX - startLeft;
initialY = e.clientY - startTop;
$element.css("z-index", 1001);
});
$(document).on("mousemove.dragMarker", function (e) {
if (!isDragging) return;
let currentX = e.clientX - initialX;
let currentY = e.clientY - initialY;
const maxX = photoData.displayWidth - $element.width();
const maxY = photoData.displayHeight - $element.height();
currentX = Math.max(0, Math.min(currentX, maxX));
currentY = Math.max(0, Math.min(currentY, maxY));
$element.css({ left: currentX + "px", top: currentY + "px" });
if (item && item.partNumber) {
item.x = (currentX + 8) / photoData.scale;
item.y = (currentY + 8) / photoData.scale;
} else {
const currentPhoto = $("#samplePhoto").attr("src");
if (photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto].descriptionPosition.x =
(currentX + 5) / photoData.scale;
photoAnnotations[currentPhoto].descriptionPosition.y =
(currentY + 5) / photoData.scale;
}
}
markUnsaved();
});
$(document).on("mouseup.dragMarker", function () {
if (!isDragging) return;
isDragging = false;
$element.css("z-index", 1000);
$(document).off("mousemove.dragMarker mouseup.dragMarker");
});
}
function updateDescriptions() {
const currentPhoto = $("#samplePhoto").attr("src");
const annotations = photoAnnotations[currentPhoto] || {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
const showMixParts = $("#showMixParts").is(":checked");
const descriptionList = $("#descriptionList");
descriptionList.empty();
if (!annotations.hasDescriptions) {
descriptionList.hide();
return;
}
const partsList = [];
$("#partsTableBody tr").each(function () {
const partNumber = $(this).find(".part-number").val();
const partDescription = $(this).find(".part-description").val();
if (
partNumber &&
partDescription &&
(showMixParts || !partDescription.startsWith("Mix"))
) {
partsList.push(`${partNumber} ${partDescription}`);
}
});
descriptionList.css({
display: "block",
top: annotations.descriptionPosition.y * photoData.scale + "px",
left: annotations.descriptionPosition.x * photoData.scale + "px",
});
partsList.forEach((part) =>
descriptionList.append(`<div>${part}</div>`),
);
makeDraggable(descriptionList);
}
function clearCanvasMarkers(clearDescriptions = true) {
const currentPhoto = $("#samplePhoto").attr("src");
if (clearDescriptions && photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto].hasDescriptions = false;
photoAnnotations[currentPhoto].descriptionPosition = {
x: 10,
y: 10,
};
}
$("#markerContainer").empty();
const canvas = document.getElementById("photoCanvas");
const ctx = canvas.getContext("2d");
canvas.width = photoData.naturalWidth;
canvas.height = photoData.naturalHeight;
canvas.style.width = `${photoData.displayWidth}px`;
canvas.style.height = `${photoData.displayHeight}px`;
ctx.clearRect(0, 0, canvas.width, canvas.height);
if ($("#samplePhoto")[0].naturalWidth) {
ctx.drawImage(
$("#samplePhoto")[0],
0,
0,
canvas.width,
canvas.height,
);
}
updateMarkers();
markUnsaved();
}
function undoLastMarker() {
const currentPhoto = $("#samplePhoto").attr("src");
if (
photoAnnotations[currentPhoto] &&
photoAnnotations[currentPhoto].markers.length > 0
) {
photoAnnotations[currentPhoto].markers.pop();
updateMarkers();
updateDescriptions();
markUnsaved();
}
}
$("#addDescriptionsBtn").on("click", function () {
const currentPhoto = $("#samplePhoto").attr("src");
if (!photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto] = {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
}
photoAnnotations[currentPhoto].hasDescriptions = true;
updateDescriptions();
markUnsaved();
});
$("#removeAnnotationsBtn").on("click", function () {
clearCanvasMarkers(true);
});
$("#undoMarkerBtn").on("click", undoLastMarker);
// ===================
// SAVE PHOTO
// ===================
$("#savePhotoBtn").on("click", function () {
const canvas = document.getElementById("photoCanvas");
const ctx = canvas.getContext("2d");
const img = $("#samplePhoto");
const naturalWidth = img[0].naturalWidth;
const naturalHeight = img[0].naturalHeight;
canvas.width = naturalWidth;
canvas.height = naturalHeight;
ctx.drawImage(img[0], 0, 0, naturalWidth, naturalHeight);
const currentPhoto = $("#samplePhoto").attr("src");
const annotations = photoAnnotations[currentPhoto] || {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
const showMixParts = $("#showMixParts").is(":checked");
if (annotations.hasDescriptions) {
const partsList = [];
$("#partsTableBody tr").each(function () {
const partNumber = $(this).find(".part-number").val();
const partDescription = $(this).find(".part-description").val();
if (
partNumber &&
partDescription &&
(showMixParts || !partDescription.startsWith("Mix"))
) {
partsList.push(`${partNumber} ${partDescription}`);
}
});
if (partsList.length > 0) {
const fontSize = Math.round(naturalWidth * 0.02);
ctx.font = fontSize + "px Arial";
const textHeight = fontSize + 8;
const boxWidth = Math.round(naturalWidth * 0.28);
const boxHeight = partsList.length * textHeight + 25;
const x = annotations.descriptionPosition.x;
const y = annotations.descriptionPosition.y;
ctx.save();
ctx.shadowColor = "rgba(0,0,0,0.3)";
ctx.shadowBlur = 8;
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 3;
ctx.fillStyle = "rgba(255, 255, 255, 0.9)";
ctx.beginPath();
ctx.roundRect(x, y, boxWidth, boxHeight, 12);
ctx.fill();
ctx.restore();
ctx.fillStyle = "#111111";
partsList.forEach((part, index) => {
ctx.fillText(part, x + 15, y + 35 + index * textHeight);
});
}
}
annotations.markers.forEach((marker) => {
const partRow = $("#partsTableBody tr").filter(function () {
return $(this).find(".part-number").val() == marker.partNumber;
});
const partDescription = partRow.find(".part-description").val();
if (
!showMixParts &&
partDescription &&
partDescription.startsWith("Mix")
)
return;
const x = marker.x;
const y = marker.y;
const radius = Math.max(5, Math.round(naturalWidth * 0.025));
const fontSize = Math.max(8, Math.round(radius * 0.9));
const markerColor =
marker.color || partColors[marker.partNumber] || "#ff0000";
ctx.beginPath();
ctx.arc(x, y, radius, 0, 2 * Math.PI);
ctx.fillStyle = markerColor;
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = markerColor;
ctx.stroke();
ctx.fillStyle = "#ffffff";
ctx.font = `bold ${fontSize}px Arial`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(marker.partNumber || "", x, y);
});
const dataURL = canvas.toDataURL("image/png");
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const iddatadb = $("#partsModal").data("iddatadb");
const idquotations = $("#partsModal").data("idquotations");
const id = iddatadb || idquotations;
const endpoint = idquotations
? "save_annotated_photo_quotation.php"
: "save_annotated_photo.php";
const dataParam = idquotations
? { idquotations: id }
: { iddatadb: id };
const defaultName = `photo_${id}_${timestamp}.png`;
const newName = prompt(
"Inserisci il nome del file (senza estensione):",
defaultName.split(".png")[0],
);
if (newName) {
const finalName = `${newName}_${timestamp}.png`;
$.ajax({
url: endpoint,
method: "POST",
data: { dataURL: dataURL, filename: finalName, ...dataParam },
success: function (response) {
if (response.success) {
alert(
`Foto salvata con successo: ${response.file_path}`,
);
$("#samplePhoto").attr("src", response.file_path);
loadPhoto(iddatadb, idquotations);
clearCanvasMarkers(false);
clearUnsaved();
} else {
alert(`Errore: ${response.message}`);
}
},
error: function (xhr, status, error) {
alert(
`Errore nel salvataggio della foto: ${error} (${xhr.status})`,
);
},
});
}
});
// ===================
// HELPER FUNCTIONS
// ===================
function markUnsaved() {
if (!unsavedChanges) {
unsavedChanges = true;
$("#savePhotoBtn").addClass("unsaved").text("⚠️ Salva Modifiche");
}
}
function clearUnsaved() {
unsavedChanges = false;
$("#savePhotoBtn").removeClass("unsaved").text("Salva Foto con Nome");
}
$(document).on("input change", "#partsTableBody input", markUnsaved);
$(document).on("click", ".add-row, .add-mix-row, .remove-row", markUnsaved);
});