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