Files
safekat/httpdocs/assets/js/safekat/pages/presupuestoAdmin/sections/envios.js

678 lines
27 KiB
JavaScript

import Ajax from "../../../components/ajax.js";
import { getToken } from "../../../common/common.js";
import ClassSelect from "../../../components/select2.js";
import ModalYesNo from "../../../components/modalYesNo.js";
class Envios {
constructor() {
this.csrf_token = getToken();
this.csrf_hash = $('#mainContainer').find('input[name="' + this.csrf_token + '"]').val();
this.recogerTaller = $('#recoger_en_taller');
this.table = null;
this.direccionesClienteForm = new ClassSelect($('#add_clientedAdd'), '/misdirecciones/getSelect2', 'Seleccione una direccion', false, {});
this.paisesClienteForm = new ClassSelect($('#add_pais_id'), '/paises/menuitems2', 'Seleccione país', false, {});
this.modalYesNo = null;
this.insertarEnvio = $('#insertar_direccion');
this.actionBtns_direcciones = function (data) {
return `
<span class="edit-add"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit-add mx-2" data-id="${data.id}"></i></a></span>
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm tiradas-alternativas delete-add-row mx-2"></i></a>
`;
};
}
init() {
const self = this;
this.paisesClienteForm.init();
this.table = $('#tableOfDireccionesEnvio').DataTable({
draw: 5,
serverSide: false,
processing: true,
autoWidth: true,
responsive: true,
order: [[0, "asc"]],
pageLength: 20,
lengthChange: false,
searching: false,
paging: false,
info: false,
scrollX: true,
columns: [
{ 'data': 'tarifa_id' },
{ 'data': 'cantidad' },
{ 'data': 'peso' },
{ 'data': 'att' },
{ 'data': 'email' },
{ 'data': 'direccion' },
{ 'data': 'cp' },
{ 'data': 'municipio' },
{ 'data': 'pais' },
{ 'data': 'pais_id', visible: false },
{ 'data': 'telefono' },
{ 'data': 'proveedor' },
{ 'data': 'proveedor_id', visible: false },
{ 'data': 'precio' },
{ 'data': 'margen', render: function (data, type, row) { return Math.round(data) } },
{ 'data': 'entregaPieCalle' },
{
data: function (row, type, set, meta) {
return `
<span class="edit-add"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit-envio mx-2" data-id="${row.id}"></i></a></span>
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm tiradas-alternativas btn-delete-envio mx-2"></i></a>
`;
},
className: 'row-edit dt-center'
}
],
columnDefs: [
{
orderable: false,
searchable: false,
targets: [$('#tableOfDireccionesEnvio').find("tr:first th").length - 1]
},
{ "orderData": [0], "targets": 0 },
],
language: {
url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
},
drawCallback: function (settings) {
const boolCols = [15];
for (let coln of boolCols) {
self.table.column(coln, { page: 'current' }).nodes().each(function (cell, i) {
cell.innerHTML = cell.innerHTML == '1' ? '<i class="ti ti-check"></i>' : '';
});
}
// obtener la suma del precio de los envios
let total = 0;
self.table.rows().every(function (rowIdx, tableLoop, rowLoop) {
let data = this.data();
total += parseFloat(data.precio);
});
$("#costeEnvios").text(total.toFixed(2) + "€" || "0€");
self.check_unidades_enviadas(null, self.recogerTaller.prop('checked'));
}
});
$(document).on('click', '.btn-delete-envio', function () {
const rowId = $(this).closest('td').parent()[0].sectionRowIndex;
self.table.row(rowId).remove().draw();
});
$(document).on('click', '.btn-edit-envio', function () {
const rowId = $(this).closest('td').parent()[0].sectionRowIndex;
const data = $('#tableOfDireccionesEnvio').DataTable().row(rowId).data();
$("#addressForm").attr('action', 'edit')
$("#addressForm").attr('row', rowId)
$("#addressForm").attr('presupuestodireccion_id', data.id)
let $newAddDialog = $("#addressForm")
let maximaCantidad = parseInt($('#tirada').val())
$("#add_cantidad").attr("max", maximaCantidad);
$("#add_cantidad").val(maximaCantidad);
$("#add_cantidad").on('change', function () {
$("#add_cantidad").val(parseInt($("#add_cantidad").val()) > maximaCantidad ? maximaCantidad : $("#add_cantidad").val())
})
let cantidad_total = 0
$('#tableOfDireccionesEnvio').DataTable().rows().every(function (rowIdx, tableLoop, rowLoop) {
let data2 = this.data();
cantidad_total += parseInt(data2.cantidad)
});
cantidad_total -= parseInt(data.cantidad) // Si es editar tienes que restar los de la linea actual
$('#add_cantidad').attr('max-value', parseInt($('#tirada').val()) - cantidad_total)
$('#add_cantidad').val(parseInt($('#tirada').val()) - cantidad_total)
$('#add_att').val(data.att)
$('#add_direccion').val(data.direccion)
$('#add_email').val(data.email)
$('#add_cp').val(data.cp)
$('#add_municipio').val(data.municipio)
$('#add_provincia').val(data.provincia)
self.paisesClienteForm.setOption(data.pais_id, data.pais);
$('#add_telefono').val(data.telefono)
$('#add_cantidad').val(data.cantidad)
$('#add_entregaPieCalle').prop('checked', data.entregaPieCalle == 1 ? true : false)
self.direccionesClienteForm.setParams({ 'cliente_id': () => $("#clienteId").select2('data')[0].id });
self.direccionesClienteForm.init();
$newAddDialog.modal('show')
});
this.recogerTaller.on('change', function () {
const current_value = this.checked;
self.recogerTaller.prop('checked', false);
if (current_value) {
self.modalYesNo = new ModalYesNo("Esto borrará todas las direcciones de envío. ¿Está seguro?", "modalYesNoEnvios");
self.modalYesNo.init();
self.modalYesNo.show(() => {
self.table.clear().draw();
self.check_unidades_enviadas(null, true);
self.recogerTaller.prop('checked', true);
self.insertarEnvio.addClass('d-none');
self.modalYesNo.hide();
});
}
else {
self.insertarEnvio.removeClass('d-none');
}
});
this.insertarEnvio.on('click', this.addEnvio.bind(this));
this.initFormularioDireccionEnvio();
$(document).on('update-envios', async function () {
await self.updateTablaEnvios();
$(document).trigger('update-envios-completed');
});
$(document).on('ckeck-lineas-envios', this.check_unidades_enviadas.bind(this));
}
addEnvio() {
$("#addressForm").attr('action', 'create');
let newAddDialog = $("#addressForm");
this.direccionesClienteForm.setParams({ 'cliente_id': () => $("#clienteId").select2('data')[0].id });
this.direccionesClienteForm.init();
let maximaCantidad = parseInt($('#tirada').val());
$("#add_cantidad").attr("max", maximaCantidad);;
$("#add_cantidad").val(maximaCantidad);
$("#add_cantidad").on('change', function () {
$("#add_cantidad").val(parseInt($("#add_cantidad").val()) > maximaCantidad ? maximaCantidad : $("#add_cantidad").val());
})
let cantidad_total = 0;
$('#tableOfDireccionesEnvio').DataTable().rows().every(function (rowIdx, tableLoop, rowLoop) {
let data = this.data();
cantidad_total += parseInt(data.cantidad);
});
$('#add_cantidad').attr('max-value', parseInt($('#tirada').val()) - cantidad_total);
$('#add_cantidad').val(parseInt($('#tirada').val()) - cantidad_total);
newAddDialog.modal('show');
}
get_peso_libro() {
var peso_total_libro = 0.0
$('#tableLineasPresupuesto').DataTable().rows().every(function (rowIdx, tableLoop, rowLoop) {
var rowData = this.data();
peso_total_libro += parseFloat(rowData.peso)
})
return peso_total_libro;
}
async guardarEnvios() {
var id = window.location.pathname.split('/').pop();
await $.post('/presupuestodirecciones/datatable',
Object.assign({ tipo: "clear_lineas", presupuesto_id: id }, window.token_ajax))
.done(function (data) {
$('#tableOfDireccionesEnvio').DataTable().rows().every(async function (rowIdx, tableLoop, rowLoop) {
var data = this.data();
await $.post('/presupuestos/presupuestodirecciones/add',
{
presupuesto_id: id,
tarifa_id: data.tarifa_id,
cantidad: data.cantidad,
peso: data.peso,
att: data.att,
email: data.email,
direccion: data.direccion,
pais_id: data.pais_id,
provincia: data.provincia,
municipio: data.municipio,
cp: data.cp,
telefono: data.telefono,
precio: data.precio,
margen: data.margen,
proveedor: data.proveedor,
proveedor_id: data.proveedor_id,
entregaPieCalle: data.entregaPieCalle
})
});
})
}
async updateTiradaBase() {
const self = this;
var peso_total_libro = this.get_peso_libro();
const tirada = parseInt($('#tirada').val());
const peso_envio = peso_total_libro * tirada / 1000.0;
let pais = 1;
let cp = 18000;
let entrega = 'cajas';
var datos_tarifa = await self.get_precio_envio(peso_envio, pais, cp, entrega);
if (datos_tarifa.id != null) {
if (peso_envio > parseFloat(datos_tarifa.peso_max) || parseFloat(datos_tarifa.peso_max) == 0) {
datos_tarifa.precio = parseFloat(datos_tarifa.peso_min) + (peso_envio - parseFloat(datos_tarifa.peso_min)) * parseFloat(datos_tarifa.precio_adicional);
}
// si no se calcula linealmente
else {
let m = ((parseFloat(datos_tarifa.precio_max) - parseFloat(datos_tarifa.precio_min)) / (parseFloat(datos_tarifa.peso_max) - parseFloat(datos_tarifa.peso_min)));
let b = parseFloat(datos_tarifa.precio_max) - m * parseFloat(datos_tarifa.peso_max);
datos_tarifa.precio = parseFloat(m * peso_envio + b);
}
$('#envio_base').val(datos_tarifa.precio.toFixed(2));
}
}
async updateTablaEnvios(event, input_data = {}) {
const self = this;
var peso_total_libro = this.get_peso_libro();
await self.updateTiradaBase();
$('#tableOfDireccionesEnvio').DataTable().rows().every(async function (rowIdx, tableLoop, rowLoop) {
var rowData = this.data();
if (Object.keys(input_data).length > 0) {
const porcentaje = parseInt(rowData.cantidad) / input_data.tirada_inicial * 100.0;
const cantidad = Math.floor(input_data.tirada * porcentaje / 100.0);
rowData.cantidad = cantidad;
}
const peso_envio = peso_total_libro * parseInt(rowData.cantidad) / 1000.0;
const tirada = parseInt($('#tirada').val());
var datos_tarifa = await self.get_precio_envio(peso_envio, rowData.pais_id, rowData.cp, parseInt(rowData.entregaPieCalle) == 1 ? 'palets' : 'cajas');
if (datos_tarifa.id != null) {
if (peso_envio > parseFloat(datos_tarifa.peso_max) || parseFloat(datos_tarifa.peso_max) == 0) {
datos_tarifa.precio = parseFloat(datos_tarifa.peso_min) + (peso_envio - parseFloat(datos_tarifa.peso_min)) * parseFloat(datos_tarifa.precio_adicional);
}
// si no se calcula linealmente
else {
let m = ((parseFloat(datos_tarifa.precio_max) - parseFloat(datos_tarifa.precio_min)) / (parseFloat(datos_tarifa.peso_max) - parseFloat(datos_tarifa.peso_min)));
let b = parseFloat(datos_tarifa.precio_max) - m * parseFloat(datos_tarifa.peso_max);
datos_tarifa.precio = parseFloat(m * peso_envio + b);
}
datos_tarifa.cantidad = parseInt($('#add_cantidad').val());
datos_tarifa.peso = peso_envio;
$('#tableOfDireccionesEnvio').DataTable().row(rowIdx)
.data({
'tarifa_id': datos_tarifa.id,
'cantidad': rowData.cantidad,
'peso': datos_tarifa.peso.toFixed(3),
'att': rowData.att,
'email': rowData.email,
'direccion': rowData.direccion,
'cp': rowData.cp,
'municipio': rowData.municipio,
'provincia': rowData.provincia,
'pais_id': rowData.pais_id,
'pais': datos_tarifa.pais,
'telefono': rowData.telefono,
'proveedor': datos_tarifa.proveedor,
'proveedor_id': datos_tarifa.proveedor_id,
'precio': datos_tarifa.precio.toFixed(2),
'margen': datos_tarifa.margen,
'entregaPieCalle': rowData.entregaPieCalle,
'actionBtns_direcciones': self.actionBtns_direcciones,
})
.draw();
$(document).trigger('update-presupuesto', {
update_lineas: false,
update_servicios: false,
update_envios: false,
update_resumen: true,
update_tiradas_alternativas: true
});
}
else {
popErrorAlert(window.error_no_tarifa_envio, 'error-tarifa')
}
})
if (Object.keys(input_data).length > 0) {
$('#tirada').val(input_data.tirada);
$('#tirada').trigger('change', [false]);
}
}
async get_precio_envio(peso, paisId, cp, tipo_envio) {
let data = {
tipo: 'get_tarifa',
peso: peso,
paisId: paisId,
cp: cp,
tipo_envio: tipo_envio,
}
const response = await fetch('/presupuestodirecciones/datatable_2', {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8",
}
});
const values = await response.json();
return values.data;
}
initFormularioDireccionEnvio() {
const self = this;
this.direccionesClienteForm.item.on('select2:select', function (e) {
$('.save-alias').css('display', 'none');
$('#add_alias').val('');
$('#add_saveDirection').attr("disabled", true);
let data = e.params.data;
$.ajax({
type: "POST",
url: '/clientedirecciones/datatable',
dataType: 'json',
data: {
tipo: 'direccion',
id: data.id,
[self.csrf_token]: self.csrf_hash
},
success: function (data) {
if (data.length > 0) {
$('#add_att').val(data[0].att);
$('#add_direccion').val(data[0].direccion);
$('#add_cp').val(data[0].cp);
$('#add_municipio').val(data[0].municipio);
$('#add_provincia').val(data[0].provincia);
$('#add_telefono').val(data[0].telefono);
$('#add_email').val(data[0].email);
self.paisesClienteForm.empty();
self.paisesClienteForm.setOption(data[0].pais_id, data[0].pais);
}
return true;
},
error: function (e) {
return false;
}
})
return false;
});
$('#addressForm').on('hidden.bs.modal', function () {
$('#add_alias').val("");
$('#add_att').val("");
$('#add_email').val("");
$('#add_direccion').val("");
self.paisesClienteForm.empty();
self.direccionesClienteForm.empty();
$('#add_municipio').val("");
$('#add_provincia').val("");
$('#add_cp').val("");
$('#add_telefono').val("");
$('#add_saveDirection').prop('checked', false)
$('#add_entregaPieCalle').prop('checked', false)
});
$('#cancelAdd').on('click', function () {
$('#addressForm').modal("hide");
})
$('#add_cantidad').on('change', function () {
if (parseInt($('#add_cantidad').val()) > $('#add_cantidad').attr('max-value'))
$('#add_cantidad').val($('#add_cantidad').attr('max-value'))
})
$('#saveDireccionEnvio').on('click', function () {
if (self.validate_fields()) {
if ($('#addressForm').attr('action') == 'edit') {
self.table.row($("#addressForm").attr('row'))
.remove()
.draw();
}
let peso_total_libro = 0
$('#tableLineasPresupuesto').DataTable().rows().every(function (rowIdx, tableLoop, rowLoop) {
let rowData = this.data();
peso_total_libro += parseFloat(rowData.peso)
})
const peso_envio = peso_total_libro * parseInt($('#add_cantidad').val()) / 1000.0
$.post('/presupuestodirecciones/datatable',
{
tipo: "get_tarifa",
peso: peso_envio,
paisId: $("#add_pais_id").val(),
cp: $('#add_cp').val(),
tipo_envio: $('#add_entregaPieCalle').is(":checked") ? 'palets' : 'cajas',
[self.csrf_token]: self.csrf_hash
})
.done(function (data) {
if (data.length > 0) {
let precios = []
for (let i = 0; i < data.length; i++) {
if (peso_envio > data[i].peso_max || data[i].precio_max == 0) {
data[i].precio = (parseFloat(data[i].precio_min) + (peso_envio - parseFloat(data[i].peso_min)) * parseFloat(data[i].precio_adicional)).toFixed(2);
}
else {
let m = ((data[i].precio_max - data[i].precio_min) / (data[i].peso_max - data[i].peso_min))
let b = data[i].precio_max - m * data[i].peso_max
data[i].precio = parseFloat(m * peso_envio + b).toFixed(2);
}
data[i].margen = data[i].margen
}
let tarifa_final = data.reduce((previous, current) => {
return current.precio < previous.precio ? current : previous;
});
tarifa_final.cantidad = parseInt($('#add_cantidad').val())
tarifa_final.peso = peso_envio
self.table.row
.add({
'tarifa_id': tarifa_final.id,
'cantidad': tarifa_final.cantidad,
'peso': tarifa_final.peso.toFixed(3),
'att': $('#add_att').val(),
'email': $('#add_email').val(),
'direccion': $('#add_direccion').val(),
'cp': $('#add_cp').val(),
'municipio': $('#add_municipio').val(),
'provincia': $('#add_provincia').val(),
'pais_id': $('#add_pais_id').select2('data')[0].id,
'pais': $('#add_pais_id').select2('data')[0].text,
'telefono': $('#add_telefono').val(),
'proveedor': tarifa_final.proveedor,
'proveedor_id': tarifa_final.proveedor_id,
'precio': tarifa_final.precio,
'margen': tarifa_final.margen,
'entregaPieCalle': $('#add_entregaPieCalle').is(":checked") ? 1 : 0,
'actionBtns_direcciones': `
<span class="edit-add"><a href="javascript:void(0);"><i class="ti ti-pencil ti-sm btn-edit-envio mx-2"></i></a></span>
<a href="javascript:void(0);"><i class="ti ti-trash ti-sm tiradas-alternativas btn-delete-envio mx-2"></i></a>
`,
})
.draw();
// Se guarda la dirección
if ($('#add_saveDirection').is(":checked") &&
$('#add_alias').val().length > 0) {
$.post('/clientes/clientedirecciones/add',
{
cliente_id: $('#clienteId').val(),
'att': $('#add_att').val(),
'email': $('#add_email').val(),
'direccion': $('#add_direccion').val(),
'cp': $('#add_cp').val(),
'municipio': $('#add_municipio').val(),
'provincia': $('#add_provincia').val(),
'paisId': $('#add_pais_id').val(),
'telefono': $('#add_telefono').val(),
'alias': $('#add_alias').val(),
[self.csrf_token]: self.csrf_hash
})
.done(function (data) {
})
}
$(document).trigger('ckeck-lineas-envios');
$(document).trigger('update-presupuesto', {
update_lineas : false,
update_servicios : true,
update_envios: false,
update_resumen: true,
update_tiradas_alternativas: true
});
$('#addressForm').modal("hide");
}
else {
popErrorAlert(window.language.PresupuestosDirecciones.validation.no_tarifa, 'error-tarifa')
}
});
}
});
$('#add_saveDirection').on('change', function () {
if (this.checked) {
$('.save-alias').css('display', 'inline')
}
else {
$('.save-alias').css('display', 'none')
}
$('#add_saveDirection').val(this.checked);
});
$('.new-address').on('change', function (e) {
if (e.originalEvent) {
// user-triggered event
$('#add_clientedAdd').val(null).trigger('change');
$('#add_saveDirection').removeAttr("disabled");
}
})
}
validate_fields() {
$(".error-text-form").remove();
let returnValue = false
$("input.new-address").each(function () {
if ($('#' + this.id).val().length == 0 && $('#' + this.id).css('display') != 'none') {
$('#' + this.id).after(
"<p style='font-size: 11px !important;" +
"padding: 0 !important; " +
"color: #b11f1f !important;' " +
"class='error-text-form'>" + window.language.PresupuestosDirecciones.validation.required + '</p>')
}
returnValue = true
})
return returnValue
}
cargar(datos) {
if (datos.entrega_taller) {
this.recogerTaller.prop('checked', true);
}
else {
this.table.rows.add(datos).draw();
}
}
check_unidades_enviadas(event, recogerTaller = null) {
if(recogerTaller === null) {
recogerTaller = this.recogerTaller.prop('checked');
}
let cantidad_total = 0
this.table.rows().every(function (rowIdx, tableLoop, rowLoop) {
cantidad_total += parseInt(this.data().cantidad)
});
const tirada = parseInt($('#tirada').val());
let htmlString = '';
if (cantidad_total < tirada && recogerTaller === false) {
htmlString = `
<div class="alert alert-warning d-flex align-items-baseline" role="alert">
<span class="alert-icon alert-icon-lg text-primary me-2">
<i class="ti ti-bell ti-sm"></i>
</span>
<div class="d-flex flex-column ps-1">
<h5 class="alert-heading mb-2">` +
window.language.Presupuestos.validation.ejemplares_envio +
`</h5>
</div>
</div>`;
$('#alert-envios').html(htmlString);
this.insertarEnvio.removeClass('d-none');
return false;
}
this.insertarEnvio.addClass('d-none');
$('#alert-envios').html(htmlString);
return true;
}
}
export default Envios;