Files
safekat/httpdocs/assets/js/safekat/components/forms/fileUploadDropzone.js
2025-07-23 11:56:43 +02:00

310 lines
11 KiB
JavaScript

// Importación de utilidades AJAX y alertas personalizadas
import Ajax from '../ajax.js';
import { alertFileUploadSuccess, alertWarningMessage } from '../alerts/sweetAlert.js'
// Template HTML para la vista previa de cada archivo en Dropzone
const PREVIEW_TEMPLATE = `
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-thumbnail">
<!-- Miniatura de imagen o PDF -->
<div class="dz-success-mark"></div>
<div class="dz-error-mark"></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<div class="progress">
<div class="progress-bar progress-bar-primary" role="progressbar" aria-valuemin="0" aria-valuemax="100" data-dz-uploadprogress></div>
</div>
</div>
<div class="dz-filename" data-dz-name></div>
<!-- Botón para descargar -->
<a class="dz-download dz-remove" href="javascript:void(0);" style="text-align:center;">Descargar</a>
<div class="dz-size" data-dz-size></div>
</div>
</div>
`;
// Clase principal que maneja el flujo de Dropzone + AJAX
class FileUploadDropzone {
constructor({ domElement, nameId = "presupuesto_id", getUri = null, postUri = null, resourcePath = "presupuestos", otId = null }) {
Dropzone.autoDiscover = false; // Desactiva la auto inicialización de Dropzone
this.domElement = domElement;
this.jqElement = $(domElement); // Referencia jQuery al elemento
this.modelId = this.jqElement.data('id'); // ID que asocia los archivos a un modelo (presupuesto, pedido, etc.)
// Botones asociados
this.btnSelectFiles = $(`#${domElement.replace('#', '')}_btnUploadFiles`);
this.btnSubmitFile = $(`#${domElement.replace('#', '')}_btnSubmitFiles`);
this.btnDownloadFiles = $(`#${domElement.replace('#', '')}_btnDownloadFiles`);
this.nameId = nameId;
this.otId = otId;
this.getUri = getUri;
this.postUri = postUri;
this.resourcePath = resourcePath;
this.dataPost = {};
this.dataPost[nameId] = this.modelId;
}
// Inicializa Dropzone y los eventos externos
init() {
if (this.jqElement.length > 0) {
// Vincula botones externos
this.btnSubmitFile.on('click', this._handleUploadFiles.bind(this));
this.btnSelectFiles.on('click', () => this.jqElement.trigger('click'));
this.btnDownloadFiles.on('click', this._handleDownloadFiles.bind(this));
// Inicializa Dropzone
this.dropzone = new Dropzone(this.domElement, {
url: this.postUri,
addRemoveLinks: true,
previewTemplate: PREVIEW_TEMPLATE,
paramName: "file",
uploadMultiple: true,
parallelUploads: 4,
maxFiles: 5,
autoProcessQueue: true,
dictRemoveFile: "Eliminar",
acceptedFiles: 'image/*, application/pdf',
maxFilesize: 5e+7, // 50 MB
init: this._handleGetFiles.bind(this) // Carga inicial de archivos
});
// Cuando se añade un archivo (manual o programático)
this.dropzone.on("addedfile", this._handleAddedFile.bind(this));
}
}
// Botones "Ver" y "Descargar" para cada archivo
_handleAddedFile(file) {
if (file.hash) {
// Botón Ver
const viewButton = Dropzone.createElement("<a class='dz-remove' style='text-align:center;'>Ver</a>");
file.previewElement.appendChild(viewButton);
viewButton.addEventListener("click", this.onViewButton.bind(this, file));
// Botón Descargar
const downloadButton = Dropzone.createElement("<a class='dz-download dz-remove' style='text-align:center;'>Descargar</a>");
file.previewElement.appendChild(downloadButton);
downloadButton.addEventListener("click", () => {
const fileUrl = `${window.location.protocol}//${window.location.host}/sistema/intranet/${this.resourcePath}/${file.hash}`;
const a = document.createElement("a");
a.href = fileUrl;
a.download = file.name;
document.body.appendChild(a);
a.click();
a.remove();
});
}
}
// Acción del botón "Ver"
onViewButton(file) {
const url = `${window.location.protocol}//${window.location.host}/sistema/intranet/${this.resourcePath}/${file.hash}`;
window.open(url, '_blank');
}
// Prepara el objeto FormData para el envío
_getDropzoneFilesFormData() {
const files = this.dropzone.files;
const formData = new FormData();
const oldFiles = [];
for (let file of files) {
if (file.upload) {
formData.append('file[]', file);
} else {
oldFiles.push(file.name);
}
}
formData.append('oldFiles', JSON.stringify(oldFiles));
formData.append(this.nameId, this.modelId);
return formData;
}
// Acción al hacer clic en "Subir archivos"
_handleUploadFiles() {
$("#loader").modal('show');
const ajax = new Ajax(
this.postUri,
this._getDropzoneFilesFormData(),
null,
this._handleUploadFilesSuccess.bind(this),
null
);
ajax.ajaxForm("POST");
}
// Éxito tras subir archivos
_handleUploadFilesSuccess(response) {
this.dropZoneClean();
this._handleGetFiles();
const summary = response?.summary || {};
const numOk = summary.subidos_ok || 0;
const numErrLocal = summary.errores_locales || 0;
const numErrRemote = summary.errores_remotos || 0;
const numDeleted = summary.borrados || 0;
const partes = [];
if (numOk > 0) {
partes.push(`Se subió${numOk === 1 ? '' : 'ron'} ${numOk} archivo${numOk === 1 ? '' : 's'} correctamente.`);
}
if (numDeleted > 0) {
partes.push(`Se eliminaron ${numDeleted} archivo${numDeleted === 1 ? '' : 's'} obsoleto${numDeleted === 1 ? '' : 's'}.`);
}
if (numErrLocal > 0) {
partes.push(`${numErrLocal} archivo${numErrLocal === 1 ? '' : 's'} falló${numErrLocal === 1 ? '' : 'n'} en el sistema.`);
}
if (numErrRemote > 0) {
partes.push(`${numErrRemote} fallo${numErrRemote === 1 ? '' : 's'} en la transferencia.`);
}
const mensaje = partes.length > 0
? partes.join(' ')
: response?.message ?? "Archivos actualizados correctamente.";
alertFileUploadSuccess(mensaje);
}
_handleUploadFilesError(errors) {
// No implementado aún
}
// Carga inicial de archivos existentes desde el servidor
_handleGetFiles() {
const ajax = new Ajax(
this.getUri,
this.dataPost,
null,
this._handelGetFilesSuccess.bind(this),
null
);
ajax.post();
}
// Manejo de respuesta del servidor al cargar archivos
_handelGetFilesSuccess(response) {
try {
$("#loader").modal('hide');
const files = Array.isArray(response)
? response
: typeof response === 'string'
? JSON.parse(response)
: [];
this.dropZoneUpdateFiles(files);
} catch (error) {
console.error("Error parseando respuesta:", error);
$("#loader").modal('hide');
}
}
// Manejo del botón "Descargar archivos ZIP"
_handleDownloadFiles() {
$("#loader").modal('show');
$.ajax({
url: `/files/download_zip`,
type: 'POST',
data: {
[this.nameId]: this.modelId,
'ot_id': this.otId
},
xhrFields: {
responseType: 'blob'
},
success: (blob, status, xhr) => {
const disposition = xhr.getResponseHeader('Content-Disposition');
let filename = "archivos.zip";
if (disposition && disposition.indexOf('attachment') !== -1) {
const match = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
if (match && match[1]) {
filename = match[1].replace(/['"]/g, '');
}
}
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
},
error: () => {
alertWarningMessage("Error", "Error al descargar el archivo ZIP.");
},
complete: () => {
$("#loader").modal('hide');
}
});
}
// Carga archivos simulados (mock) al Dropzone visual
dropZoneUpdateFiles(files) {
files.forEach(file => {
//console.log("Iterando archivo:", file.name);
this.dropZoneAddFile(file);
});
}
// Limpia todos los archivos de Dropzone visualmente
dropZoneClean() {
this.dropzone.files.forEach(file => {
this.dropzone.removeFile(file);
});
}
// Inserta un archivo en Dropzone manualmente (mock)
dropZoneAddFile(mockFileData) {
const extension = mockFileData.name.split('.').pop().toLowerCase();
const isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(extension);
const isPDF = extension === 'pdf';
const fileUrl = `${window.location.protocol}//${window.location.host}/sistema/intranet/${this.resourcePath}/${mockFileData.hash}`;
const mockFile = {
name: mockFileData.name,
size: mockFileData.size,
type: isImage ? `image/${extension === 'jpg' ? 'jpeg' : extension}` : 'application/pdf',
hash: mockFileData.hash,
upload: false // Impide que se vuelva a subir
};
this.dropzone.emit("addedfile", mockFile);
// Espera a que Dropzone genere el DOM para modificar la miniatura
setTimeout(() => {
if (isImage) {
this.dropzone.emit("thumbnail", mockFile, fileUrl);
} else if (isPDF) {
const preview = mockFile.previewElement?.querySelector('.dz-thumbnail');
if (preview) {
preview.innerHTML = `<img src="/assets/img/pdf.png" alt="PDF" style="width:100%; height:auto;" />`;
}
}
this.dropzone.emit("complete", mockFile);
}, 10);
this.dropzone.files.push(mockFile);
}
}
// Exporta la clase para usarla en otros módulos JS
export default FileUploadDropzone;