guardando direcciones ferro en presupuesto cliente

This commit is contained in:
2025-06-28 11:27:39 +02:00
parent 410d21dc5f
commit 9fcda514f0
8 changed files with 324 additions and 120 deletions

View File

@ -319,6 +319,7 @@ $routes->group('clienteusuarios', ['namespace' => 'App\Controllers\Clientes'], f
$routes->group('misdirecciones', ['namespace' => 'App\Controllers\Clientes'], function ($routes) {
$routes->get('', 'Clientedirecciones::index', ['as' => 'clientedireccionesIndex']);
$routes->get('get/(:num)', 'Clientedirecciones::get/$1', ['as' => 'get']);
$routes->get('getId', 'Clientedirecciones::getDireccionIdFromData');
$routes->get('getDireccionPresupuesto/(:num)', 'Clientedirecciones::getDireccionPresupuesto/$1', ['as' => 'getDireccionPresupuesto']);
$routes->post('add', 'Clientedirecciones::add', ['as' => 'newClientedirecciones']);
$routes->get('getSelect2', 'Clientedirecciones::getSelect2', ['as' => 'listaClientedirecciones']);

View File

@ -215,13 +215,13 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
{
try {
$resourceData = $this->model->getDireccion($id);
$response = (object)[
$response = (object) [
'error' => false,
'data' => $resourceData
];
return $this->respond($response);
} catch (\Exception $e) {
$response = (object)[
$response = (object) [
'error' => true,
'message' => $e->getMessage()
];
@ -229,22 +229,61 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
}
}
public function getDireccionIdFromData()
{
$data = $this->request->getGet('data') ?? [];
$cliente_id = $this->request->getGet('cliente_id') ?? -1;
$att = $data['att'] ?? "";
$direccion = $data['direccion'] ?? "";
$cp = $data['cp'] ?? "";
$municipio = $data['municipio'] ?? "";
$provincia = $data['provincia'] ?? "";
$pais_id = $data['pais_id'] ?? -1;
$email = $data['email'] ?? "";
$telefono = $data['telefono'] ?? "";
try {
$model = model('App\Models\Clientes\ClienteDireccionesModel');
$id = $model->select('id')
->where('att', $att)
->where('direccion', $direccion)
->where('cp', $cp)
->where('municipio', $municipio)
->where('provincia', $provincia)
->where('pais_id', $pais_id)
->where('email', $email)
->where('telefono', $telefono)
->where('cliente_id', $cliente_id)
->get()
->getResultObject();
if (count($id) > 0) {
$id = $id[0]->id;
} else {
$id = null;
}
return $id;
} catch (\Exception $e) {
throw new \RuntimeException($e->getMessage());
}
}
public function getDireccionPresupuesto($id)
{
try {
$model = model('App\Models\Presupuestos\PresupuestoDireccionesModel');
$resourceData = $model->getDireccion($id);
if(count($resourceData) > 0){
if (count($resourceData) > 0) {
$resourceData[0]->direccionId = $id;
}
$response = (object)[
$response = (object) [
'error' => false,
'data' => $resourceData
];
return $this->respond($response);
} catch (\Exception $e) {
$response = (object)[
$response = (object) [
'error' => true,
'message' => $e->getMessage()
];
@ -400,11 +439,11 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
protected function getComunidadAutonomaListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('ComunidadesAutonomas.comunidadAutonoma'))])];
if (!is_null($selId)) :
if (!is_null($selId)):
$comunidadAutonomaModel = model('App\Models\Configuracion\ComunidadAutonomaModel');
$selOption = $comunidadAutonomaModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) :
if (!empty($selOption)):
$data[$selId] = $selOption[0];
endif;
endif;
@ -414,11 +453,11 @@ class Clientedirecciones extends \App\Controllers\BaseResourceController
protected function getProvinciaListItems($selId = null)
{
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Provincias.provincia'))])];
if (!empty($selId)) :
if (!empty($selId)):
$provinciaModel = model('App\Models\Configuracion\ProvinciaModel');
$selOption = $provinciaModel->where('id', $selId)->findColumn('nombre');
if (!empty($selOption)) :
if (!empty($selOption)):
$data[$selId] = $selOption[0];
endif;
endif;

View File

@ -1065,6 +1065,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$direcciones = $reqData['direcciones'] ?? [];
$direccionesFP1 = $reqData['direccionesFP1'] ?? [];
$direccionesFP2 = $reqData['direccionesFP2'] ?? [];
if ($tipo != "")
$tipo_impresion_id = $this->getTipoImpresion($tipo, $cubierta['tipoCubierta']);
else
@ -1557,6 +1560,14 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
}
if (count($direccionesFP1) > 0) {
$this->guardarLineaEnvio($id, $direccionesFP1, $peso_libro, true);
}
if (count($direccionesFP2) > 0) {
$this->guardarLineaEnvio($id, $direccionesFP2, $peso_libro, true);
}
if ($confirmar) {
$model_presupuesto->confirmarPresupuesto($id);
PresupuestoService::crearPedido($id);
@ -1860,12 +1871,13 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
}
protected function guardarLineaEnvio($presupuestoId, $direccion, $peso_libro)
protected function guardarLineaEnvio($presupuestoId, $direccion, $peso_libro, $coste_cero = false)
{
$unidades = intval($direccion['unidades']);
$peso_envio = $peso_libro * $unidades / 1000.0;
$data = $this->getCosteEnvio(
$direccion['direccion'],
$peso_libro,
@ -1879,7 +1891,11 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
$data->presupuesto_id = $presupuestoId;
$data->tarifa_id = $data->id;
unset($data->id);
$data->precio = $data->coste;
if($coste_cero) {
$data->coste = 0;
} else {
$data->precio = $data->coste;
}
unset($data->coste);
$data->entregaPieCalle = ($direccion['entregaPalets'] == 'false' || $direccion['entregaPalets'] == 0) ? 0 : 1;
unset($data->tipo);
@ -3625,9 +3641,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController
foreach ($data as $servicio) {
$id = "service_extra_" . $servicio->id;
$tarifa_excluyente = false;
if(str_contains(strtolower($servicio->nombre), 'ferro') || str_contains(strtolower($servicio->nombre), 'prototipo')) {
if (str_contains(strtolower($servicio->nombre), 'ferro') || str_contains(strtolower($servicio->nombre), 'prototipo')) {
$tarifa_excluyente = true;
}
$atributo_excluyente = $tarifa_excluyente ? 'data-tarifa-extra-excluyente="1"' : '';

View File

@ -0,0 +1,30 @@
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class DireccionesFerroPrototipo extends Migration
{
public function up()
{
// Insertar nuevo campo: lomo_maximo_espiral
$this->forge->addColumn('presupuesto_direcciones', [
'num_ferro_prototipo' => [
'type' => 'INT',
'constraint' => 3,
'null' => false,
'default' => '0',
'description' => 'numero de ferro/prototipo',
],
]);
}
public function down()
{
$this->db->table('presupuesto_direcciones')->whereIn('name', [
'num_ferro_prototipo',
'lomo_maximo_wireo'
])->delete();
}
}

View File

@ -1,24 +1,24 @@
class Ajax{
constructor(url, data, headers, success, error, type='default'){
this.url = url;
this.data = data;
this.headers = headers;
this.success = success;
this.error = error;
this.type = type;
this.jqXHR = null;
}
post(){
(this.type == 'default') ? this.ajax('POST'): this.ajaxForm('POST');
class Ajax {
constructor(url, data, headers, success, error, type = 'default') {
this.url = url;
this.data = data;
this.headers = headers;
this.success = success;
this.error = error;
this.type = type;
this.jqXHR = null;
}
get(){
post() {
(this.type == 'default') ? this.ajax('POST') : this.ajaxForm('POST');
}
get() {
this.ajax('GET');
}
put(){
(this.type == 'default') ? this.ajax('PUT'): this.ajaxForm('PUT');
put() {
(this.type == 'default') ? this.ajax('PUT') : this.ajaxForm('PUT');
}
delete(){
(this.type == 'default') ? this.ajax('DELETE'): this.ajaxForm('DELETE');
delete() {
(this.type == 'default') ? this.ajax('DELETE') : this.ajaxForm('DELETE');
}
abort() {
if (this.jqXHR) {
@ -26,31 +26,31 @@ class Ajax{
this.jqXHR = null; // Limpiamos la referencia a la petición
}
}
setData(data){
setData(data) {
this.data = data;
}
ajax(method){
ajax(method) {
if (this.jqXHR) {
this.jqXHR.abort();
}
this.jqXHR = $.ajax({
url : this.url,
type : method,
url: this.url,
type: method,
data: this.data,
headers: this.headers,
success: this.success,
error: this.error
})
}
ajaxForm(method){
ajaxForm(method) {
if (this.jqXHR) {
this.jqXHR.abort();
}
this.jqXHR = $.ajax({
url : this.url,
type : method,
url: this.url,
type: method,
data: this.data,
processData: false,
contentType: false,
@ -59,6 +59,28 @@ class Ajax{
error: this.error
})
}
getPromise() {
if (this.jqXHR) {
this.jqXHR.abort();
}
return new Promise((resolve, reject) => {
this.jqXHR = $.ajax({
url: this.url,
type: 'GET',
data: this.data,
headers: this.headers,
success: (response) => {
if (this.success) this.success(response);
resolve(response);
},
error: (xhr) => {
if (this.error) this.error(xhr);
reject(xhr);
}
});
});
}
}
export default Ajax

View File

@ -5,12 +5,13 @@ class tarjetaDireccion {
this.container = container;
this.id = id;
this.direccionId = direccion.id;
this.direccion = direccion;
this.isFerroPrototipo = isFerroPrototipo;
this.numFerro = numFerro || 0;
this.card = this.#generateHTML(id, direccion);
this.deleteBtn = this.card.find('.direccion-eliminar');
this.editBtn = this.card.find('.direccion-editar');
this.direccion = direccion;
this.isFerroPrototipo = direccion.isFerroPrototipo;
this.numFerro = this.numFerro || 0;
}
@ -40,7 +41,13 @@ class tarjetaDireccion {
var $hr = $('<hr>', { class: 'my-2' });
var $eliminar = $('<a>', { class: 'ms-auto direccion-eliminar', href: 'javascript:void(0)', text: 'Eliminar' });
var $editar = $('<a>', { class: 'me-auto direccion-editar', href: 'javascript:void(0)', text: 'Editar' });
var $eliminarContainer = $('<span>', { class: 'd-flex w-100 position-relative' }).append($editar, $eliminar);
var $eliminarContainer = '';
if(!this.isFerroPrototipo) {
$eliminarContainer = $('<span>', { class: 'd-flex w-100 position-relative' }).append($editar, $eliminar);
}
else{
$eliminarContainer = $('<span>', { class: 'd-flex w-100 position-relative' }).append($eliminar);
}
// Construir la estructura del HTML
$header.append($name, $unidades);

View File

@ -70,6 +70,13 @@ class Direcciones {
this.btnAdd.on('click', this.#insertDireccion.bind(this));
this.btnNew.on('click', this.#nuevaDireccion.bind(this));
$('#insertarDireccionFP1').on('click', () => {
this.#insertDireccionFP(1);
});
$('#insertarDireccionFP2').on('click', () => {
this.#insertDireccionFP(2);
});
// evento para actualizar el selector de tiradas
$(document).on('update-tiradas-envios', (event, data) => {
self.divTiradas.empty();
@ -165,29 +172,6 @@ class Direcciones {
tarjeta.card.find('.direccion-eliminar').on('click', this.#deleteDireccion.bind(self));
this.divDirecciones.append(tarjeta.card);
this.direcciones.push(tarjeta);
/*let peticion = new Ajax('/misdirecciones/getDireccionPresupuesto/' + id, {}, {},
(response) => {
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 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) {
@ -357,42 +341,107 @@ class Direcciones {
return;
}
}
this.#addTarjetaDireccion(this.divDirecciones, this.direcciones, divId, id, unidades, entregaPalets);
$('#loader').modal('show');
let peticion = new Ajax('/misdirecciones/get/' + id, {}, {},
(response) => {
if (this.direcciones.length == 0) {
$('#loader').modal('hide');
if (entregaPalets) {
this.calcularPresupuesto = true;
}
}
else {
this.calcularPresupuesto = true;
}
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);
self.divDirecciones.trigger('change');
},
() => {
console.error('Error getting address');
$('#loader').modal('hide');
});
peticion.get();
} catch (e) {
console.error(e);
$('#loader').modal('hide');
}
}
#insertDireccionFP(num_ferroPrototipo) {
self = this;
try {
let id = 0;
if( num_ferroPrototipo === 1) {
id = this.direccionesClienteFP1.getVal();
}
if( num_ferroPrototipo === 2) {
id = this.direccionesClienteFP2.getVal();
}
let unidades = 1;
if (id == null || id <= 0 || id == undefined)
return;
let divId = "dirEnvio-FP-" + num_ferroPrototipo;
let containerId = num_ferroPrototipo === 1 ? "#divDireccionesFerroPrototipo" : "#divDireccionesFerroPrototipo2";
let arrayName = num_ferroPrototipo === 1 ? this.direccionesFP1 : this.direccionesFP2;
this.#addTarjetaDireccion(
$(containerId),
arrayName,
divId,
id,
1, false, true, num_ferroPrototipo);
$('.div-direcciones-fp' + num_ferroPrototipo).addClass('d-none');
} catch (e) {
console.error(e);
$('#loader').modal('hide');
}
}
async #addTarjetaDireccion(container, addArray, divId, data, unidades, entregaPalets = false, isFerroPrototipo = false, numFerroPrototipo = 0) {
const self = this;
let id = data;
try {
if (typeof data === 'object') {
const ajaxGetId = new Ajax('/misdirecciones/getId', {
data: data,
cliente_id: $("#clienteId").select2('data')[0].id
}, {}, null, null);
const response = await ajaxGetId.getPromise();
id = response;
}
$('#loader').modal('show');
const ajaxGetDireccion = new Ajax('/misdirecciones/get/' + id, {}, {}, null, null);
const response = await ajaxGetDireccion.getPromise();
if (this.direcciones.length === 0) {
$('#loader').modal('hide');
if (entregaPalets) {
this.calcularPresupuesto = true;
}
} else {
this.calcularPresupuesto = true;
}
const tarjeta = new tarjetaDireccion(container, divId, response.data[0], isFerroPrototipo, numFerroPrototipo);
tarjeta.setUnidades(unidades);
tarjeta.setEntregaPalets(entregaPalets);
if (!isFerroPrototipo) {
tarjeta.card.find('.direccion-eliminar').on('click', this.#deleteDireccion.bind(self));
tarjeta.card.find('.direccion-editar').on('click', this.#editUnits.bind(self));
}
else {
tarjeta.card.find('.direccion-eliminar').on('click', (event) => {
this.#deleteDireccionFP(event, numFerroPrototipo);
$('.div-direcciones-fp' + numFerroPrototipo).removeClass('d-none');
});
}
container.append(tarjeta.card);
addArray.push(tarjeta);
container.trigger('change');
} catch (err) {
console.error('Error en petición Ajax:', err);
$('#loader').modal('hide');
}
}
handleChangeCliente() {
@ -453,22 +502,43 @@ class Direcciones {
this.divDirecciones.trigger('change');
}
#deleteDireccionFP(event, num_ferroPrototipo = 1) {
let tarjeta = event.currentTarget.closest('.direccion-cliente');
this.calcularPresupuesto = true;
if (num_ferroPrototipo === 1) {
this.direccionesFP1 = [];
this.sameAddPrincipalFP1.prop('checked', false);
$('#divDireccionesFerroPrototipo1').trigger('change');
}
if (num_ferroPrototipo === 2) {
this.direccionesFP2 = [];
this.sameAddPrincipalFP2.prop('checked', false);
this.sameAddFP1.prop('checked', false);
$('#divDireccionesFerroPrototipo2').trigger('change');
}
tarjeta.remove();
}
#handleSameAddPrincipalFP1() {
if (this.sameAddPrincipalFP2.is(':checked')) {
if (this.sameAddPrincipalFP1.is(':checked')) {
$('.div-direcciones-fp1').addClass('d-none');
$('#divDireccionesFerroPrototipo').empty();
if (this.direcciones.length > 0) {
// get first element
let firstDireccion = this.direcciones[0];
let tarjeta = new tarjetaDireccion(
$("#divDireccionesFerroPrototipo"),
'dirEnvio-FP-1',
firstDireccion.getData(), true, 1);
tarjeta.setUnidades(1);
$('#divDireccionesFerroPrototipo').append(tarjeta.card);
let data = this.direcciones[0].getDireccion();
this.direccionesFP1 = [];
this.direccionesFP1.push(tarjeta);
this.#addTarjetaDireccion(
$("#divDireccionesFerroPrototipo"),
this.direccionesFP1,
'dirEnvio-FP-1',
data,
1, false, true, 1);
$('#divDireccionesFerroPrototipo').removeClass('d-none');
}
else {
@ -486,19 +556,21 @@ class Direcciones {
#handleSameAddPrincipalFP2() {
if (this.sameAddPrincipalFP2.is(':checked')) {
if(this.sameAddFP1.is(':checked')) {
this.sameAddFP1.prop('checked', false);
}
$('.div-direcciones-fp2').addClass('d-none');
$('#divDireccionesFerroPrototipo2').empty();
if (this.direcciones.length > 0) {
// get first element
let firstDireccion = this.direcciones[0];
let tarjeta = new tarjetaDireccion(
$("#divDireccionesFerroPrototipo2"),
'dirEnvio-FP-2',
firstDireccion.getData(), true, 1);
tarjeta.setUnidades(1);
$('#divDireccionesFerroPrototipo2').append(tarjeta.card);
let data = this.direcciones[0].getDireccion();
this.direccionesFP2 = [];
this.direccionesFP2.push(tarjeta);
this.#addTarjetaDireccion(
$("#divDireccionesFerroPrototipo2"),
this.direccionesFP2,
'dirEnvio-FP-2',
data,
1, false, true, 2);
$('#divDireccionesFerroPrototipo2').removeClass('d-none');
}
else {
@ -516,19 +588,23 @@ class Direcciones {
#handleSameAddFP1() {
if (this.sameAddFP1.is(':checked')) {
if(this.sameAddPrincipalFP2.is(':checked')) {
this.sameAddPrincipalFP2.prop('checked', false);
}
$('.div-direcciones-fp2').addClass('d-none');
$('#divDireccionesFerroPrototipo2').empty();
if (this.direccionesFP1.length > 0) {
// get first element
let firstDireccion = this.direccionesFP1[0];
let tarjeta = new tarjetaDireccion(
let data = this.direccionesFP1[0].getDireccion();
this.direccionesFP1 = [];
this.#addTarjetaDireccion(
$("#divDireccionesFerroPrototipo2"),
this.direccionesFP2,
'dirEnvio-FP-2',
firstDireccion.getData(), true, 1);
tarjeta.setUnidades(1);
$('#divDireccionesFerroPrototipo2').append(tarjeta.card);
this.direccionesFP2 = [];
this.direccionesFP2.push(tarjeta);
data,
1, false, true, 2);
$('#divDireccionesFerroPrototipo2').removeClass('d-none');
}
else {

View File

@ -793,6 +793,19 @@ class PresupuestoCliente {
};
}
}
if( this.direcciones.direccionesFP1.length > 0) {
this.datos.direccionesFP1 = this.direcciones.direccionesFP1.map((direccion) => {
return direccion.getFormData();
});
}
if( this.direcciones.direccionesFP2.length > 0) {
this.datos.direccionesFP2 = this.direcciones.direccionesFP2.map((direccion) => {
return direccion.getFormData();
});
}
if (save) {
this.datos.datosCabecera = {
titulo: this.datosGenerales.titulo.val(),