added collage, fixed parts marker color, added ri number

This commit is contained in:
2025-09-04 15:01:03 +02:00
parent 1303cff9fd
commit 0749032fbc
10 changed files with 1241 additions and 235 deletions
+430 -152
View File
@@ -2,7 +2,7 @@ $(document).ready(function () {
console.log("parts.js caricato correttamente");
// ===================
// GLOBAL STATE (NEW)
// GLOBAL STATE
// ===================
let photoData = {
naturalWidth: 0,
@@ -12,13 +12,13 @@ $(document).ready(function () {
scale: 1,
};
// markers keyed by photo src => [{ partNumber, x, y } using NATURAL coords]
let photoMarkers = {};
// annotations keyed by photo src
let photoAnnotations = {};
// colors keyed by part number
let partColors = {};
// selection & descriptions
// selection
let selectedPartNumber = null;
let descriptionPosition = {x: 10, y: 10}; // NATURAL coords
let hasDescriptions = false;
// ===================
// POPUP HANDLING
@@ -33,8 +33,14 @@ $(document).ready(function () {
console.log("Pulsante Parts cliccato");
const iddatadb = $(this).data("iddatadb");
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";
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} - ${importRef} - ${description}`);
$("#partsModal").data("iddatadb", iddatadb);
@@ -76,19 +82,25 @@ $(document).ready(function () {
$.ajax({
url: "load_photo.php",
method: "GET",
data: {iddatadb: iddatadb},
data: { iddatadb: iddatadb },
success: function (response) {
if (response.success) {
if (response.photos && response.photos.length > 1) {
showPhotoSelector(response.photos);
} else if (response.photos && response.photos.length === 1) {
} else if (
response.photos &&
response.photos.length === 1
) {
loadSinglePhoto(response.photos[0]);
} else {
$("#samplePhoto").attr("src", "");
alert("Nessuna foto trovata per questo TRF.");
}
} else {
alert(response.message || "Errore nel caricamento della foto.");
alert(
response.message ||
"Errore nel caricamento della foto.",
);
}
},
error: function (xhr, status, error) {
@@ -103,8 +115,9 @@ $(document).ready(function () {
const selector = $('<select id="photoSelector"></select>');
photos.forEach((photo, index) => {
const option = $('<option></option>').val(photo).text(`Photo ${index + 1}`);
// display option with photo name if available
const option = $("<option></option>")
.val(photo)
.text(`Photo ${index + 1}`);
if (photo.includes("/")) {
const photoName = photo.split("/").pop();
option.text(`Photo ${index + 1} - ${photoName}`);
@@ -135,41 +148,47 @@ $(document).ready(function () {
const canvas = document.getElementById("photoCanvas");
const ctx = canvas.getContext("2d");
// Real image size
const naturalWidth = img[0].naturalWidth;
const naturalHeight = img[0].naturalHeight;
// Compute scale to FIT inside its parent without distorting aspect ratio
const parent = $(canvas).parent();
const maxW = parent.width();
const maxH = parent.height();
const scale = Math.min(maxW / naturalWidth, maxH / naturalHeight);
// Display size on screen
const displayWidth = Math.max(1, Math.round(naturalWidth * scale));
const displayHeight = Math.max(1, Math.round(naturalHeight * scale));
const displayHeight = Math.max(
1,
Math.round(naturalHeight * scale),
);
// Save globally
photoData = {naturalWidth, naturalHeight, displayWidth, displayHeight, scale};
photoData = {
naturalWidth,
naturalHeight,
displayWidth,
displayHeight,
scale,
};
// Canvas in REAL size (so saving uses natural coords 1:1)
canvas.width = naturalWidth;
canvas.height = naturalHeight;
// Visual size on screen
canvas.style.width = `${displayWidth}px`;
canvas.style.height = `${displayHeight}px`;
// Also size/align the overlay containers to match the canvas
$("#markerContainer").css({width: `${displayWidth}px`, height: `${displayHeight}px`});
$("#descriptionList").css({maxWidth: `${Math.max(200, Math.round(displayWidth * 0.35))}px`});
$("#markerContainer").css({
width: `${displayWidth}px`,
height: `${displayHeight}px`,
});
$("#descriptionList").css({
maxWidth: `${Math.max(200, Math.round(displayWidth * 0.35))}px`,
});
// Draw fresh image at full resolution
ctx.clearRect(0, 0, naturalWidth, naturalHeight);
ctx.drawImage(img.get(0), 0, 0, naturalWidth, naturalHeight);
updateMarkers();
if (hasDescriptions) drawDescriptions(descriptionPosition.x, descriptionPosition.y);
updateDescriptions();
});
}
@@ -178,6 +197,7 @@ $(document).ready(function () {
// ===================
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>
@@ -192,22 +212,28 @@ $(document).ready(function () {
</tr>`;
$("#partsTableBody").append(newRow);
updateRowButtons();
// Initialize color for the new part
const partNumber = nextPartNumber || 1;
partColors[partNumber] = defaultColor;
}
function updateRowButtons() {
const rowCount = $("#partsTableBody tr").length;
$("#partsTableBody tr").each(function () {
const $removeBtn = $(this).find(".remove-row");
if (rowCount > 1) $removeBtn.show(); else $removeBtn.hide();
if (rowCount > 1) $removeBtn.show();
else $removeBtn.hide();
});
}
$(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(),
...$("#partsTableBody tr")
.map(function () {
return parseInt($(this).find(".part-number").val()) || 0;
})
.get(),
);
addNewRow(maxPartNumber + 1);
updatePartsList();
@@ -216,9 +242,11 @@ $(document).ready(function () {
$(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(),
...$("#partsTableBody tr")
.map(function () {
return parseInt($(this).find(".part-number").val()) || 0;
})
.get(),
);
addNewRow(maxPartNumber + 1, true);
updatePartsList();
@@ -228,29 +256,39 @@ $(document).ready(function () {
e.preventDefault();
const $row = $(this).closest("tr");
const partId = $row.data("part-id");
const partNumber = $row.find(".part-number").val();
if (partId !== "new" && partId !== undefined && partId !== null) {
$.ajax({
url: "delete_part.php",
method: "POST",
data: JSON.stringify({part_id: partId}),
data: JSON.stringify({ part_id: partId }),
contentType: "application/json",
success: function (response) {
if (response.success) {
$row.remove();
delete partColors[partNumber];
updateRowButtons();
updatePartsList();
clearCanvasMarkers();
clearCanvasMarkers(false); // Preserve descriptions
} else {
alert("Errore nell'eliminazione: " + response.message);
}
},
error: function (xhr, status, error) {
alert("Errore nell'eliminazione: " + error + ". Stato: " + xhr.status + " - " + xhr.responseText);
alert(
"Errore nell'eliminazione: " +
error +
". Stato: " +
xhr.status +
" - " +
xhr.responseText,
);
},
});
} else {
$row.remove();
delete partColors[partNumber];
updateRowButtons();
updatePartsList();
}
@@ -266,7 +304,6 @@ $(document).ready(function () {
const iddatadb = $("#partsModal").data("iddatadb");
const isMix = partDescription.startsWith("Mix") ? "Y" : "N";
// არსებული part-id row-დან (თუ უკვე არსებობს)
const partId = $row.data("part-id") || null;
if (partDescription && iddatadb) {
@@ -280,7 +317,7 @@ $(document).ready(function () {
iddatadb: iddatadb,
parts: [
{
id: partId, // გავგზავნე part-ის ID (თუ არის)
id: partId,
part_number: partNumber,
part_description: partDescription,
mix: isMix,
@@ -293,7 +330,6 @@ $(document).ready(function () {
$saveLoading.hide();
$saveStatus.show();
updatePartsList();
// თუ ახალია, backend-მა მოგვცა ახალი ID
if (response.part_id) {
$row.attr("data-part-id", response.part_id);
$row.data("part-id", response.part_id);
@@ -312,16 +348,28 @@ $(document).ready(function () {
}
});
$(document).on("change", ".part-color", function () {
const partNumber = $(this).closest("li").data("part-number");
const partColor = $(this).val();
partColors[partNumber] = partColor;
updateMarkers();
markUnsaved();
});
function loadExistingParts(iddatadb) {
$.ajax({
url: "load_parts.php",
method: "GET",
data: {iddatadb: iddatadb},
data: { iddatadb: iddatadb },
success: function (response) {
if (response.success) {
$("#partsTableBody").empty();
if (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>
@@ -335,6 +383,7 @@ $(document).ready(function () {
</td>
</tr>`;
$("#partsTableBody").append(newRow);
partColors[part.part_number] = defaultColor;
});
} else {
addNewRow(1);
@@ -342,7 +391,10 @@ $(document).ready(function () {
updateRowButtons();
updatePartsList();
} else {
alert("Errore nel caricamento delle parti: " + response.message);
alert(
"Errore nel caricamento delle parti: " +
response.message,
);
addNewRow(1);
}
},
@@ -354,27 +406,138 @@ $(document).ready(function () {
}
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();
if (partNumber && partDescription && !partDescription.startsWith("Mix")) {
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}
<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>
<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");
let newPartColors = {};
// Raccogli tutte le righe con i loro dati attuali
let partsData = $rows
.map(function (index) {
const $row = $(this);
const partNumber = $row.find(".part-number").val();
const partDescription = $row.find(".part-description").val();
const partId = $row.data("part-id");
return { partNumber, partDescription, partId };
})
.get();
// Rinumera in modo sequenziale
partsData.forEach((part, index) => {
const newNumber = index + 1;
newPartColors[newNumber] = partColors[part.partNumber] || "#ff0000";
part.partNumber = newNumber;
});
// Aggiorna i valori nella tabella
$rows.each(function (index) {
const $row = $(this);
$row.find(".part-number").val(index + 1);
});
// Aggiorna partColors
partColors = newPartColors;
// Aggiorna i marker nelle annotazioni
const currentPhoto = $("#samplePhoto").attr("src");
if (photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto].markers.forEach((marker) => {
const oldPartNumber = marker.partNumber;
const newPartNumber = partsData.find(
(p) => p.partNumber == oldPartNumber,
)?.partNumber;
if (newPartNumber) {
marker.partNumber = newPartNumber;
marker.color = partColors[newPartNumber];
}
});
}
// Salva le modifiche nel database
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: "save_parts.php",
method: "POST",
data: JSON.stringify({
iddatadb: iddatadb,
parts: partsToSave,
}),
contentType: "application/json",
success: function (response) {
if (response.success) {
$rows.each(function (index) {
const $row = $(this);
if (response.part_ids && response.part_ids[index]) {
$row.attr("data-part-id", response.part_ids[index]);
$row.data("part-id", response.part_ids[index]);
}
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 nel salvataggio delle parti: " +
response.message,
);
}
},
error: function (xhr, status, error) {
alert("Errore nel salvataggio delle parti: " + error);
},
});
}
$(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();
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'.");
@@ -398,11 +561,22 @@ $(document).ready(function () {
});
$("#partsList").on("click", "li", function (e) {
if ($(e.target).hasClass("add-to-mix-btn")) return;
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", function () {
updatePartsList();
});
$("#renumberPartsBtn").on("click", function () {
renumberParts();
});
// ===================
// MARKERS & DESCRIPTIONS
// ===================
@@ -420,18 +594,35 @@ $(document).ready(function () {
const y = clickY / photoData.scale;
const currentPhoto = $("#samplePhoto").attr("src");
if (!photoMarkers[currentPhoto]) photoMarkers[currentPhoto] = [];
if (!photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto] = {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
}
const existingMarker = photoMarkers[currentPhoto].find(m => m.partNumber == selectedPartNumber);
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 {
photoMarkers[currentPhoto].push({partNumber: selectedPartNumber, x, y});
photoAnnotations[currentPhoto].markers.push({
partNumber: selectedPartNumber,
x,
y,
color: partColor,
});
}
updateMarkers();
if (hasDescriptions) drawDescriptions(descriptionPosition.x, descriptionPosition.y);
updateDescriptions();
markUnsaved();
selectedPartNumber = null;
$("#partsList li").removeClass("active");
@@ -441,17 +632,41 @@ $(document).ready(function () {
const markerContainer = $("#markerContainer");
markerContainer.empty();
// keep overlay sized to canvas display
markerContainer.css({width: `${photoData.displayWidth}px`, height: `${photoData.displayHeight}px`});
markerContainer.css({
width: `${photoData.displayWidth}px`,
height: `${photoData.displayHeight}px`,
});
const currentPhoto = $("#samplePhoto").attr("src");
const markers = photoMarkers[currentPhoto] || [];
const annotations = photoAnnotations[currentPhoto] || {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
const markers = annotations.markers;
const showMixParts = $("#showMixParts").is(":checked");
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">${marker.partNumber}</div>`).css({
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",
});
@@ -488,15 +703,21 @@ $(document).ready(function () {
currentX = Math.max(0, Math.min(currentX, maxX));
currentY = Math.max(0, Math.min(currentY, maxY));
$element.css({left: currentX + "px", top: currentY + "px"});
$element.css({ left: currentX + "px", top: currentY + "px" });
if (item && item.partNumber) {
item.x = (currentX + 8) / photoData.scale;
item.y = (currentY + 8) / photoData.scale;
markUnsaved();
} else {
// draggable description panel
descriptionPosition.x = (currentX + 5) / photoData.scale;
descriptionPosition.y = (currentY + 5) / photoData.scale;
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();
}
}
});
@@ -508,39 +729,65 @@ $(document).ready(function () {
});
}
function drawDescriptions(x, y) {
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.css("display", "none");
return;
}
const partsList = [];
$("#partsTableBody tr").each(function () {
const partNumber = $(this).find(".part-number").val();
const partDescription = $(this).find(".part-description").val();
if (partNumber && partDescription && !partDescription.startsWith("Mix")) {
if (
partNumber &&
partDescription &&
(showMixParts || !partDescription.startsWith("Mix"))
) {
partsList.push(`${partNumber} ${partDescription}`);
}
});
const descriptionList = $("#descriptionList");
descriptionList.empty();
descriptionList.css({
display: "block",
top: y * photoData.scale + "px",
left: x * photoData.scale + "px",
top: annotations.descriptionPosition.y * photoData.scale + "px",
left: annotations.descriptionPosition.x * photoData.scale + "px",
});
partsList.forEach((part) => descriptionList.append(`<div>${part}</div>`));
partsList.forEach((part) =>
descriptionList.append(`<div>${part}</div>`),
);
updateMarkers();
}
function clearCanvasMarkers() {
function clearCanvasMarkers(clearDescriptions = true) {
const currentPhoto = $("#samplePhoto").attr("src");
photoMarkers[currentPhoto] = [];
hasDescriptions = false;
$("#descriptionList").css("display", "none");
if (clearDescriptions) {
if (photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto].hasDescriptions = false;
photoAnnotations[currentPhoto].descriptionPosition = {
x: 10,
y: 10,
};
}
$("#descriptionList").css("display", "none");
}
$("#markerContainer").empty();
const canvas = document.getElementById("photoCanvas");
const ctx = canvas.getContext("2d");
// reset canvas to current image (keeps proportions)
canvas.width = photoData.naturalWidth;
canvas.height = photoData.naturalHeight;
canvas.style.width = `${photoData.displayWidth}px`;
@@ -551,22 +798,49 @@ $(document).ready(function () {
if (img[0].naturalWidth) {
ctx.drawImage(img.get(0), 0, 0, canvas.width, canvas.height);
}
markUnsaved();
updateMarkers();
}
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 () {
hasDescriptions = true;
descriptionPosition = {x: 10, y: 10};
drawDescriptions(descriptionPosition.x, descriptionPosition.y);
const currentPhoto = $("#samplePhoto").attr("src");
if (!photoAnnotations[currentPhoto]) {
photoAnnotations[currentPhoto] = {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
}
photoAnnotations[currentPhoto].hasDescriptions = true;
updateDescriptions();
makeDraggable($("#descriptionList"));
markUnsaved();
});
$("#removeAnnotationsBtn").on("click", function () {
clearCanvasMarkers();
clearCanvasMarkers(true); // Remove only descriptions
});
$("#undoMarkerBtn").on("click", function () {
undoLastMarker();
});
let unsavedChanges = false;
// --- helper functions ---
// --- helper functions ---
function markUnsaved() {
if (!unsavedChanges) {
unsavedChanges = true;
@@ -579,18 +853,13 @@ $(document).ready(function () {
$("#savePhotoBtn").removeClass("unsaved").text("Salva Foto con Nome");
}
// --- event listeners ---
// როცა ვცვლით input-ს ცხრილში
// --- event listeners ---
$(document).on("input change", "#partsTableBody input", markUnsaved);
// როცა ვამატებთ/ვშლით რიგს
$(document).on("click", ".add-row, .add-mix-row, .remove-row", markUnsaved);
// თუ გაქვს draggable marker ან description list
$(document).on("markerChanged descriptionChanged", markUnsaved);
// --- modal close protection ---
$('#partsModal').on('hide.bs.modal', function (e) {
// --- modal close protection ---
$("#partsModal").on("hide.bs.modal", function (e) {
if (unsavedChanges) {
if (!confirm("Hai modifiche non salvate. Vuoi davvero uscire?")) {
e.preventDefault();
@@ -598,94 +867,99 @@ $(document).ready(function () {
}
});
// --- SAVE BUTTON ---
// --- SAVE BUTTON ---
$("#savePhotoBtn").on("click", function () {
const canvas = document.getElementById("photoCanvas");
const ctx = canvas.getContext("2d");
const img = $("#samplePhoto");
// Ensure canvas is real size
const naturalWidth = img.get(0).naturalWidth;
const naturalHeight = img.get(0).naturalHeight;
canvas.width = naturalWidth;
canvas.height = naturalHeight;
// Redraw base image
ctx.drawImage(img.get(0), 0, 0, naturalWidth, naturalHeight);
// Descriptions box
const partsList = [];
$("#partsTableBody tr").each(function () {
const partNumber = $(this).find(".part-number").val();
const partDescription = $(this).find(".part-description").val();
if (partNumber && partDescription && !partDescription.startsWith("Mix")) {
partsList.push(`${partNumber} ${partDescription}`);
}
});
const currentPhoto = $("#samplePhoto").attr("src");
const annotations = photoAnnotations[currentPhoto] || {
markers: [],
hasDescriptions: false,
descriptionPosition: { x: 10, y: 10 },
};
const showMixParts = $("#showMixParts").is(":checked");
if (hasDescriptions && 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 = descriptionPosition.x;
const y = 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) => {
const domWidth = $("#samplePhoto").width();
const domHeight = $("#samplePhoto").height();
// NATURAL ზომა (ფაილის რეალური ზომა)
const naturalWidth = photoData.naturalWidth;
const naturalHeight = photoData.naturalHeight;
// მასშტაბები
const scaleX = naturalWidth / domWidth;
const scaleY = naturalHeight / domHeight;
// გადაყვანილი კოორდინატები
const x = descriptionPosition.x * scaleX;
const y = descriptionPosition.y * scaleY;
ctx.fillText(part, x + 15, y + 35 + index * textHeight);
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);
});
}
}
// Markers
const currentPhoto = $("#samplePhoto").attr("src");
const markers = photoMarkers[currentPhoto] || [];
const markers = annotations.markers;
markers.forEach((marker) => {
const x = marker.x; // already NATURAL coords
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 = "rgba(255,0,0,0.85)";
ctx.fillStyle = markerColor; // Use the stored color
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = "#ffffff";
ctx.strokeStyle = markerColor; // Use the same color for the border
ctx.stroke();
ctx.fillStyle = "#ffffff";
@@ -700,7 +974,10 @@ $(document).ready(function () {
const iddatadb = $("#partsModal").data("iddatadb");
const defaultName = `photo_${iddatadb}_${timestamp}.png`;
const newName = prompt("Inserisci il nome del file (senza estensione):", defaultName.split(".png")[0]);
const newName = prompt(
"Inserisci il nome del file (senza estensione):",
defaultName.split(".png")[0],
);
if (newName) {
const finalName = newName + "_" + timestamp + ".png";
@@ -710,16 +987,17 @@ $(document).ready(function () {
data: {
dataURL: dataURL,
filename: finalName,
iddatadb: iddatadb
iddatadb: iddatadb,
},
success: function (response) {
if (response.success) {
alert("Foto salvata con successo: " + response.file_path);
alert(
"Foto salvata con successo: " + response.file_path,
);
$("#samplePhoto").attr("src", response.file_path);
loadPhoto(iddatadb);
clearCanvasMarkers();
clearUnsaved(); // ✅ reset unsaved status
clearCanvasMarkers(false); // Preserve descriptions
clearUnsaved();
} else {
alert("Errore: " + response.message);
}