Files
PVM/public_html/gest-lib/articoli_anag/js/newModal.js

1335 lines
51 KiB
JavaScript

// $(function () {
// _modalArticolo.init();
// });
//
const _modalArticolo = {
module: null,
currentProductData: null,
uploadedImages: [],
uploadedDocuments: [],
allImagesData: [],
pendingDeleteImageId: null,
pendingDeleteImageType: null,
arrDown: FontAwesome.icon({
prefix: 'fas',
iconName: 'caret-down'
}),
arrUp: FontAwesome.icon({
prefix: 'fas',
iconName: 'caret-up'
}),
showModal: function (options = {}) {
const modalBox = new ModalBox();
modalBox
.content(options.message)
.title(options.title)
.onShow(() => {
$('body').append(modalBox);
});
if (options.confirm) {
modalBox.okCancel()
.btCancel({
text: "Annulla",
onClick: function () {
modalBox.close();
if (typeof options.onCancel === 'function') {
options.onCancel();
}
}
})
.btOK({
text: "Ok",
onClick: function () {
modalBox.close();
if (typeof options.onConfirm === 'function') {
options.onConfirm();
}
}
});
} else {
modalBox.btOK({
text: options.okText || "Ok",
onClick: function () {
modalBox.close();
if (typeof options.onClose === 'function') {
options.onClose();
}
}
});
}
modalBox.style(options.type);
modalBox.show();
},
showAlert: function (message, title = 'Attenzione', type = 'info') {
this.showModal({
title: title,
message: message,
type: type,
confirm: false
});
},
//
// showConfirm: function (message, onConfirm, onCancel, title = 'Conferma') {
// this.showModal({
// title: title,
// message: message,
// type: 'warning',
// confirm: true,
// onConfirm: onConfirm,
// onCancel: onCancel
// });
// },
uploadFileToServer: async function(file, productKey, imageId) {
const formData = new FormData();
formData.append('file', file);
const uploadData = {
cod_mart: productKey,
// id_riga: idRiga,
imageId: imageId
};
formData.append('upload_photo', JSON.stringify((uploadData)));
try{
const ret = await new Ajax()
.post("upload_photo")
.data(uploadData)
.formData(formData)
.onSuccess(function () {
new Toast().success("Elemento aggiunto con successo");
})
.noticeAsModal()
.execute();
let parsedResponse = ret;
if (typeof ret === 'string') {
try {
parsedResponse = JSON.parse(ret);
} catch (e) {
return false;
}
}
if (parsedResponse && parsedResponse.returnId === 1) {
return parsedResponse.returnData || parsedResponse;
}
}catch(e){
return false;
}
},
saveImageUrlToServer: async function (imageUrl, idRiga, productKey, imageId) {
const self = this;
try {
const response = await fetch(imageUrl);
if (!response.ok) {
throw new Error("Impossibile scaricare l'immagine dall'URL");
}
const blob = await response.blob();
const fileName = self.extractFileNameFromUrl(imageUrl);
const file = new File([blob], fileName, { type: blob.type });
const formData = new FormData();
formData.append('file', file);
const uploadData = {
cod_mart: productKey,
id_riga: idRiga,
imageId: imageId,
isFromUrl: true,
originalUrl: imageUrl
};
formData.append('upload_photo', JSON.stringify(uploadData));
const ret = await new Ajax()
.post("upload_photo")
.data(uploadData)
.formData(formData)
.onSuccess(function () {
new Toast().success("Elemento aggiunto con successo");
})
.noticeAsModal()
.execute();
let parsedResponse = ret;
if (typeof ret === 'string') {
try {
parsedResponse = JSON.parse(ret);
} catch (e) {
return false;
}
}
if (parsedResponse && parsedResponse.returnId === 1) {
return parsedResponse.returnData || parsedResponse;
}
return false;
} catch (error) {
console.error("Errore durante il salvataggio dell'immagine:", error);
return false;
}
},
deleteImageFromServer: async function (idRiga, imageId, productKey) {
const deleteData = {
id_riga: idRiga,
imageId: imageId,
cod_mart: productKey
};
try {
const ret = await new Ajax()
.post("delete_photo")
.data(deleteData)
.waitModal()
.noticeAsModal()
.confirmModal({
message: "Sei sicuro di voler confermare l'eliminazione?",
style: "warning",
title: "Conferma Eliminazione"
})
.onSuccess(function () {
new Toast().success("Elemento eliminato con successo");
})
.execute();
let parsedResponse = ret;
if (typeof ret === 'string') {
try {
parsedResponse = JSON.parse(ret);
} catch (e) {
return false;
}
}
return parsedResponse && parsedResponse.returnId === 1;
} catch (error) {
return false;
}
},
downloadFile: function (fileId, fileName, fileUrl) {
try {
const $link = $('<a>', {
href: fileUrl,
download: fileName || 'file'
}).appendTo('body');
$link[0].click();
$link.remove();
} catch (error) {
console.error('Errore durante il download:', error);
}
},
annulElimina: function () {
const self = this;
const containers = [
$('#imageContainer'),
$('#imageContainer1'),
$('#toggleImages'),
$('#toggleImages1'),
$('.modal-body .container')
];
containers.forEach(container => {
if (container) {
container.css("opacity", 1);
container.css("pointerEvents", "auto");
}
});
self.pendingDeleteImageId = null;
self.pendingDeleteImageType = null;
},
confElimina: async function () {
// const self = this;
//
// if (!self.pendingDeleteImageId || !self.pendingDeleteImageType) {
// self.showAlert('Errore: nessuna immagine selezionata per l\'eliminazione', 'Errore', 'warning');
// self.annulElimina();
// return;
// }
//
// if (!self.currentProductData) {
// self.showAlert('Nessun prodotto selezionato', 'Errore', 'warning');
// self.annulElimina();
// return;
// }
//
// const productKey = self.currentProductData.cod_mart;
// const imageData = self.allImagesData[productKey] && self.allImagesData[productKey][self.pendingDeleteImageId];
//
// if (!imageData) {
// console.error('Dati immagine non trovati per ID:', self.pendingDeleteImageId);
// self.showAlert('Impossibile trovare i dati dell\'immagine selezionata.', 'Errore', 'warning');
// self.annulElimina();
// return;
// }
//
// console.log('Eliminazione immagine confermata:', self.pendingDeleteImageId, self.pendingDeleteImageType, imageData);
//
// if (self.pendingDeleteImageType === 'uploaded' || self.pendingDeleteImageType === 'existing') {
// const idRiga = imageData.id_riga || imageData.key?.id_riga;
//
// if (!idRiga) {
// console.error('ID riga non trovato per l\'immagine:', imageData);
// self.showAlert('Impossibile trovare l\'ID riga per l\'immagine selezionata.', 'Errore', 'warning');
// self.annulElimina();
// return;
// }
//
// console.log('Eliminazione dal server - ID Riga:', idRiga, 'Product Key:', productKey);
//
// const loadingHtml = `
// <div class="text-center">
// <i class="fa fa-spinner fa-spin fa-2x"></i>
// <p>Eliminazione in corso...</p>
// </div>
// `;
//
// const result = await self.deleteImageFromServer(idRiga, self.pendingDeleteImageId, productKey);
//
// if (result) {
// console.log('Immagine eliminata dal server:', response);
//
// if (self.uploadedImages[productKey]) {
// self.uploadedImages[productKey] = self.uploadedImages[productKey].filter(img => img.id !== self.pendingDeleteImageId);
// }
// if (self.uploadedDocuments[productKey]) {
// self.uploadedDocuments[productKey] = self.uploadedDocuments[productKey].filter(img => img.id !== self.pendingDeleteImageId);
// }
//
// if (self.allImagesData[productKey]) {
// delete self.allImagesData[productKey][self.pendingDeleteImageId];
// }
//
// $(`#image-${self.pendingDeleteImageId}`).remove();
// self.reorganizeImageLayout();
// self.reorganizeDocumentLayout();
// _articoliAnag.refreshGrid();
//
// self.annulElimina();
//
// } else {
// console.error('Errore eliminazione:', error);
// self.showAlert('Errore durante l\'eliminazione dell\'immagine: ' + error, 'Errore', 'danger');
// self.annulElimina();
// }
//
//
// } else {
// $(`#image-${self.pendingDeleteImageId}`).remove();
// self.reorganizeImageLayout();
// self.reorganizeDocumentLayout();
// self.annulElimina();
// }
},
deleteImage: async function (id,type) {
const self = this;
self.pendingDeleteImageId=id;
self.pendingDeleteImageType=type;
if (!self.pendingDeleteImageId || !self.pendingDeleteImageType) {
self.showAlert('Errore: nessuna immagine selezionata per l\'eliminazione', 'Errore', 'warning');
self.annulElimina();
return;
}
if (!self.currentProductData) {
self.showAlert('Nessun prodotto selezionato', 'Errore', 'warning');
self.annulElimina();
return;
}
const productKey = self.currentProductData.cod_mart;
const imageData = self.allImagesData[productKey] && self.allImagesData[productKey][self.pendingDeleteImageId];
if (!imageData) {
console.error('Dati immagine non trovati per ID:', self.pendingDeleteImageId);
self.showAlert('Impossibile trovare i dati dell\'immagine selezionata.', 'Errore', 'warning');
self.annulElimina();
return;
}
console.log('Eliminazione immagine confermata:', self.pendingDeleteImageId, self.pendingDeleteImageType, imageData);
if (self.pendingDeleteImageType === 'uploaded' || self.pendingDeleteImageType === 'existing') {
const idRiga = imageData.id_riga || imageData.key?.id_riga;
if (!idRiga) {
console.error('ID riga non trovato per l\'immagine:', imageData);
self.showAlert('Impossibile trovare l\'ID riga per l\'immagine selezionata.', 'Errore', 'warning');
self.annulElimina();
return;
}
console.log('Eliminazione dal server - ID Riga:', idRiga, 'Product Key:', productKey);
const loadingHtml = `
<div class="text-center">
<i class="fa fa-spinner fa-spin fa-2x"></i>
<p>Eliminazione in corso...</p>
</div>
`;
const result = await self.deleteImageFromServer(idRiga, self.pendingDeleteImageId, productKey);
if (result) {
console.log('Immagine eliminata dal server:', result);
if (self.uploadedImages[productKey]) {
self.uploadedImages[productKey] = self.uploadedImages[productKey].filter(img => img.id !== self.pendingDeleteImageId);
}
if (self.uploadedDocuments[productKey]) {
self.uploadedDocuments[productKey] = self.uploadedDocuments[productKey].filter(img => img.id !== self.pendingDeleteImageId);
}
if (self.allImagesData[productKey]) {
delete self.allImagesData[productKey][self.pendingDeleteImageId];
}
$(`#image-${self.pendingDeleteImageId}`).remove();
self.reorganizeImageLayout();
self.reorganizeDocumentLayout();
_articoliAnag.refreshGrid();
} else{
self.annulElimina();
}
} else {
$(`#image-${self.pendingDeleteImageId}`).remove();
self.reorganizeImageLayout();
self.reorganizeDocumentLayout();
self.annulElimina();
}
},
isImageFile: function (fileName) {
if (!fileName || typeof fileName !== 'string') return false;
const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'php'];
const match = fileName.toLowerCase().match(/\.(\w{3,4})$/);
if (!match) return false;
return imageExtensions.includes(match[1]);
},
isDocumentFile: function (fileName) {
if (!fileName || typeof fileName !== 'string') return false;
const documentExtensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'txt', 'csv', 'zip', 'rar'];
const match = fileName.toLowerCase().match(/\.(\w{3,5})$/);
if (!match) return false;
return documentExtensions.includes(match[1]);
},
reorganizeImageLayout: function () {
const images = $('#imageContainer .image-item');
const totalImages = images.length;
images.each(function () {
const $this = $(this);
$this.removeClass('col-xs-12 col-xs-6 col-md-4');
if (totalImages === 1) {
$this.addClass('col-xs-12');
} else {
$this.addClass('col-xs-6 col-md-4');
}
});
if (totalImages === 0) {
$('#imageContainer').html(`
<div class="col-xs-12 text-center" style="white-space: nowrap;">
<p>Nessuna immagine disponibile per questo prodotto.</p>
</div>
`);
}
},
reorganizeDocumentLayout: function () {
const documents = $('#imageContainer1 .document-item');
const totalDocuments = documents.length;
documents.each(function () {
const $this = $(this);
$this.removeClass('col-xs-12 col-xs-6 col-md-4');
if (totalDocuments === 1) {
$this.addClass('col-xs-12');
} else {
// $this.addClass('col-xs-6 col-md-4');
}
});
if (totalDocuments === 0) {
$('#imageContainer1').html(`
<div class="col-xs-12 text-center" style="white-space: nowrap;">
<p>Nessun documento disponibile per questo prodotto.</p>
</div>
`);
}
},
addImageUrlBtn: function ($div) {
const url = $("#imageUrlInput").val().trim();
if (!url) {
$div.showAlert('Inserisci un URL valido', 'Errore', 'danger');
return;
}
const testImg = new Image();
testImg.onload = function () {
function handleSuccessfulImageSave(response, imageId, productKey, url) {
const imageData = {
id: imageId,
id_riga: response.key?.id_riga || $div.currentProductData.id_riga,
src: response.imageUrl || response.cache_path || url,
alt: `Immagine da URL per ${$div.currentProductData.descr_articolo}`,
type: 'uploaded',
fileName: response.fileName || $div.extractFileNameFromUrl(url),
fileSize: null,
cache_path: response.cache_path || url,
key: response.key
};
if ($div.isImageFile(imageData.fileName)) {
if (!$div.uploadedImages[productKey]) {
$div.uploadedImages[productKey] = [];
}
$div.uploadedImages[productKey].push(imageData);
} else {
if (!$div.uploadedDocuments[productKey]) {
$div.uploadedDocuments[productKey] = [];
}
$div.uploadedDocuments[productKey].push(imageData);
if ($div.currentProductData && !$div.currentProductData.allegati) {
$div.currentProductData.allegati = [];
}
$div.currentProductData.allegati.push({
cache_path: imageData.cache_path,
key: imageData.key,
allow_delete: true,
name: imageData.fileName
});
}
if (!$div.allImagesData[productKey]) {
$div.allImagesData[productKey] = {};
}
$div.allImagesData[productKey][imageId] = imageData;
const downloadFileName = imageData.fileName || 'immagine';
const imageHtml = `
<div class="panel panel-default" style="position: relative;">
<div class="panel-body" style="padding: 0; display: flex; flex-direction: column; height: 100%;">
<div style="padding: 15px; text-align: center;">
<img src="${imageData.src}" alt="${imageData.alt}"
class="img-responsive img-rounded"
style="max-height: 200px; display: block; margin: 0 auto;">
</div>
<div style="flex: 1; background: #eeeeee; padding: 10px; display: flex; justify-content: center; align-items: center; gap: 10px;">
<button class="btn btn-success btn-xs btn-download-img"
title="Scarica immagine">
<i class="fa fa-download"></i>
</button>
<button class="btn btn-danger btn-xs btn-elimina-img"
title="Elimina immagine">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
</div>
`;
const $imageElement = $(`#image-${imageId}`);
$imageElement.html(imageHtml);
$imageElement.off('click', '.btn-elimina-img').on('click', '.btn-elimina-img', function (e) {
e.preventDefault();
e.stopPropagation();
$div.deleteImage(imageId, 'uploaded');
});
$imageElement.off('click', '.btn-download-img').on('click', '.btn-download-img', function (e) {
e.preventDefault();
e.stopPropagation();
$div.downloadFile(imageId, downloadFileName, imageData.src);
});
$div.reorganizeImageLayout();
$div.reorganizeDocumentLayout();
$("#imageUrlInput").val('');
_articoliAnag.refreshGrid();
}
async function proceedWithUrlSave(url) {
if (!$div.currentProductData) {
$div.showAlert('Seleziona prima un prodotto aprendo il modal delle immagini', 'Errore', 'warning');
return;
}
const productKey = $div.currentProductData.cod_mart;
const imageId = `uploaded-url-${Date.now()}`;
const loadingHtml = `
<div class="col-xs-6 col-md-4 image-item" id="image-${imageId}">
<div class="panel panel-default">
<div class="panel-body text-center">
<i class="fa fa-spinner fa-spin fa-2x"></i>
<p>Caricamento...</p>
</div>
</div>
</div>
`;
$("#imageContainer").append(loadingHtml);
const idRiga = $div.currentProductData.id_riga || $div.currentProductData.key?.id_riga;
const result = await $div.saveImageUrlToServer(url, idRiga, productKey, imageId);
if(result) {
handleSuccessfulImageSave(result, imageId, productKey, url);
}else {
$(`#image-${imageId}`).remove();
$div.showAlert('Errore durante il salvataggio URL', 'Errore', 'danger');
}
}
proceedWithUrlSave(url);
};
testImg.onerror = () => {
this.showAlert('Impossibile caricare l\'immagine dall\'URL fornito. Verifica che l\'URL sia corretto e accessibile.', 'Errore', 'danger');
};
testImg.src = url;
},
addFile: async function(e, $div) {
if (!$div.currentProductData) {
$div.showAlert('Seleziona prima un prodotto aprendo il modal delle immagini', 'Errore', 'warning');
$(this).val('');
e.target.value = '';
return;
}
const files = e.target.files;
const productKey = $div.currentProductData.cod_mart;
const idRiga = $div.currentProductData.id_riga || $div.currentProductData.key?.id_riga;
const $fileInput = $(e.target);
if (!files || files.length === 0) {
return;
}
const fileList = Array.from(files);
$fileInput.val('');
for (let index = 0; index < fileList.length; index++){
const file = fileList[index];
console.log(`File #${index}:`, file.name);
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.pdf', '.doc', '.docx', '.xls', '.xlsx', '.txt'];
const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(fileExtension)) {
$div.showAlert(`Formato file non supportato: ${file.name}`, 'Errore', 'danger');
return;
}
if (file.size > 5 * 1024 * 1024) {
$div.showAlert(`File troppo grande: ${file.name} (max 5MB)`, 'Errore', 'danger');
return;
}
const imageId = `uploaded-${Date.now()}-${index}`;
const loadingHtml = `
<div class="image-item" id="image-${imageId}">
<div class="panel panel-default">
<div class="panel-body text-center">
<i class="fa fa-spinner fa-spin fa-2x"></i>
<p>Caricamento ${file.name}...</p>
</div>
</div>
</div>
`;
if ($div.isImageFile(file.name)) {
$("#imageContainer .col-xs-12.text-center").remove();
$("#imageContainer").append(loadingHtml);
} else if ($div.isDocumentFile(file.name)) {
$("#imageContainer1 .col-xs-12.text-center").remove();
$("#imageContainer1").append(loadingHtml);
} else {
$("#imageContainer1 .col-xs-12.text-center").remove();
$("#imageContainer1").append(loadingHtml);
}
const result = await $div.uploadFileToServer(file, productKey, imageId);
if(result) {
const isImage = $div.isImageFile(file.name);
const isDoc = $div.isDocumentFile(file.name);
const imageData = {
id: imageId,
id_riga: result.key?.id_riga || result.id_riga || idRiga,
src: result.cache_path || result.imageUrl || result.url,
alt: file.name,
type: 'uploaded',
fileName: file.name,
fileSize: file.size,
cache_path: result.cache_path || result.imageUrl || result.url || '',
key: result.key || { id_riga: result.id_riga || idRiga }
};
if (!$div.allImagesData[productKey]) {
$div.allImagesData[productKey] = {};
}
$div.allImagesData[productKey][imageId] = imageData;
if (isImage) {
if (!$div.uploadedImages[productKey]) {
$div.uploadedImages[productKey] = [];
}
$div.uploadedImages[productKey].push(imageData);
} else if (isDoc) {
if (!$div.uploadedDocuments[productKey]) {
$div.uploadedDocuments[productKey] = [];
}
$div.uploadedDocuments[productKey].push(imageData);
console.log($div.uploadedImages[productKey]);
}
if (isDoc) {
if ($div.currentProductData && !$div.currentProductData.allegati) {
$div.currentProductData.allegati = [];
}
$div.currentProductData.allegati = Object.values($div.allImagesData[productKey])
.filter(file => $div.isDocumentFile(file.fileName))
.map(file => ({
cache_path: file.cache_path,
key: file.key,
allow_delete: true,
name: file.fileName
}));
$div.currentProductData.exist_images = "1";
}
if (!$div.allImagesData[productKey]) {
$div.allImagesData[productKey] = {};
}
$div.allImagesData[productKey][imageId] = imageData;
const fileHtml = isImage ? `
<div class="panel panel-default" style="max-width: 248px; position: relative;">
<div class="panel-body" style="max-width: 248px; padding: 0; display: flex; flex-direction: column; height: 100%;">
<div style="padding: 15px; text-align: center;">
<img src="${imageData.src}" alt="${imageData.alt}"
class="img-responsive img-rounded"
style="display: block; margin: 0 auto;">
</div>
<div style="flex: 1; background: #eeeeee; padding: 10px; display: flex; justify-content: center; align-items: center; gap: 10px;">
<button class="btn btn-success btn-xs btn-download-img"
title="Scarica immagine">
<i class="fa fa-download"></i>
</button>
<button class="btn btn-danger btn-xs btn-elimina-img"
title="Elimina immagine">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
</div>
` : `
<div class="panel panel-default" style="position: relative; height: 147px;">
<div class="panel-body text-center" style="padding: 0; display: flex; flex-direction: column; height: 100%;">
<div style="padding-top: 10px;">
<i class="fa fa-file fa-4x"></i>
</div>
<div style="padding: 5px;">
<strong style="font-size: 12px; word-break: break-all;">${file.name}</strong>
</div>
<div style="margin-top: auto; background: #eeeeee; padding: 10px; display: flex; justify-content: center; align-items: center; gap: 10px;">
<button class="btn btn-success btn-xs btn-download-img"
title="Scarica immagine">
<i class="fa fa-download"></i>
</button>
<button class="btn btn-danger btn-xs btn-elimina-img"
title="Elimina immagine">
<i class="fa fa-trash"></i>
</button>
</div>
</div>
</div>
`;
const $imageElement = $(`#image-${imageId}`);
if ($imageElement.length > 0) {
$imageElement.html(fileHtml);
if (isDoc) {
$imageElement.removeClass('image-item').addClass('document-item');
}
}
$imageElement.off('click', '.btn-elimina-img').on('click', '.btn-elimina-img', function (e) {
e.preventDefault();
e.stopPropagation();
$div.deleteImage(imageId, 'uploaded');
});
$imageElement.off('click', '.btn-download-img').on('click', '.btn-download-img', function (e) {
e.preventDefault();
e.stopPropagation();
$div.downloadFile(imageId, file.name, imageData.src);
});
$div.reorganizeImageLayout();
$div.reorganizeDocumentLayout();
_articoliAnag.refreshGrid();
}else{
$(`#image-${imageId}`).remove();
const errorMessage = result?.error || 'Errore durante l\'upload del file';
$div.showAlert(`Errore durante l'upload di ${file.name}: ${errorMessage}`, 'Errore', 'danger');
$div.reorganizeImageLayout();
$div.reorganizeDocumentLayout();
}
}
$(this).val('');
},
displayFile: function ($container) {
const dataItem = this.currentProductData;
const $imageContainer = $container.find('#imageContainer');
const $documentContainer = $container.find('#imageContainer1');
$imageContainer.empty();
$documentContainer.empty();
const productKey = dataItem.cod_mart;
const idRiga = dataItem.id_riga;
this.allImagesData[productKey] = {};
const allImages = [];
const allDocuments = [];
if (dataItem.allegati && dataItem.allegati.length > 0) {
dataItem.allegati.forEach((allegato, index) => {
let fileName = '';
if (allegato.name && allegato.name.trim() !== '') {
fileName = allegato.name.trim();
} else if (allegato.filename && allegato.filename.trim() !== '') {
fileName = allegato.filename.trim();
} else if (allegato.fileName && allegato.fileName.trim() !== '') {
fileName = allegato.fileName.trim();
} else if (allegato.cache_path) {
fileName = this.extractFileNameFromUrl(allegato.cache_path);
} else {
fileName = `image_${index}`;
}
const fileId = `server-img-${allegato.key?.id_riga || index}`;
const fileData = {
id: fileId,
src: allegato.cache_path,
alt: dataItem.descr_articolo,
type: 'existing',
key: allegato.key,
id_riga: allegato.key?.id_riga,
allow_delete: allegato.allow_delete !== false,
fileName: fileName,
cache_path: allegato.cache_path
};
if (this.isImageFile(fileData.fileName)) {
allImages.push(fileData);
} else {
allDocuments.push(fileData);
}
this.allImagesData[productKey][fileId] = fileData;
});
}
if (dataItem.arr_files && dataItem.arr_files.length > 0) {
console.log("errore");
dataItem.arr_files.forEach((documento, index) => {
let fileName = '';
if (documento.file_name && documento.file_name.trim() !== '') {
fileName = documento.file_name.trim();
} else if (documento.name && documento.name.trim() !== '') {
fileName = documento.name.trim();
} else if (documento.filename && documento.filename.trim() !== '') {
fileName = documento.filename.trim();
} else if (documento.fileName && documento.fileName.trim() !== '') {
fileName = documento.fileName.trim();
} else if (documento.cache_path) {
fileName = this.extractFileNameFromUrl(documento.cache_path);
} else {
fileName = `document_${index}`;
}
const fileId = `server-doc-${documento.key?.id_riga || index}`;
const fileData = {
id: fileId,
src: documento.cache_path,
alt: dataItem.descr_articolo,
type: 'existing',
key: documento.key,
id_riga: documento.key?.id_riga,
allow_delete: documento.allow_delete !== false,
fileName: fileName,
cache_path: documento.cache_path
};
if (this.isImageFile(fileData.fileName)) {
allImages.push(fileData);
} else {
allDocuments.push(fileData);
}
console.log(fileData.fileName);
this.allImagesData[productKey][fileId] = fileData;
});
}
if (this.uploadedImages[productKey]) {
this.uploadedImages[productKey].forEach((uploadedFile) => {
const isDuplicate = dataItem.allegati?.some(allegato =>
allegato.key?.id_riga === uploadedFile.id_riga
);
if (!isDuplicate) {
if (this.isImageFile(uploadedFile.fileName)) {
// allImages.push(uploadedFile);
} else if (this.isDocumentFile(uploadedFile.fileName)) {
// allDocuments.push(uploadedFile);
}
this.allImagesData[productKey][uploadedFile.id] = uploadedFile;
}
});
}
if (this.uploadedDocuments && this.uploadedDocuments[productKey]) {
this.uploadedDocuments[productKey].forEach((uploadedDoc) => {
const isDuplicate = dataItem.arr_files?.some(documento =>
documento.key?.id_riga === uploadedDoc.id_riga
);
if (!isDuplicate) {
if (this.isImageFile(uploadedDoc.fileName)) {
// allImages.push(uploadedDoc);
} else if (this.isDocumentFile(uploadedDoc.fileName)) {
// allDocuments.push(uploadedDoc);
}
this.allImagesData[productKey][uploadedDoc.id] = uploadedDoc;
}
});
}
console.log('Immagini finali per prodotto', productKey, ':', allImages);
console.log('Documenti finali per prodotto', productKey, ':', allDocuments);
if ((dataItem.allegati && dataItem.allegati.length > 0) ||
(dataItem.arr_files && dataItem.arr_files.length > 0)) {
dataItem.exist_images = "1";
}
this.displayImages(allImages);
this.displayDocuments(allDocuments);
},
openImageModal: function (dataItem) {
const self = this;
const modalBox1 = new ModalBox();
const modalContent = `
<div class="container-fluid mb-20">
<div class="file-upload-section">
<input class="btn btn-primary" name="files" id="files" type="file" aria-label="Allega Foto" multiple />
</div>
<div class="url-input-section">
<div class="input-group">
<input type="text" id="imageUrlInput" class="form-control" placeholder="Inserisci URL immagine" aria-label="URL Immagine">
<span class="input-group-btn">
<button class="btn btn-primary" id="addImageUrlBtn" type="button">Aggiungi URL</button>
</span>
</div>
</div>
</div>
<div></div>
<div class="clearfix"></div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingImages">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" href="#collapseImages" aria-expanded="true" aria-controls="collapseImages" class="panel-toggle-link">
<strong><u>Immagini</u></strong>
<span class="arrow-icon">${self.arrUp.html}</span>
</a>
</h4>
</div>
<div id="collapseImages" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingImages">
<div class="panel-body panel-body-no-padding p-10">
<div class="image-container" id="imageContainer"></div>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingDocuments">
<h4 class="panel-title">
<a role="button" data-toggle="collapse" href="#collapseDocuments" aria-expanded="true" aria-controls="collapseDocuments" class="panel-toggle-link">
<strong><u>Documenti</u></strong>
<span class="arrow-icon">${self.arrUp.html}</span>
</a>
</h4>
</div>
<div id="collapseDocuments" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingDocuments">
<div class="panel-body panel-body-no-padding p-10">
<div class="document-container" id="imageContainer1"></div>
</div>
</div>
</div>
`;
modalBox1
.content(modalContent)
.title(`Immagini e Documenti - ${dataItem.descr_articolo} - ${dataItem.cod_mart}`)
.onBeforeShow(($div) => {
$('.arrow-icon').html(_modalArticolo.arrUp.html);
$div.on('show.bs.collapse', '.panel-collapse', function () {
const panelId = $(this).attr('id');
$('[href="#' + panelId + '"] .arrow-icon').html(_modalArticolo.arrUp.html);
});
$div.on('hide.bs.collapse', '.panel-collapse', function () {
const panelId = $(this).attr('id');
$('[href="#' + panelId + '"] .arrow-icon').html(_modalArticolo.arrDown.html);
});
$("#addImageUrlBtn").on("click", function () {
self.addImageUrlBtn(self);
});
$("#files").on("change", function (e) {
self.addFile(e, self);
});
self.currentProductData = dataItem;
self.displayFile($div);
})
.btOK({
text: "Chiudi",
onClick: function () {
modalBox1.close();
}
});
modalBox1.style("primary");
modalBox1.show();
setTimeout(() => {
$('.modalBox, .modal-dialog, .modal-content').css({
'width': '900px',
'min-width': '900px'
});
}, 0);
},
extractFileNameFromUrl: function (url) {
try {
const urlObj = new URL(url, window.location.origin);
const urlWithoutQuery = urlObj.pathname;
const parts = urlWithoutQuery.split('/');
let filename = parts.pop();
return filename;
} catch (e) {
console.error('Errore nell\'estrazione del nome file dall\'URL:', e);
return 'file_errore';
}
},
displayImages: function (allImages) {
const self = this;
const imageContainer = $('#imageContainer');
if (allImages.length > 0) {
allImages.forEach(image => {
const colClass = allImages.length === 1 ? 'col-xs-12' : 'col-xs-6 col-md-4';
const downloadFileName = image.fileName || image.alt || self.extractFileNameFromUrl(image.src);
const imageInfo = image.type === 'uploaded' && image.fileName ?
`<div class="image-info" style="font-size: 10px; margin-top: 5px;">
<strong>${image.fileName}</strong><br>
${image.fileSize ? (image.fileSize / 1024).toFixed(1) + ' KB' : 'URL Immagine'}
</div>` : '';
const imageHtml = `
<div style="width: 280px" class="${colClass} image-item" id="image-${image.id}">
<div class="panel panel-default" style="position: relative;">
<div class="panel-body" style="padding: 0; display: flex; flex-direction: column; height: 100%;">
<div style="text-center; padding: 15px;">
<img src="${image.src}" alt="${image.alt}"
class="img-responsive img-rounded"
style="max-height: 200px; display: block; margin: 0 auto;">
</div>
<div style="flex: 1; background: #eeeeee; padding: 10px; display: flex; justify-content: center; align-items: center; gap: 10px;">
<button class="btn btn-success btn-xs btn-download-img"
title="Scarica immagine">
<i class="fa fa-download"></i>
</button>
<button class="btn btn-danger btn-xs btn-elimina-img"
title="Elimina immagine">
<i class="fa fa-trash"></i>
</button>
</div>
${imageInfo}
</div>
</div>
</div>
`;
const $imageElement = $(imageHtml);
$imageElement.off('click', '.btn-elimina-img').on('click', '.btn-elimina-img', function (e) {
e.preventDefault();
e.stopPropagation();
self.deleteImage(image.id, image.type);
});
$imageElement.off('click', '.btn-download-img').on('click', '.btn-download-img', function (e) {
e.preventDefault();
e.stopPropagation();
self.downloadFile(image.id, downloadFileName, image.src);
});
imageContainer.append($imageElement);
});
} else {
imageContainer.html(`
<div class="col-xs-12 text-center" style="white-space: nowrap;">
<p>Nessuna immagine disponibile per questo prodotto.</p>
</div>
`);
}
$('#imageModal').modal('show');
},
displayDocuments: function (allDocuments) {
const self = this;
const imageContainer1 = $('#imageContainer1');
console.log(allDocuments.length);
if (allDocuments.length > 0) {
allDocuments.forEach(file => {
const colClass = allDocuments.length === 1 ? 'col-xs-12' : 'col-xs-6 col-md-4';
const downloadFileName = file.fileName || file.alt || self.extractFileNameFromUrl(file.src);
const fileInfo = file.type === 'uploaded' && file.fileName ?
`<div class="document-info" style="font-size: 10px; margin-top: 5px;">
<strong>${file.fileName}</strong><br>
${file.fileSize ? (file.fileSize / 1024).toFixed(1) + ' KB' : 'URL Documento'}
</div>` : '';
const fileHtml = `
<div class="document-item" id="image-${file.id}">
<div class="panel panel-default mb-0" style="position: relative; height: 147px;">
<div class="panel-body text-center" style="padding: 0; display: flex; flex-direction: column; height: 100%;">
<div style="padding-top: 10px;">
<i class="fa fa-file fa-4x"></i>
</div>
<div style="padding: 5px;">
<strong style="font-size: 12px; word-break: break-all;">${file.fileName}</strong>
</div>
<div style="margin-top: auto; background: #eeeeee; padding: 10px; display: flex; justify-content: center; align-items: center; gap: 10px;">
<button class="btn btn-success btn-xs btn-download-img"
title="Scarica immagine">
<i class="fa fa-download"></i>
</button>
<button class="btn btn-danger btn-xs btn-elimina-img"
title="Elimina immagine">
<i class="fa fa-trash"></i>
</button>
</div>
${fileInfo}
</div>
</div>
</div>
`;
const $imageElement = $(fileHtml);
$imageElement.on("click", ".btn-elimina-img", () => {
self.deleteImage(file.id, file.type);
});
$imageElement.on("click", ".btn-download-img", () => {
self.downloadFile(file.id, downloadFileName, file.src);
})
imageContainer1.append($imageElement);
});
} else {
imageContainer1.html(`
<div class="col-xs-12 text-center" style="white-space: nowrap;">
<p>Nessun documento disponibile per questo prodotto.</p>
</div>
`);
}
$('#imageModal').modal('show');
},
showPage: function () {
let self = this;
return self;
}
}