From af25237fa52eb30b87e9b1fc6d8de90f9aa1a504 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Thu, 20 Mar 2025 22:26:48 +0100 Subject: [PATCH 1/2] modificado el listado. faltan los selects --- ci4/app/Config/Routes.php | 2 +- ci4/app/Controllers/Facturacion/Facturas.php | 435 ++++++++++++------ ci4/app/Models/Facturas/FacturaModel.php | 48 +- .../vuexy/form/facturas/viewFacturasList.php | 336 +++----------- 4 files changed, 387 insertions(+), 434 deletions(-) diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 77d018b3..ce84fa2a 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -769,7 +769,7 @@ $routes->resource('albaranes', ['namespace' => 'App\Controllers\Pedidos', 'contr $routes->group('facturas', ['namespace' => 'App\Controllers\Facturacion'], function ($routes) { $routes->get('list', 'Facturas::list', ['as' => 'facturasList']); - $routes->post('datatable', 'Facturas::datatable', ['as' => 'dataTableOfFacturas']); + $routes->get('datatable', 'Facturas::datatable', ['as' => 'dataTableOfFacturas']); $routes->get('add', 'Facturas::add', ['as' => 'newFactura']); $routes->post('add', 'Facturas::add', ['as' => 'createFactura']); $routes->get('edit/(:any)', 'Facturas::edit/$1', ['as' => 'editarFactura']); diff --git a/ci4/app/Controllers/Facturacion/Facturas.php b/ci4/app/Controllers/Facturacion/Facturas.php index e2755e8e..676ae45a 100755 --- a/ci4/app/Controllers/Facturacion/Facturas.php +++ b/ci4/app/Controllers/Facturacion/Facturas.php @@ -6,7 +6,7 @@ use App\Models\Facturas\FacturaModel; use App\Entities\Facturas\FacturaEntity; use App\Models\Clientes\ClienteModel; use App\Models\Collection; - +use Hermawan\DataTables\DataTable; class Facturas extends \App\Controllers\BaseResourceController { @@ -26,9 +26,9 @@ class Facturas extends \App\Controllers\BaseResourceController { $this->viewData['pageTitle'] = lang('Facturas.facturas'); // Se indica que este controlador trabaja con soft_delete - + $this->viewData = ['usingServerSideDataTable' => true]; - + // Breadcrumbs $this->viewData['breadcrumb'] = [ ['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false], @@ -47,7 +47,7 @@ class Facturas extends \App\Controllers\BaseResourceController $user = $model_user->find(auth()->user()->id); $clienteId = $user->cliente_id; } else { - $clienteId = 0; + $clienteId = -1; } $this->viewData['cliente_id'] = $clienteId; @@ -58,10 +58,10 @@ class Facturas extends \App\Controllers\BaseResourceController parent::index(); } - + public function list() { - + $viewData = [ 'currentModule' => static::$controllerSlug, 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Facturas.facturas')]), @@ -81,7 +81,7 @@ class Facturas extends \App\Controllers\BaseResourceController $user = $model_user->find(auth()->user()->id); $clienteId = $user->cliente_id; } else { - $clienteId = 0; + $clienteId = -1; } $viewData['cliente_id'] = $clienteId; @@ -92,16 +92,16 @@ class Facturas extends \App\Controllers\BaseResourceController public function add() { - if ($this->request->getPost()) : + if ($this->request->getPost()): $nullIfEmpty = true; // !(phpversion() >= '8.1'); $postData = $this->request->getPost(); $noException = true; - $allData = true; + $allData = true; - if( !isset($postData['cliente_id']) || !isset($postData['serie_id']) ) { + if (!isset($postData['cliente_id']) || !isset($postData['serie_id'])) { $this->viewData['errorMessage'] = lang('Facturas.errors.requiredFields'); $this->session->setFlashdata('formErrors', $this->model->errors()); @@ -113,8 +113,8 @@ class Facturas extends \App\Controllers\BaseResourceController try { $clienteModel = model('App\Models\Clientes\ClienteModel'); $datosCliente = $clienteModel->getClienteDataFacturas($postData['cliente_id']); - if(count($datosCliente)>0){ - // add array data datosCliente to postData + if (count($datosCliente) > 0) { + // add array data datosCliente to postData $postData = array_merge($postData, $datosCliente[0]); } } catch (\Exception $e) { @@ -122,20 +122,20 @@ class Facturas extends \App\Controllers\BaseResourceController $this->dealWithException($e); } - + $sanitizedData = $this->sanitized($postData, $nullIfEmpty); $sanitizedData['user_updated_id'] = auth()->user()->id; $sanitizedData['user_created_id'] = auth()->user()->id; - if(!$sanitizedData['creditoAsegurado']){ + if (!$sanitizedData['creditoAsegurado']) { $sanitizedData['creditoAsegurado'] = 0; } - - if ($allData && $successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : + + if ($allData && $successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) : - if ($this->canValidate()) : + if ($this->canValidate()): try { $successfulResult = $this->model->skipValidation(true)->save($sanitizedData); } catch (\Exception $e) { @@ -148,15 +148,15 @@ class Facturas extends \App\Controllers\BaseResourceController endif; endif; - if ($noException && $successfulResult) : + if ($noException && $successfulResult): $id = $this->model->db->insertID(); $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.'; return redirect()->to(route_to('editarFactura', $id))->with('sweet-success', $message); - - + + endif; // $noException && $successfulResult endif; // ($requestMethod === 'post') @@ -174,7 +174,7 @@ class Facturas extends \App\Controllers\BaseResourceController ['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false], ['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true] ]; - + $this->viewData['usingSelect2'] = true; $validation = \Config\Services::validation(); @@ -187,19 +187,20 @@ class Facturas extends \App\Controllers\BaseResourceController } // end function add() - public function edit($id=null){ - - if ($id == null) : + public function edit($id = null) + { + + if ($id == null): return $this->redirect2listView(); endif; $id = filter_var($id, FILTER_SANITIZE_URL); $factura = $this->model->find($id); - if ($factura == false) : + if ($factura == false): $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Facturas.factura')), $id]); return $this->redirect2listView('sweet-error', $message); endif; - + $this->obtenerDatosFormulario($factura); @@ -209,56 +210,185 @@ class Facturas extends \App\Controllers\BaseResourceController ]; $userModel = model('App\Models\UserModel'); - $factura->created_by = $userModel->getFullName($factura->user_created_id); - $factura->updated_by = $userModel->getFullName($factura->user_updated_id); + $factura->created_by = $userModel->getFullName($factura->user_created_id); + $factura->updated_by = $userModel->getFullName($factura->user_updated_id); $factura->created_at_footer = $factura->created_at ? date(' H:i d/m/Y', strtotime($factura->created_at)) : ''; $factura->updated_at_footer = $factura->updated_at ? date(' H:i d/m/Y', strtotime($factura->updated_at)) : ''; $this->viewData['facturaEntity'] = $factura; - + $this->viewData['boxTitle'] = lang('Basic.global.edit2') . ' ' . lang('Facturas.factura') . ' ' . lang('Basic.global.edit3'); return $this->displayForm(__METHOD__, $id); } + /* + public function datatable() + { - public function datatable(){ + if ($this->request->isAJAX()) { - if ($this->request->isAJAX()) { + $reqData = $this->request->getPost(); + if (!isset($reqData['draw']) || !isset($reqData['columns'])) { + $errstr = 'No data available in response to this specific request.'; + $response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr); + return $response; + } + $start = $reqData['start'] ?? 0; + $length = $reqData['length'] ?? 5; + $search = $reqData['search']['value']; + $requestedOrder = $reqData['order']['0']['column'] ?? 0; + $order = FacturaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0]; + $dir = $reqData['order']['0']['dir'] ?? 'asc'; + $cliente_id = $reqData['cliente_id'] ?? -1; - $reqData = $this->request->getPost(); - if (!isset($reqData['draw']) || !isset($reqData['columns']) ) { - $errstr = 'No data available in response to this specific request.'; - $response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr); - return $response; + $resourceData = $this->model->getResource($search, $cliente_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); + + return $this->respond(Collection::datatable( + $resourceData, + $this->model->getResource("", $cliente_id)->countAllResults(), + $this->model->getResource($search, $cliente_id)->countAllResults() + )); + } else { + return $this->failUnauthorized('Invalid request', 403); } - $start = $reqData['start'] ?? 0; - $length = $reqData['length'] ?? 5; - $search = $reqData['search']['value']; - $requestedOrder = $reqData['order']['0']['column'] ?? 0; - $order = FacturaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0]; - $dir = $reqData['order']['0']['dir'] ?? 'asc'; - $cliente_id = $reqData['cliente_id'] ?? -1; - - $resourceData = $this->model->getResource($search, $cliente_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); - - return $this->respond(Collection::datatable( - $resourceData, - $this->model->getResource("", $cliente_id)->countAllResults(), - $this->model->getResource($search, $cliente_id)->countAllResults() - )); - } else { - return $this->failUnauthorized('Invalid request', 403); } + */ + public function datatable() + { + + if (auth()->user()->inGroup('cliente-admin') || auth()->user()->inGroup('cliente-editor')) { + // Se obtiene el cliente ID a partir del usuario de la sesion + $model_user = model('App\Models\Usuarios\UserModel'); + $user = $model_user->find(auth()->user()->id); + $clienteId = $user->cliente_id; + } else { + $clienteId = -1; + } + + $model = model(FacturaModel::class); + $q = $model->getDatatableQuery($clienteId); + + $result = DataTable::of($q) + ->edit( + "creditoAsegurado", + function ($row, $meta) { + switch ($row->creditoAsegurado) { + case "0": + return lang('Basic.global.no'); + case "1": + return lang('Basic.global.yes'); + default: + return '--'; // Debug + } + } + ) + ->edit( + "estado", + function ($row, $meta) { + switch ($row->estado) { + case "borrador": + return lang('Facturas.borrador'); + case "validada": + return lang('Facturas.validada'); + default: + return '--'; // Debug + } + } + ) + ->edit( + "estado_pago", + function ($row, $meta) { + switch ($row->estado_pago) { + case "pendiente": + return lang('Facturas.pendiente'); + case "pagada": + return lang('Facturas.pagada'); + case "insolvente": + return lang('Facturas.insolvente'); + default: + return '--'; // Debug + } + } + ) + ->edit( + "forma_pago", + function ($row, $meta) { + switch ($row->forma_pago) { + case "cheque": + return lang('Facturas.cheque'); + case "compensada": + return lang('Facturas.compensada'); + case "confirming": + return lang('Facturas.confirming'); + case "giroDomiciliado": + return lang('Facturas.giroDomiciliado'); + case "pagare": + return lang('Facturas.pagare'); + case "transferencia": + return lang('Facturas.transferencia'); + default: + return $row->forma_pago; // Debug + + } + } + ) + ->add("action", callback: function ($q) { + if ($q->estado == 'borrador') { + return ' + +
+ +
+ '; + } else { + return ' + +
+ +
+ '; + } + }); + if ($clienteId != -1) { + $result->hide('cliente'); + $result->hide('creditoAsegurado'); + $result->hide('estado'); + $result->hide('estado_pago'); + $result->hide('forma_pago'); + $result->hide('vencimiento'); + $result->hide('dias_vencimiento'); + } + + //return $result->toJson(returnAsObject: true); + + // Obtener el resultado como array para inspeccionarlo + $jsonResult = $result->toJson(returnAsObject: true); + $data = json_decode($jsonResult->getBody(), true); + + // Verificar si "data" contiene solo una fila vacía + if (empty($data['data']) || (count($data['data']) === 1 && $data['data'][0]['id'] === null)) { + return $this->response->setJSON([ + 'draw' => $data['draw'] ?? $this->request->getVar('draw') ?? 0, + 'recordsTotal' => $data['recordsTotal'] ?? 0, + 'recordsFiltered' => 0, + 'data' => [] + ]); + } + + // Si hay datos válidos, devolver el resultado original + return $jsonResult; + } - public function datatablePedidos(){ + public function datatablePedidos() + { if ($this->request->isAJAX()) { $reqData = $this->request->getPost(); - if (!isset($reqData['draw']) || !isset($reqData['columns']) ) { + if (!isset($reqData['draw']) || !isset($reqData['columns'])) { $errstr = 'No data available in response to this specific request.'; - $response = $this->respond(Collection::datatable( [], 0, 0, $errstr ), 400, $errstr); + $response = $this->respond(Collection::datatable([], 0, 0, $errstr), 400, $errstr); return $response; } $start = $reqData['start'] ?? 0; @@ -282,13 +412,14 @@ class Facturas extends \App\Controllers\BaseResourceController } } - public function update($id = null){ + public function update($id = null) + { if ($this->request->isAJAX()) { $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); - if ($id == null) : + if ($id == null): $data = [ 'error' => 2, $csrfTokenName => $newTokenHash @@ -298,7 +429,7 @@ class Facturas extends \App\Controllers\BaseResourceController $id = filter_var($id, FILTER_SANITIZE_URL); $facturaEntity = $this->model->find($id); - if ($facturaEntity == false) : + if ($facturaEntity == false): $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Factura.factura')), $id]); $data = [ 'error' => $message, @@ -307,21 +438,21 @@ class Facturas extends \App\Controllers\BaseResourceController return $this->respond($data); endif; - if ($this->request->getPost()) : + if ($this->request->getPost()): $nullIfEmpty = true; // !(phpversion() >= '8.1'); $postData = $this->request->getPost(); $sanitizedData = $this->sanitized($postData, $nullIfEmpty); - + // JJO $sanitizedData['user_updated_id'] = auth()->user()->id; $noException = true; - if ($successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : + if ($successfulResult = $this->canValidate()): // if ($successfulResult = $this->validate($this->formValidationRules) ) : - if ($this->canValidate()) : + if ($this->canValidate()): try { $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData); } catch (\Exception $e) { @@ -337,7 +468,7 @@ class Facturas extends \App\Controllers\BaseResourceController $facturaEntity->fill($sanitizedData); endif; - if ($noException && $successfulResult) : + if ($noException && $successfulResult): $id = $facturaEntity->id ?? $id; $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.'; @@ -355,24 +486,23 @@ class Facturas extends \App\Controllers\BaseResourceController $csrfTokenName => $newTokenHash ]; return $this->respond($data); - } - else { + } else { return $this->failUnauthorized('Invalid request', 403); } } - public function menuPedidosPendientes($cliente_id){ + public function menuPedidosPendientes($cliente_id) + { if ($this->request->isAJAX()) { $model = model('\App\Models\Pedidos\PedidoLineaModel'); - + $pedidos = []; - try{ + try { $pedidos = $model->obtenerLineasPedidoSinFacturar($cliente_id); - } - catch(Exception $e){ - + } catch (Exception $e) { + } $newTokenHash = csrf_hash(); @@ -382,14 +512,14 @@ class Facturas extends \App\Controllers\BaseResourceController $csrfTokenName => $newTokenHash ]; return $this->respond($data); - } - else { + } else { return $this->failUnauthorized('Invalid request', 403); } } - public function duplicate($factura_id = 0){ - if($this->request->isAJAX()){ + public function duplicate($factura_id = 0) + { + if ($this->request->isAJAX()) { $factura_origen = $this->model->find($factura_id); // se quita la key "id" del objeto @@ -412,18 +542,19 @@ class Facturas extends \App\Controllers\BaseResourceController 'id' => $id, $csrfTokenName => $newTokenHash ]; - return $this->respond($data); + return $this->respond($data); - }else{ + } else { return $this->failUnauthorized('Invalid request', 403); } } - public function updateTotales($factura_id = 0){ - if($this->request->isAJAX()){ + public function updateTotales($factura_id = 0) + { + if ($this->request->isAJAX()) { $postData = $this->request->getPost(); - + $pendiente = $postData['pendiente'] ?? 0; $total = $postData['total'] ?? 0; @@ -433,7 +564,7 @@ class Facturas extends \App\Controllers\BaseResourceController 'pendiente' => $pendiente, 'total_pagos' => $postData['total_pagos'] ?? 0, 'user_updated_id' => auth()->user()->id, - 'estado_pago' => (intval($pendiente)==0 && intval($total)!=0) ? 'pagada' : 'pendiente', + 'estado_pago' => (intval($pendiente) == 0 && intval($total) != 0) ? 'pagada' : 'pendiente', ]; $newTokenHash = csrf_hash(); @@ -441,23 +572,23 @@ class Facturas extends \App\Controllers\BaseResourceController $data_ret = [ $csrfTokenName => $newTokenHash ]; - - if($factura_id == 0){ - return $this->respond($data_ret); + + if ($factura_id == 0) { + return $this->respond($data_ret); } $data_ret['estado_pago'] = $data['estado_pago']; $model = model('\App\Models\Facturas\FacturaModel'); $model->update($factura_id, $data); - return $this->respond($data_ret); - } - else { + return $this->respond($data_ret); + } else { return $this->failUnauthorized('Invalid request', 403); } } - public function addExcedentes($factura_id){ + public function addExcedentes($factura_id) + { if ($this->request->isAJAX()) { $model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel'); @@ -472,26 +603,26 @@ class Facturas extends \App\Controllers\BaseResourceController $pedido_linea_maquetacion_id = $postData['pedido_linea_maquetacion_id'] ?? null; $pedido_id = $postData['pedido_id'] ?? 0; - $nuevo_precio_unidad = round($precio_unidad*(100-floatval($descuento))/100, 4); + $nuevo_precio_unidad = round($precio_unidad * (100 - floatval($descuento)) / 100, 4); $base = round($cantidad * $nuevo_precio_unidad, 2); $total_iva = round($base * $iva / 100, 2); - $data = (object)[ - 'factura_id'=>$factura_id, - 'pedido_linea_impresion_id'=>$pedido_linea_impresion_id, - 'pedido_linea_maquetacion_id'=>$pedido_linea_maquetacion_id, - 'descripcion'=>$newString = preg_replace_callback('/Impresión de (\d+) ejemplares/', function ($matches) use ($cantidad) { - return 'Impresión de ' . $cantidad . ' ejemplares'; - }, $descripcion), - 'cantidad'=>$cantidad, - 'precio_unidad'=> $nuevo_precio_unidad, + $data = (object) [ + 'factura_id' => $factura_id, + 'pedido_linea_impresion_id' => $pedido_linea_impresion_id, + 'pedido_linea_maquetacion_id' => $pedido_linea_maquetacion_id, + 'descripcion' => $newString = preg_replace_callback('/Impresión de (\d+) ejemplares/', function ($matches) use ($cantidad) { + return 'Impresión de ' . $cantidad . ' ejemplares'; + }, $descripcion), + 'cantidad' => $cantidad, + 'precio_unidad' => $nuevo_precio_unidad, 'iva' => $iva, 'base' => $base, 'total_iva' => $total_iva, 'total' => round($base + $total_iva, 2), 'user_updated_id' => auth()->user()->id, ]; - + $model_factura_linea->insert($data); $newTokenHash = csrf_hash(); @@ -499,49 +630,49 @@ class Facturas extends \App\Controllers\BaseResourceController $data_ret = [ $csrfTokenName => $newTokenHash ]; - return $this->respond($data_ret); - } - else { + return $this->respond($data_ret); + } else { return $this->failUnauthorized('Invalid request', 403); } } - - public function addLineaPedidoImpresion($factura_id){ + + public function addLineaPedidoImpresion($factura_id) + { if ($this->request->isAJAX()) { $model_pedido_linea = model('\App\Models\Pedidos\PedidoLineaModel'); $model_presupuesto = model('\App\Models\Presupuestos\PresupuestoModel'); $model_factura_linea = model('\App\Models\Facturas\FacturaLineaModel'); - - try{ + + try { $pedido_linea_id = $this->request->getPost('lineaPedido') ?? 0; $linea = $model_pedido_linea->find($pedido_linea_id); $factura = $this->model->find($factura_id); - - if($factura){ - if($linea){ + if ($factura) { + + if ($linea) { $presupuesto = $model_presupuesto->find($linea->presupuesto_id); - if($presupuesto){ + if ($presupuesto) { // Se añade la linea de factura $descripcion = $model_presupuesto->generarLineaPedido($presupuesto->id, true, $linea->pedido_id); $cantidad = intval($presupuesto->tirada) - intval($this->model->getCantidadLineaPedidoFacturada($linea->id)); $base = $cantidad * floatval($presupuesto->total_precio_unidad); $base = round($base, 2); - $total_iva = $base * ($presupuesto->iva_reducido==1 ? 0.04 : 0.21); + $total_iva = $base * ($presupuesto->iva_reducido == 1 ? 0.04 : 0.21); // se redondea a dos decimales $total_iva = round($total_iva, 2); $total = $base + $total_iva; - $data = (object)[ - 'factura_id'=>$factura_id, - 'pedido_linea_impresion_id'=>$linea->pedido_id, - 'descripcion'=>$descripcion[0]->concepto, - 'cantidad'=>$cantidad, - 'precio_unidad'=>$presupuesto->total_precio_unidad, - 'iva' => $presupuesto->iva_reducido==1 ? 4 : 21, + $data = (object) [ + 'factura_id' => $factura_id, + 'pedido_linea_impresion_id' => $linea->pedido_id, + 'descripcion' => $descripcion[0]->concepto, + 'cantidad' => $cantidad, + 'precio_unidad' => $presupuesto->total_precio_unidad, + 'iva' => $presupuesto->iva_reducido == 1 ? 4 : 21, 'base' => $base, 'total_iva' => $total_iva, 'total' => $total, @@ -552,10 +683,10 @@ class Facturas extends \App\Controllers\BaseResourceController $id = $model_factura_linea->getInsertID(); - if($id){ + if ($id) { $model_factura_linea->addFacturaPedidoLinea($factura_id, $linea->id, $cantidad); - + $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); $data = [ @@ -568,9 +699,8 @@ class Facturas extends \App\Controllers\BaseResourceController } } } - } - catch(Exception $e){ - + } catch (Exception $e) { + } $newTokenHash = csrf_hash(); @@ -579,13 +709,13 @@ class Facturas extends \App\Controllers\BaseResourceController $csrfTokenName => $newTokenHash ]; return $this->respond($data); - } - else { + } else { return $this->failUnauthorized('Invalid request', 403); } } - public function deleteLineaPedidoImpresion(){ + public function deleteLineaPedidoImpresion() + { if ($this->request->isAJAX()) { @@ -603,20 +733,20 @@ class Facturas extends \App\Controllers\BaseResourceController $csrfTokenName => $newTokenHash ]; return $this->respond($data); - } - else { + } else { return $this->failUnauthorized('Invalid request', 403); } } - - public function validar($factura_id){ - if($this->request->isAJAX()){ + public function validar($factura_id) + { + + if ($this->request->isAJAX()) { $factura = $this->model->find($factura_id); - if($factura){ + if ($factura) { $model_series = model('\App\Models\Configuracion\SeriesFacturasModel'); $numero = $model_series->getSerieNumerada($factura->serie_id); @@ -626,13 +756,13 @@ class Facturas extends \App\Controllers\BaseResourceController 'user_updated_id' => auth()->user()->id, ]; - if((strpos($numero, "REC ") === 0)){ - $data['estado_pago'] = 'pagada'; + if ((strpos($numero, "REC ") === 0)) { + $data['estado_pago'] = 'pagada'; } $this->model->update($factura_id, $data); } - + $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); @@ -640,30 +770,30 @@ class Facturas extends \App\Controllers\BaseResourceController $csrfTokenName => $newTokenHash ]; return $this->respond($data); - } - else { + } else { return $this->failUnauthorized('Invalid request', 403); } } - public function updateCabecera($factura_id){ - - if($this->request->isAJAX()){ - if($factura_id == 0){ + public function updateCabecera($factura_id) + { + + if ($this->request->isAJAX()) { + if ($factura_id == 0) { return; } $factura = $this->model->find($factura_id); - if($factura){ + if ($factura) { $postData = $this->request->getPost(); $dataName = $postData['name'] ?? ''; $dataValue = $postData['value'] ?? ''; - if($dataName == 'factura_rectificativa_id'){ + if ($dataName == 'factura_rectificativa_id') { // se actualiza la factura donde el campo 'numero' sea igual al valor de $dataValue. El campo a actualizar es 'factura_rectificada_id' $factura_rectificada = $this->model->where('numero', $dataValue)->first(); - if($factura_rectificada){ + if ($factura_rectificada) { $data2 = [ 'factura_rectificada_id' => $factura->numero, 'user_updated_id' => auth()->user()->id, @@ -686,8 +816,7 @@ class Facturas extends \App\Controllers\BaseResourceController ]; return $this->respond($data); } - } - else { + } else { return $this->failUnauthorized('Invalid request', 403); } } @@ -696,12 +825,13 @@ class Facturas extends \App\Controllers\BaseResourceController * FUNCIONES AUXILIARES ************************************/ - private function obtenerDatosFormulario(&$factura){ - - if($factura->estado == 'borrador'){ + private function obtenerDatosFormulario(&$factura) + { + + if ($factura->estado == 'borrador') { $serieModel = model('App\Models\Configuracion\SeriesFacturasModel'); $serie = $serieModel->find($factura->serie_id); - if($serie){ + if ($serie) { $factura->numero = str_replace("{numero}", $serie->next, $serie->formato); } } @@ -716,9 +846,8 @@ class Facturas extends \App\Controllers\BaseResourceController $formaPagoModel = model('App\Models\Configuracion\FormaPagoModel'); $factura->formas_pago = $formaPagoModel->getMenuItems(); - + $factura->fecha_factura_at_text = $factura->fecha_factura_at ? date('d/m/Y', strtotime($factura->fecha_factura_at)) : ''; } } - \ No newline at end of file diff --git a/ci4/app/Models/Facturas/FacturaModel.php b/ci4/app/Models/Facturas/FacturaModel.php index 80cc59e6..bf4fd2e2 100644 --- a/ci4/app/Models/Facturas/FacturaModel.php +++ b/ci4/app/Models/Facturas/FacturaModel.php @@ -2,7 +2,10 @@ namespace App\Models\Facturas; -class FacturaModel extends \App\Models\BaseModel { +use CodeIgniter\Database\BaseBuilder; + +class FacturaModel extends \App\Models\BaseModel +{ protected $table = 'facturas'; @@ -71,8 +74,8 @@ class FacturaModel extends \App\Models\BaseModel { protected $updatedField = "updated_at"; public static $labelField = "id"; - - public function getResource(string $search = "", $cliente_id=-1) + + public function getResource(string $search = "", $cliente_id = -1) { $builder = $this->db ->table($this->table . " t1") @@ -88,16 +91,16 @@ class FacturaModel extends \App\Models\BaseModel { $builder->join("clientes t2", "t2.id = t1.cliente_id", "left"); $builder->join("facturas_pagos t3", "t3.factura_id = t1.id", "left"); $builder->join("formas_pago t4", "t3.forma_pago_id = t4.id", "left"); - + $builder->where("t1.deleted_at IS NULL"); - if(auth()->user()->inGroup("cliente-admin") || auth()->user()->inGroup("cliente-editor")) { + if (auth()->user()->inGroup("cliente-admin") || auth()->user()->inGroup("cliente-editor")) { $builder->where("t1.estado", "validada"); } - if($cliente_id != -1) { + if ($cliente_id != -1) { $builder->where("t1.cliente_id", $cliente_id); } - + $builder->groupBy("t1.id"); // Agrupa por id de la factura return empty($search) @@ -109,6 +112,35 @@ class FacturaModel extends \App\Models\BaseModel { ->groupEnd(); } + public function getDatatableQuery($cliente_id): BaseBuilder + { + $builder = $this->db + ->table($this->table . " t1") + ->select( + "t1.id AS id, t1.numero AS numero, DATE_FORMAT(t1.fecha_factura_at, '%d/%m/%Y') AS fecha_factura_at, + t2.nombre AS cliente, t1.base AS base, t1.total AS total, t1.pendiente AS pendiente, + t1.creditoAsegurado AS creditoAsegurado, t1.estado AS estado, t1.estado_pago AS estado_pago, + GROUP_CONCAT(DISTINCT t4.nombre ORDER BY t4.nombre ASC SEPARATOR ', ') AS forma_pago, + DATE_FORMAT(MIN(CASE WHEN t3.fecha_vencimiento_at != '0000-00-00 00:00:00' THEN t3.fecha_vencimiento_at ELSE NULL END), '%d/%m/%Y') AS vencimiento, + t2.vencimiento AS dias_vencimiento" + ); + $builder->join("clientes t2", "t2.id = t1.cliente_id", "left"); + $builder->join("facturas_pagos t3", "t3.factura_id = t1.id", "left"); + $builder->join("formas_pago t4", "t3.forma_pago_id = t4.id", "left"); + $builder->where("t1.deleted_at", null); + + $builder->where("t1.deleted_at IS NULL"); + if (auth()->user()->inGroup("cliente-admin") || auth()->user()->inGroup("cliente-editor")) { + $builder->where("t1.estado", "validada"); + } + + if ($cliente_id != -1) { + $builder->where("t1.cliente_id", $cliente_id); + } + + return $builder; + } + /** * Get resource data for creating PDFs. @@ -164,7 +196,7 @@ class FacturaModel extends \App\Models\BaseModel { $builder->where("t6.id", $pedido_id); $builder->groupBy("t1.id"); // Agrupa por id de la factura - + return $builder; } diff --git a/ci4/app/Views/themes/vuexy/form/facturas/viewFacturasList.php b/ci4/app/Views/themes/vuexy/form/facturas/viewFacturasList.php index 2741c977..87a54bee 100644 --- a/ci4/app/Views/themes/vuexy/form/facturas/viewFacturasList.php +++ b/ci4/app/Views/themes/vuexy/form/facturas/viewFacturasList.php @@ -1,301 +1,93 @@ -include('themes/_commonPartialsBs/datatables') ?> +include('themes/_commonPartialsBs/datatables') ?> include('themes/_commonPartialsBs/_confirm2delete') ?> -extend('themes/vuexy/main/defaultlayout') ?> -section('content'); ?> +extend('themes/vuexy/main/defaultlayout') ?> +section('content'); ?>
-

-
+

+
- + - - - - - - + + +
+ + + + + + - - - + + + + + - - - - + + + + + + + + + + + + + + + + + + + + + + + + - -
+ +
-endSection() ?> +endSection() ?> -section('additionalInlineJs') ?> - - const lastColNr = $('#tableOfFacturas').find("tr:first th").length - 1; - const actionBtns = function(data) { - if(data.estado == 'borrador'){ - return ` - -
- -
- `; - } - else{ - return ` - -
- -
- `; - } - }; - - theTable = $('#tableOfFacturas').DataTable({ - processing: true, - serverSide: true, - autoWidth: true, - responsive: true, - scrollX: true, - lengthMenu: [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ], - pageLength: 250, - lengthChange: true, - "dom": 'lfBrtip', - buttons: [ - { - text: 'Exportar Excel Contaplus', - action: function (e, dt, button, config) { - var searchValue = theTable.search(); // Captura el valor del campo de búsqueda - var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla - - console.log(searchValue); - - /* - $.ajax({ - url: '/ruta/exportarExcel', // URL del servidor para manejar la exportación - type: 'POST', - data: { - search: searchValue, - extraParams: ajaxParams - }, - xhrFields: { - responseType: 'blob' // Para manejar la descarga del archivo - }, - success: function(blob, status, xhr) { - // Crear un enlace temporal para descargar el archivo - var link = document.createElement('a'); - var url = window.URL.createObjectURL(blob); - link.href = url; - link.download = 'datos_personalizados.xlsx'; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - window.URL.revokeObjectURL(url); - } - }); - */ - } - }, - { - text: 'Exportar Lineas a Excel', - action: function (e, dt, button, config) { - var searchValue = theTable.search(); // Captura el valor del campo de búsqueda - var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla - - console.log(searchValue); - - } - }, - { - text: 'Exportar Girosgit ', - action: function (e, dt, button, config) { - var searchValue = theTable.search(); // Captura el valor del campo de búsqueda - var ajaxParams = theTable.ajax.params(); // Captura otros parámetros de la tabla - - console.log(searchValue); - - } - } - ], - stateSave: true, - order: [[0, 'asc']], - language: { - url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" - }, - ajax : $.fn.dataTable.pipeline( { - url: '', - method: 'POST', - data: function(d, settings){ - d.cliente_id = ""; - }, - headers: {'X-Requested-With': 'XMLHttpRequest'}, - async: true, - }), - columnDefs: [ - { - orderable: false, - searchable: false, - targets: [lastColNr] - } - ], - columns : [ - { 'data': 'id' }, - { 'data': 'numero' }, - { 'data': 'fecha_factura_at' }, - { 'data': 'cliente' }, - { 'data': 'base' ,render : (d) => `${d}`}, - { 'data': 'total',render : (d) => `${d}`}, - { 'data': 'pendiente',render : (d) => `${d}` }, - { 'data': 'creditoAsegurado' , - render: function(data, type, row, meta) { - switch(data){ - case "0": - return ''; - break; - - case "1": - return ''; - break; - - default: - return '--'; // Debug - break; - - } - }, - }, - { 'data': 'estado', - render: function(data, type, row, meta) { - switch(data){ - case "borrador": - return ''; - break; - - case "validada": - return ''; - break; - - default: - return '--'; // Debug - break; - - } - } - }, - { 'data': 'estado_pago', - render: function(data, type, row, meta) { - switch(data){ - case "pendiente": - return ''; - break; - - case "pagada": - return ''; - break; - - case "insolvente": - return ''; - break; - - default: - return '--'; // Debug - break; - - } - } - }, - { 'data': 'forma_pago', - render: function(data, type, row, meta) { - switch(data){ - case "cheque": - return ''; - break; - - case "compensada": - return ''; - break; - - case "confirming": - return ''; - break; - - case "giroDomiciliado": - return ''; - break; - - case "pagare": - return ''; - break; - - case "transferencia": - return ''; - break; - - default: - return data; // Debug - break; - - } - } - }, - { 'data': 'vencimiento' }, - { 'data': 'dias_vencimiento' }, - { 'data': actionBtns } - ] - }); - - theTable.on( 'draw.dt', function () { - if( != -1){ - theTable.column(3).visible(false); - theTable.column(7).visible(false); - theTable.column(8).visible(false); - theTable.column(9).visible(false); - theTable.column(10).visible(false); - theTable.column(11).visible(false); - theTable.column(12).visible(false); - } - }); - - - $(document).on('click', '.btn-edit', function(e) { - var url = ''; - url = url.replace(':id', `${$(this).attr('data-id')}` ); - window.location.href = url; - }); - - -endSection() ?> - - -section('css') ?> - "> -endSection() ?> +section('css') ?> +"> +endSection() ?> section('additionalExternalJs') ?> - - - - - - - -endSection() ?> + + + + + + + + +endSection() ?> \ No newline at end of file From e1d208a4ddfbe4ab281db4b305533404168a2b02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Fri, 21 Mar 2025 18:27:31 +0100 Subject: [PATCH 2/2] resuelto problema presupuesto cliente --- .../Presupuestos/Presupuestocliente.php | 67 ++++++++++--------- ci4/app/Language/es/App.php | 1 + .../Models/Presupuestos/PresupuestoModel.php | 10 +-- .../presupuestos/cliente/items/_resumen.php | 8 ++- .../vuexy/main/menus/presupuesto_menu.php | 38 ++++++----- .../presupuestoAdmin/sections/resumen.js | 56 ++++++++-------- .../presupuestoCliente/presupuestoCliente.js | 8 ++- .../pages/presupuestoCliente/resumen.js | 24 +++++-- .../tarjetaTiradasPrecio.js | 14 +++- 9 files changed, 134 insertions(+), 92 deletions(-) diff --git a/ci4/app/Controllers/Presupuestos/Presupuestocliente.php b/ci4/app/Controllers/Presupuestos/Presupuestocliente.php index e7741ab0..b25d3db9 100755 --- a/ci4/app/Controllers/Presupuestos/Presupuestocliente.php +++ b/ci4/app/Controllers/Presupuestos/Presupuestocliente.php @@ -605,8 +605,16 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } } + // para el calculo del precio unidad, sólo se tiene en cuenta el envío base + for ($i = 0; $i < count($tirada); $i++) { + $coste_envio = 0.0; + $coste_envio += ($return_data['eb'][$i] / $tirada[$i]); + $return_data['precio_u'][$i] = round(floatval($return_data['precio_u'][$i]) + $coste_envio, 4); + } $envio_base = true; + $coste_envio = 0.0; // se inicializa para calcular los costes de envíos restantes si es que hay + $return_data['coste_envio'] = []; if (count($direcciones) > 0) { for ($i = 0; $i < count($tirada); $i++) { @@ -614,8 +622,6 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController foreach ($direcciones as $direccion) { // El primer envio no se calcula ya que se añade el base if ($envio_base) { - //aporte del envio al precio unidad - $coste_envio += ($return_data['eb'][$i] / $tirada[$i]); $envio_base = false; continue; } @@ -651,19 +657,17 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController ]; return $return_data; } else { - //aporte del envio al precio unidad - $coste_envio += ($coste_direccion->coste / $tirada[$i]); + // Se añade a los costes de envío + $coste_envio += $coste_direccion->coste; } } - $return_data['precio_u'][$i] = round(floatval($return_data['precio_u'][$i]) + $coste_envio, 4); + + $return_data['coste_envio'][$i] = round($coste_envio, 2); } - } else { - for ($i = 0; $i < count($tirada); $i++) { - $coste_envio = 0.0; - $coste_envio += ($return_data['eb'][$i] / $tirada[$i]); - $return_data['precio_u'][$i] = round(floatval($return_data['precio_u'][$i]) + $coste_envio, 4); - } - } + } + + + if ($this->request) { if ($this->request->isAJAX()) return $this->respond($return_data); @@ -1158,6 +1162,18 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $resultado_presupuesto['info']['totales'][$i]['coste_envio'] = 0.0; $resultado_presupuesto['info']['totales'][$i]['margen_envio'] = 0.0; } + + // para el calculo del precio unidad, sólo se tiene en cuenta el envío base + for ($i = 0; $i < count($tirada); $i++) { + $coste_envio = 0.0; + $coste_envio += ($resultado_presupuesto['eb'][$i] / $tirada[$i]); + $resultado_presupuesto['info']['totales'][$i]['envio_base_coste'] = $resultado_presupuesto['eb'][$i] - $resultado_presupuesto['eb_margen'][$i]; + $resultado_presupuesto['info']['totales'][$i]['envio_base_margen'] = $resultado_presupuesto['eb_margen'][$i]; + $resultado_presupuesto['precio_u'][$i] = round(floatval($resultado_presupuesto['precio_u'][$i]) + $coste_envio, 4); + } + + $coste_envio = 0.0; // se inicializa para calcular los costes de envíos restantes si es que hay + $resultado_presupuesto['coste_envio'] = []; if (count($direcciones) > 0) { for ($i = 0; $i < count($tirada); $i++) { @@ -1168,11 +1184,6 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController foreach ($direcciones as $direccion) { // El primer envio no se calcula ya que se añade el base if ($envio_base) { - //aporte del envio al precio unidad - $coste_envio += ($resultado_presupuesto['eb'][$i] / $tirada[$i]); - $margen_envio += ($resultado_presupuesto['eb_margen'][$i] / $tirada[$i]); - $resultado_presupuesto['info']['totales'][$i]['coste_envio'] += $resultado_presupuesto['eb'][$i] - $resultado_presupuesto['eb_margen'][$i]; - $resultado_presupuesto['info']['totales'][$i]['margen_envio'] += $resultado_presupuesto['eb_margen'][$i]; $envio_base = false; continue; } @@ -1212,18 +1223,9 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } } - $resultado_presupuesto['precio_u'][$i] = round(floatval($resultado_presupuesto['precio_u'][$i]) + $coste_envio, 4); + $resultado_presupuesto['coste_envio'][$i] = round($coste_envio, 2); } - } else { - for ($i = 0; $i < count($tirada); $i++) { - $coste_envio = 0.0; - $coste_envio += ($resultado_presupuesto['eb'][$i] / $tirada[$i]); - $resultado_presupuesto['info']['totales'][$i]['coste_envio'] = $resultado_presupuesto['eb'][$i] - $resultado_presupuesto['eb_margen'][$i]; - $resultado_presupuesto['info']['totales'][$i]['margen_envio'] = $resultado_presupuesto['eb_margen'][$i]; - $resultado_presupuesto['precio_u'][$i] = round(floatval($resultado_presupuesto['precio_u'][$i]) + $coste_envio, 4); - } - } - + } $model_presupuesto = new PresupuestoModel(); $tiradas_alternativas = []; @@ -1240,7 +1242,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $resultado_presupuesto['info']['totales'][$i]['margenPapel'] + $resultado_presupuesto['info']['totales'][$i]['margen_envio']) / ($coste_total + $coste_envio) * 100.0, 2); $total_pedido = round(($coste_total + $resultado_presupuesto['info']['totales'][$i]['totalServicios'] + $resultado_presupuesto['info']['totales'][$i]['margenServicios'] + $coste_envio), 2); - $precio_u = round(($coste_total + $resultado_presupuesto['info']['totales'][$i]['totalServicios'] + $resultado_presupuesto['info']['totales'][$i]['margenServicios'] + $coste_envio) / $tirada[$i], 4); + $precio_u = round( $resultado_presupuesto['precio_u'][$i], 4); array_push($tiradas_alternativas, (object) array( 'tirada' => $tirada[$i], @@ -1252,6 +1254,8 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController )); } else { $resumen_totales = $resultado_presupuesto['info']['totales'][$i]; + $resumen_totales['precio_unidad'] = round($resultado_presupuesto['precio_u'][$i], 4); + } } @@ -1607,7 +1611,10 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } if (intval($presupuesto->estado_id) == 2) { - $data['resumen']['base'] = $presupuesto->total_aceptado; + $data['resumen']['base'] = $presupuesto->total_antes_descuento; + $data['resumen']['total_envio'] = round( + floatval($presupuesto->total_coste_envios) + + floatval($presupuesto->total_margen_envios), 2); $data['resumen']['precio_unidad'] = $presupuesto->total_precio_unidad; } diff --git a/ci4/app/Language/es/App.php b/ci4/app/Language/es/App.php index 3bb95036..5fad7c09 100755 --- a/ci4/app/Language/es/App.php +++ b/ci4/app/Language/es/App.php @@ -754,6 +754,7 @@ return [ "menu_presupuestos_clientes" => "Presupuestos (Clientes)", "menu_presupuesto" => "Libros", "menu_presupuesto_buscador" => "Buscador", + "menu_presupuesto_importador" => "Importador ERP antiguo", "menu_libros" => "Libros", "menu_libros_fresasdo_tapa_dura" => "Fresado tapa dura", "menu_libros_fresasdo_tapa_blanda" => "Fresado tapa blanda", diff --git a/ci4/app/Models/Presupuestos/PresupuestoModel.php b/ci4/app/Models/Presupuestos/PresupuestoModel.php index 341b10b9..de3a817b 100755 --- a/ci4/app/Models/Presupuestos/PresupuestoModel.php +++ b/ci4/app/Models/Presupuestos/PresupuestoModel.php @@ -404,9 +404,9 @@ class PresupuestoModel extends \App\Models\BaseModel $is_cosido = (new TipoPresupuestoModel())->get_isCosido($data['tipo_impresion_id']); $totalCostes = $resumen_totales['totalPapel'] + $resumen_totales['totalImpresion'] + - $resumen_totales['totalServicios'] + $resumen_totales['coste_envio']; + $resumen_totales['totalServicios'] + $resumen_totales['envio_base_coste']; $totalMargenes = $resumen_totales['margenPapel'] + $resumen_totales['margenImpresion'] + - $resumen_totales['margenServicios'] + $resumen_totales['margen_envio']; + $resumen_totales['margenServicios'] + $resumen_totales['envio_base_margen']; $fields = [ 'cliente_id' => $data['clienteId'], @@ -486,9 +486,9 @@ class PresupuestoModel extends \App\Models\BaseModel 'total_descuento' => 0, 'total_descuentoPercent' => 0, - 'total_precio_unidad' => round(($totalCostes + $totalMargenes) / $tirada, 4), - 'total_presupuesto' => round($totalCostes + $totalMargenes, 2), - 'total_aceptado' => round($totalCostes + $totalMargenes, 2), + 'total_precio_unidad' => $resumen_totales['precio_unidad'], + 'total_presupuesto' => round($totalCostes + $totalMargenes + $resumen_totales['coste_envio']+$resumen_totales['margen_envio'], 2), + 'total_aceptado' => round($totalCostes + $totalMargenes + $resumen_totales['coste_envio']+$resumen_totales['margen_envio'], 2), 'total_factor' => round(($totalCostes + $totalMargenes - $resumen_totales['coste_envio'] - $resumen_totales['margen_envio']) / $resumen_totales['sumForFactor'], 2), 'total_factor_ponderado' => round(($totalCostes + $totalMargenes - $resumen_totales['coste_envio'] - $resumen_totales['margen_envio']) / $resumen_totales['sumForFactorPonderado'], 2), diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/items/_resumen.php b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/items/_resumen.php index 7eb9dee7..3f447a46 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/items/_resumen.php +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/items/_resumen.php @@ -5,9 +5,11 @@
Precio unidad:
-

Total base: € -

Iva (%): € -

Total: € +

Total base:

+

Envío:

+

Total antes de I.V.A:

+

Iva (%):

+

Total:

diff --git a/ci4/app/Views/themes/vuexy/main/menus/presupuesto_menu.php b/ci4/app/Views/themes/vuexy/main/menus/presupuesto_menu.php index 0b253bdb..52af9ab7 100644 --- a/ci4/app/Views/themes/vuexy/main/menus/presupuesto_menu.php +++ b/ci4/app/Views/themes/vuexy/main/menus/presupuesto_menu.php @@ -23,27 +23,23 @@ if (auth()->user()->can('presupuesto.menu')) { - - - + \ No newline at end of file diff --git a/httpdocs/assets/js/safekat/pages/presupuestoAdmin/sections/resumen.js b/httpdocs/assets/js/safekat/pages/presupuestoAdmin/sections/resumen.js index cbc1c042..1e152889 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoAdmin/sections/resumen.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoAdmin/sections/resumen.js @@ -18,7 +18,7 @@ class Resumen { await self.updateTotales(); $(document).trigger('update-totales-completed'); }); - $("#totalDespuesDecuento").on('change',this.updateToastSummary.bind(this)) + $("#totalDespuesDecuento").on('change', this.updateToastSummary.bind(this)) } cargar(resumen) { @@ -26,7 +26,7 @@ class Resumen { // Mapear los valores a los elementos HTML por ID $("#totalCostePapel").text(resumen.total_coste_papel.toString().replace('.', ',') + "€" || "0€"); $("#porcentajeMargenPapel").text(resumen.total_margenPercent_papel ? resumen.total_margenPercent_papel.toString().replace('.', ',') + "%" : "0%"); - $("#margenPapel").text(resumen.total_margen_papel.toString().replace('.', ',')+ "€" || "0€"); + $("#margenPapel").text(resumen.total_margen_papel.toString().replace('.', ',') + "€" || "0€"); $("#totalCosteImpresion").text(resumen.total_coste_impresion.toString().replace('.', ',') + "€" || "0€"); $("#porcentajeMargenImpresion").text(resumen.total_margenPercent_impresion ? resumen.total_margenPercent_impresion.toString().replace('.', ',') + "%" : "0%"); @@ -56,7 +56,7 @@ class Resumen { $("#totalAceptado").val(resumen.total_aceptado.toString().replace('.', ',') + "€" || "0€"); } - $('#ivaReducido').val(resumen.iva_reducido ? 1: 0); + $('#ivaReducido').val(resumen.iva_reducido ? 1 : 0); } @@ -100,6 +100,7 @@ class Resumen { let margenServicios = parseFloat(0); let totalEnvios = 0; + let totalEnvios_base = 0; let margenEnvios = 0; let sumForFactor = 0.0; @@ -134,7 +135,7 @@ class Resumen { if (rowData.maquinaTipo == 'inkjet') { totalImpresion += parseFloat(rowData.totalTinta) - totalImpresion += parseFloat(rowData.totalCorte)?? 0; + totalImpresion += parseFloat(rowData.totalCorte) ?? 0; //sumForFactor += (parseFloat(rowData.totalTinta) + parseFloat(rowData.totalCorte)) } @@ -189,7 +190,7 @@ class Resumen { let margen_servicio = parseFloat(rowData.margen); totalServicios += total_servicio let base = self.roundToTwoDecimals(total_servicio / (1 + margen_servicio / 100.0)); - base = self.roundToTwoDecimals(base / parseInt($('#tirada').val()))*parseInt($('#tirada').val()); + base = self.roundToTwoDecimals(base / parseInt($('#tirada').val())) * parseInt($('#tirada').val()); margenServicios += self.roundToTwoDecimals(parseFloat(total_servicio - base)); }); } @@ -201,7 +202,7 @@ class Resumen { let margen_servicio = parseFloat(rowData.margen); totalServicios += total_servicio let base = self.roundToTwoDecimals(total_servicio / (1 + margen_servicio / 100.0)); - base = self.roundToTwoDecimals(base / parseInt($('#tirada').val()))*parseInt($('#tirada').val()); + base = self.roundToTwoDecimals(base / parseInt($('#tirada').val())) * parseInt($('#tirada').val()); margenServicios += self.roundToTwoDecimals(parseFloat(total_servicio - base)); }); } @@ -211,7 +212,7 @@ class Resumen { let rowData = this.data(); let total_servicio = self.roundToTwoDecimals(parseFloat(rowData.precio)); let base = (parseFloat(rowData.precio / (1 + parseFloat(rowData.margen) / 100.0)).toFixed(2)); - base = self.roundToTwoDecimals(base / parseInt($('#tirada').val()))*parseInt($('#tirada').val()); + base = self.roundToTwoDecimals(base / parseInt($('#tirada').val())) * parseInt($('#tirada').val()); margenServicios += self.roundToTwoDecimals(parseFloat(total_servicio - base)); totalServicios += total_servicio }); @@ -222,7 +223,7 @@ class Resumen { let rowData = this.data(); let total_servicio = self.roundToTwoDecimals(parseFloat(rowData.precio)); let base = (parseFloat(rowData.precio / (1 + parseFloat(rowData.margen) / 100.0)).toFixed(2)); - base = self.roundToTwoDecimals(base / parseInt($('#tirada').val()))*parseInt($('#tirada').val()); + base = self.roundToTwoDecimals(base / parseInt($('#tirada').val())) * parseInt($('#tirada').val()); margenServicios += self.roundToTwoDecimals(parseFloat(total_servicio - base)); totalServicios += total_servicio; }); @@ -235,7 +236,7 @@ class Resumen { let margen_servicio = parseFloat(rowData.margen); totalServicios += total_servicio let base = self.roundToTwoDecimals(total_servicio / (1 + margen_servicio / 100.0)); - base = self.roundToTwoDecimals(base / parseInt($('#tirada').val()))*parseInt($('#tirada').val()); + base = self.roundToTwoDecimals(base / parseInt($('#tirada').val())) * parseInt($('#tirada').val()); margenServicios += self.roundToTwoDecimals(parseFloat(total_servicio - base)); }); } @@ -262,15 +263,16 @@ class Resumen { if (updateEnvio) { - totalEnvios = parseFloat($('#envio_base').val()); + totalEnvios_base = parseFloat($('#envio_base').val()); if (typeof $('#tableOfDireccionesEnvio').DataTable() !== 'undefined' && $('#tableOfDireccionesEnvio').DataTable().rows().count() > 0) { $('#tableOfDireccionesEnvio').DataTable().rows().every(function (rowIdx, tableLoop, rowLoop) { - if (rowIdx == 0) { - return; + // el primer envio es el base, y no se debe de cobrar + if (rowIdx != 0) { + + let data = this.data() + totalEnvios += parseFloat(data.precio) + margenEnvios += parseFloat((data.precio) * data.margen / 100) } - let data = this.data() - totalEnvios += parseFloat(data.precio) - margenEnvios += parseFloat((data.precio) * data.margen / 100) }); } @@ -298,10 +300,11 @@ class Resumen { if ($('#total_descuentoPercent').val() < 0) { $('#total_descuentoPercent').val(0) } - let totalAntesDescuento = totalCostes + totalMargenes + let totalAntesDescuento = totalCostes + totalMargenes - parseFloat(totalEnvios.toFixed(2)) + totalEnvios_base; let totalDescuento = totalAntesDescuento * parseInt($('#total_descuentoPercent').val() || 0) / 100 - let totalPresupuesto = totalAntesDescuento - totalDescuento + let totalPresupuesto = totalAntesDescuento - totalDescuento; // para el calculo del precio_u solo se tiene en cuenta el base let precioUnidad = totalPresupuesto / parseInt($('#tirada').val()) + totalPresupuesto += totalEnvios; $('#totalAntesDescuento').text((this.addSeparatorsNF(totalAntesDescuento.toFixed(2), ".", ",", ".")) + "€") $('#descuentoTotal').text((this.addSeparatorsNF(totalDescuento.toFixed(2), ".", ",", ".")) + "€") @@ -313,15 +316,15 @@ class Resumen { $('#precioUnidadPresupuesto').attr('val', (precioUnidad).toFixed(4)) $('#totalDespuesDecuento').trigger("change") - $('#factor').text(this.addSeparatorsNF(((totalPresupuesto - totalEnvios - margenEnvios) / sumForFactor).toFixed(2), ".", ",", ".")) - $('#factor').attr('val', ((totalPresupuesto - totalEnvios - margenEnvios) / sumForFactor).toFixed(2)) - $('#factor_ponderado').text(this.addSeparatorsNF(((totalPresupuesto - totalEnvios - margenEnvios) / sumForFactorPonderado).toFixed(2), ".", ",", ".")) - $('#factor_ponderado').attr('val', ((totalPresupuesto - totalEnvios - margenEnvios) / sumForFactorPonderado).toFixed(2)) + $('#factor').text(this.addSeparatorsNF(((totalPresupuesto - totalEnvios - totalEnvios_base - margenEnvios) / sumForFactor).toFixed(2), ".", ",", ".")) + $('#factor').attr('val', ((totalPresupuesto - totalEnvios - totalEnvios_base - margenEnvios) / sumForFactor).toFixed(2)) + $('#factor_ponderado').text(this.addSeparatorsNF(((totalPresupuesto - totalEnvios - totalEnvios_base - margenEnvios) / sumForFactorPonderado).toFixed(2), ".", ",", ".")) + $('#factor_ponderado').attr('val', ((totalPresupuesto - totalEnvios - totalEnvios_base - margenEnvios) / sumForFactorPonderado).toFixed(2)) } - getData(){ + getData() { let data = { 'total_coste_papel': $('#totalCostePapel').text().replace('€', '').replace(',', '.'), @@ -354,7 +357,7 @@ class Resumen { 'iva_reducido': $('#ivaReducido').val() }; - if($('#confirmar_presupuesto').prop('checked')){ + if ($('#confirmar_presupuesto').prop('checked')) { data.confirmar = '1'; data.total_aceptado = $('#totalDespuesDecuento').text().replace('€', '').replace(',', '.'); } @@ -365,15 +368,14 @@ class Resumen { roundToTwoDecimals(num) { return parseFloat(num.toFixed(2)); } - updateToastSummary() - { - if(this.toastPresupuestoTotal){ + updateToastSummary() { + if (this.toastPresupuestoTotal) { this.toastPresupuestoTotal.close() } this.toastPresupuestoTotal = toastPresupuestoSummary($("#totalDespuesDecuento").text() ?? 0) this.toastPresupuestoTotal.fire().then((result) => { - if(result.isDismissed && result.dismiss == 'close'){ + if (result.isDismissed && result.dismiss == 'close') { this.updateToastSummary() $('html, body').animate( { diff --git a/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js b/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js index 8965dea4..fa45b210 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoCliente/presupuestoCliente.js @@ -622,7 +622,8 @@ class PresupuestoCliente { ('precio-tiradas-' + response.tiradas[i]), response.tiradas[i], precio, - response.precio_u[i] + response.precio_u[i], + response.coste_envio[i] ); if (this.actualizarTiradasEnvio) { @@ -895,7 +896,10 @@ class PresupuestoCliente { $('#menu_resumen_button').trigger('click'); setTimeout(() => { self.resumen.init_dropzone(); - self.resumen.generate_total(response.data.resumen.base, response.data.resumen.precio_unidad, response.data.datosGenerales.ivaReducido); + self.resumen.generate_total(response.data.resumen.base, + response.data.resumen.precio_unidad, + response.data.resumen.total_envio, + response.data.datosGenerales.ivaReducido); }, 0); } }, 0); diff --git a/httpdocs/assets/js/safekat/pages/presupuestoCliente/resumen.js b/httpdocs/assets/js/safekat/pages/presupuestoCliente/resumen.js index 4c297776..0ccd5839 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoCliente/resumen.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoCliente/resumen.js @@ -48,6 +48,8 @@ class Resumen { this.precio_unidad = $(this.domItem.find("#resumenPrecioU")); this.total_base = $(this.domItem.find("#resumenTotalBase")); + this.total_envios = $(this.domItem.find("#resumenTotalEnvio")); + this.total_antes_iva = $(this.domItem.find("#resumenTotalAntesIVA")); this.iva_porcentaje = $(this.domItem.find("#resumenIvaPorcentaje")); this.iva = $(this.domItem.find("#resumenIva")); this.total = $(this.domItem.find("#resumenTotal")); @@ -308,19 +310,26 @@ class Resumen { return parseInt($(this).find('.tarjeta-tiradas-precios-tirada').attr('data')) == unidades; }); + + let envios = tarjetaPrecio.find('.tarjeta-tiradas-precios-envio').val(); + this.total_envios.text(this.#changeDecimalFormat(parseFloat(envios).toFixed(2))); + let precio_u_text = tarjetaPrecio.find('.tarjeta-tiradas-precios-precio-unidad').text(); precio_u_text = precio_u_text.replace('€/ud', ''); const base = tarjetaPrecio.find('.tarjeta-tiradas-precios-precio').attr('data'); let base_text = this.#changeDecimalFormat(parseFloat(base).toFixed(2)); + const total_antes_iva_text = this.#changeDecimalFormat((parseFloat(base) + parseFloat(envios)).toFixed(2)); + const iva_porcentaje = parseInt(this.datosGenerales.ivaReducido.find('option:selected').val()) == 1 ? 0.04 : 0.21; - const iva = (parseFloat(base) * iva_porcentaje).toFixed(2); + const iva = ((parseFloat(base) + parseFloat(envios))* iva_porcentaje).toFixed(2); let iva_text = this.#changeDecimalFormat(iva); - const total = (parseFloat(base) + parseFloat(iva)).toFixed(2); + const total = (parseFloat(base) + parseFloat(envios) +parseFloat(iva)).toFixed(2); let total_text = this.#changeDecimalFormat(total); + this.precio_unidad.text(precio_u_text); this.total_base.text(base_text); this.iva_porcentaje.text(this.datosGenerales.ivaReducido.find('option:selected').val() == 1 ? '4' : '21'); @@ -329,23 +338,28 @@ class Resumen { } - generate_total(base, precio_u, iva_reducido) { + generate_total(base, precio_u, total_envio, iva_reducido) { let precio_u_text = String(precio_u); precio_u_text = precio_u_text.replace('€/u', ''); precio_u_text = this.#changeDecimalFormat(precio_u_text); let base_text = this.#changeDecimalFormat(String(base)); + let envios_text = this.#changeDecimalFormat(total_envio.toFixed(2)); + let total_antes_iva = parseFloat(base) + parseFloat(total_envio); + let total_antes_iva_text = this.#changeDecimalFormat(total_antes_iva.toFixed(2)); const iva_porcentaje = !iva_reducido? 0.21 : 0.04; - const iva = (parseFloat(base) * iva_porcentaje).toFixed(2); + const iva = ((parseFloat(base) + parseFloat(total_envio)) * iva_porcentaje).toFixed(2); let iva_text = this.#changeDecimalFormat(iva); - const total = (parseFloat(base) + parseFloat(iva)).toFixed(2); + const total = (parseFloat(base) + parseFloat(total_envio) + parseFloat(iva)).toFixed(2); let total_text = this.#changeDecimalFormat(total); this.precio_unidad.text(precio_u_text); this.total_base.text(base_text); + this.total_envios.text(envios_text); + this.total_antes_iva.text(total_antes_iva_text); this.iva_porcentaje.text(!iva_reducido? '21' : '4'); this.iva.text(iva_text); this.total.text(total_text); diff --git a/httpdocs/assets/js/safekat/pages/presupuestoCliente/tarjetaTiradasPrecio.js b/httpdocs/assets/js/safekat/pages/presupuestoCliente/tarjetaTiradasPrecio.js index 25e11ef5..1fbeead7 100644 --- a/httpdocs/assets/js/safekat/pages/presupuestoCliente/tarjetaTiradasPrecio.js +++ b/httpdocs/assets/js/safekat/pages/presupuestoCliente/tarjetaTiradasPrecio.js @@ -1,13 +1,14 @@ class tarjetaTiradasPrecio { - constructor(domItem, id, tirada, precio, precio_unidad) { + constructor(domItem, id, tirada, precio, precio_unidad, envio) { this.domItem = domItem; this.id = id; this.tirada = tirada; this.precio = precio; this.precio_unidad = precio_unidad; + this.envio = envio; - this.card = this.#generateHTML(id, tirada, precio, precio_unidad); + this.card = this.#generateHTML(id, tirada, precio, precio_unidad, envio); this.domItem.append(this.card); } @@ -15,7 +16,7 @@ class tarjetaTiradasPrecio { return value.toLocaleString("de-DE", { minimumFractionDigits: digits, maximumFractionDigits: digits }); } - #generateHTML(id, tirada, precio, precio_unidad) { + #generateHTML(id, tirada, precio, precio_unidad, envio) { let $html = $('
', { id: id, @@ -37,6 +38,7 @@ class tarjetaTiradasPrecio { const formattedPrecio = this.formatNumber(precio, 2); const formattedPrecioUnidad = this.formatNumber(precio_unidad, 4); + $listContent.append($('', { id: 'ud_' + id, @@ -56,6 +58,12 @@ class tarjetaTiradasPrecio { text: formattedPrecioUnidad + '€/ud' }).attr('data', precio_unidad)); + $listContent.append($('', { + id: 'envio_' + id, + type: 'hidden', + class: 'mb-1 tarjeta-tiradas-precios-envio', + }).val(envio)); + $liWrapper.append($listContent); $link.append($liWrapper); $html.append($link);