Files
safekat/httpdocs/assets/js/safekat/pages/presupuestoCliente/resumen.js
2025-07-23 11:56:43 +02:00

453 lines
21 KiB
JavaScript

import previewFormas from "../../components/preview.js";
import { capitalizeFirstLetter } from "../../common/common.js";
class Resumen {
constructor(domItem, datosGenerales, disenioInterior, disenioCubierta) {
this.domItem = domItem;
this.datosGenerales = datosGenerales;
this.disenioInterior = disenioInterior;
this.disenioCubierta = disenioCubierta;
this.titulo = $(this.domItem.find("#resumenTitulo"));
this.tipoLibro = $(this.domItem.find("#resumenTipoLibro"));
this.formato = $(this.domItem.find("#resumenFormato"));
this.paginas = $(this.domItem.find("#resumenPaginas"));
this.paginasColor = $(this.domItem.find("#resumenPaginasColor"));
this.paginasNegro = $(this.domItem.find("#resumenPaginasNegro"));
this.tirada = $(this.domItem.find("#resumenTirada"));
this.prototipo = $(this.domItem.find("#resumenPrototipo"));
this.impresionInterior = $(this.domItem.find("#resumenImpresion"));
this.papelInterior = $(this.domItem.find("#resumenPapelInterior"));
this.gramajeInterior = $(this.domItem.find("#resumenGramajeInterior"));
this.papelInteriorColor = $(this.domItem.find("#resumenPapelInteriorColor"));
this.gramajeInteriorColor = $(this.domItem.find("#resumenGramajeInteriorColor"));
this.papelInteriorNegro = $(this.domItem.find("#resumenPapelInteriorNegro"));
this.gramajeInteriorNegro = $(this.domItem.find("#resumenGramajeInteriorNegro"));
this.cubiertaTipo = $(this.domItem.find("#resumenCubiertaTipo"));
this.itemsCubiertaTapaBlanda = $(this.domItem.find(".cubierta-tapa-blanda"));
this.itemsCubiertaTapaDura = $(this.domItem.find(".cubierta-tapa-dura"));
this.carasCubierta = $(this.domItem.find("#resumenCarasCubierta"));
this.papelCubierta = $(this.domItem.find("#resumenPapelCubierta"));
this.gramajeCubierta = $(this.domItem.find("#resumenGramajeCubierta"));
this.lomoCubierta = $(this.domItem.find("#resumenLomoCubierta"));
this.solapasCubierta = $(this.domItem.find("#resumenSolapasCubierta"));
this.papelGuardas = $(this.domItem.find("#resumenPapelGuardas"));
this.guardasImpresas = $(this.domItem.find("#resumenGuardasImpresas"));
this.cabezada = $(this.domItem.find("#resumenCabezada"));
this.cubiertaAcabados = $(this.domItem.find("#resumenCubiertaAcabados"));
this.divSobrecubierta = $(this.domItem.find("#divResumenSobrecubierta"));
this.papelSobrecubierta = $(this.domItem.find("#resumenPapelSobrecubierta"));
this.gramajeSobrecubierta = $(this.domItem.find("#resumenGramajeSobrecubierta"));
this.solapasSobrecubierta = $(this.domItem.find("#resumenSolapaSobrecubierta"));
this.plastificadoSobrecubierta = $(this.domItem.find("#resumenPlastificadoSobreCubierta"));
this.precio_unidad = $(this.domItem.find("#resumenPrecioU"));
this.total_base = $(this.domItem.find("#resumenTotalBase"));
this.total_envios = $(this.domItem.find("#resumenTotalEnvio"));
this.total_antes_iva = $(this.domItem.find("#resumenTotalAntesIVA"));
this.iva_porcentaje = $(this.domItem.find("#resumenIvaPorcentaje"));
this.iva = $(this.domItem.find("#resumenIva"));
this.total = $(this.domItem.find("#resumenTotal"));
this.divPreview = $(this.domItem.find("#pv_ec_shape"));
this.btnPreviewCubierta = $(this.domItem.find("#btnPreviewCubierta"));
this.btnDownloadPreviewCubierta = this.domItem.find('.download-shape');
this.submitFiles = $(this.domItem.find("#submit-all-files"));
this.btnDownloadAllFiles = this.domItem.find("#download-all-files");
this.dropzone = null;
this.presupuesto_id = -1;
}
init(presupuesto_id = -1) {
this.btnPreviewCubierta.on('click', this.#btnPreview.bind(this));
this.submitFiles.on('click', this.#btnUploadFiles.bind(this));
this.btnDownloadAllFiles.on('click', this.#downloadAllFiles.bind(this));
this.downloadPreviewImage()
if (presupuesto_id != -1) {
this.presupuesto_id = presupuesto_id;
}
}
init_dropzone() {
let id = this.presupuesto_id;
Dropzone.autoDiscover = false;
const previewTemplate = `<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> --->
<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>
<div class="dz-size" data-dz-size></div>
</div>
</div>`;
this.dropzone = new Dropzone('#dropzone-multi', {
url: "/presupuestos/presupuestocliente/upload_files",
addRemoveLinks: true,
previewTemplate: previewTemplate,
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
autoProcessQueue: true,
dictRemoveFile: "Eliminar",
acceptedFiles: 'image/*, application/pdf',
maxFilesize: 5e+7, // Bytes
init: function () {
let thisDropzone = this;
$('#loader').show();
$.ajax({
url: "/files/get_files",
type: 'POST',
data: { presupuesto_id: id }
}).done(function (response) {
if (response == null || response == "") {
return;
}
let values = JSON.parse(response);
for (var i = 0; i < values.length; i++) {
var mockFile = { name: values[i].name, size: values[i].size, hash: values[i].hash };
thisDropzone.files.push(mockFile); // add to files array
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, window.location.host + "/sistema/intranet/presupuestos/" + values[i].hash);
thisDropzone.emit("complete", mockFile);
thisDropzone.options.success.call(thisDropzone, mockFile);
};
}).always(function () {
$('#loader').hide();
});
this.on("addedfile", function (file) {
if (file.hash) {
var viewButton = Dropzone.createElement("<span class='dz-remove'>Ver</span>");
file.previewElement.appendChild(viewButton);
// Listen to the view button click event
viewButton.addEventListener("click", function (e) {
window.open(window.location.protocol + "//" + window.location.host + "/sistema/intranet/presupuestos/" + file.hash, '_blank');
});
}
});
},
});
}
#btnUploadFiles() {
var files = this.dropzone.files;
$('#loader').show();
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];
formData.append('file[' + counter + ']', file);
counter += 1;
}
else {
oldFiles.push(files[i].name);
}
}
formData.append('oldFiles', JSON.stringify(oldFiles));
formData.append('presupuesto_id', this.presupuesto_id);
$.ajax({
url: "/presupuestos/presupuestocliente/upload_files",
type: 'POST',
data: formData,
processData: false, // Indicar a jQuery que no procese los datos
contentType: false // Indicar a jQuery que no establezca el tipo de contenido
}).done(function (response) {
popSuccessAlert("Archivos actualizados correctamente");
}).always(function () {
$('#loader').hide();
});
}
#downloadAllFiles() {
$('#loader').show();
$.ajax({
url: "/files/download_zip",
type: 'POST',
data: { presupuesto_id: this.presupuesto_id },
xhrFields: {
responseType: 'blob' // importante para recibir un archivo binario
},
success: function (blob, status, xhr) {
const disposition = xhr.getResponseHeader('Content-Disposition');
let filename = "archivos_presupuesto.zip";
if (disposition && disposition.indexOf('attachment') !== -1) {
const match = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
if (match != null && 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: function () {
popErrorAlert("Error al descargar el archivo ZIP");
},
complete: function () {
$('#loader').hide();
}
});
}
#btnPreview() {
if (this.divPreview.hasClass('d-none')) {
this.btnPreviewCubierta.text('Ocultar desarrollo cubierta');
this.divPreview.removeClass('d-none');
this.btnDownloadPreviewCubierta.parent().removeClass('d-none')
this.generate();
}
else {
this.btnPreviewCubierta.text('Mostrar desarrollo cubierta');
this.btnDownloadPreviewCubierta.parent().addClass('d-none')
this.divPreview.addClass('d-none');
}
}
generate() {
this.titulo.text(this.datosGenerales.titulo.val());
this.tipoLibro.text(capitalizeFirstLetter(this.datosGenerales.tiposLibro.filter('.selected').attr('id')));
let ancho = 0, alto = 0;
if (this.datosGenerales.checkFormatoPersonalizado.is(':checked')) {
ancho = parseFloat(this.datosGenerales.anchoPersonalizado.val());
alto = parseFloat(this.datosGenerales.altoPersonalizado.val());
this.formato.text(ancho + ' x ' + alto);
}
else {
ancho = parseFloat(this.datosGenerales.papelFormatoId.find('option:selected').text().split(" x ")[0]);
alto = parseFloat(this.datosGenerales.papelFormatoId.find('option:selected').text().split(" x ")[1]);
this.formato.text(this.datosGenerales.papelFormatoId.find('option:selected').text());
}
this.divPreview.empty();
new previewFormas(
this.divPreview,
this.datosGenerales.tiposLibro.filter('.selected').attr('id'),
this.disenioCubierta.disenioCubierta.filter('.selected').attr('id'),
"resumen",
{
ancho: () => { return ancho },
alto: () => { return alto },
lomo: () => { return $('#lc').val() === '' ? parseFloat('0.0') : parseFloat($('#lc').val()) },
solapas: () => { return this.disenioCubierta.getSolapasCubierta() },
lomoRedondo: () => { return this.disenioCubierta.tapaDuraLomoRedondo.hasClass('selected') ? 1 : 0 },
}
).previewEsquemaCubierta();
this.paginas.text(this.datosGenerales.paginas.val());
this.paginasColor.text(this.datosGenerales.paginasColor.val());
this.paginasNegro.text(this.datosGenerales.paginasNegro.val());
if (this.datosGenerales.selectedTirada) {
this.tirada.text(this.datosGenerales.selectedTirada);
}
else {
this.tirada.text(parseInt($($('.check-tirada-envio:checked')[0]).attr('tirada')));
}
this.prototipo.text(this.datosGenerales.prototipo.is(':checked') ? 'Sí' : 'No');
const HQ = this.disenioInterior.getIsHq();
const color = this.datosGenerales.getIsColor();
const papelInterior = this.disenioInterior.getPapel(true);
const gramajeInterior = this.disenioInterior.getGramaje();
if ($(".interior-color").hasClass('d-none')) {
this.domItem.find(".mismoInterior").removeClass('d-none');
this.domItem.find(".diferenteInterior").addClass('d-none');
const impInterior = (color ? "Color " : "Blanco y Negro ") + (HQ ? "Premium" : "Estándar");
this.impresionInterior.text(impInterior);
this.papelInterior.text(papelInterior);
this.gramajeInterior.text(gramajeInterior);
}
else {
this.domItem.find(".mismoInterior").addClass('d-none');
this.domItem.find(".diferenteInterior").removeClass('d-none');
const impInterior = ("Negro " + (HQ.negro ? "Premium" : "Estándar") + " / Color " + (HQ.color ? "Premium" : "Estándar"));
this.impresionInterior.text(impInterior);
this.papelInteriorNegro.text(papelInterior.negro);
this.papelInteriorColor.text(papelInterior.color);
this.gramajeInteriorNegro.text(gramajeInterior.negro);
this.gramajeInteriorColor.text(gramajeInterior.color);
}
this.cubiertaTipo.text($($('.tipo-cubierta.selected').find('.form-label')).text());
this.carasCubierta.text(this.disenioCubierta.carasCubierta.find('option:selected').text());
if (this.cubiertaTipo.text().toLowerCase().includes('blanda')) {
this.itemsCubiertaTapaBlanda.removeClass('d-none');
this.itemsCubiertaTapaDura.addClass('d-none');
const solapasCubierta = this.disenioCubierta.getSolapasCubierta();
this.solapasCubierta.text(solapasCubierta == false ? 'No' : solapasCubierta);
}
else {
this.itemsCubiertaTapaDura.removeClass('d-none');
this.itemsCubiertaTapaBlanda.addClass('d-none');
const guardas = this.disenioCubierta.getGuardas(true);
this.papelGuardas.text(guardas.papel + ' ' + guardas.gramaje);
this.guardasImpresas.text(guardas.caras);
this.cabezada.text(this.disenioCubierta.getCabezada(true));
}
this.papelCubierta.text(this.disenioCubierta.getPapel(true));
this.gramajeCubierta.text(this.disenioCubierta.getGramaje());
this.lomoCubierta.text(this.disenioCubierta.getLomoCubierta().toFixed(0) + " mm");
this.cubiertaAcabados.text(this.disenioCubierta.getAcabados(true));
if (this.disenioCubierta.getSobrecubierta()) {
this.divSobrecubierta.removeClass('d-none');
const sobrecubierta = this.disenioCubierta.getSobrecubierta(true);
this.papelSobrecubierta.text(sobrecubierta.papel);
this.gramajeSobrecubierta.text(sobrecubierta.gramaje);
this.solapasSobrecubierta.text(sobrecubierta.solapas);
this.plastificadoSobrecubierta.text(sobrecubierta.acabado);
}
else {
this.divSobrecubierta.addClass('d-none');
}
const unidades = parseInt($($('.check-tirada-envio:checked')[0]).attr('tirada'));
const tarjetaPrecio = $('.tarjeta-tiradas-precios').filter(function () {
return parseInt($(this).find('.tarjeta-tiradas-precios-tirada').attr('data')) == unidades;
});
let envios = tarjetaPrecio.find('.tarjeta-tiradas-precios-envio').val();
this.total_envios.text(this.#changeDecimalFormat(parseFloat(envios || 0).toFixed(2)));
let precio_u_text = tarjetaPrecio.find('.tarjeta-tiradas-precios-precio-unidad').text();
precio_u_text = precio_u_text.replace('€/ud', '');
const base = tarjetaPrecio.find('.tarjeta-tiradas-precios-precio').attr('data');
let base_text = this.#changeDecimalFormat(parseFloat(base || 0).toFixed(2));
const total_antes_iva_text = this.#changeDecimalFormat((parseFloat(base || 0) + parseFloat(envios || 0)).toFixed(2));
const iva_porcentaje = parseInt(this.datosGenerales.ivaReducido.find('option:selected').val()) == 1 ? 0.04 : 0.21;
const iva = ((parseFloat(base || 0) + parseFloat(envios || 0)) * iva_porcentaje).toFixed(2);
let iva_text = this.#changeDecimalFormat(iva);
const total = (parseFloat(base || 0) + parseFloat(envios || 0) + parseFloat(iva || 0)).toFixed(2);
let total_text = this.#changeDecimalFormat(total);
this.precio_unidad.text(precio_u_text);
this.total_base.text(base_text);
this.total_antes_iva.text(total_antes_iva_text);
this.iva_porcentaje.text(this.datosGenerales.ivaReducido.find('option:selected').val() == 1 ? '4' : '21');
this.iva.text(iva_text);
this.total.text(total_text);
}
generate_total(base, precio_u, total_envio, iva_reducido) {
let precio_u_text = String(precio_u);
precio_u_text = precio_u_text.replace('€/u', '');
precio_u_text = this.#changeDecimalFormat(precio_u_text);
let base_text = this.#changeDecimalFormat(String(base));
let envios_text = this.#changeDecimalFormat(total_envio.toFixed(2));
let total_antes_iva = parseFloat(base) + parseFloat(total_envio);
let total_antes_iva_text = this.#changeDecimalFormat(total_antes_iva.toFixed(2));
const iva_porcentaje = !iva_reducido ? 0.21 : 0.04;
const iva = ((parseFloat(base) + parseFloat(total_envio)) * iva_porcentaje).toFixed(2);
let iva_text = this.#changeDecimalFormat(iva);
const total = (parseFloat(base) + parseFloat(total_envio) + parseFloat(iva)).toFixed(2);
let total_text = this.#changeDecimalFormat(total);
this.precio_unidad.text(precio_u_text);
this.total_base.text(base_text);
this.total_envios.text(envios_text);
this.total_antes_iva.text(total_antes_iva_text);
this.iva_porcentaje.text(!iva_reducido ? '21' : '4');
this.iva.text(iva_text);
this.total.text(total_text);
}
#changeDecimalFormat(number) {
let cleanedNumber = String(number).replace(/[^\d.]/g, '');
let partes = cleanedNumber.split('.');
partes[0] = partes[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.');
return partes.join(',');
}
downloadPreviewImage() {
$(document).on("click", ".download-shape", (event) => {
let parentDiv = $(event.currentTarget).parent().parent();
let shapeSvgElQuery = $(parentDiv).find("svg");
let shapeSvgEl = shapeSvgElQuery[0];
const filename = shapeSvgElQuery.parent().attr("id") ?? "image"
const serializer = new XMLSerializer();
const svgData = serializer.serializeToString(shapeSvgEl);
const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
const svgUrl = URL.createObjectURL(svgBlob);
const img = new Image(shapeSvgEl.getBoundingClientRect().width, shapeSvgEl.getBoundingClientRect().height);
img.onload = () => {
const scaleFactor = 3; // Increase resolution (e.g., 2x, 3x)
const canvas = document.createElement('canvas');
// Scale canvas for high resolution
const width = img.naturalWidth || img.width;
const height = img.naturalHeight || img.height;
canvas.width = width * scaleFactor;
canvas.height = height * scaleFactor;
const ctx = canvas.getContext('2d');
ctx.scale(scaleFactor, scaleFactor);
ctx.drawImage(img, 0, 0, width, height);
const pngUrl = canvas.toDataURL('image/png');
const downloadLink = document.createElement('a');
downloadLink.href = pngUrl;
downloadLink.download = filename ?? '.png';
document.body.appendChild(downloadLink);
downloadLink.click();
URL.revokeObjectURL(svgUrl);
};
img.src = svgUrl;
})
}
}
export default Resumen;