diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 01f07dbd..58d03ffe 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -76,7 +76,7 @@ $routes->group('configuracion', ['namespace' => 'App\Controllers\Configuracion'] $routes->match(['get', 'post'], 'edit/(:num)', 'SeriesFacturas::edit/$1', ['as' => 'seriesFacturasEdit']); $routes->get('delete/(:num)', 'SeriesFacturas::delete/$1', ['as' => 'seriesFacturasDelete']); $routes->post('datatable', 'SeriesFacturas::datatable', ['as' => 'seriesFacturasDT']); - + $routes->post('menuitemsFacturas', 'SeriesFacturas::menuItemsFacturas', ['as' => 'menuItemsOfSeriesFacturas']); }); }); @@ -652,8 +652,14 @@ $routes->group('facturas', ['namespace' => 'App\Controllers\Facturacion'], funct $routes->get('list', 'Facturas::list', ['as' => 'facturasList']); $routes->post('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']); + $routes->post('update/(:any)', 'Facturas::update/$1', ['as' => 'actualizarFactura']); + $routes->post('datatable/(:any)', 'FacturasLineas::datatable/$1', ['as' => 'dataTableOfLineasFacturas']); }); + $routes->group( 'printpresupuestos', ['namespace' => 'App\Controllers\Pdf'], diff --git a/ci4/app/Controllers/Clientes/Cliente.php b/ci4/app/Controllers/Clientes/Cliente.php index f41401c1..2f7faefa 100755 --- a/ci4/app/Controllers/Clientes/Cliente.php +++ b/ci4/app/Controllers/Clientes/Cliente.php @@ -312,10 +312,6 @@ class Cliente extends \App\Controllers\BaseResourceController $onlyActiveOnes = false; try{ $menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr); - $nonItem = new \stdClass; - $nonItem->id = ''; - $nonItem->text = '- ' . lang('Basic.global.None') . ' -'; - array_unshift($menu, $nonItem); } catch(Exception $e){ $menu = []; diff --git a/ci4/app/Controllers/Configuracion/SeriesFacturas.php b/ci4/app/Controllers/Configuracion/SeriesFacturas.php index b5e0faef..6dd1a0dc 100644 --- a/ci4/app/Controllers/Configuracion/SeriesFacturas.php +++ b/ci4/app/Controllers/Configuracion/SeriesFacturas.php @@ -238,10 +238,24 @@ class SeriesFacturas extends BaseResourceController $onlyActiveOnes = false; $menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr); $nonItem = new \stdClass; - $nonItem->id = ''; - $nonItem->text = '- ' . lang('Basic.global.None') . ' -'; - array_unshift($menu, $nonItem); + + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + $data = [ + 'menu' => $menu, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + } else { + return $this->failUnauthorized('Invalid request', 403); + } + } + public function menuItemsFacturas() + { + if ($this->request->isAJAX()) { + $menu = $this->model->getMenuItemsFacturas(); + $newTokenHash = csrf_hash(); $csrfTokenName = csrf_token(); $data = [ diff --git a/ci4/app/Controllers/Facturacion/Facturas.php b/ci4/app/Controllers/Facturacion/Facturas.php index ae61b3af..637dc9de 100755 --- a/ci4/app/Controllers/Facturacion/Facturas.php +++ b/ci4/app/Controllers/Facturacion/Facturas.php @@ -3,6 +3,8 @@ namespace App\Controllers\Facturacion; use App\Models\Facturas\FacturaModel; +use App\Entities\Facturas\FacturaEntity; +use App\Models\Clientes\ClienteModel; use App\Models\Collection; @@ -22,14 +24,14 @@ class Facturas extends \App\Controllers\BaseResourceController public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) { - $this->viewData['pageTitle'] = lang('Pedidos.moduleTitle'); + $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_pedidos"), 'route' => "javascript:void(0);", 'active' => false], + ['title' => lang("App.menu_facturas"), 'route' => "javascript:void(0);", 'active' => false], ]; parent::initController($request, $response, $logger); @@ -51,10 +53,9 @@ class Facturas extends \App\Controllers\BaseResourceController $viewData = [ 'currentModule' => static::$controllerSlug, - 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Pedidos.pedido')]), + 'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Facturas.facturas')]), 'usingServerSideDataTable' => true, 'pageTitle' => lang('Facturas.facturas'), - 'estadoPedidos' => 'todos', ['title' => lang("App.menu_facturas"), 'route' => site_url('facturas/list'), 'active' => true] ]; @@ -66,6 +67,117 @@ class Facturas extends \App\Controllers\BaseResourceController return view(static::$viewPath . 'viewFacturasList', $viewData); } + + public function add() + { + if ($this->request->getPost()) : + + $nullIfEmpty = true; // !(phpversion() >= '8.1'); + + $postData = $this->request->getPost(); + + $noException = true; + $allData = true; + + if( !isset($postData['cliente_id']) || !isset($postData['serie_id']) ) { + + $this->viewData['errorMessage'] = lang('Facturas.errors.requiredFields'); + $this->session->setFlashdata('formErrors', $this->model->errors()); + + $allData = false; + $noException = false; + } + + try { + $clienteModel = model('App\Models\Clientes\ClienteModel'); + $datosCliente = $clienteModel->getClienteDataFacturas($postData['cliente_id']); + if(count($datosCliente)>0){ + // add array data datosCliente to postData + $postData = array_merge($postData, $datosCliente[0]); + } + } catch (\Exception $e) { + $noException = false; + $this->dealWithException($e); + } + + + $sanitizedData = $this->sanitized($postData, $nullIfEmpty); + + $sanitizedData['user_updated_id'] = auth()->user()->id; + $sanitizedData['user_created_id'] = auth()->user()->id; + + if ($allData && $successfulResult = $this->canValidate()) : // if ($successfulResult = $this->validate($this->formValidationRules) ) : + + + if ($this->canValidate()) : + try { + $successfulResult = $this->model->skipValidation(true)->save($sanitizedData); + } catch (\Exception $e) { + $noException = false; + $this->dealWithException($e); + } + else: + $this->viewData['errorMessage'] = lang('Basic.global.formErr1', [lang('Basic.global.record')]); + $this->session->setFlashdata('formErrors', $this->model->errors()); + endif; + + endif; + 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') + + $this->viewData['factura'] = isset($sanitizedData) ? new FacturaEntity($sanitizedData) : new FacturaEntity(); + + $this->viewData['formAction'] = route_to('createFactura'); + + $this->viewData['boxTitle'] = lang('Basic.global.addNew') . ' ' . lang('Facturas.facturas') . ' ' . lang('Basic.global.addNewSuffix'); + + + helper('form'); + + $this->viewData['usingSelect2'] = true; + + $validation = \Config\Services::validation(); + + $this->viewData['validation'] = $validation; + + $viewFilePath = static::$viewPath . 'viewAddFactura'; + + return view($viewFilePath, $this->viewData); + } // end function add() + + + 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) : + $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Facturas.factura')), $id]); + return $this->redirect2listView('sweet-error', $message); + endif; + + $this->obtenerDatosFormulario($factura); + + $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(){ if ($this->request->isAJAX()) { @@ -87,13 +199,118 @@ class Facturas extends \App\Controllers\BaseResourceController return $this->respond(Collection::datatable( $resourceData, - $model_linea->getResource("")->countAllResults(), - $model_linea->getResource($search)->countAllResults() + $this->model->getResource("")->countAllResults(), + $this->model->getResource($search)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); } } + public function update($id = null){ + + if ($this->request->isAJAX()) { + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + + if ($id == null) : + $data = [ + 'error' => 2, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + endif; + $id = filter_var($id, FILTER_SANITIZE_URL); + $facturaEntity = $this->model->find($id); + + if ($facturaEntity == false) : + $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Factura.factura')), $id]); + $data = [ + 'error' => $message, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + endif; + + 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 ($this->canValidate()) : + try { + $successfulResult = $this->model->skipValidation(true)->update($id, $sanitizedData); + } catch (\Exception $e) { + $noException = false; + $this->dealWithException($e); + } + else: + $this->viewData['warningMessage'] = lang('Basic.global.formErr1', [mb_strtolower(lang('Facturas.factura'))]); + $this->session->setFlashdata('formErrors', $this->model->errors()); + + endif; + + $facturaEntity->fill($sanitizedData); + + endif; + if ($noException && $successfulResult) : + $id = $facturaEntity->id ?? $id; + $message = lang('Basic.global.updateSuccess', [lang('Basic.global.record')]) . '.'; + + $data = [ + 'error' => 0, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + + endif; // $noException && $successfulResult + endif; // ($requestMethod === 'post') + + $data = [ + 'error' => 1, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + } + else { + return $this->failUnauthorized('Invalid request', 403); + } + } + + + /************************************* + * FUNCIONES AUXILIARES + ************************************/ + + private function obtenerDatosFormulario(&$factura){ + + if($factura->estado == 'borrador'){ + $serieModel = model('App\Models\Configuracion\SeriesFacturasModel'); + $serie = $serieModel->find($factura->serie_id); + if($serie){ + $factura->numero = str_replace("{numero}", $serie->next, $serie->formato); + } + } + + $clienteModel = model('App\Models\Clientes\ClienteModel'); + $cliente = $clienteModel->find($factura->cliente_id); + $factura->cliente_alias = $cliente->alias; + + $serieModel = model('App\Models\Configuracion\SeriesFacturasModel'); + $serie = $serieModel->find($factura->serie_id); + $factura->serie_nombre = $serie->nombre; + + $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/Controllers/Facturacion/FacturasLineas.php b/ci4/app/Controllers/Facturacion/FacturasLineas.php new file mode 100644 index 00000000..7d490cc1 --- /dev/null +++ b/ci4/app/Controllers/Facturacion/FacturasLineas.php @@ -0,0 +1,45 @@ +request->isAJAX() && $factura_id != null) { + + $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'; + + $resourceData = $this->model->getResource($factura_id)->orderBy(1, $dir)->limit($length, $start)->get()->getResultObject(); + + return $this->respond(Collection::datatable( + $resourceData, + $this->model->getResource($factura_id)->countAllResults(), + $this->model->getResource($factura_id)->countAllResults() + )); + } else { + return $this->failUnauthorized('Invalid request', 403); + } + } +} \ No newline at end of file diff --git a/ci4/app/Controllers/Pedidos/Pedido.php b/ci4/app/Controllers/Pedidos/Pedido.php index 93e41170..bc8254dd 100755 --- a/ci4/app/Controllers/Pedidos/Pedido.php +++ b/ci4/app/Controllers/Pedidos/Pedido.php @@ -258,6 +258,17 @@ class Pedido extends \App\Controllers\BaseResourceController } } + + public function obtenerPedidosForFacturas(){ + if ($this->request->isAJAX()) { + $reqData = $this->request->getPost(); + $start = $reqData['start'] ?? 0; + } + else { + return $this->failUnauthorized('Invalid request', 403); + } + } + public function getlineas(){ if ($this->request->isAJAX()) { diff --git a/ci4/app/Entities/Facturas/FacturaEntity.php b/ci4/app/Entities/Facturas/FacturaEntity.php index 8d4e97a5..131ac828 100644 --- a/ci4/app/Entities/Facturas/FacturaEntity.php +++ b/ci4/app/Entities/Facturas/FacturaEntity.php @@ -43,8 +43,6 @@ class FacturaEntity extends \CodeIgniter\Entity\Entity 'factura_retificativa_id' => 'int', 'cliente_id' => 'int', 'serie_id' => 'int', - 'estado' => 'int', - 'estado_pago' => 'int', 'base' => 'float', 'total' => 'float', 'pendiente' => 'float', diff --git a/ci4/app/Language/en/Facturas.php b/ci4/app/Language/en/Facturas.php index 2645b729..762954bb 100644 --- a/ci4/app/Language/en/Facturas.php +++ b/ci4/app/Language/en/Facturas.php @@ -1,6 +1,7 @@ 'ID', 'factura' => 'Invoice', 'facturaList' => 'Invoice List', 'facturas' => 'Invoices', @@ -54,4 +55,14 @@ return [ 'giroDocimiliado' => 'Direct Debit', 'pagare' => 'Promissory Note', 'transferencia' => 'Transfer', + 'datosFactura' => 'Invoice Data', + 'addPedidosImpresion' => 'Add Print Orders', + 'addPedidosMaquetacion' => 'Add Layout Orders', + 'peiddoImpresion' => 'Print Order', + 'peiddoMaquetacion' => 'Layout Order', + 'nuevaLinea' => 'New Line', + + 'errors' => [ + 'requiredFields' => 'Fields marked with * are required', + ] ]; \ No newline at end of file diff --git a/ci4/app/Language/es/Basic.php b/ci4/app/Language/es/Basic.php index 01e547a1..1c98ea3d 100755 --- a/ci4/app/Language/es/Basic.php +++ b/ci4/app/Language/es/Basic.php @@ -89,6 +89,7 @@ return [ 'ok' => 'Ok', 'wait' => 'Espere', 'yes' => 'Si', + 'no' => 'No', ], diff --git a/ci4/app/Language/es/Facturas.php b/ci4/app/Language/es/Facturas.php index 39bc6aa9..36bcbcf5 100644 --- a/ci4/app/Language/es/Facturas.php +++ b/ci4/app/Language/es/Facturas.php @@ -1,6 +1,7 @@ 'ID', 'factura' => 'Factura', 'facturaList' => 'Listado de Facturas', 'facturas' => 'Facturas', @@ -54,4 +55,14 @@ return [ 'giroDomiciliado' => 'Giro domiciliado', 'pagare' => 'Pagaré', 'transferencia' => 'Transferencia', + 'datosFactura' => 'Datos Factura', + 'addPedidosImpresion' => 'Añadir Pedidos Impresión', + 'addPedidosMaquetacion' => 'Añadir Pedidos Maquetación', + 'pedidoImpresion' => 'Pedido Impresión', + 'pedidoMaquetacion' => 'Pedido Maquetación', + 'nuevaLinea' => 'Nueva Línea', + + 'errors' => [ + 'requiredFields' => 'Los campos marcados con * son obligatorios', + ] ]; \ No newline at end of file diff --git a/ci4/app/Models/Clientes/ClienteModel.php b/ci4/app/Models/Clientes/ClienteModel.php index f6e09af2..741a736a 100755 --- a/ci4/app/Models/Clientes/ClienteModel.php +++ b/ci4/app/Models/Clientes/ClienteModel.php @@ -315,4 +315,21 @@ class ClienteModel extends \App\Models\BaseModel public function creditoDisponible($cliente_id){ return true; } + + public function getClienteDataFacturas($cliente_id){ + $builder = $this->db + ->table($this->table . " t1") + ->select( + " + t1.nombre AS cliente_nombre, t1.direccion AS cliente_address, t1.cif AS cliente_cif, + t2.nombre AS cliente_pais, t1.cp AS cliente_cp, t1.ciudad AS cliente_ciudad, + t3.nombre AS cliente_provincia, t1.credito_asegurado AS creditoAsegurado" + ) + ->where("t1.is_deleted", 0) + ->where("t1.id", $cliente_id); + $builder->join("lg_paises t2", "t1.pais_id = t2.id", "left"); + $builder->join("lg_provincias t3", "t1.provincia_id = t3.id", "left"); + + return $builder->get()->getResultArray(); + } } diff --git a/ci4/app/Models/Configuracion/SeriesFacturasModel.php b/ci4/app/Models/Configuracion/SeriesFacturasModel.php index 0999b0a4..5b914953 100644 --- a/ci4/app/Models/Configuracion/SeriesFacturasModel.php +++ b/ci4/app/Models/Configuracion/SeriesFacturasModel.php @@ -91,4 +91,21 @@ class SeriesFacturasModel extends \App\Models\BaseModel ->orLike("t1.grupo", $search) ->groupEnd(); } + + public function getMenuItemsFacturas(){ + + $resultSorting = $this->getPrimaryKeyName(); + + $id = 'id AS id'; + $text = 'nombre AS text'; + + $queryBuilder = $this->db->table($this->table); + $queryBuilder->select([$id, $text]); + $queryBuilder->where('tipo', 'facturacion'); + $queryBuilder->where('grupo', '1'); + $queryBuilder->orderBy($resultSorting); + $result = $queryBuilder->get()->getResult(); + + return $result; + } } diff --git a/ci4/app/Models/Facturas/FacturaLineaModel.php b/ci4/app/Models/Facturas/FacturaLineaModel.php index f53cf805..f9fea0ab 100644 --- a/ci4/app/Models/Facturas/FacturaLineaModel.php +++ b/ci4/app/Models/Facturas/FacturaLineaModel.php @@ -30,4 +30,19 @@ class FacturaLineaModel extends \App\Models\BaseModel { protected $useSoftDeletes = true; public static $labelField = "id"; + + public function getResource($factura_id) + { + $builder = $this->db + ->table($this->table . " t1") + ->select( + "t1.id AS id, t1.factura_id AS factura_id, + t1.pedido_impresion_id AS pedido_impresion_id, t1.pedido_maquetacion_id AS pedido_maquetacion_id, + t1.descripcion AS concepto, t1.cantidad as cantidad, t1.precio_unidad AS precio_unidad, t1.iva AS iva, + t1.base AS base, t1.total_iva AS total_iva, t1.total AS total, t1.data AS data," + ) + ->where("t1.factura_id", $factura_id); + + return $builder; + } } \ No newline at end of file diff --git a/ci4/app/Models/Facturas/FacturaModel.php b/ci4/app/Models/Facturas/FacturaModel.php index 94895a80..f859fed9 100644 --- a/ci4/app/Models/Facturas/FacturaModel.php +++ b/ci4/app/Models/Facturas/FacturaModel.php @@ -28,7 +28,7 @@ class FacturaModel extends \App\Models\BaseModel { 'pedido_id', 'factura_retificada_id', 'factura_retificativa_id', - 'customer_id', + 'cliente_id', 'serie_id', 'numero', 'estado', @@ -40,13 +40,13 @@ class FacturaModel extends \App\Models\BaseModel { 'pendiente', 'total_pagos', 'creditoAsegurado', - 'customer_nombre', - 'customer_address', - 'customer_cif', - 'customer_pais', - 'customer_cp', - 'customer_ciudad', - 'customer_provincia', + 'cliente_nombre', + 'cliente_address', + 'cliente_cif', + 'cliente_pais', + 'cliente_cp', + 'cliente_ciudad', + 'cliente_provincia', 'created_at', 'updated_at', 'deleted_at', @@ -69,10 +69,10 @@ class FacturaModel extends \App\Models\BaseModel { $builder = $this->db ->table($this->table . " t1") ->select( - "t1.id AS id, t1.numero AS numero, t1.fecha_factura_at AS fecha_factura_at, + "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, - t4.nombre AS forma_pago, t3.fecha_vencimiento_at AS venciemento" + t4.nombre AS forma_pago, DATE_FORMAT(t3.fecha_vencimiento_at, '%d/%m/%Y') AS vencimiento" ); $builder->join("clientes t2", "t2.id = t1.cliente_id", "left"); diff --git a/ci4/app/Views/themes/vuexy/form/facturas/_addPedidosItems.php b/ci4/app/Views/themes/vuexy/form/facturas/_addPedidosItems.php new file mode 100644 index 00000000..8a105dca --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/facturas/_addPedidosItems.php @@ -0,0 +1,87 @@ +
| + | + | + | = lang('Facturas.unidades') ?> | += lang('Facturas.concepto') ?> | += lang('Facturas.precioUnidad') ?> | += lang('Facturas.iva') ?> | += lang('Facturas.subtotal') ?> | +
|---|