Desacople e inyeccion de dependencias

This commit is contained in:
imnavajas
2025-07-22 16:01:34 +02:00
parent a1aaa095d4
commit 9ed397e9ad
9 changed files with 391 additions and 154 deletions

BIN
httpdocs/assets/img/pdf.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

View File

@ -1,73 +1,84 @@
// Importación de utilidades AJAX y alertas personalizadas
import Ajax from '../ajax.js';
import { alertSuccessMessage, 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">
<!---<img data-dz-thumbnail>
<span class="dz-nopreview">No preview</span> --->
<!-- 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 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>
<!-- Estilo uniforme con Eliminar / Ver -->
<a class="dz-download dz-remove" href="javascript:void(0);" style="text-align:center;">Descargar</a>
<!-- 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;
this.domElement = domElement
this.jqElement = $(domElement)
this.modelId = this.jqElement.data('id')
this.btnSelectFiles = $(`#${domElement.replace('#', '')}_btnUploadFiles`)
this.btnSubmitFile = $(`#${domElement.replace('#', '')}_btnSubmitFiles`)
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.dataPost = {}
this.nameId = nameId;
this.otId = otId;
this.getUri = getUri
this.postUri = postUri
this.dataPost[nameId] = this.modelId;
this.resourcePath = resourcePath
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) {
this.btnSubmitFile.on('click', this._handleUploadFiles.bind(this))
this.btnSelectFiles.on('click', () => {
this.jqElement.trigger('click')
})
this.btnDownloadFiles.on('click', this._handleDownloadFiles.bind(this))
// 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, // Ajusta este número al máximo número de archivos que esperas subir a la vez
maxFiles: 5, // Ajusta este número al máximo número de archivos que esperas subir a la vez
parallelUploads: 4,
maxFiles: 5,
autoProcessQueue: true,
dictRemoveFile: "Eliminar",
acceptedFiles: 'image/*, application/pdf',
maxFilesize: 5e+7, // Bytes
init: this._handleGetFiles.bind(this)
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
@ -90,70 +101,86 @@ class FileUploadDropzone {
}
}
// Acción del botón "Ver"
onViewButton(file) {
console.log(window.location.protocol + "//" + window.location.host + "/sistema/intranet/" + this.resourcePath + "/" + file.hash)
window.open(window.location.protocol + "//" + window.location.host + "/sistema/intranet/" + this.resourcePath + "/" + file.hash, '_blank');
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() {
var files = this.dropzone.files;
const files = this.dropzone.files;
const formData = new FormData();
const oldFiles = [];
var formData = new FormData();
var oldFiles = [];
var counter = 0;
for (var i = 0; i < files.length; i++) {
if (files[i].upload) {
var file = files[i];
for (let file of files) {
if (file.upload) {
formData.append('file[]', file);
counter += 1;
}
else {
oldFiles.push(files[i].name);
} else {
oldFiles.push(file.name);
}
}
formData.append('oldFiles', JSON.stringify(oldFiles));
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')
let ajax = new Ajax(this.postUri,
$("#loader").modal('show');
const ajax = new Ajax(
this.postUri,
this._getDropzoneFilesFormData(),
null,
this._handleUploadFilesSuccess.bind(this),
null)
null
);
ajax.ajaxForm("POST");
}
// Éxito tras subir archivos
_handleUploadFilesSuccess(response) {
this.dropZoneClean()
this._handleGetFiles()
this.dropZoneClean(); // Limpia visualmente
this._handleGetFiles(); // Recarga archivos desde backend
alertSuccessMessage(response?.message ?? "Archivos subidos correctamente");
}
_handleUploadFilesError(errors) { }
_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()
null
);
ajax.post();
}
// Manejo de respuesta del servidor al cargar archivos
_handelGetFilesSuccess(response) {
try {
$("#loader").modal('hide')
const files = JSON.parse(response)
this.dropZoneUpdateFiles(files)
$("#loader").modal('hide');
const files = Array.isArray(response)
? response
: typeof response === 'string'
? JSON.parse(response)
: [];
this.dropZoneUpdateFiles(files);
} catch (error) {
$("#loader").modal('hide')
console.error("Error parseando respuesta:", error);
$("#loader").modal('hide');
}
}
// Manejo del botón "Descargar archivos ZIP"
_handleDownloadFiles() {
$("#loader").modal('show');
@ -172,7 +199,7 @@ class FileUploadDropzone {
let filename = "archivos.zip";
if (disposition && disposition.indexOf('attachment') !== -1) {
const match = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
if (match != null && match[1]) {
if (match && match[1]) {
filename = match[1].replace(/['"]/g, '');
}
}
@ -195,28 +222,57 @@ class FileUploadDropzone {
});
}
// Carga archivos simulados (mock) al Dropzone visual
dropZoneUpdateFiles(files) {
files.forEach(file => {
this.dropZoneAddFile(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);
})
});
}
dropZoneAddFile(mockFile) {
this.dropzone.files.push(mockFile); // add to files array
this.dropzone.emit("addedfile", mockFile);
this.dropzone.emit("thumbnail", mockFile, window.location.host + "/sistema/intranet/" + this.resourcePath + "/" + mockFile.hash);
this.dropzone.emit("complete", mockFile);
this.dropzone.options.success.call(this.dropzone, mockFile);
// 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);
}
}
export default FileUploadDropzone;
// Exporta la clase para usarla en otros módulos JS
export default FileUploadDropzone;