merge from main

This commit is contained in:
amazuecos
2024-12-15 19:49:33 +01:00
65 changed files with 2009 additions and 4007 deletions

View File

@ -7,6 +7,8 @@ class Alert {
this.icon = this.item.find(".icon-alert")
this.iconSuccess = "ti-circle-check"
this.iconError = "ti-exclamation-mark"
this.iconInfo = "ti-question-mark"
@ -14,6 +16,7 @@ class Alert {
setIcon(iconClass){
this.icon.removeClass(this.iconSuccess)
this.icon.removeClass(this.iconError)
this.icon.removeClass(this.iconInfo)
this.icon.addClass(iconClass)
}
setAsError() {
@ -24,16 +27,25 @@ class Alert {
}
setAsSuccess() {
this.item.removeClass("alert-danger")
this.item.removeClass("alert-warning")
this.item.removeClass("alert-info")
this.item.addClass("alert-success")
this.setIcon(this.iconSuccess)
}
setAsWarning() {
this.item.removeClass("alert-success")
this.item.removeClass("alert-danger")
this.item.removeClass("alert-info")
this.item.addClass("alert-warning")
this.setIcon(this.iconError)
}
setAsInfo() {
this.item.removeClass("alert-*")
this.item.removeClass("alert-success")
this.item.removeClass("alert-danger")
this.item.addClass("alert-warning")
this.item.addClass("alert-info")
this.setIcon(this.iconInfo)
}
show() {
this.item.removeClass("d-none")
@ -48,6 +60,16 @@ class Alert {
this.body.append(content)
}
setErrors() { }
reset(){
this.item.removeClass("alert-success")
this.item.removeClass("alert-danger")
this.item.removeClass("alert-warning")
this.item.removeClass("alert-info")
this.item.setContent("")
this.item.setHeadingTitle("")
this.item.hide()
}
}
export default Alert;

View File

@ -7,8 +7,10 @@ class ModalYesNo {
this.btnCancelId = alias !== "" ? `btnCancelModal-${alias}` : 'btnCancelModal';
this.btnConfirmId = alias !== "" ? `btnYesModal-${alias}` : 'btnYesModal';
this.callback = () => {};
this.modalHtml = `
<div class="modal fade" id="${this.modalId}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="${this.modalId}Label" aria-hidden="true">
<div class="modal modalYesNo fade" id="${this.modalId}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="${this.modalId}Label" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
@ -30,13 +32,22 @@ class ModalYesNo {
init() {
const self = this;
// Insertar el modal en el body del documento si no existe
if (!document.getElementById(this.modalId)) {
document.body.insertAdjacentHTML('beforeend', this.modalHtml);
}
document.getElementById(this.btnCancelId).addEventListener('click', () => {
const modal = new bootstrap.Modal(document.getElementById(this.modalId));
modal.hide();
$('#' + this.btnCancelId).on('click', () => {
$('#' + self.modalId).modal('hide');
});
$('#' + this.btnConfirmId).on('click', () => {
self.callback(); // Llamar al callback que el usuario haya proporcionado
$('#' + self.modalId).modal('hide');
});
}
@ -47,21 +58,15 @@ class ModalYesNo {
// Método para mostrar el modal
show(callback) {
// Mostrar el modal usando Bootstrap
const modal = new bootstrap.Modal(document.getElementById(this.modalId));
modal.show();
this.callback = callback;
// Configurar el evento de confirmación de eliminación
document.getElementById(this.btnConfirmId).addEventListener('click', () => {
callback(); // Llamar al callback que el usuario haya proporcionado
modal.hide(); // Cerrar el modal
});
// Mostrar el modal usando Bootstrap
$('#' + this.modalId).modal('show');
}
// Método para ocultar el modal si es necesario
hide() {
const modal = new bootstrap.Modal(document.getElementById(this.modalId));
modal.hide();
$('#' + this.modalId).modal('hide');
}
}

View File

@ -0,0 +1,85 @@
import Ajax from "../ajax.js";
import Modal from "../modal.js"
import ClassSelect from "../select2.js";
import Alert from "../alerts/alert.js";
class ModalDirectMessageClient {
constructor(model="presupuesto",domItem = null) {
this.item = domItem
this.modal = new Modal(domItem)
this.alert = new Alert(this.item.find("#alertDirectMessage"))
this.modelId = this.item.data("id");
this.selectItem = this.item.find("#select-clients")
this.model = model
this.selectClientUser = new ClassSelect(this.selectItem,`/chat/direct/client/users/select/${this.model}/${this.modelId}`,"Seleccione contacto",true)
this.messageInput = this.item.find("#new-direct-message-cliente-text")
this.title = this.item.find("#new-direct-message-cliente-title")
this.btnSubmitMessage = this.item.find("#submit-new-direct-message-client")
}
init() {
this.selectClientUser.init()
this.modal.item.on("hidden.bs.modal",this.reset_close.bind(this))
this.modal.item.on("shown.bs.modal",this.reset_show.bind(this))
this.btnSubmitMessage.on("click",this._handleStoreChatDirectMessage.bind(this))
}
reset(){
this.messageInput.val("")
this.title.val("")
this.selectClientUser.reset();
}
reset_close(){
this.messageInput.val("")
this.title.val("")
this.selectClientUser.reset();
this.alert.hide()
this.alert.setHeadingTitle("")
this.alert.setContent("")
this.alert.setAsSuccess()
}
reset_show(){
this.messageInput.val("")
this.title.val("")
this.selectClientUser.reset();
this.alert.hide()
this.alert.setHeadingTitle("")
this.alert.setContent("")
this.alert.setAsSuccess()
}
_handleStoreChatDirectMessage() {
const data = { "message": this.messageInput.val(), "title": this.title.val() , "users" : this.selectClientUser.getVal() }
if (data.message) {
const ajax = new Ajax(
`/messages/direct`,
data,
null,
this._handleStoreNewDirectMessageSuccess.bind(this),
this._handleStoreNewDirectMessageError.bind(this)
)
ajax.post()
}else{
this.alert.show()
this.alert.setAsWarning()
this.alert.setHeadingTitle("Tienes que añadir un mensaje")
}
}
_handleStoreNewDirectMessageSuccess(response) {
try {
this.alert.setAsSuccess()
this.alert.setHeadingTitle(response.message)
this.alert.setContent(response.message)
this.alert.show()
} catch (error) {
} finally {
this.reset()
}
}
_handleStoreNewDirectMessageError(error){
this.alert.setHeadingTitle(error.message)
this.alert.setAsError()
this.alert.setContent(JSON.stringify(error.errors))
this.alert.show()
}
}
export default ModalDirectMessageClient

View File

@ -93,7 +93,7 @@ let Table = function (
autoWidth: true,
responsive: true,
scrollX: true,
stateSave: true,
stateSave: false,
lengthMenu: [5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500],
order: order,
orderCellsTop: true,

View File

@ -4,7 +4,7 @@ class tarjetaDireccion {
this.container = container;
this.id = id;
this.direccionId = direccion.direccionId;
this.direccionId = direccion.id;
this.card = this.#generateHTML(id, direccion);
this.deleteBtn = this.card.find('.direccion-eliminar');
this.editBtn = this.card.find('.direccion-editar');

View File

@ -1,5 +1,6 @@
import Chat from '../components/chat.js'
import InternalMessages from "../components/internalMessagesSection.js"
import ModalDirectMessageClient from '../components/modals/modalDirectMessageClient.js'
$(document).ready(() => {
let chat = new Chat($("#chat-factura"))
@ -9,5 +10,9 @@ $(document).ready(() => {
let internalMessages = new InternalMessages($("#internal_messages_chat"))
internalMessages.init()
}
let modalDirectMessageClient = new ModalDirectMessageClient("factura", $("#modalNewDirectMessageClient"))
modalDirectMessageClient.init()
$("#direct-message-cliente").on("click",() => {
modalDirectMessageClient.modal.show()
})
})

View File

@ -1,5 +1,6 @@
import Chat from '../components/chat.js'
import InternalMessages from "../components/internalMessagesSection.js"
import ModalDirectMessageClient from '../components/modals/modalDirectMessageClient.js'
$(document).ready(() => {
let chat = new Chat($("#chat-pedido"))
@ -9,5 +10,10 @@ $(document).ready(() => {
let internalMessages = new InternalMessages($("#internal_messages_chat"))
internalMessages.init()
}
let modalDirectMessageClient = new ModalDirectMessageClient("pedido", $("#modalNewDirectMessageClient"))
modalDirectMessageClient.init()
$("#direct-message-cliente").on("click",() => {
modalDirectMessageClient.modal.show()
})
})

View File

@ -1,13 +1,18 @@
import Chat from '../components/chat.js'
import InternalMessages from "../components/internalMessagesSection.js"
$(document).ready(() => {
import ModalDirectMessageClient from '../components/modals/modalDirectMessageClient.js'
$(function () {
let chat = new Chat($("#chat-presupuesto"))
chat.init()
chat.initPresupuesto()
if($("#internal_messages_chat").length > 0){
let internalMessages = new InternalMessages($("#internal_messages_chat"))
internalMessages.init()
if ($("#internal_messages_chat").length > 0) {
let internalMessages = new InternalMessages($("#internal_messages_chat"))
internalMessages.init()
let modalDirectMessageClient = new ModalDirectMessageClient("presupuesto", $("#modalNewDirectMessageClient"))
modalDirectMessageClient.init()
$("#direct-message-cliente").on("click",() => {
modalDirectMessageClient.modal.show()
})
}
})

View File

@ -1,5 +1,7 @@
import ClassSelect from '../../components/select2.js';
import tarifasClienteView from './tarifasCliente.js';
import ClienteUsuarios from './clienteUsuarios.js';
import Ajax from '../../components/ajax.js';
class Cliente {
@ -15,6 +17,8 @@ class Cliente {
this.provincia = new ClassSelect($("#provinciaId"), '/provincias/menuitems2', "Seleccione una provincia", {[this.csrf_token]: this.csrf_hash});
this.comunidadAutonoma = new ClassSelect($("#comunidadAutonomaId"), '/comunidades-autonomas/menuitems2', "Seleccione una comunidad autónoma", {[this.csrf_token]: this.csrf_hash});
this.clienteUsuarios = new ClienteUsuarios($('#usuarios'));
}
init() {
@ -32,6 +36,7 @@ class Cliente {
this.comunidadAutonoma.init();
this.tarifas.init();
this.clienteUsuarios.init();
$(document).keypress(function (e) {
var key = e.which;

View File

@ -0,0 +1,162 @@
import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import { getToken } from '../../common/common.js';
class ClienteList {
constructor() {
this.domItem = $('.card-body');
this.csrf_token = getToken();
this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();
this.tableClientes = null;
this.deleteModal = null;
}
init() {
const self = this;
this.headerSearcher();
this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente');
this.deleteModal.init();
this.#initTable();
// Editar en linea la fila
this.tableClientes.table.on('click', '.btn-edit-' + this.tableClientes.getAlias(), function (e) {
const dataId = $(this).attr('data-id');
if (!Number.isNaN(Number(dataId))) {
window.location.href = '/clientes/cliente/edit/' + dataId;
}
});
// Eliminar la fila
this.tableClientes.table.on('click', '.btn-delete-' + this.tableClientes.getAlias(), function (e) {
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
self.deleteModal.setData($(this).attr('data-id'));
self.deleteModal.show(() => {
if (!Number.isNaN(Number(self.deleteModal.getData()))) {
new Ajax(
'/clientes/cliente/delete/' + dataId,
{
},
{},
(data, textStatus, jqXHR) => {
self.tableClientes.table.clearPipeline();
self.tableClientes.table.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).get();
self.deleteModal.hide();
}
});
});
}
#initTable() {
const self = this;
const columns = [
{ 'data': 'id' },
{ 'data': 'nombre' },
{ 'data': 'alias' },
{ 'data': 'cif' },
{ 'data': 'email' },
{ 'data': 'comercial' },
{ 'data': 'forma_pago_id' },
{ 'data': 'vencimiento' },
];
const actions = ['edit', 'delete'];
this.tableClientes = new Table(
$('#tableOfClientes'),
'clienteList',
'/clientes/cliente/datatable',
columns,
[]
);
this.tableClientes.init({
actions: actions,
colVisibility: true,
buttonsExport: true,
});
this.tableClientes.table.on('init.dt', function () {
self.tableClientes.table.page.len(50).draw();
});
}
headerSearcher() {
const self = this;
$('#tableOfClientes thead tr').clone(false).appendTo('#tableOfClientes thead');
$('#tableOfClientes thead tr:eq(1) th').each(function (i) {
if (!$(this).hasClass("noFilter")) {
let min_width = 100;
if(i == 0){
min_width = 50;
}
$(this).html(`<input type="text" class="form-control " style="min-width:${min_width}px;max-width:500px;font-size:0.8rem !important;" />`);
$('input', this).on('change clear', function () {
if (self.tableClientes.table.column(i).search() !== this.value) {
self.tableClientes.table
.column(i)
.search(this.value)
.draw();
}
});
}
else {
$(this).html('<span></span>');
}
});
}
}
document.addEventListener('DOMContentLoaded', function () {
const locale = document.querySelector('meta[name="locale"]').getAttribute('content');
new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['Clientes', 'FormasPago', 'Users'] }, {},
function (translations) {
window.language = JSON.parse(translations);
new ClienteList().init();
},
function (error) {
console.log("Error getting translations:", error);
}
).post();
});

View File

@ -0,0 +1,115 @@
import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import ClassSelect from '../../components/select2.js';
class ClienteUsuarios {
constructor(domItem) {
this.domItem = domItem;
this.table = null;
this.deleteModal = null;
this.usersSelect = new ClassSelect($('#usuariosDisponibles'), '/clienteusuarios/getusers', "");
this.userAdd = this.domItem.find('#addUserToClient');
this.clienteId = window.location.href.split("/").pop();
}
init() {
const self = this;
this.#initTable();
this.usersSelect.init();
this.deleteModal = new ConfirmDeleteModal('clienteUsuarios');
this.deleteModal.init();
// Eliminar la fila
this.table.table.on('click', '.btn-delete-' + this.table.getAlias(), function (e) {
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
self.deleteModal.setData($(this).attr('data-id'));
self.deleteModal.show(() => {
if (!Number.isNaN(Number(self.deleteModal.getData()))) {
new Ajax(
'/clienteusuarios/delete/' + dataId,
{
},
{},
(data, textStatus, jqXHR) => {
self.table.table.clearPipeline();
self.table.table.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).get();
self.deleteModal.hide();
}
});
});
this.userAdd.on('click', function (e) {
e.preventDefault();
const userId = self.usersSelect.getVal();
if (userId != "") {
new Ajax(
'/clienteusuarios/adduser',
{
cliente_id: self.clienteId,
user_id: userId,
},
{},
(data, textStatus, jqXHR) => {
self.table.table.clearPipeline();
self.table.table.draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).post();
}
});
}
#initTable() {
const columns = [
{ 'data': 'id' },
{ 'data': 'nombre' },
{ 'data': 'apellidos' },
{ 'data': 'email' },
];
const actions = ['delete'];
this.table = new Table(
$('#tableOfClienteUsuarios'),
'clienteUsuarios',
'/clienteusuarios/datatable',
columns,
[{ name: 'id_cliente', value: this.clienteId },]
);
this.table.init({
actions: actions,
colVisibility: false,
buttonsExport: false,
});
}
}
export default ClienteUsuarios;

View File

@ -49,7 +49,7 @@ class tarifasClienteView {
this.#initTable();
this.selectorPlantilla.init();
this.#getPlantillaPrecios();
this.convertToTemplateBtn.on('click', function () {
@ -188,15 +188,17 @@ class tarifasClienteView {
this.editorTarifas.editor.on('postEdit', function (e, json, data, action) {
self.#borrarPlantillaTarifa(self.clienteId);
self.selectorPlantilla.offChange();
self.selectorPlantilla.empty();
self.selectorPlantilla.setOption(0, 'Personalizado');
self.selectorPlantilla.onChange(self.#changePlantilla.bind(this));
self.selectorPlantilla.onChange(self.#changePlantilla.bind(self));
})
this.editorTarifas.editor.on('postCreate', function (e, json, data, action) {
self.#borrarPlantillaTarifa(self.clienteId);
self.selectorPlantilla.offChange();
self.selectorPlantilla.empty();
self.selectorPlantilla.setOption(0, 'Personalizado');
self.selectorPlantilla.onChange(self.#changePlantilla.bind(this));
self.selectorPlantilla.onChange(self.#changePlantilla.bind(self));
})
this.editorTarifas.editor.on('postCancel', function (e, json, data) {
@ -246,7 +248,9 @@ class tarifasClienteView {
},
{},
(data) => {
this.selectorPlantilla.offChange();
if (data !== null && typeof data === 'object') {
if (data.hasOwnProperty('id') && data.id != null)
this.selectorPlantilla.setOption(data.id, data.nombre);
else {
@ -254,6 +258,7 @@ class tarifasClienteView {
}
}
else {
this.selectorPlantilla.setOption(0, 'Personalizado');
}
this.selectorPlantilla.onChange(this.#changePlantilla.bind(this));
@ -268,6 +273,7 @@ class tarifasClienteView {
#changePlantilla() {
const self = this;
const data = $('#plantillas').select2('data');
if (data.length > 0) {
if (data[0].id == 0) {
@ -280,12 +286,14 @@ class tarifasClienteView {
const id = data[0].id;
if(id == 0)
id = -1;
new Ajax(
'/clienteprecios/changeplantilla',
{
'cliente_id': self.clienteId,
'plantilla_id': id,
[this.csrf_token]: this.csrf_hash
[self.csrf_token]: self.csrf_hash
},
{},
() => {

View File

@ -0,0 +1,185 @@
import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import { getToken } from '../../common/common.js';
class MaquinasList {
constructor() {
this.domItem = $('.card-body');
this.csrf_token = getToken();
this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();
this.tableMaquinas = null;
this.deleteModal = null;
}
init() {
const self = this;
this.headerSearcher();
this.deleteModal = new ConfirmDeleteModal('maquinas');
this.deleteModal.init();
this.#initTable();
// Editar en linea la fila
this.tableMaquinas.table.on('click', '.btn-edit-' + this.tableMaquinas.getAlias(), function (e) {
const dataId = $(this).attr('data-id');
if (!Number.isNaN(Number(dataId))) {
window.location.href = '/maquinas/edit/' + dataId;
}
});
// Eliminar la fila
this.tableMaquinas.table.on('click', '.btn-delete-' + this.tableMaquinas.getAlias(), function (e) {
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
self.deleteModal.setData($(this).attr('data-id'));
self.deleteModal.show(() => {
if (!Number.isNaN(Number(self.deleteModal.getData()))) {
new Ajax(
'/maquinas/delete/' + dataId,
{
},
{},
(data, textStatus, jqXHR) => {
self.tableMaquinas.table.clearPipeline();
self.tableMaquinas.table.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).get();
self.deleteModal.hide();
}
});
});
}
#initTable() {
const self = this;
const columns = [
{ 'data': 'id' },
{ 'data': 'nombre' },
{ 'data': 'tipo' },
{ 'data': 'ancho_impresion' },
{ 'data': 'alto_impresion' },
{ 'data': 'min' },
{ 'data': 'max' }
];
const actions = ['edit', 'delete'];
this.tableMaquinas = new Table(
$('#tableOfMaquinas'),
'maquinasList',
'/maquinas/datatable',
columns,
[]
);
this.tableMaquinas.init({
actions: actions,
colVisibility: false,
buttonsExport: true,
});
this.tableMaquinas.table.on('init.dt', function () {
self.tableMaquinas.table.page.len(50).draw();
});
}
headerSearcher() {
const self = this;
$('#tableOfMaquinas thead tr').clone(false).appendTo('#tableOfMaquinas thead');
$('#tableOfMaquinas thead tr:eq(1) th').each(function (i) {
if (!$(this).hasClass("noFilter")) {
let min_width = 100;
if (i == 0) {
min_width = 50;
}
if (i == 2) {
// Agregar un selector en la segunda columna
$(this).html('<select class="form-control" style="min-width:100px;max-width:120px;font-size:0.8rem !important;"></select>');
// Agregar opciones al selector
var selector = $('select', this);
selector.append('<option value="">Todos</option>'); // Opción vacía
selector.append('<option value="acabado">Acabado</option>');
selector.append('<option value="manipulado">Manupulado</option>');
selector.append('<option value="impresion">Impresión</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tableMaquinas.table.column(i).search(val).draw();
});
}
else {
$(this).html(`<input type="text" class="form-control " style="min-width:${min_width}px;max-width:500px;font-size:0.8rem !important;" />`);
$('input', this).on('change clear', function () {
if (self.tableMaquinas.table.column(i).search() !== this.value) {
self.tableMaquinas.table
.column(i)
.search(this.value)
.draw();
}
});
}
}
else {
$(this).html('<span></span>');
}
});
}
}
document.addEventListener('DOMContentLoaded', function () {
const locale = document.querySelector('meta[name="locale"]').getAttribute('content');
new Ajax('/translate/getTranslation', { locale: locale, translationFile: ['Maquinas'] }, {},
function (translations) {
window.language = JSON.parse(translations);
new MaquinasList().init();
},
function (error) {
console.log("Error getting translations:", error);
}
).post();
});

View File

@ -23,6 +23,11 @@ class PlantillasTarifasClienteForm {
this.localEditor = null;
this.ajaxEditor = null;
this.rows = [];
this.rowsDeleted = [];
this.rowsEdited = [];
this.rowsCreated = [];
}
init() {
@ -42,6 +47,20 @@ class PlantillasTarifasClienteForm {
this.#initTable();
new Ajax(
'/clienteplantillaprecioslineas/getrows',
{
[this.csrf_token]: this.csrf_hash,
plantilla_id: this.plantillaId
},
{},
(response) => {
self.rows = response.data;
},
(error) => {
console.log(error);
}
).post();
// Editar en linea la fila
this.tablePlantilla.table.on('click', 'tbody span.edit', function (e) {
@ -62,10 +81,38 @@ class PlantillasTarifasClienteForm {
);
});
this.tablePlantilla.table.on('draw.dt', function (e) {
self.tablePlantilla.table.rows().every(function (rowIdx, tableLoop, rowLoop) {
var row = this.data();
if (self.rowsDeleted.includes(row.id)) {
$('#' + row.id).css('background-color', '#ffcccc');
$('#' + row.id).addClass('row-deleted');
$('#' + row.id).find('span.edit').addClass('d-none');
$('#' + row.id).find('.btn-delete-' + self.tablePlantilla.getAlias()).addClass('d-none');
}
else if (self.rowsEdited.includes(row.id)) {
$('#' + row.id).css('background-color', '#E9DEAC');
$('#' + row.id).addClass('row-edited');
}
else if (row.id === '') {
self.tablePlantilla.table.row(rowIdx).nodes().to$().addClass('row-created');
self.tablePlantilla.table.row(rowIdx).nodes().to$().css('background-color', '#C9E2C7');
}
});
});
this.tablePlantilla.table.on('click', '.btn-delete-' + this.tablePlantilla.getAlias(), function (e) {
self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = false;
if ($(this).closest('tr').hasClass('row-created')) {
$(this).closest('tr').remove();
}
const row = $(this).attr('data-id');
self.btnApply.removeClass('d-none');
self.btnUndo.removeClass('d-none');
@ -76,6 +123,9 @@ class PlantillasTarifasClienteForm {
// find closest span.edit
$('#' + row).find('span.edit').addClass('d-none');
$('#' + row).find('.btn-delete-' + self.tablePlantilla.getAlias()).addClass('d-none');
if (self.rowsDeleted.indexOf(row) == -1)
self.rowsDeleted.push(row);
});
this.btnApply.on('click', function (e) {
@ -121,7 +171,7 @@ class PlantillasTarifasClienteForm {
{
name: "id",
type: "readonly",
def: new Date().toISOString().slice(0, 19).replace('T', ' ')
def: ''
}, {
name: "tipo",
type: "select",
@ -192,6 +242,10 @@ class PlantillasTarifasClienteForm {
const row = self.tablePlantilla.table.row('#' + json.data[0].id);
if (row.length) {
self.rowsCreated.push(row);
}
let rowNode = row.node();
$(rowNode).addClass('row-created');
@ -209,6 +263,9 @@ class PlantillasTarifasClienteForm {
let rowNode = row.node();
// Añadir una clase usando jQuery
if (!$(rowNode).hasClass('row-created')) {
$(rowNode).addClass('row-edited');
@ -234,6 +291,15 @@ class PlantillasTarifasClienteForm {
self.btnApply.removeClass('d-none');
self.btnUndo.removeClass('d-none');
// modificar la fila en rows que tenga el mismo id
let index = self.rows.findIndex(r => r.id == data.id);
if (index != -1) {
self.rows[index] = data;
}
if (self.rowsEdited.indexOf(row.id) == -1)
self.rowsEdited.push(row.id);
}
});
@ -251,12 +317,8 @@ class PlantillasTarifasClienteForm {
const self = this;
const deletedRows = self.tablePlantilla.table.rows('.row-deleted').data().toArray();
const editedRows = self.tablePlantilla.table.rows('.row-edited').data().toArray();
const createdRows = self.tablePlantilla.table.rows('.row-created').data().toArray();
if (editedRows.length != 0) {
let error = self.#checkInterval(editedRows);
if (this.rowsEdited.length != 0) {
let error = self.#checkInterval(self.rowsEdited);
if (error) {
if (error == 1) {
popErrorAlert('Hay filas EDITADAS con el tiempo mínimo mayor que el tiempo máximo');
@ -268,8 +330,8 @@ class PlantillasTarifasClienteForm {
}
}
if (createdRows.length != 0) {
let error = self.#checkInterval(editedRows);
if (this.rowsCreated.length != 0) {
let error = self.#checkInterval(self.rowsCreated.map(row => row.data()));
if (error) {
if (error == 1) {
popErrorAlert('Hay filas CREADAS con el tiempo mínimo mayor que el tiempo máximo');
@ -281,9 +343,9 @@ class PlantillasTarifasClienteForm {
}
}
if (deletedRows.length != 0) {
if (this.rowsDeleted.length != 0) {
let rowIds = deletedRows.map(row => '#' + row.id);
let rowIds = self.rowsDeleted.map(row => '#' + row);
// Iterar sobre cada fila y actualizar los campos necesarios
self.ajaxEditor.editor
@ -297,13 +359,15 @@ class PlantillasTarifasClienteForm {
if (editedRows.length != 0) {
if (this.rowsEdited.length != 0) {
let rowIds = editedRows.map(row => '#' + row.id);
let rowIds = this.rowsEdited.map(row => '#' + this.tablePlantilla.table.row(row).data().id);
let updatedFields = {};
// Iterar sobre las filas editadas y construir el objeto actualizado
editedRows.forEach(row => {
this.rowsEdited.forEach(row2Edit => {
const row = this.tablePlantilla.table.row(row2Edit).data();
updatedFields['tipo'] = updatedFields['tipo'] || {};
updatedFields['tipo'][row.id] = row.tipo;
@ -332,13 +396,13 @@ class PlantillasTarifasClienteForm {
}
if (createdRows.length != 0) {
if (this.rowsCreated.length != 0) {
let updatedFields = {};
let count = 0;
// Iterar sobre las filas editadas y construir el objeto actualizado
createdRows.forEach(row => {
this.rowsCreated.forEach(row => {
updatedFields['id'] = updatedFields['id'] || {};
updatedFields['id'][row.id] = count;
@ -370,48 +434,68 @@ class PlantillasTarifasClienteForm {
count++;
});
self.ajaxEditor.editor.create(createdRows.length, false).multiSet(updatedFields)
self.ajaxEditor.editor.create(self.rowsCreated.length, false).multiSet(updatedFields)
.submit()
}
if (deletedRows.length != 0 || editedRows.length != 0 || createdRows.length != 0) {
new Ajax(
'/clienteprecios/update',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
).post();
new Ajax(
'/clienteprecios/update',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
() => {
self.tablePlantilla.table.settings()[0].oFeatures.bServerSide = true;
}
new Ajax(
'/clienteplantillaprecioslineas/getrows',
{
[self.csrf_token]: self.csrf_hash,
plantilla_id: self.plantillaId
},
{},
(response) => {
self.rows = response.data;
self.rowsDeleted = [];
self.rowsEdited = [];
self.rowsCreated = [];
self.tablePlantilla.table.clearPipeline();
self.tablePlantilla.table.draw(true);
},
(error) => {
console.log(error);
}).post();
},
(error) => {
console.log(error);
}
).post();
}
#checkInterval(rows) {
// obtener todas las filas de la tabla que no tengan la clase row-deleted
let rowsNotDeletedDT = this.tablePlantilla.table.rows(':not(.row-deleted)').nodes().toArray();
for (let row of rowsNotDeletedDT) {
let rowData = this.tablePlantilla.table.row(row).data();
for (let rowEdited of rows) {
if (rowEdited.tiempo_min > rowEdited.tiempo_max) {
for (let row of this.rows) {
let rowData = this.tablePlantilla.table.row(row).data();
for (let row2Check of rows) {
let checkRow = this.tablePlantilla.table.row(row2Check).data();
if (checkRow.tiempo_min > checkRow.tiempo_max) {
return 1;
}
if (rowData.tipo == rowEdited.tipo && rowData.tipo_maquina == rowEdited.tipo_maquina && rowData.tipo_impresion == rowEdited.tipo_impresion) {
if (checkRow.id == rowData.id) continue;
if (rowData.tipo == checkRow.tipo && rowData.tipo_maquina == checkRow.tipo_maquina && rowData.tipo_impresion == checkRow.tipo_impresion) {
// check overlapping intervals
if (rowEdited.tiempo_min >= rowData.tiempo_min || rowEdited.tiempo_min <= rowData.tiempo_max) {
if (Math.max(checkRow.tiempo_max, rowData.tiempo_max) - Math.min(checkRow.tiempo_min, rowData.tiempo_min)
<= Math.min(checkRow.tiempo_max - checkRow.tiempo_min) + Math.min(rowData.tiempo_max - rowData.tiempo_min))
return 2;
}
}
}
}
@ -518,12 +602,38 @@ class PlantillasTarifasClienteForm {
selector.append('<option value="sobrecubierta">Sobrecubierta</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
var val = $(this).val(); // El valor seleccionado
var searchVal = "";
// Determinar el texto renderizado que debe buscarse
if (val === "interior") {
searchVal = window.language.ClientePrecios.interior;
} else if (val === "cubierta") {
searchVal = window.language.ClientePrecios.cubierta;
} else if (val === "sobrecubierta") {
searchVal = window.language.ClientePrecios.sobrecubierta;
}
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
// Aplicar el filtro sobre los valores renderizados
self.tablePlantilla.table.column(i).search(searchVal ? '^' + searchVal + '$' : '', true, false).draw();
}
else {
// Aplicar el filtro sobre los valores renderizados
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
}
});
}
else if (i == 2) {
@ -537,10 +647,35 @@ class PlantillasTarifasClienteForm {
selector.append('<option value="inkjet">Inkjet</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
var val = $(this).val(); // El valor seleccionado
var searchVal = "";
// Determinar el texto renderizado que debe buscarse
if (val === "toner") {
searchVal = window.language.ClientePrecios.toner;
} else if (val === "inkjet") {
searchVal = window.language.ClientePrecios.inkjet;
}
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
// Aplicar el filtro sobre los valores renderizados
self.tablePlantilla.table.column(i).search(val).draw();
}
else {
// Aplicar el filtro sobre los valores renderizados
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
}
});
}
@ -557,17 +692,52 @@ class PlantillasTarifasClienteForm {
selector.append('<option value="colorhq">' + window.language.ClientePrecios.colorhq + '</option>');
selector.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
var val = $(this).val(); // El valor seleccionado
var searchVal = "";
// Determinar el texto renderizado que debe buscarse
if (val === "negro") {
searchVal = window.language.ClientePrecios.negro;
} else if (val === "negrohq") {
searchVal = window.language.ClientePrecios.negrohq;
} else if (val === "color") {
searchVal = window.language.ClientePrecios.color;
} else if (val === "colorhq") {
searchVal = window.language.ClientePrecios.colorhq;
}
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
self.tablePlantilla.table.column(i).search(searchVal ? '^' + searchVal + '$' : '', true, false).draw();
}
else {
// Aplicar el filtro sobre los valores renderizados
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
self.tablePlantilla.table.column(i).search(val).draw();
}
});
}
else {
$(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:120px;font-size:0.8rem !important;" />');
$('input', this).on('change clear', function () {
if (self.tablePlantilla.table.column(i).search() !== this.value) {
if (!self.tablePlantilla.table.settings()[0].oFeatures.bServerSide) {
const allRows = [...self.rows, ...self.rowsCreated.map(row => row.data())];
// Actualizar los datos de la tabla
self.tablePlantilla.table.clear().rows.add(allRows).draw();
}
self.tablePlantilla.table
.column(i)
.search(this.value)

View File

@ -14,6 +14,8 @@ class Direcciones {
this.validatorStepper = validatorStepper;
this.allowNext = true;
this.recogidaTaller = this.domItem.find('#recogerEnTaller');
this.unidadesAdd = this.domItem.find('#unidadesEnvio');
this.btnAdd = this.domItem.find('#insertarDireccion');
this.btnNew = this.domItem.find('#nuevaDireccion');
@ -39,6 +41,20 @@ class Direcciones {
$("#clienteId").on('change', this.handleChangeCliente.bind(this));
this.recogidaTaller.on('change', () => {
if (this.recogidaTaller.is(':checked')) {
this.divDirecciones.empty();
this.direcciones = [];
$('.div-direcciones').addClass('d-none');
}
else{
$('.div-direcciones').removeClass('d-none');
}
});
this.direccionesCliente.init();
this.btnAdd.on('click', this.#insertDireccion.bind(this));
this.btnNew.on('click', this.#nuevaDireccion.bind(this));
@ -70,44 +86,52 @@ class Direcciones {
});
}, 0);
setTimeout(function () {
$(`#containerTiradasEnvios .tirada-envio input[tirada="${datosGenerales.tirada}"]`).trigger('click');
}, 0);
if (datos.entrega_taller == 1) {
this.recogidaTaller.prop('checked', true);
}
else {
this.recogidaTaller.prop('checked', false);
setTimeout(function () {
$(`#containerTiradasEnvios .tirada-envio input[tirada="${datosGenerales.tirada}"]`).trigger('click');
}, 0);
for (let i = 0; i < datos.length; i++) {
for (let i = 0; i < datos.length; i++) {
let id = datos[i].id;
let unidades = datos[i].unidades;
let entregaPalets = datos[i].palets;
let divId = "dirEnvio-1";
let direccionesActuales = this.divDirecciones.find('.direccion-cliente');
if (direccionesActuales.length > 0) {
// the the lass item
let last = direccionesActuales[direccionesActuales.length - 1];
divId = "dirEnvio-" + (parseInt(last.id.split('-')[1]) + 1);
let id = datos[i].id;
let unidades = datos[i].unidades;
let entregaPalets = datos[i].palets;
let divId = "dirEnvio-1";
let direccionesActuales = this.divDirecciones.find('.direccion-cliente');
if (direccionesActuales.length > 0) {
// the the lass item
let last = direccionesActuales[direccionesActuales.length - 1];
divId = "dirEnvio-" + (parseInt(last.id.split('-')[1]) + 1);
}
if (id == null || id <= 0 || id == undefined)
return;
if (unidades == null || unidades <= 0 || unidades == undefined)
return;
let peticion = new Ajax('/misdirecciones/getDireccionPresupuesto/' + id, {}, {},
(response) => {
let tarjeta = new tarjetaDireccion(this.divDirecciones, divId, response.data[0]);
tarjeta.setUnidades(unidades);
tarjeta.setEntregaPalets(entregaPalets);
tarjeta.card.find('.direccion-editar').on('click', this.#editUnits.bind(self));
tarjeta.card.find('.direccion-eliminar').on('click', this.#deleteDireccion.bind(self));
this.divDirecciones.append(tarjeta.card);
this.direcciones.push(tarjeta);
},
() => {
console.error('Error getting address');
});
peticion.get();
}
if (id == null || id <= 0 || id == undefined)
return;
if (unidades == null || unidades <= 0 || unidades == undefined)
return;
let peticion = new Ajax('/misdirecciones/getDireccionPresupuesto/' + id, {}, {},
(response) => {
let tarjeta = new tarjetaDireccion(this.divDirecciones, divId, response.data[0]);
tarjeta.setUnidades(unidades);
tarjeta.setEntregaPalets(entregaPalets);
tarjeta.card.find('.direccion-editar').on('click', this.#editUnits.bind(self));
tarjeta.card.find('.direccion-eliminar').on('click', this.#deleteDireccion.bind(self));
this.divDirecciones.append(tarjeta.card);
this.direcciones.push(tarjeta);
},
() => {
console.error('Error getting address');
});
peticion.get();
}
} catch (e) {
console.error(e);

View File

@ -62,15 +62,13 @@ class DisenioCubierta {
this.divPapelCubierta = this.domItem.find("#divPapelCubierta");
this.divGramajeCubierta = this.domItem.find("#divGramajeCubierta");
this.cubiertaPlastificado = this.domItem.find("#plastificado");
this.cubiertaBarniz = this.domItem.find("#barniz");
this.cubiertaEstampado = this.domItem.find("#estampado");
this.acabadoCubierta = this.domItem.find("#acabadoCubierta");
this.cubiertaRetractilado = this.domItem.find("#retractilado");
this.configuracionSobrecubierta = this.domItem.find(".config-sobrecubierta");
this.sobrecubierta = this.domItem.find("#addSobrecubierta");
this.papelSobrecubierta = this.domItem.find("#papelSobrecubierta");
this.plastificadoSobrecubierta = this.domItem.find("#plastificadoSobrecubierta");
this.acabadoSobrecubierta = this.domItem.find("#acabadoSobrecubierta");
this.configuracionFaja = this.domItem.find(".config-faja");
this.faja = this.domItem.find("#addFaja");
@ -94,6 +92,26 @@ class DisenioCubierta {
this.rl_tamanio_sobrecubierta = $('#rl_tamanio_sobrecubierta');
this.rl_acabado_sobrecubierta = $("#rl_acabado_sobrecubierta");
this.acabadoCubierta = new ClassSelect($("#acabadoCubierta"),
'/serviciosacabados/getacabados',
'',
false,
{
[this.csrf_token]: this.csrf_hash,
"cubierta": 1
}
);
this.acabadoSobrecubierta = new ClassSelect($("#acabadoSobrecubierta"),
'/serviciosacabados/getacabados',
'',
false,
{
[this.csrf_token]: this.csrf_hash,
"sobrecubierta": 1
}
);
this.initValidation();
// Creamos un nuevo observador que detecta cambios en los atributos
@ -116,6 +134,10 @@ class DisenioCubierta {
this.gramaje = null;
this.cargando = true;
this.presupuestoConfirmado = false;
this.papelForResumen = "";
this.gramajeForResumen = "";
}
@ -124,6 +146,9 @@ class DisenioCubierta {
const self = this;
this.papelEspecial.init();
this.acabadoCubierta.init();
this.acabadoSobrecubierta.init();
$('#papelEspecialCubiertaSel').on("change", this.#handlePapelCubiertaEspecial.bind(this));
// Eventos
@ -195,9 +220,8 @@ class DisenioCubierta {
$(`#divGramajeCubierta .gramaje-cubierta input[data-value="${datosCubierta.gramaje}"]`).trigger('click');
}, 0);
this.cubiertaPlastificado.val(datosCubierta.plastificado).trigger('change');
this.cubiertaBarniz.val(datosCubierta.barniz).trigger('change');
this.cubiertaEstampado.val(datosCubierta.estampado).trigger('change');
this.acabadoCubierta.setOption(datosCubierta.acabado.id, datosCubierta.acabado.text);
if (datosCubierta.retractilado) {
setTimeout(() => {
this.cubiertaRetractilado.trigger('click');
@ -208,7 +232,7 @@ class DisenioCubierta {
this.sobrecubierta.trigger('click');
this.papelSobrecubierta.val(datosSobrecubierta.papel.code + "_" + datosSobrecubierta.gramaje).trigger('change');
this.solapasSobrecubierta.val(datosSobrecubierta.solapas_ancho);
this.plastificadoSobrecubierta.val(datosSobrecubierta.plastificado).trigger('change');
this.acabadoSobrecubierta.setOption(datosSobrecubierta.acabado.id, datosSobrecubierta.acabado.text);
}
}
@ -390,7 +414,7 @@ class DisenioCubierta {
if (papel != null && gramaje != null) {
this.rl_papel_cubierta.text(papel + " " + gramaje + " gr");
this.rl_acabado_cubierta.text(this.domItem.find("#plastificado").children("option:selected").text());
this.rl_acabado_cubierta.text("Acabado: " + this.acabadoCubierta.getText());
this.rl_papel_cubierta.removeClass('d-none');
this.rl_acabado_cubierta.removeClass('d-none');
@ -433,10 +457,7 @@ class DisenioCubierta {
const sobrecubierta = this.getSobrecubierta(true);
this.rl_papel_sobrecubierta.text(sobrecubierta.papel + " " + sobrecubierta.gramaje + " gr")
this.rl_tamanio_sobrecubierta.text("Solapas: " + sobrecubierta.solapas + " mm")
let acabado_text = sobrecubierta.plastificado;
if (acabado_text.includes("Sin plastificar"))
acabado_text = "Sin plastificar";
this.rl_acabado_sobrecubierta.text(acabado_text);
this.rl_acabado_sobrecubierta.text("Acabado: " + this.acabadoSobrecubierta.getText());
}
}
else {
@ -470,6 +491,9 @@ class DisenioCubierta {
getPapel(forResumen = false) {
try {
if (this.presupuestoConfirmado)
return this.papelForResumen;
let checkedPapel = $('.custom-selector-papel-cubierta input[type="radio"]:checked');
if (this.papelCubierta != null && checkedPapel != null && checkedPapel.length > 0) {
if (forResumen) {
@ -506,9 +530,12 @@ class DisenioCubierta {
try {
if (checkedGramaje.length == 0)
return null;
return checkedGramaje[0].id.split('_')[1];
if (this.presupuestoConfirmado)
return this.gramajeForResumen;
if (checkedGramaje.length == 0)
return null;
return checkedGramaje[0].id.split('_')[1];
} catch (e) {
return null;
}
@ -516,25 +543,14 @@ class DisenioCubierta {
getAcabados(forResumen = false) {
try {
let acabados = {};
let acabado;
if (forResumen) {
acabados = 'Plastificado ' + this.domItem.find("#plastificado").children("option:selected").text();
if (this.domItem.find("#barniz").children("option:selected").val() != 'NONE')
acabados += ", Barniz UVI " + this.domItem.find("#barniz").children("option:selected").text();
if (this.domItem.find("#estampado").children("option:selected").val() != 'NONE')
acabados += ", Estampado " + this.domItem.find("#estampado").children("option:selected").text();
if (this.domItem.find("#retractilado").hasClass('selected')) {
acabados += ", Retractilado ";
}
return acabados;
acabado = this.acabadoCubierta.getText();
}
else {
acabados.plastificado = this.domItem.find("#plastificado ").children("option:selected").val();
acabados.barniz = this.domItem.find("#barniz").children("option:selected").val();
acabados.estampado = this.domItem.find("#estampado").children("option:selected").val();
acabados.retractilado = this.domItem.find("#retractilado").hasClass('selected') ? 'RETR' : 'NONE';
acabado = this.acabadoCubierta.getVal();
}
return acabados;
return acabado;
} catch (e) {
return null;
}
@ -599,7 +615,7 @@ class DisenioCubierta {
sobrecubierta.papel = papel.split(' ')[0] + ' ' + papel.split(' ')[1];
sobrecubierta.gramaje = papel.split(' ')[2];
sobrecubierta.solapas = this.domItem.find("#solapasSobrecubierta").val();
sobrecubierta.plastificado = 'Plastificado ' + this.domItem.find("#plastificadoSobrecubierta").children("option:selected").text();
sobrecubierta.acabado = this.acabadoSobrecubierta.getText();
return sobrecubierta;
}
else {
@ -608,7 +624,7 @@ class DisenioCubierta {
sobrecubierta.papel = papel.split('_')[0];
sobrecubierta.gramaje = papel.split('_')[1];
sobrecubierta.solapas = this.domItem.find("#solapasSobrecubierta").val();
sobrecubierta.plastificado = this.domItem.find("#plastificadoSobrecubierta").children("option:selected").val();
sobrecubierta.acabado = this.acabadoSobrecubierta.getVal();
return sobrecubierta;
}
}
@ -867,20 +883,20 @@ class DisenioCubierta {
const element = $(event.target);
const papel = element[0].id.split('_')[1];
this.papelCubierta = papel;
$('#' + papel).prop('checked', true);
if (element[0].id == 'papelEspecialCubierta') {
if(!this.cargando)
if (!this.cargando)
this.gramaje = null;
this.divGramajeCubierta.empty();
this.divPapelEspecial.removeClass("d-none");
$('#papelEspecialCubiertaSel').off("change");
this.papelEspecial.empty();
$('#papelEspecialCubiertaSel').on("change", this.#handlePapelCubiertaEspecial.bind(this));
}

View File

@ -79,9 +79,13 @@ class DisenioInterior {
this.cargando = true;
this.presupuestoConfirmado = false;
this.papelNegroForResumen = "";
this.gramajeNegroForResumen = "";
this.papelColorForResumen = "";
this.gramajeColorForResumen = "";
this.initValidation();
}
@ -350,7 +354,7 @@ class DisenioInterior {
this.gramaje = datos.negro.gramaje;
}
}
if(datos.paginasColorConsecutivas)
if (datos.paginasColorConsecutivas)
this.updatePapeles();
else
this.updatePapeles('negro');
@ -666,6 +670,21 @@ class DisenioInterior {
getPapel(forResumen = false) {
try {
if (this.presupuestoConfirmado) {
if (this.papelColorForResumen.length > 0 && this.papelNegroForResumen.length > 0)
return {
negro: this.papelNegroForResumen,
color: this.papelColorForResumen
}
else if (this.papelColorForResumen.length > 0) {
return this.papelColorForResumen;
}
else {
return this.papelNegroForResumen;
}
}
let checkedPapel = $('.custom-selector-papel input[type="radio"]:checked');
if (this.papelInterior != null && checkedPapel != null && checkedPapel.length > 0) {
@ -748,6 +767,22 @@ class DisenioInterior {
getGramaje() {
try {
if (this.presupuestoConfirmado) {
if (this.gramajeColorForResumen.length > 0 && this.gramajeNegroForResumen.length > 0)
return {
negro: this.gramajeNegroForResumen,
color: this.gramajeColorForResumen
}
else if (this.gramajeColorForResumen.length > 0) {
return this.gramajeColorForResumen;
}
else {
return this.gramajeNegroForResumen;
}
}
let checkedGramaje = $('.custom-selector-gramaje input[type="radio"]:checked');
if (this.interiorColor.filter('.d-none').length == 0) {
@ -830,14 +865,14 @@ class DisenioInterior {
const element = $(event.target);
const papel = element[0].id.split('_')[1];
this.papelInterior = papel;
$('#' + papel).prop('checked', true);
let tipo = this.getTipoImpresion();
if (element[0].id == 'papelEspecialInterior') {
if(!this.cargando)
if (!this.cargando)
this.gramaje = null;
this.divGramajeInterior.empty();
this.divPapelEspecialInterior.removeClass("d-none");

View File

@ -45,7 +45,7 @@ class PresupuestoCliente {
this.datos = {};
this.ajax_calcular = new Ajax('/presupuestocliente/calcular',
this.datos,
{},
{},
this.#procesarPresupuesto.bind(this),
() => { $('#loader').modal('hide'); });
@ -71,6 +71,7 @@ class PresupuestoCliente {
this.disenioInterior.init();
this.disenioCubierta.init();
this.direcciones.init();
if (window.location.href.includes("edit")) {
this.resumen.init(window.location.href.split("/").pop());
}
@ -156,7 +157,7 @@ class PresupuestoCliente {
return !(noPOD && siPOD);
}
calcularSolapas(){
calcularSolapas() {
/* Solapas Max */
this.#getDatos(false, true);
@ -174,7 +175,7 @@ class PresupuestoCliente {
this.disenioCubierta.textoSolapasCubierta.text("Entre 60 y " + response + " mm");
this.disenioCubierta.textoSolapasSobrecubierta.text("Entre 60 y " + response + " mm");
},
() => { }
() => { }
).post();
}
}
@ -187,7 +188,7 @@ class PresupuestoCliente {
return;
}
if (this.calcularPresupuesto) {
if (event.target.id === 'divDirecciones') {
@ -414,13 +415,17 @@ class PresupuestoCliente {
#confirmPresupuesto() {
let total_unidades = 0;
this.direcciones.direcciones.forEach(element => {
total_unidades += parseInt(element.tirada.val());
});
if (!this.direcciones.recogidaTaller.is(':checked')) {
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.direcciones.direcciones.forEach(element => {
total_unidades += parseInt(element.getUnidades());
});
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);
@ -588,17 +593,11 @@ class PresupuestoCliente {
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.acabado == 0) {
delete datos_to_check.cubierta.acabado;
}
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;
if (datos_to_check.sobrecubierta.acabado == 0) {
delete datos_to_check.sobrecubierta.acabado;
}
return datos_to_check;
@ -650,7 +649,7 @@ class PresupuestoCliente {
papelCubierta: this.disenioCubierta.getPapel(),
gramajeCubierta: this.disenioCubierta.getGramaje(),
cabezada: this.disenioCubierta.getCabezada(),
acabados: this.disenioCubierta.getAcabados(),
acabado: this.disenioCubierta.getAcabados(),
carasImpresion: this.disenioCubierta.carasCubierta.val(),
};
@ -691,13 +690,16 @@ class PresupuestoCliente {
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());
};
}
this.datos.entrega_taller = this.direcciones.recogidaTaller.is(':checked') ? 1 : 0;
if (!this.direcciones.recogidaTaller.is(':checked')) {
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(),
@ -717,6 +719,8 @@ class PresupuestoCliente {
#cargarPresupuesto() {
const self = this;
$('#loader').modal('show');
let id = window.location.href.split("/").pop()
new Ajax('/presupuestocliente/cargar/' + id,
@ -726,18 +730,18 @@ class PresupuestoCliente {
if (response.status === 1) {
this.lc.val(parseFloat(response.data.lc).toFixed(2));
this.lsc.val(parseFloat(response.data.lsc).toFixed(2));
self.lc.val(parseFloat(response.data.lc).toFixed(2));
self.lsc.val(parseFloat(response.data.lsc).toFixed(2));
this.calcularPresupuesto = false;
self.calcularPresupuesto = false;
this.datosGenerales.cargarDatos(response.data.datosGenerales);
this.direcciones.handleChangeCliente();
self.datosGenerales.cargarDatos(response.data.datosGenerales);
self.direcciones.handleChangeCliente();
this.direcciones.cargarDatos(response.data.direcciones, response.data.datosGenerales);
self.direcciones.cargarDatos(response.data.direcciones, response.data.datosGenerales);
this.disenioInterior.cargarDatos(response.data.interior, response.data.datosGenerales.papelInteriorDiferente);
this.disenioCubierta.cargarDatos(response.data.cubierta, response.data.guardas, response.data.sobrecubierta);
self.disenioInterior.cargarDatos(response.data.interior, response.data.datosGenerales.papelInteriorDiferente);
self.disenioCubierta.cargarDatos(response.data.cubierta, response.data.guardas, response.data.sobrecubierta);
setTimeout(() => {
@ -746,14 +750,28 @@ class PresupuestoCliente {
if (response.data.state != 2) {
this.calcularPresupuesto = true;
this.checkForm({ target: { id: 'tirada' } });
self.calcularPresupuesto = true;
self.checkForm({ target: { id: 'tirada' } });
}
else {
self.disenioInterior.presupuestoConfirmado = true;
if (response.data.interior.negro) {
self.disenioInterior.papelNegroForResumen = response.data.interior.negro.papel.nombre;
self.disenioInterior.gramajeNegroForResumen = response.data.interior.negro.gramaje;
}
if (response.data.interior.color) {
self.disenioInterior.papelColorForResumen = response.data.interior.color.nombre;
self.disenioInterior.gramajeColorForResumen = response.data.interior.color.gramaje;
}
self.disenioCubierta.presupuestoConfirmado = true;
self.disenioCubierta.papelForResumen = response.data.cubierta.papel.nombre;
self.disenioCubierta.gramajeForResumen = response.data.cubierta.gramaje;
$('#menu_resumen_button').trigger('click');
setTimeout(() => {
this.resumen.init_dropzone();
this.resumen.generate_total(response.data.resumen.base, response.data.resumen.precio_unidad);
self.resumen.init_dropzone();
self.resumen.generate_total(response.data.resumen.base, response.data.resumen.precio_unidad);
}, 0);
}
}, 0);

View File

@ -1,4 +1,4 @@
import previewFormas from "../preview.js";
import previewFormas from "../../components/preview.js";
import { capitalizeFirstLetter } from "../../common/common.js";
class Resumen {
@ -290,7 +290,7 @@ class Resumen {
this.papelSobrecubierta.text(sobrecubierta.papel);
this.gramajeSobrecubierta.text(sobrecubierta.gramaje);
this.solapasSobrecubierta.text(sobrecubierta.solapas);
this.plastificadoSobrecubierta.text(sobrecubierta.plastificado);
this.plastificadoSobrecubierta.text(sobrecubierta.acabado);
}
else {
this.divSobrecubierta.addClass('d-none');

View File

@ -31,6 +31,9 @@ class tarjetaTiradasPrecio {
class: 'list-content'
});
const formattedPrecio = precio.toString().replace('.', ',');
const formattedPrecioUnidad = precio_unidad.toString().replace('.', ',');
$listContent.append($('<h7>', {
id: 'ud_' + id,
class: 'mb-1 tarjeta-tiradas-precios-tirada',
@ -40,13 +43,13 @@ class tarjetaTiradasPrecio {
$listContent.append($('<h6>', {
id: 'tot_' + id,
class: 'mb-1 tarjeta-tiradas-precios-precio',
text: 'Total: ' + precio + '€'
text: 'Total: ' + formattedPrecio + '€'
}).attr('data', precio));
$listContent.append($('<h7>', {
id: 'pu_' + id,
class: 'mb-1 tarjeta-tiradas-precios-precio-unidad',
text: precio_unidad + '€/ud'
text: formattedPrecioUnidad + '€/ud'
}).attr('data', precio_unidad));
$liWrapper.append($listContent);

View File

@ -0,0 +1,144 @@
import Table from '../../components/table.js';
import ConfirmDeleteModal from '../../components/ConfirmDeleteModal.js';
import Ajax from '../../components/ajax.js';
import { getToken } from '../../common/common.js';
class UserList {
constructor() {
this.domItem = $('.card-body');
this.csrf_token = getToken();
this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();
this.tableUsers = null;
this.deleteModal = null;
}
init() {
const self = this;
this.headerSearcher();
this.deleteModal = new ConfirmDeleteModal('plantillasTarifasCliente');
this.deleteModal.init();
this.#initTable();
// Editar en linea la fila
this.tableUsers.table.on('click', '.btn-edit-' + this.tableUsers.getAlias(), function (e) {
const dataId = $(this).attr('data-id');
if (!Number.isNaN(Number(dataId))) {
window.location.href = '/users/edit/' + dataId;
}
});
// Eliminar la fila
this.tableUsers.table.on('click', '.btn-delete-' + this.tableUsers.getAlias(), function (e) {
const row = $(this).closest('tr')[0]._DT_RowIndex;
const dataId = $(this).attr('data-id');
self.deleteModal.setData($(this).attr('data-id'));
self.deleteModal.show(() => {
if (!Number.isNaN(Number(self.deleteModal.getData()))) {
new Ajax(
'/users/delete/' + dataId,
{
},
{},
(data, textStatus, jqXHR) => {
self.tableUsers.table.clearPipeline();
self.tableUsers.table.row($(row)).invalidate().draw();
popSuccessAlert(data.msg ?? jqXHR.statusText);
},
(error) => {
console.log(error);
}
).get();
self.deleteModal.hide();
}
});
});
}
#initTable() {
const self = this;
const columns = [
{ 'data': 'id' },
{ 'data': 'first_name' },
{ 'data': 'last_name' },
{ 'data': 'email' },
{ 'data': 'cliente' },
{ 'data': 'last_active' },
];
const actions = ['edit', 'delete'];
this.tableUsers = new Table(
$('#tableOfUsers'),
'users',
'/users/datatable',
columns,
[]
);
this.tableUsers.init({
actions: actions,
colVisibility: false,
buttonsExport: true,
});
this.tableUsers.table.on('init.dt', function () {
self.tableUsers.table.page.len(50).draw();
});
}
headerSearcher() {
const self = this;
$('#tableOfUsers thead tr').clone(false).appendTo('#tableOfUsers thead');
$('#tableOfUsers thead tr:eq(1) th').each(function (i) {
if (!$(this).hasClass("noFilter")) {
$(this).html('<input type="text" class="form-control " style="min-width:100px;max-width:500px;font-size:0.8rem !important;" />');
$('input', this).on('change clear', function () {
if (self.tableUsers.table.column(i).search() !== this.value) {
self.tableUsers.table
.column(i)
.search(this.value)
.draw();
}
});
}
else {
$(this).html('<span></span>');
}
});
}
}
document.addEventListener('DOMContentLoaded', function () {
new UserList().init();
});