diff --git a/ci4/app/Controllers/Presupuestos/Presupuestoadmin.php b/ci4/app/Controllers/Presupuestos/Presupuestoadmin.php index e9eabcae..07a9fc5e 100644 --- a/ci4/app/Controllers/Presupuestos/Presupuestoadmin.php +++ b/ci4/app/Controllers/Presupuestos/Presupuestoadmin.php @@ -523,66 +523,34 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController $data['comentarios_produccion'] = $presupuesto->comentarios_produccion; $data['tiradasAlternativas'] = json_decode($presupuesto->tirada_alternativa_json_data); - /* - - - - $datos_papel = $this->obtenerDatosPapel($presupuesto->id); - $data['interior'] = $datos_papel['interior'] ? $datos_papel['interior'] : []; - - $data['cubierta'] = $datos_papel['cubierta'] ? $datos_papel['cubierta'] : []; - $data['cubierta']['tapa'] = $this->obtenerTipoTapa($presupuesto->tipo_impresion_id ?? null); - $data['cubierta']['lomoRedondo'] = $presupuesto->lomo_redondo ? 1 : 0; - $data['cubierta']['solapas'] = $presupuesto->solapas ? 1 : 0; - $data['cubierta']['solapas_ancho'] = $presupuesto->solapas_ancho; - $data['cubierta']['cabezada'] = $presupuesto->cabezada; - $modelAcabado = model("App\Models\Tarifas\Acabados\TarifaAcabadoModel"); - $data['cubierta']['acabado']['id'] = $presupuesto->acabado_cubierta_id; - if ($presupuesto->acabado_cubierta_id == 0) { - $data['cubierta']['acabado']['text'] = "Ninguno"; - } else { - $data['cubierta']['acabado']['text'] = $modelAcabado->find($presupuesto->acabado_cubierta_id)->nombre; - } - $data['cubierta']['retractilado'] = $presupuesto->retractilado ? 1 : 0; - - $data['sobrecubierta'] = array_key_exists('sobrecubierta', $datos_papel) ? $datos_papel['sobrecubierta'] : []; - $data['sobrecubierta']['solapas'] = $presupuesto->solapas_sobrecubierta ? 1 : 0; - $data['sobrecubierta']['solapas_ancho'] = $presupuesto->solapas_ancho_sobrecubierta; - $data['sobrecubierta']['acabado']['id'] = $presupuesto->acabado_sobrecubierta_id; - if ($presupuesto->acabado_sobrecubierta_id == 0) { - $data['sobrecubierta']['acabado']['text'] = "Ninguno"; - } else { - $data['sobrecubierta']['acabado']['text'] = $modelAcabado->find($presupuesto->acabado_sobrecubierta_id)->nombre; - } - - $data['guardas'] = array_key_exists('guardas', $datos_papel) ? $datos_papel['guardas'] : []; - - $modelLinea = new PresupuestoLineaModel(); - $lineas = $modelLinea->where('presupuesto_id', $id)->findAll(); - - [$data['datosGenerales']['paginasNegro'], $data['datosGenerales']['paginasColor']] = - $this->getPaginas($lineas); - - if (intval($presupuesto->envios_recoge_cliente) == 1) { - $data['direcciones']['entrega_taller'] = 1; - } else { - $data['direcciones']['entrega_taller'] = 0; - $data['direcciones'] = $this->obtenerDireccionesEnvio($id, $presupuesto->cliente_id); - } - - if (intval($presupuesto->estado_id) == 2) { - $data['resumen']['base'] = $presupuesto->total_aceptado; - $data['resumen']['precio_unidad'] = $presupuesto->total_precio_unidad; - } - - $tiradas_alternativas = json_decode($presupuesto->tirada_alternativa_json_data); - if (!is_null($tiradas_alternativas)) { - for ($i = 0; $i < count($tiradas_alternativas); $i++) { - $tirada = $tiradas_alternativas[$i]; - $data['datosGenerales']['tirada' . ($i + 2)] = $tirada->tirada; - } - }*/ + $data['resumen']['total_coste_papel'] = $presupuesto->total_coste_papel; + $data['resumen']['total_margenPercent_papel'] = $presupuesto->total_margenPercent_papel; + $data['resumen']['total_margen_papel'] = $presupuesto->total_margen_papel; + $data['resumen']['total_coste_impresion'] = $presupuesto->total_coste_impresion; + $data['resumen']['total_margenPercent_impresion'] = $presupuesto->total_margenPercent_impresion; + $data['resumen']['total_margen_impresion'] = $presupuesto->total_margen_impresion; + $data['resumen']['total_coste_servicios'] = $presupuesto->total_coste_servicios; + $data['resumen']['total_margenPercent_servicios'] = $presupuesto->total_margenPercent_servicios; + $data['resumen']['total_margen_servicios'] = $presupuesto->total_margen_servicios; + $data['resumen']['total_coste_envios'] = $presupuesto->total_coste_envios; + $data['resumen']['total_margen_envios'] = $presupuesto->total_margen_envios; + $data['resumen']['total_costes'] = $presupuesto->total_costes; + $data['resumen']['porcentajeMargen'] = + round(($presupuesto->total_costes + $presupuesto->total_margenes) > 0 ? + 100 * $presupuesto->total_margenes / ($presupuesto->total_costes + $presupuesto->total_margenes) : + 0, 0); + $data['resumen']['total_margenes'] = $presupuesto->total_margenes; + $data['resumen']['total_antes_descuento'] = $presupuesto->total_antes_descuento; + $data['resumen']['total_descuentoPercent'] = $presupuesto->total_descuentoPercent; + $data['resumen']['total_descuento'] = $presupuesto->total_descuento; + $data['resumen']['total_presupuesto'] = $presupuesto->total_presupuesto; + $data['resumen']['total_precio_unidad'] = $presupuesto->total_precio_unidad; + $data['resumen']['total_factor'] = is_numeric($presupuesto->total_factor) ? $presupuesto->total_factor : 0; + $data['resumen']['total_factor_ponderado'] = is_numeric($presupuesto->total_factor_ponderado) ? $presupuesto->total_factor_ponderado : 0; + if($presupuesto->estado_id == 2){ + $data['resumen']['total_aceptado'] = $presupuesto->total_aceptado; + } return $this->respond([ 'status' => 1, 'data' => $data @@ -604,8 +572,8 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController $papel_generico = $this->request->getPost('papel_generico'); $gramaje = $this->request->getPost('gramaje'); $paginas_color = $this->request->getPost('paginas_color'); - $isColor = $this->request->getPost('isColor')?1:0; - $isHq = $this->request->getPost('isHq')?1:0; + $isColor = $this->request->getPost('isColor') ? 1 : 0; + $isHq = $this->request->getPost('isHq') ? 1 : 0; $tipo_impresion_id = $this->request->getPost('tipo_impresion_id'); $uso = $this->request->getPost('uso'); @@ -849,7 +817,7 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController endif; endforeach; - } + } return $this->respond(Collection::datatable( $resourceData, @@ -890,7 +858,7 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController 'nombre' => $reqData['papel_generico'] ?? "", ]; - if($papel_generico['id'] != 0 && $papel_generico['nombre'] == ""){ + if ($papel_generico['id'] != 0 && $papel_generico['nombre'] == "") { $modelPapelGenerico = new PapelGenericoModel(); $papel_generico['nombre'] = $modelPapelGenerico->getNombre($papel_generico['id'])['nombre']; } diff --git a/ci4/app/Controllers/Presupuestos/Presupuestodirecciones.php b/ci4/app/Controllers/Presupuestos/Presupuestodirecciones.php index d99d9fd3..300e68ef 100755 --- a/ci4/app/Controllers/Presupuestos/Presupuestodirecciones.php +++ b/ci4/app/Controllers/Presupuestos/Presupuestodirecciones.php @@ -145,6 +145,7 @@ class Presupuestodirecciones extends \App\Controllers\BaseResourceController $reqData = $this->request->getJSON(); if($reqData->tipo=='get_tarifa'){ + $peso = $reqData->peso ?? 0; $paisId = $reqData->paisId ?? 0; $cp = $reqData->cp ?? 0; diff --git a/ci4/app/Models/Tarifas/TarifaEnvioModel.php b/ci4/app/Models/Tarifas/TarifaEnvioModel.php index c5348c6e..c73aff07 100755 --- a/ci4/app/Models/Tarifas/TarifaEnvioModel.php +++ b/ci4/app/Models/Tarifas/TarifaEnvioModel.php @@ -98,11 +98,13 @@ class TarifaEnvioModel extends \App\Models\BaseModel // Si el pais es españa se tienen que tener en cuenta los postales // Se busca primero la tarifa a la que corresponde $builder = $this->db->table($this->table . " t1") - ->select("t1.id AS tarifa_envio_id, t2.importe_fijo as importe_fijo") + ->select("t1.id AS tarifa_envio_id, t2.importe_fijo as importe_fijo, t3.nombre as pais") ->join("tarifas_envios_zonas t2", "t1.id = t2.tarifa_envio_id") + ->join("lg_paises t3", "t1.pais_id = t3.id") ->where("t1.pais_id", $paisId) ->where("t1.is_deleted", 0) ->where("t2.is_deleted", 0); + if ($paisId == 1) { // España $builder->where("CAST(t2.cp_inicial AS UNSIGNED)<=", intval($cp)) @@ -117,10 +119,12 @@ class TarifaEnvioModel extends \App\Models\BaseModel $precio_tarifas = $model->getEnvioPrecio($tarifa->tarifa_envio_id, $peso, $tipo_envio); foreach ($precio_tarifas as $precio_tarifa) { $precio_tarifa->importe_fijo = $tarifa->importe_fijo; + $precio_tarifa->pais = $tarifa->pais; array_push($resultado, $precio_tarifa); } } + return $resultado; } } diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_datosEnvios.js b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_datosEnvios.js deleted file mode 100644 index 0aa5b37c..00000000 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_datosEnvios.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - -// Funcion para obtener el peso total del libro -function 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 function get_precio_envio(peso, paisId, cp, tipo_envio){ - - data = { - tipo: 'get_tarifa', - peso: peso, - paisId: paisId, - cp: cp, - tipo_envio: tipo_envio, - } - data = Object.assign(data, window.token_ajax); - - const response = await fetch(window.location.origin + window.url_get_precio_envio , { - method: "POST", - body: JSON.stringify(data), - headers: { - "Content-type": "application/json; charset=UTF-8", - } - }); - - const values = await response.json(); - yeniden(values[window.csrf_token]); - return values.data; -} - - -async function get_coste_envio_tiradasAlternativas(tirada){ - - var peso_libro = get_peso_libro(); - var tirada_inicial = parseInt($('#tirada').val()); - var coste = 0.0; - var margen = 0.0; - - const table = $('#tableOfDireccionesEnvio').DataTable(); - const rows = table.rows().nodes(); - - for (let i = 0; i < rows.length; i++) { - const rowData = table.row(rows[i]).data(); - const porcentaje = parseInt(rowData.cantidad)/tirada_inicial*100.0; - const cantidad = Math.floor(tirada*porcentaje/100.0); - const peso_envio = cantidad*peso_libro/1000.0; - const datos_tarifa = await get_precio_envio(peso_envio, rowData.paisId, rowData.cp, parseInt(rowData.entregaPieCalle)==1?'palets':'cajas'); - - if(datos_tarifa.id!=null){ - - if(peso_envio>parseFloat(datos_tarifa.peso_max)){ - coste += (parseFloat(datos_tarifa.precio_min) + (peso_envio-parseFloat(datos_tarifa.peso_min)) * parseFloat(datos_tarifa.precio_adicional)).toFixed(2); - } - // si no se calcula linealmente - else{ - m=((parseFloat(datos_tarifa.precio_max)-parseFloat(datos_tarifa.precio_min))/(parseFloat(datos_tarifa.peso_max)-parseFloat(datos_tarifa.peso_min))); - b=parseFloat(datos_tarifa.precio_max)-m*parseFloat(datos_tarifa.peso_max); - coste += parseFloat(m*peso_envio+b); - } - } - margen += coste*datos_tarifa.margen/100.0; - } - - return {coste, margen}; -} - - -async function updateTablaEnvios(tirada_inicial = null, tirada = null){ - - var peso_total_libro = get_peso_libro(); - - $('#tableOfDireccionesEnvio').DataTable().rows().every(async function ( rowIdx, tableLoop, rowLoop ) { - - var rowData = this.data(); - - if(tirada_inicial!=null && tirada!=null){ - const porcentaje = parseInt(rowData.cantidad)/tirada_inicial*100.0; - const cantidad = Math.floor(tirada*porcentaje/100.0); - rowData.cantidad = cantidad - } - const peso_envio = peso_total_libro*parseInt(rowData.cantidad)/1000.0; - - var datos_tarifa = await get_precio_envio(peso_envio, rowData.paisId, 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{ - m=((parseFloat(datos_tarifa.precio_max)-parseFloat(datos_tarifa.precio_min))/(parseFloat(datos_tarifa.peso_max)-parseFloat(datos_tarifa.peso_min))); - 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, - 'paisId': rowData.paisId, - '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': actionBtns_direcciones, - }) - .draw(); - - checkInsertar() - //updateTotales(false, false, true) - updatePresupuesto({ - 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') - } - }) -} - -$('#insertar_direccion').on('click', function(){ - - $("#addressForm").attr('action','create') - var $newAddDialog = $("#addressForm") - var 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()) - }) - - cantidad_total = 0 - tableEnvios.rows().every( function ( rowIdx, tableLoop, rowLoop ) { - var 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') -}) - - - - - - - - - - - - - - -function save_datos_envios(){ - - var id = $('#presupuesto_id').val() - - $.post( window.routes_envios.dataTableOfPresupuestoDirecciones, - Object.assign({tipo: "clear_lineas", presupuesto_id: id}, window.token_ajax)) - .done(function( data ) { - - $('#tableOfDireccionesEnvio').DataTable().rows().every( function ( rowIdx, tableLoop, rowLoop ) { - var data = this.data(); - $.post( '/presupuestos/presupuestodirecciones/add', - Object.assign({ - presupuesto_id : id, - tarifa_id : data.tarifa_id, - cantidad : data.cantidad, - peso : data.peso, - att : data.att, - email : data.email, - direccion : data.direccion, - paisId : data.paisId, - 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}, window.token_ajax)) - }); - - }) - -} - - - -*/ \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_presupuestos.js b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_presupuestos.js deleted file mode 100644 index 8e85a96a..00000000 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_presupuestos.js +++ /dev/null @@ -1,91 +0,0 @@ -async function updatePresupuesto( - { - update_lineas = false, - update_servicios = false, - update_envios = false, - update_resumen = false, - update_tiradas_alternativas = false - }) { - - new Promise( - async function(resolve, reject){ - if(update_lineas){ - await updateLineasPresupuesto() - } - else - resolve() - } - ).then(function(){ - new Promise( - async function(resolve, reject){ - if(update_servicios){ - await actualizar_servicios() - } - else - resolve() - } - ) - }).then(function(){ - new Promise( - function(resolve, reject){ - if(update_envios){ - updateTablaEnvios() - } - else - resolve() - } - ) - }).then(function(){ - new Promise( - function(resolve, reject){ - if(update_resumen){ - updateTotales() - } - else - resolve() - } - ) - }).then(function(){ - new Promise( - async function(resolve, reject){ - if(update_tiradas_alternativas){ - await actualizar_tiradas_alternativas() - } - else - resolve() - } - ) - }) -} - -async function updateLineasPresupuesto(){ - - $('#tableLineasPresupuesto tbody tr:visible ').each(async function(){ - - if(this.id.endsWith('lp_bn')){ - await calcularPresupuesto_bn({}, true); - } - else if(this.id.endsWith('lp_bnhq')){ - await calcularPresupuesto_bnhq({}, true); - } - else if(this.id.endsWith('lp_color')){ - await calcularPresupuesto_color({}, true); - } - else if(this.id.endsWith('lp_colorhq')){ - await calcularPresupuesto_colorhq({}, true); - } - else if(this.id.endsWith('lp_rot_bn')){ - await calcularPresupuesto_rot_bn(false, true, {}) - } - else if(this.id.endsWith('lp_rot_color')){ - await calcularPresupuesto_rot_color(false, true, {}) - } - else if(this.id.endsWith('_cubierta')){ - await calcularPresupuesto_cubierta(false, {}) - } - else if(this.id.endsWith('_guardas')){ - await calcularPresupuesto_guardas(false, {}) - } - }) - -} \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenPresupuestoItems.php b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenPresupuestoItems.php index 2dcd7588..e0ffa2e0 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenPresupuestoItems.php +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenPresupuestoItems.php @@ -18,55 +18,57 @@
Coste papel
-
total_coste_papel) ?>€
+
Margen papel
-
total_margenPercent_papel) ?>%
-
total_margen_papel) ?>€
+
+
Coste impresión
-
total_coste_impresion) ?>€
+
Margen impresión
-
total_margenPercent_impresion) ?>%
-
total_margen_impresion) ?>€
+
+
Coste servicios
-
total_coste_servicios) ?>€
+
Margen servicios
-
total_margenPercent_servicios) ?>%
-
total_margen_servicios) ?>€
+
+
Coste de envío
-
total_coste_envios) ?>€
+
+
Precio de envío
+
Margen envío
-
total_margen_envios) ?>€
+

Total Costes
-
total_costes) ?>€
+
Total Margen
-
total_costes+$presupuestoEntity->total_margenes)>0? 100*$presupuestoEntity->total_margenes/($presupuestoEntity->total_costes+$presupuestoEntity->total_margenes) : 0,0)) ?>%
-
total_margenes) ?>€
+
+

Total
-
total_antes_descuento) ?>€
+
Descuento
-
-
total_descuento) ?>€
+
%
+
Total presupuesto
-
total_presupuesto) ?>€
+
Precio unidad
-
total_precio_unidad) ?>€
+
Factor
-
total_factor) ? $presupuestoEntity->total_factor : 0) ?>
+
Factor Ponderado
-
total_factor_ponderado) ? $presupuestoEntity->total_factor_ponderado : 0) ?>
+
@@ -83,7 +85,7 @@ - > + >
diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenPresupuestos.js b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenPresupuestos.js index 4e3c8088..221c108d 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenPresupuestos.js +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_resumenPresupuestos.js @@ -231,21 +231,6 @@ function updateTotales(updateLP=true, updateServicios=true, updateEnvio=true){ } -function addSeparatorsNF(nStr, inD, outD, sep) -{ - nStr += ''; - var dpos = nStr.indexOf(inD); - var nStrEnd = ''; - if (dpos != -1) { - nStrEnd = outD + nStr.substring(dpos + 1, nStr.length); - nStr = nStr.substring(0, dpos); - } - var rgx = /(\d+)(\d{3})/; - while (rgx.test(nStr)) { - nStr = nStr.replace(rgx, '$1' + sep + '$2'); - } - return nStr + nStrEnd; -} function getValuesResumenForm(){ var formResumen = ""; @@ -288,12 +273,3 @@ function getValuesResumenForm(){ -$(".update-totales").on("change", function(){ - updatePresupuesto({ - update_lineas: false, - update_servicios: false, - update_envios: false, - update_resumen: true, - update_tiradas_alternativas: false - }) -}) \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_tiradasAlternativasItems.js b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_tiradasAlternativasItems.js deleted file mode 100644 index fba0656f..00000000 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/_tiradasAlternativasItems.js +++ /dev/null @@ -1,244 +0,0 @@ - - -// Evento de añadir una tirada alternativa -$('#add_tirada_alt').on('click', function () { - - const tirada_alt = parseInt($('#tirada_alt').val()); - add_tirada_alternativa(tirada_alt); - showBreadCrumbSaveButton(true); -}); - - -// Funcion para añadir una tirada alternativa -async function add_tirada_alternativa(tirada_alt) { - - // se comprueba que la tirada no existe ya en la tabla - const exists = tableTiradas.rows().data().toArray().some(row => row.tirada == tirada_alt); - const isPOD = parseInt($('#tirada').val())<= parseInt($('#POD').val()); - - const typeIsOk = tirada_alt <= parseInt($('#POD').val()) && isPOD || tirada_alt > parseInt($('#POD').val()) && !isPOD; - - if (!exists && typeIsOk) { - - const dimension = getDimensionLibro(); - - let datos = { - tirada: tirada_alt, - merma: get_merma_tirada_alternativa(tirada_alt), - tipo_impresion_id: $('#tipo_impresion_id').val(), - json_tiradas: generate_json_tiradas(), - ancho: dimension.ancho, - alto: dimension.alto, - cliente_id: $('#clienteId').find(":selected").val(), - solapas_cubierta: $('#solapas').is(':checked')?1:0, - solapas_cubierta_ancho: $('#solapas').is(':checked')?parseInt($('#solapas_ancho').val()):0, - solapas_sobrecubierta: $('#solapas_sobrecubierta').is(':checked')?1:0, - solapas_sobrecubierta_ancho: $('#solapas_sobrecubierta').is(':checked')?parseInt($('#solapas_ancho_sobrecubierta').val()):0, - lomo: getLomoExterior(), - }; - - datos = Object.assign(datos, window.token_ajax); - - // Se realiza la petición AJAX - await $.ajax({ - type: "POST", - url: window.get_tirada_url, - data: datos, - success: async function (data) { - - var coste_total = 0.0; - var margen_total = 0.0; - - var costes_servicios = 0.0; - var margen_servicios = 0.0; - - var coste_envio = 0.0; - var margen_envio = 0.0; - - if(data.lineas.length >0){ - // Se cogen los valores de la linea con los datos correspondientes - data.lineas.forEach(function(value) { - coste_total += value.total_coste; - margen_total += value.total_margen; - }); - - //console.log(datos.tirada); - - // Se obtiene el precio de los servicios - const valueAcabados = await get_servAcabados_tiradasAlternativas(parseInt(datos.tirada)); - costes_servicios += parseFloat(valueAcabados.coste); - margen_servicios += parseFloat(valueAcabados.margen); - - //console.log('coste acabados ('+ datos.tirada +'): ' + valueAcabados.coste); - - const valueEncuadernacion = await get_servEncuadernacion_tiradasAlternativas( - parseInt(datos.tirada), parseInt( $('#paginas').val()), parseInt(dimension.ancho), parseInt(dimension.alto)); - costes_servicios += parseFloat(valueEncuadernacion.coste); - margen_servicios += parseFloat(valueEncuadernacion.margen); - - //console.log('coste encuadernacion ('+ datos.tirada +'): ' + valueEncuadernacion.coste); - - const valueManipulado = await get_servManipulado_tiradasAlternativas(parseInt(datos.tirada)); - costes_servicios += parseFloat(valueManipulado.coste); - margen_servicios += parseFloat(valueManipulado.margen); - - //console.log('coste manipulado ('+ datos.tirada +'): ' + valueManipulado.coste); - - const valuePreimpresion = await get_servPreimpresion_tiradasAlternativas(parseInt(datos.tirada)); - costes_servicios += parseFloat(valuePreimpresion.coste); - margen_servicios += parseFloat(valuePreimpresion.margen); - - const valueServiciosExtra = await get_servExtra_tiradasAlternativas(parseInt(datos.tirada)); - costes_servicios += parseFloat(valueServiciosExtra.coste); - margen_servicios += parseFloat(valueServiciosExtra.margen); - - //console.log('coste preimpresion ('+ datos.tirada +'): ' + valuePreimpresion.coste); - - const valueTransporte = await get_coste_envio_tiradasAlternativas(parseInt(datos.tirada)); - coste_envio = valueTransporte.coste; - margen_envio = valueTransporte.margen; - - - // Se añade la fila a la tabla de tiradas - tableTiradas.row.add({ - tirada: datos.tirada, - coste_impresion: coste_total.toFixed(2), - coste_envio: coste_envio.toFixed(2), - margen: ((margen_total + margen_servicios + margen_envio)/(coste_total+coste_envio)*100.0).toFixed(2), - total_pedido: (coste_total + costes_servicios + coste_envio).toFixed(2), - precio_unidad: ((coste_total + costes_servicios + coste_envio) / datos.tirada).toFixed(4), - - }).draw(false); - } - - yeniden(data[window.csrf_token]); - - }, - error: function(e){} - }); - } - else { - var htmlString = ''; - if(typeIsOk){ - htmlString = ` - `; - } - - else{ - htmlString = ` - `; - } - $('#alert-tiradas_alt').hide().empty().html(htmlString).fadeIn("slow", function(){ - setTimeout(function(){ - $('#alert-tiradas_alt').fadeOut("slow"); - }, 5000); - }); - } - - -} - -// Función para obtener el lomo exterior -function getLomoExterior(){ - let lomoTotal = 0 - try{ - $('#tableLineasPresupuesto').DataTable().rows().every( function ( rowIdx, tableLoop, rowLoop ) { - var rowData = this.data(); - if(rowData.row_id != 'lp_cubierta' && rowData.tipo != 'lp_sobrecubierta') - lomoTotal += parseFloat(rowData.lomo) - }) - } - catch(error){ - lomoTotal = 0 - } - return lomoTotal -} - - - -// Función para usar la tirada alternativa como tirada principal -$(document).on('click', '.comfirm-tirada-alt', function (e) { - - const row = $(this).closest('tr'); - const data = tableTiradas.row(row).data(); - - updateTablaEnvios($('#tirada').val(), data.tirada).then(function(){ - $('#tirada').val(data.tirada); - $('#tirada').trigger('change', [false]); - }) -}) - - -// Función para generar el JSON de las lineas de presupuesto para calcular las tiradas -function generate_json_tiradas() { - - const data = $('#tableLineasPresupuesto').DataTable().data().toArray(); - - //return data; // For debugging purposes - json = filterData(data, - ['paginas', - 'numPagColor', - 'paginas_impresion', - 'papel', // papel generico - 'papel_impresion_id', - 'gramaje', - 'maquina_id', - 'aFavorFibra', - 'row_id', - 'check_papel_total', - 'check_impresion_total', - 'cobAmarillo', // tipologia de papel - 'cobCyan', - 'cobMagenta', - 'cobNegro', - 'cobCG', - 'gotaColor', - 'gotaNegro']); - - json.forEach(element => { - element['check_papel_total'] = $('#' + element['row_id'] + '_checkPapel').is(':checked') ? 1 : 0; - element['check_impresion_total'] = $('#' + element['row_id'] + '_checkClicks').is(':checked') ? 1 : 0; - }); - return JSON.stringify(json); -} - - -// Función para filtrar las columnas de la tabla de tiradas -function filterData(data, keys) { - return data.map(obj => { - const newObj = {}; - keys.forEach(key => { - if (obj.hasOwnProperty(key)) { - newObj[key] = obj[key]; - } - }); - return newObj; - }); -} - - - - - - - - - \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/viewPresupuestoadminForm.php b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/viewPresupuestoadminForm.php index f8ef50a5..5114447c 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/admin/viewPresupuestoadminForm.php +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/admin/viewPresupuestoadminForm.php @@ -187,6 +187,7 @@ section("additionalInlineJs") ?> + endSection() ?> @@ -271,17 +272,6 @@ endSection() ?> - - - - - section("additionalInlineJs") ?> - - window.token_ajax= {: v}; - window.csrf_token = ''; - - endSection() ?> - diff --git a/httpdocs/assets/js/safekat/pages/presupuestoAdmin/presupuestoAdminEdit.js b/httpdocs/assets/js/safekat/pages/presupuestoAdmin/presupuestoAdminEdit.js index b912047f..500de09e 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoAdmin/presupuestoAdminEdit.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoAdmin/presupuestoAdminEdit.js @@ -9,6 +9,7 @@ import PreviewFormasAdmin from './sections/previewFormasAdmin.js'; import Servicios from './sections/servicios.js'; import Envios from './sections/envios.js'; import TiradasAlernativas from './sections/tiradasAlternativas.js'; +import Resumen from './sections/resumen.js'; class PresupuestoAdminEdit { @@ -44,6 +45,10 @@ class PresupuestoAdminEdit { this.tiradasAlternativas = new TiradasAlernativas({ getDimensionLibro: this.getDimensionLibro, }); + this.resumen = new Resumen(); + + this.guardar = $('#saveForm'); + this.calcularPresupuesto = false; } @@ -89,6 +94,7 @@ class PresupuestoAdminEdit { this.servicios.init(); this.envios.init(); this.tiradasAlternativas.init(); + this.resumen.init(); if (window.location.href.includes("edit")) { @@ -103,8 +109,62 @@ class PresupuestoAdminEdit { } } this.downloadPreviewImage(); + + $(document).on('update-presupuesto', this.updatePresupuesto.bind(this)); + + this.guardar.on('click', this.guardarPresupuesto.bind(this)); } + + guardarPresupuesto() { + + this.servicios.guardar(); + } + + + async updatePresupuesto(event, { + update_lineas = true, + update_servicios = true, + update_envios = true, + update_resumen = true, + update_tiradas_alternativas = true + }) { + const waitForEvent = (eventName) => { + return new Promise((resolve) => { + $(document).one(eventName, () => { + resolve(); + }); + }); + }; + + // Ejecutar los pasos de forma secuencial si están habilitados + if (update_lineas) { + $(document).trigger('update-lineas-presupuesto'); + await waitForEvent('update-lineas-presupuesto-completed'); + } + + if (update_servicios) { + $(document).trigger('update-servicios'); + await waitForEvent('update-servicios-completed'); + } + + if (update_envios) { + $(document).trigger('update-envios'); + await waitForEvent('update-envios-completed'); + } + + if (update_resumen) { + $(document).trigger('update-totales'); + await waitForEvent('update-totales-completed'); + } + + if (update_tiradas_alternativas) { + $(document).trigger('update-tiradas-alternativas'); + await waitForEvent('update-tiradas-alternativas-completed'); + } + } + + #cargarPresupuesto() { const self = this; @@ -140,14 +200,9 @@ class PresupuestoAdminEdit { $('#comentariosProduccion').val(response.data.comentarios_produccion); self.tiradasAlternativas.cargar(response.data.tiradasAlternativas); - - /*self.direcciones.handleChangeCliente(); - self.direcciones.cargarDatos(response.data.direcciones, response.data.datosGenerales); + self.resumen.cargar(response.data.resumen); - self.disenioInterior.cargarDatos(response.data.interior, response.data.datosGenerales.papelInteriorDiferente); - self.disenioCubierta.cargarDatos(response.data.cubierta, response.data.guardas, response.data.sobrecubierta); - */ setTimeout(() => { $('#loader').modal('hide'); @@ -187,7 +242,7 @@ class PresupuestoAdminEdit { cantidad_total += parseInt(rowData.paginas) }) htmlString = '' - + if (cantidad_total != parseInt($('#paginas').val())) { htmlString = `