Files
safekat/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js

774 lines
25 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.rl_interior = $(".rl-interior");
this.rl_cubierta = $(".rl-cubierta");
this.rl_sobrecubierta = $(".rl-sobrecubierta");
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.titulosMenu = $(".titulos-menu");
this.datos = {};
this.ajax_calcular = new Ajax('/presupuestocliente/calcular',
{}, this.datos,
this.#procesarPresupuesto.bind(this),
() => { $('#loader').modal('hide'); });
this.actualizarTiradasEnvio = false;
this.calcularPresupuesto = false;
if(!window.location.href.includes("edit")) {
this.#processResumenLateral();
}
}
init() {
// 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();
if (window.location.href.includes("edit")) {
this.resumen.init(window.location.href.split("/").pop());
}
else {
this.resumen.init();
}
if (this.datosGenerales.excluirRotativa.length == 0) {
this.direcciones.direccionesCliente.setParams({ 'cliente_id': $("#clienteId").val() })
}
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.btnConfirm.on('click', this.#confirmPresupuesto.bind(this));
this.titulosMenu.on('click', this.#handleTitulosMenu.bind(this));
if (window.location.href.includes("edit")) {
setTimeout(() => {
this.#cargarPresupuesto();
}, 0);
const successMessage = sessionStorage.getItem('message');
if (successMessage) {
popSuccessAlert(successMessage);
sessionStorage.removeItem('message');
}
}
else {
this.calcularPresupuesto = true;
}
$(".calcular-presupuesto").on('change', this.checkForm.bind(this));
}
#processResumenLateral() {
this.datosGenerales.processMenuLateral();
this.disenioInterior.processMenuLateral();
this.disenioCubierta.processMenuLateral();
}
#checkTiradas() {
let tiradas = [parseInt(this.datosGenerales.tirada1.val())];
if (this.datosGenerales.tirada2.val().length > 0 &&
Number.isInteger(parseInt(this.datosGenerales.tirada2.val())) &&
parseInt(this.datosGenerales.tirada2.val()) > 0 &&
this.datosGenerales.tirada2.val() != "") {
tiradas.push(parseInt(this.datosGenerales.tirada2.val()));
}
if (this.datosGenerales.tirada3.val().length > 0 &&
Number.isInteger(parseInt(this.datosGenerales.tirada3.val())) &&
parseInt(this.datosGenerales.tirada3.val()) > 0 &&
this.datosGenerales.tirada3.val() != "") {
tiradas.push(parseInt(this.datosGenerales.tirada3.val()));
}
if (this.datosGenerales.tirada4.val().length > 0 &&
Number.isInteger(parseInt(this.datosGenerales.tirada4.val())) &&
parseInt(this.datosGenerales.tirada4.val()) > 0 &&
this.datosGenerales.tirada4.val() != "") {
tiradas.push(parseInt(this.datosGenerales.tirada4.val()));
}
const noPOD = (tiradas.some(tirada => parseInt(tirada) > 30));
const siPOD = (tiradas.some(tirada => parseInt(tirada) <= 30));
this.datosGenerales.formValidation.validateField('tirada');
return !(noPOD && siPOD);
}
checkForm(event) {
this.#processResumenLateral();
if (!this.#checkTiradas()) {
return;
}
if (this.calcularPresupuesto) {
if (event.target.id === 'divDirecciones') {
this.actualizarTiradasEnvio = false;
if (!this.direcciones.calcularPresupuesto) {
$('#loader').modal('hide');
return;
}
}
else {
this.actualizarTiradasEnvio = true;
this.direcciones.divTiradas.empty();
}
this.divTiradasPrecios.empty();
let datos_to_check = this.#prepareData();
if (Object.values(datos_to_check).every(this.#isValidDataForm)) {
try {
setTimeout(function () {
$('#loader').modal('show');
}, 0);
// 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');
}
}
}
}
#handleTitulosMenu(event) {
$('.titulos-menu').removeClass('crossed');
const nextElement = $(event.target).attr('data-target')
const currentElement = $('.dstepper-block.active').attr('id');
if (currentElement === nextElement) {
return;
}
if (nextElement === 'resumen-libro') {
$(".rl-item").addClass('d-none');
}
if (currentElement !== 'resumen-libro') {
this.#validateCurrentForm(currentElement, nextElement);
}
else {
this.#goToForm(nextElement);
}
if(!nextElement.includes('resumen-libro'))
this.#processResumenLateral();
else{
$(".rl-item").addClass('d-none');
}
}
#goToForm(form) {
switch (form) {
case '#datos-generales':
this.validationStepper.to(1);
break;
case '#interior-libro':
this.validationStepper.to(2);
break;
case '#cubierta-libro':
this.validationStepper.to(3);
break;
case '#direcciones-libro':
this.validationStepper.to(4);
break;
case '#resumen-libro':
this.validationStepper.to(5);
break;
default:
break;
}
}
#validateCurrentForm(form, nextForm) {
switch (form) {
case 'datos-generales':
this.datosGenerales.allowNext = false;
validateForm(this.datosGenerales.formValidation).then((status) => {
if (status !== 'Valid') {
this.datosGenerales.allowNext = true;
return false;
}
this.#goToForm(nextForm);
this.datosGenerales.allowNext = true;
return true;
}).catch(error => {
this.datosGenerales.allowNext = true;
console.error('Error al validar:', error);
return false;
});
break;
case 'interior-libro':
this.disenioInterior.allowNext = false;
validateForm(this.disenioInterior.formValidation).then((status) => {
if (status !== 'Valid') {
this.disenioInterior.allowNext = true;
return false;
}
this.#goToForm(nextForm);
this.disenioInterior.allowNext = true;
return true;
}
).catch(error => {
this.disenioInterior.allowNext = true;
console.error('Error al validar:', error);
return false;
});
break;
case 'cubierta-libro':
this.disenioCubierta.allowNext = false;
validateForm(this.disenioCubierta.formValidation).then((status) => {
if (status !== 'Valid') {
this.disenioCubierta.allowNext = true;
return false;
}
this.#goToForm(nextForm);
this.disenioCubierta.allowNext = true;
return true;
}
).catch(error => {
this.disenioCubierta.allowNext = true;
console.error('Error al validar:', error);
return false;
});
break;
case 'direcciones-libro':
this.direcciones.allowNext = false;
validateForm(this.direcciones.formValidation).then((status) => {
if (status !== 'Valid') {
this.direcciones.allowNext = true;
return false;
}
this.#goToForm(nextForm);
this.direcciones.allowNext = true;
return true;
}
).catch(error => {
this.direcciones.allowNext = true;
console.error('Error al validar:', error);
return false;
});
break;
default:
return false;
}
}
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.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.btnConfirm.addClass('d-none');
break;
case 'resumen-libro':
this.btnPrev.removeClass('d-none');
this.btnNext.addClass('d-none');
this.btnPrint.removeClass('d-none');
this.btnConfirm.removeClass('d-none');
this.resumen.generate();
break;
default:
break;
}
}
#confirmPresupuesto() {
let total_unidades = 0;
this.direcciones.direcciones.forEach(element => {
total_unidades += parseInt(element.tirada.val());
});
if(total_unidades != parseInt(this.direcciones.getSelectedTirada())){
popErrorAlert("No se puede confirmar el presupuesto. La suma de las unidades enviadas no coincide con la tirada seleccionada.");
return;
}
this.#solicitudGuardarPresupuesto(true);
}
#savePresupuesto() {
this.#solicitudGuardarPresupuesto(false);
}
#solicitudGuardarPresupuesto(confirmar = false) {
try {
$('#loader').modal('show');
this.#getDatos();
let datos_to_check = this.#prepareData();
if (!Object.values(datos_to_check).every(this.#isValidDataForm)) {
popErrorAlert("Por favor, rellene todos los datos del presupuesto antes de guardar.");
$('#loader').modal('hide');
return;
}
this.#getDatos(true);
if (confirmar) {
this.datos["confirmar"] = 1;
}
if (window.location.href.includes("edit")) {
this.datos["id"] = window.location.href.split("/").pop();
}
new Ajax('/presupuestocliente/guardar',
this.datos,
{},
(response) => {
$('#loader').modal('hide');
if (this.datos["confirmar"] || window.location.href.includes("add")) {
if (response.status) {
sessionStorage.setItem('message', response.message);
window.location.href = response.url + '/' + response.status;
}
else {
popErrorAlert("Presupuesto no válido, corrija los errores antes de guardar.");
}
}
else {
if (response.error) {
popErrorAlert("Presupuesto no válido, corrija los errores antes de guardar.");
}
else
popSuccessAlert(response.message);
}
},
() => { $('#loader').modal('hide'); }
).post();
}
catch (e) {
console.log(e);
$('#loader').modal('hide');
}
}
#procesarPresupuesto(response) {
$('#loader').modal('hide');
if (response === null || response === undefined || response === "") {
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;
}
if (Object.values(response.errors).some((value) => value !== "")) {
if (response.errors.status == 1) {
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;
}
}
popAlert2Hide();
if (response.tiradas && response.tiradas.length) {
let tiradas = { ...response.tiradas };
tiradas = Object.keys(tiradas).map((key) => tiradas[key]);
tiradas.sort((a, b) => a - b);
this.divTiradasPrecios.empty();
for (let i = 0; i < tiradas.length; i++) {
new tarjetaTiradasPrecio(
this.divTiradasPrecios,
('precio-tiradas-' + response.tiradas[i]),
tiradas[i],
(parseFloat(response.precio_u[i]) * parseInt(tiradas[i])).toFixed(2),
response.precio_u[i]
);
if (this.actualizarTiradasEnvio){
this.direcciones.insertTirada(tiradas[i]);
}
}
this.lc.val(parseFloat(response.info.lomo_cubierta).toFixed(2));
this.lsc.val(parseFloat(response.info.lomo_sobrecubierta).toFixed(2));
setTimeout(() => {
$(`#containerTiradasEnvios .tirada-envio input[tirada="${response.tiradas[0]}"]`).trigger('click');
}, 0);
}
$('#loader').modal('hide');
// 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();
}
}
#prepareData(save = false) {
this.#getDatos(save);
let datos_to_check = { ...this.datos };
if (datos_to_check.direcciones) {
delete datos_to_check.direcciones;
}
if (datos_to_check.posPaginasColor == "" || datos_to_check.posPaginasColor == null) {
delete datos_to_check.posPaginasColor;
}
if (datos_to_check.cubierta.acabados.barniz == undefined) {
delete datos_to_check.cubierta.acabados.barniz;
}
if (datos_to_check.cubierta.acabados.plastificado == undefined) {
delete datos_to_check.cubierta.acabados.plastificado;
}
if (datos_to_check.cubierta.acabados.estampado == undefined) {
delete datos_to_check.cubierta.acabados.estampado;
}
if (datos_to_check.sobrecubierta.plastificado == undefined) {
delete datos_to_check.sobrecubierta.plastificado;
}
return datos_to_check;
}
#getDatos(save = false) {
this.datos = {
clienteId: this.datosGenerales.getCliente(),
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'),
prototipo: this.datosGenerales.prototipo.is(':checked') ? 1 : 0,
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,
},
};
let lomoRedondo = 0;
if (this.disenioCubierta.disenioCubierta.filter('.selected').length > 0)
lomoRedondo = this.disenioCubierta.disenioCubierta.filter('.selected').attr('id').includes('Redondo') ? 1 : 0;
this.datos.cubierta.lomoRedondo = lomoRedondo;
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();
}
if (window.location.href.includes("edit")) {
this.datos["id"] = window.location.href.split("/").pop();
}
}
#cargarPresupuesto() {
$('#loader').modal('show');
let id = window.location.href.split("/").pop()
new Ajax('/presupuestocliente/cargar/' + id,
{},
{},
(response) => {
if (response.status === 1) {
this.lc.val(parseFloat(response.data.lc).toFixed(2));
this.lsc.val(parseFloat(response.data.lsc).toFixed(2));
this.calcularPresupuesto = false;
this.datosGenerales.cargarDatos(response.data.datosGenerales);
this.direcciones.handleChangeCliente();
this.disenioInterior.cargarDatos(response.data.interior, response.data.datosGenerales.papelInteriorDiferente);
this.disenioCubierta.cargarDatos(response.data.cubierta, response.data.guardas, response.data.sobrecubierta);
this.direcciones.cargarDatos(response.data.direcciones, response.data.datosGenerales);
setTimeout(() => {
$('#loader').modal('hide');
if (response.data.state != 2) {
this.calcularPresupuesto = true;
this.checkForm({ target: { id: 'tirada' } });
}
else {
$('#menu_resumen_button').trigger('click');
setTimeout(() => {
this.resumen.init_dropzone();
this.resumen.generate_total(response.data.resumen.base, response.data.resumen.precio_unidad);
}, 0);
}
}, 0);
}
},
() => {
$('#loader').modal('hide');
this.calcularPresupuesto = true;
}
).get();
}
#isValidDataForm(value) {
if (value === null || value === undefined || value === '') {
return false;
}
if (typeof value === 'object' && value !== null) {
const isValidData = Object.values(value).every(isValid);
return isValidData;
}
return true;
}
}
async function validateForm(formValidation) {
try {
const validationResult = await formValidation.validate();
return validationResult;
} catch (error) {
console.error('Error durante la validación:', error);
throw error;
}
}
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();
});