Files
safekat/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js
2024-10-19 09:36:48 +02:00

488 lines
15 KiB
JavaScript

import DatosGenerales from './datosGenerales.js';
import DisenioInterior from './disenioInterior.js';
import DisenioCubierta from './disenioCubierta.js';
import Direcciones from './direcciones.js';
import Resumen from './resumen.js';
import Ajax from '../../components/ajax.js';
import tarjetaTiradasPrecio from './tarjetaTiradasPrecio.js';
class PresupuestoCliente {
constructor() {
this.clientePresupuestoWizard = document.querySelector('#wizard-presupuesto-cliente');
this.validationStepper = new Stepper(this.clientePresupuestoWizard, {
linear: true
});
this.btnNext = $('#btnNext');
this.btnPrev = $('#btnPrev');
this.btnPrint = $('#btnPrint');
this.btnSave = $('#btnSave');
this.btnConfirm = $('#btnConfirm');
this.c = $("#c");
this.lc = $("#lc");
this.lsc = $("#lsc");
this.datosGenerales = new DatosGenerales($("#datos-generales"), this.clientePresupuestoWizard, this.validationStepper);
this.disenioInterior = new DisenioInterior($("#interior-libro"), this.clientePresupuestoWizard, this.validationStepper);
this.disenioCubierta = new DisenioCubierta($("#cubierta-libro"), this.clientePresupuestoWizard, this.validationStepper);
this.direcciones = new Direcciones($("#direcciones-libro"), this.clientePresupuestoWizard, this.validationStepper);
this.resumen = new Resumen($("#resumen-libro"), this.datosGenerales, this.disenioInterior, this.disenioCubierta, this.direcciones);
this.divTiradasPrecios = $("#divTiradasPrecio");
this.datos = {};
this.ajax_calcular = new Ajax('/presupuestocliente/calcular',
{}, this.datos,
this.#procesarPresupuesto.bind(this),
() => { $('#loader').modal('hide'); });
this.actualizarTiradasEnvio = false;
}
init() {
this.RELLENAR_PRESUPUESTO(false);
// Fuerza el foco en el campo de búsqueda de select2
$(document).on('select2:open', () => {
document.querySelector('.select2-search__field').focus();
});
this.validationStepper._element.addEventListener('shown.bs-stepper', this.stepperHandler.bind(this));
this.datosGenerales.init();
this.disenioInterior.init();
this.disenioCubierta.init();
this.direcciones.init();
this.btnNext.on('click', this.#nextStep.bind(this));
this.btnPrev.on('click', this.#prevtStep.bind(this));
this.btnSave.on('click', this.#savePresupuesto.bind(this));
//this.RELLENAR_PRESUPUESTO(true);
if (window.location.href.includes("edit")) {
$(".calcular-presupuesto").on('change', ()=>{});
this.#cargarPresupuesto();
const successMessage = sessionStorage.getItem('message');
if (successMessage) {
popSuccessAlert(successMessage);
sessionStorage.removeItem('message');
}
}
else{
$(".calcular-presupuesto").on('change', this.checkForm.bind(this));
}
}
checkForm(event) {
if (event.target.id === 'divDirecciones') {
if (!this.direcciones.calcularPresupuesto) {
this.actualizarTiradasEnvio = false;
$('#loader').modal('hide');
return;
}
}
else {
this.actualizarTiradasEnvio = true;
this.direcciones.divTiradas.empty();
}
this.#getDatos();
this.divTiradasPrecios.empty();
let datos_to_check = { ...this.datos };
if (datos_to_check.direcciones) {
delete datos_to_check.direcciones;
}
if (Object.values(datos_to_check).every(this.#isValidDataForm)) {
try {
$('#loader').modal('show');
// Si se está ejecutando la petición, abortar la petición anterior
this.ajax_calcular.abort();
this.ajax_calcular.setData(this.datos);
this.ajax_calcular.post();
this.direcciones.calcularPresupuesto = false;
}
catch (e) {
console.log(e);
$('#loader').modal('hide');
}
}
}
RELLENAR_PRESUPUESTO(finalizar) {
if (finalizar) {
$("#titulo").val("Titulo del libro");
$("#titulo").trigger('change');
const clienteId = $("#clienteId");
const newOption = new Option("Cliente Potencial", "1817", true, true);
clienteId.append(newOption).trigger('change');
const papelFormatoId = $("#papelFormatoId");
const newOption2 = new Option("148 x 210", "1", true, true);
papelFormatoId.append(newOption2).trigger('change');
$("#paginasColor").val("6");
$("#paginasColor").trigger('change');
$("#fresado").trigger("click");
$("#colorPremium").trigger("click");
$("#offsetBlanco").trigger("click");
setTimeout(function () {
$("#gramaje90").trigger("click");
}, 0);
setTimeout(function () {
$("#tapaDura").trigger("click");
}, 0);
setTimeout(function () {
$("#btnNext").trigger("click");
}, 0);
setTimeout(function () {
$("#btnNext").trigger("click");
}, 0);
setTimeout(function () {
$("#btnNext").trigger("click");
}, 0);
setTimeout(function () {
$("#unidadesEnvio").val("50");
}, 0);
}
else {
$("#titulo").trigger('change');
}
}
stepperHandler() {
const element = $('.fv-plugins-bootstrap5.fv-plugins-framework.active');
switch (element.attr('id')) {
case 'datos-generales':
this.btnPrev.addClass('d-none');
this.btnNext.removeClass('d-none');
this.btnPrint.addClass('d-none');
this.btnSave.addClass('d-none');
this.btnConfirm.addClass('d-none');
break;
case 'interior-libro':
case 'cubierta-libro':
case 'direcciones-libro':
this.btnPrev.removeClass('d-none');
this.btnNext.removeClass('d-none');
this.btnPrint.addClass('d-none');
this.btnSave.addClass('d-none');
this.btnConfirm.addClass('d-none');
break;
case 'resumen-libro':
this.btnPrev.removeClass('d-none');
this.btnNext.addClass('d-none');
this.btnPrint.removeClass('d-none');
this.btnSave.removeClass('d-none');
this.btnConfirm.removeClass('d-none');
this.resumen.generate();
break;
default:
break;
}
}
#savePresupuesto() {
this.#getDatos(true);
try {
$('#loader').modal('show');
if (window.location.href.includes("edit")) {
this.datos["id"] = window.location.href.split("/").pop();
}
new Ajax('/presupuestocliente/guardar',
this.datos,
{},
(response) => {
$('#loader').modal('hide');
console.log(response);
if (this.datos["confirmar"] || window.location.href.includes("add")) {
sessionStorage.setItem('message', response.message);
window.location.href = response.url + '/' + response.status;
}
else {
popSuccessAlert(response.message);
}
},
() => { $('#loader').modal('hide'); }
).post();
}
catch (e) {
console.log(e);
$('#loader').modal('hide');
}
}
#procesarPresupuesto(response) {
$('#loader').modal('hide');
if (Object.values(response.errors).some((value) => value !== "")) {
popErrorAlert("No se ha podido calcular el presupuesto para los datos proporcionados. Por favor, póngase en contacto con el departamento comercial."
, "sk-alert-2", false);
return;
}
else{
popAlert2Hide();
}
if (response.tiradas && response.tiradas.length) {
this.divTiradasPrecios.empty();
for (let i = 0; i < response.tiradas.length; i++) {
new tarjetaTiradasPrecio(
this.divTiradasPrecios,
('precio-tiradas-' + response.tiradas[i]),
response.tiradas[i],
(parseFloat(response.precio_u[i]) * parseInt(response.tiradas[i])).toFixed(2),
response.precio_u[i]
);
if (this.actualizarTiradasEnvio)
this.direcciones.insertTirada(response.tiradas[i]);
this.lc.val(parseFloat(response.info.lomo_cubierta).toFixed(2));
this.lsc.val(parseFloat(response.info.lomo_sobrecubierta).toFixed(2));
}
}
// DEBUG
//console.log(response);
}
#nextStep() {
switch (this.validationStepper._currentIndex) {
case 0:
this.datosGenerales.formValidation.validate();
break;
case 1:
this.disenioInterior.formValidation.validate();
break;
case 2:
this.disenioCubierta.formValidation.validate();
break;
case 3:
this.direcciones.formValidation.validate();
break;
default:
break;
}
}
#prevtStep() {
if (this.validationStepper._currentIndex >= 1 && this.validationStepper._currentIndex <= 4) {
this.validationStepper.previous();
}
}
#getDatos(save = false) {
this.datos = {
clienteId: this.datosGenerales.cliente.getVal(),
tamanio: this.datosGenerales.getDimensionLibro(),
tirada: this.datosGenerales.getTiradas(),
paginas: this.datosGenerales.paginas.val(),
paginasColor: this.datosGenerales.paginasColor.val(),
posPaginasColor: this.datosGenerales.posPaginasColor.val(),
pagColorConsecutivas: this.datosGenerales.pagColorConsecutivas.is(':checked') ? 1 : 0,
papelInteriorDiferente: this.datosGenerales.papelDiferente.is(':checked') ? 1 : 0,
paginasCuadernillo: this.datosGenerales.paginasCuadernillo.val(),
tipo: this.datosGenerales.tiposLibro.filter('.selected').attr('id'),
isColor: this.datosGenerales.getIsColor() ? 1 : 0,
isHq: this.disenioInterior.getIsHq() ? 1 : 0,
interior: {
papelInterior: this.disenioInterior.getPapel(),
gramajeInterior: this.disenioInterior.getGramaje(),
},
cubierta: {
tipoCubierta: this.disenioCubierta.disenioCubierta.filter('.selected').attr('id'),
papelCubierta: this.disenioCubierta.getPapel(),
gramajeCubierta: this.disenioCubierta.getGramaje(),
cabezada: this.disenioCubierta.getCabezada(),
acabados: this.disenioCubierta.getAcabados(),
carasImpresion: this.disenioCubierta.carasCubierta.val(),
},
guardas: this.disenioCubierta.getGuardas(),
sobrecubierta: this.disenioCubierta.getSobrecubierta(),
faja: this.disenioCubierta.getFaja(),
excluirRotativa: this.datosGenerales.excluirRotativa.is(':checked') ? 1 : 0,
ivaReducido: this.datosGenerales.ivaReducido.find('option:selected').val(),
servicios: {
'prototipo': this.datosGenerales.prototipo.is(':checked') ? 1 : 0,
},
};
if (this.datos.tipo == "cosido") {
this.datos.paginasCuadernillo = this.datosGenerales.paginasCuadernillo.val();
}
let solapasCubierta = this.disenioCubierta.getSolapasCubierta();
if (solapasCubierta !== null && solapasCubierta !== undefined) {
if (solapasCubierta === false)
this.datos.cubierta.solapas = 0;
else {
this.datos.cubierta.solapas = 1;
this.datos.cubierta.tamanioSolapas = solapasCubierta;
}
}
else {
this.datos.cubierta.solapas = 0;
}
if (this.direcciones.direcciones.length > 0) {
this.datos.direcciones = [];
for (let i = 0; i < this.direcciones.direcciones.length; i++) {
this.datos.direcciones.push(this.direcciones.direcciones[i].getFormData());
};
}
if (save) {
this.datos.datosCabecera = {
titulo: this.datosGenerales.titulo.val(),
autor: this.datosGenerales.autor.val(),
isbn: this.datosGenerales.isbn.val(),
coleccion: this.datosGenerales.coleccion.val(),
referenciaCliente: this.datosGenerales.referenciaCliente.val(),
}
this.datos.selectedTirada = this.direcciones.getSelectedTirada();
}
}
#cargarPresupuesto() {
$('#loader').modal('show');
let id = window.location.href.split("/").pop()
new Ajax('/presupuestocliente/cargar/' + id,
{},
{},
(response) => {
if (response.status === 1) {
this.datosGenerales.cargarDatos(response.data.datosGenerales);
/*this.disenioInterior.cargarDatos(response);
this.disenioCubierta.cargarDatos(response);
this.direcciones.cargarDatos(response);
*/
}
console.log(response);
$('#loader').modal('hide');
$(".calcular-presupuesto").on('change', this.checkForm.bind(this));
},
() => {
$('#loader').modal('hide');
$(".calcular-presupuesto").on('change', this.checkForm.bind(this));
}
).get();
}
#isValidDataForm(value) {
if (value === null || value === undefined || value === '') {
return false;
}
if (typeof value === 'object' && value !== null) {
return Object.values(value).every(isValid);
}
return true;
}
}
function isValid(value) {
if (value === null || value === undefined || value === '') {
return false;
}
if (typeof value === 'object' && value !== null) {
return Object.values(value).every(isValid);
}
return true;
}
function initialize(translations) {
window.translations = JSON.parse(translations);
let presupuestoCliente = new PresupuestoCliente();
presupuestoCliente.init();
}
document.addEventListener('DOMContentLoaded', function () {
const locale = document.querySelector('meta[name="locale"]').getAttribute('content');
new Ajax('/translate/getTranslation', { locale: locale, translationFile: 'Presupuestos' }, {},
initialize,
function (error) {
console.log("Error getting translations:", error);
}
).post();
});