diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 01f07dbd..f55032f7 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,19 @@ $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->post('menuPedidosPendientes/(:num)', 'Facturas::menuPedidosPendientes/$1', ['as' => 'menuPedidosPendientesImpresion']); + $routes->post('addLineaPedidoImpresion/(:num)', 'Facturas::addLineaPedidoImpresion/$1', ['as' => 'addLineaPedidoImpresion2Factura']); + $routes->post('addLineaPedidoImpresion/(:num)', 'Facturas::addLineaPedidoImpresion/$1', ['as' => 'addLineaPedidoImpresion2Factura']); + $routes->get('deleteLinea/(:any)', 'FacturasLineas::deleteLinea/$1', ['as' => 'deleteLineaFactura']); + $routes->post('editorLineas', 'FacturasLineas::datatable_editor', ['as' => 'editorOfLineasFacturas']); }); + $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..7f673e1e 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,217 @@ 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); + } + } + + + public function menuPedidosPendientes($cliente_id){ + + if ($this->request->isAJAX()) { + $model = model('\App\Models\Pedidos\PedidoLineaModel'); + + $pedidos = []; + try{ + $pedidos = $model->obtenerLineasPedidoSinFacturar($cliente_id); + } + catch(Exception $e){ + + } + + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + $data = [ + 'menu' => $pedidos, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + } + else { + return $this->failUnauthorized('Invalid request', 403); + } + } + + + 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{ + $pedido_linea_id = $this->request->getPost('lineaPedido') ?? 0; + $linea = $model_pedido_linea->find($pedido_linea_id); + + if($linea){ + $presupuesto = $model_presupuesto->find($linea->presupuesto_id); + 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); + $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, + 'base' => $base, + 'total_iva' => $total_iva, + 'total' => $total, + 'user_updated_id' => auth()->user()->id, + ]; + + $model_factura_linea->insert($data); + + $id = $model_factura_linea->getInsertID(); + + if($id){ + + $model_factura_linea->addFacturaPedidoLinea($factura_id, $linea->id, $cantidad); + + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + $data = [ + 'error' => 0, + 'id' => $id, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + } + } + } + } + catch(Exception $e){ + + } + + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + $data = [ + $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..22ae8580 --- /dev/null +++ b/ci4/app/Controllers/Facturacion/FacturasLineas.php @@ -0,0 +1,192 @@ +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); + } + } + + + public function deleteLinea($factura_linea_id = 0){ + + if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) { + $objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc)); + } else { + $objName = lang('Basic.global.record'); + } + + if($factura_linea_id == 0){ + return $this->failNotFound(lang('Basic.global.deleteError', [$objName])); + } + + $facturaLinea = $this->model->find($factura_linea_id); + if($facturaLinea == null){ + return $this->failNotFound(lang('Basic.global.deleteError', [$objName])); + } + + if($facturaLinea->pedido_linea_impresion_id != null){ + $this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_linea_impresion_id, $facturaLinea->cantidad); + } + + if($facturaLinea->pedido_maquetacion_id != null){ + //$this->model->deleteFacturasLineasPedido($facturaLinea->factura_id, $facturaLinea->pedido_maquetacion_id, $facturaLinea->cantidad); + } + + $facturaLinea = $this->model->delete($factura_linea_id); + $message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]); + $response = $this->respondDeleted(['id' => $factura_linea_id, 'msg' => $message]); + return $response; + } + + + public function datatable_editor() { + if ($this->request->isAJAX()) { + + include(APPPATH . "ThirdParty/DatatablesEditor/DataTables.php"); + + + // Build our Editor instance and process the data coming from _POST + $response = Editor::inst( $db, 'cliente_plantilla_precios_lineas' ) + ->fields( + Field::inst( 'plantilla_id' ), + Field::inst( 'tipo' ), + Field::inst( 'tipo_maquina' ), + Field::inst( 'tipo_impresion' ), + Field::inst( 'user_updated_id' ), + Field::inst( 'updated_at' ), + Field::inst( 'tiempo_min' ) + ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') + ->validator( 'Validate::notEmpty',array( + 'message' => lang('ClientePrecios.validation.required')) + ) + ->validator('Validate::numeric', array( + "decimal" => ',', + 'message' => lang('ClientePrecios.validation.decimal')) + ), + + Field::inst( 'tiempo_max' ) + ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') + ->validator( 'Validate::notEmpty',array( + 'message' => lang('ClientePrecios.validation.required')) + ) + ->validator('Validate::numeric', array( + "decimal" => ',', + 'message' => lang('ClientePrecios.validation.decimal')) + ), + + Field::inst( 'precio_hora' ) + ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') + ->validator( 'Validate::notEmpty',array( + 'message' => lang('ClientePrecios.validation.required')) + ) + ->validator('Validate::numeric', array( + "decimal" => ',', + 'message' => lang('ClientePrecios.validation.decimal')) + ), + + Field::inst( 'margen' ) + ->getFormatter( 'Format::toDecimalChar')->setFormatter( 'Format::fromDecimalChar') + ->validator( 'Validate::notEmpty',array( + 'message' => lang('ClientePrecios.validation.required')) + ) + ->validator('Validate::numeric', array( + "decimal" => ',', + 'message' => lang('ClientePrecios.validation.decimal')) + ), + + ) + ->validator(function ($editor, $action, $data) { + if ($action === Editor::ACTION_CREATE || $action === Editor::ACTION_EDIT) { + foreach ($data['data'] as $pkey => $values) { + // Si no se quiere borrar... + if ($data['data'][$pkey]['is_deleted'] != 1) { + $process_data['tiempo_min'] = $data['data'][$pkey]['tiempo_min']; + $process_data['tiempo_max'] = $data['data'][$pkey]['tiempo_max']; + $process_data['tipo'] = $data['data'][$pkey]['tipo']; + $process_data['tipo_maquina'] = $data['data'][$pkey]['tipo_maquina']; + $process_data['tipo_impresion'] = $data['data'][$pkey]['tipo_impresion']; + + $response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['plantilla_id']); + // No se pueden duplicar valores al crear o al editar + if (!empty($response)) { + return $response; + } + } + } + } + }) + ->on('preCreate', function ($editor, &$values) { + $session = session(); + $datetime = (new \CodeIgniter\I18n\Time("now")); + $editor + ->field('user_updated_id') + ->setValue($session->id_user); + $editor + ->field('updated_at') + ->setValue($datetime->format('Y-m-d H:i:s')); + }) + ->on('preEdit', function ($editor, &$values) { + $session = session(); + $datetime = (new \CodeIgniter\I18n\Time("now")); + $editor + ->field('user_updated_id') + ->setValue($session->id_user); + $editor + ->field('updated_at') + ->setValue($datetime->format('Y-m-d H:i:s')); + }) + ->debug(true) + ->process($_POST) + ->data(); + + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + + $response[$csrfTokenName] = $newTokenHash; + + echo json_encode($response); + + } 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/Controllers/Presupuestos/Presupuestocliente.php b/ci4/app/Controllers/Presupuestos/Presupuestocliente.php index dd0b609c..6e2a81c7 100755 --- a/ci4/app/Controllers/Presupuestos/Presupuestocliente.php +++ b/ci4/app/Controllers/Presupuestos/Presupuestocliente.php @@ -192,7 +192,7 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController $this->viewData['presupuestoEntity'] = $presupuestoEntity; $this->viewData['datosPresupuesto'] = $datosPresupuesto; - $this->viewData['clienteId'] = $clienteId; + $this->viewData['clienteId'] = $presupuestoEntity->cliente_id; // En el caso del edit, se mantiene el clienteId del presupuesto // Si se ha llamado a esta funcion porque se ha duplicado el presupuesto // se actualiza la bbdd para que sólo ejecute algunas funciones una vez @@ -1449,9 +1449,18 @@ class Presupuestocliente extends \App\Controllers\BaseResourceController } // Servicios - if ($datos_guardas > 0) { - array_push($servicios, 62); // Plegado de guardas + // se comprueba si $datos guardas es un array + if(is_array($datos_guardas)){ + if(count($datos_guardas) > 0){ + array_push($servicios, 62); // Plegado de guardas + } } + else{ + if ($datos_guardas > 0) { + array_push($servicios, 62); // Plegado de guardas + } + } + /* 'retractilado' => 3, 'retractilado5' => 5, diff --git a/ci4/app/Controllers/Test.php b/ci4/app/Controllers/Test.php index 3b6973fc..972808b2 100755 --- a/ci4/app/Controllers/Test.php +++ b/ci4/app/Controllers/Test.php @@ -20,11 +20,18 @@ class Test extends BaseController public function index() { - $model = new PresupuestoModel(); - $data = $model->generarLineaPedido(123); - echo '
';
+        /*
+        $model = model("\App\Models\Pedidos\PedidoLineaModel");
+        $data = $model->obtenerLineasPedidoSinFacturar(999);
+        */
+
+        $model = model("\App\Models\Facturas\FacturaLineaModel");
+        $data = $model->getResource(9)->get()->getResultObject();
+        
+        echo('
');
         var_dump($data);
-        echo '
'; + echo('
'); + } 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/Entities/Facturas/FacturaLineaEntity.php b/ci4/app/Entities/Facturas/FacturaLineaEntity.php index f9df393a..7ce467bb 100644 --- a/ci4/app/Entities/Facturas/FacturaLineaEntity.php +++ b/ci4/app/Entities/Facturas/FacturaLineaEntity.php @@ -8,7 +8,7 @@ class FacturaLineaEntity extends \CodeIgniter\Entity\Entity protected $attributes = [ 'id' => null, 'factura_id' => null, - 'pedido_impresion_id' => null, + 'pedido_linea_impresion_id' => null, 'pedido_maquetacion_id' => null, 'descripcion' => null, 'cantidad' => null, @@ -19,14 +19,14 @@ class FacturaLineaEntity extends \CodeIgniter\Entity\Entity 'total' => null, 'data' => null, 'deleted_at' => null, - 'user_update_id' => null, + 'user_updated_id' => null, ]; protected $casts = [ 'id' => 'int', 'factura_id' => 'int', - 'pedido_impresion_id' => 'int', + 'pedido_linea_impresion_id' => 'int', 'pedido_maquetacion_id' => 'int', 'cantidad' => 'float', 'precio_unidad' => '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/en/Pedidos.php b/ci4/app/Language/en/Pedidos.php index 0e58640a..69a30669 100644 --- a/ci4/app/Language/en/Pedidos.php +++ b/ci4/app/Language/en/Pedidos.php @@ -52,7 +52,9 @@ return [ 'dosCaras' => '2 sides', 'lineasTemplates' =>[ - 'libro' => "[BUDGET %s] Printing of %s copies of %s pages.\nTitle: %s. Author: %s. ISBN: %s.Size: %smm.\n", + 'presupuesto' => '[BUDGET %s] ', + 'pedido' => '[ORDER %s] ', + 'libro' => "Printing of %s copies of %s pages.\nTitle: %s. Author: %s. ISBN: %s.Size: %smm.\n", 'libro_linea_interior' => "%s black pages on %s paper of %s grams", 'libro_linea_cubierta' => "\nCover printed on %s on %s paper of %s grams", 'libro_linea_sobrecubierta' => "\nDust jacket on %s paper of %s grams", 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/Language/es/Pedidos.php b/ci4/app/Language/es/Pedidos.php index 5e790760..f8556058 100644 --- a/ci4/app/Language/es/Pedidos.php +++ b/ci4/app/Language/es/Pedidos.php @@ -51,7 +51,9 @@ return [ 'dosCaras' => '2 caras', 'lineasTemplates' =>[ - 'libro' => "[PRESUPUESTO %s] Impresión de %s ejemplares de %s páginas.\nTítulo: %s. Autor: %s. ISBN: %s.Tamaño: %smm.\n", + 'presupuesto' => '[PRESUPUESTO %s] ', + 'pedido' => '[PEDIDO %s] ', + 'libro' => "Impresión de %s ejemplares de %s páginas.\nTítulo: %s. Autor: %s. ISBN: %s.Tamaño: %smm.\n", 'libro_linea_interior' => "%s páginas en negro sobre papel %s de %s gramos", 'libro_linea_cubierta' => "\nCubierta impresa a %s sobre papel %s de %s gramos", 'libro_linea_sobrecubierta' => "\nSobrecubierta sobre papel %s de %s gramos", diff --git a/ci4/app/Language/es/Presupuestos.php b/ci4/app/Language/es/Presupuestos.php index 5fc672eb..e61122b3 100755 --- a/ci4/app/Language/es/Presupuestos.php +++ b/ci4/app/Language/es/Presupuestos.php @@ -210,6 +210,8 @@ return [ 'confirmar' => 'Confirmar presupuesto', 'confirmado' => 'Presupuesto confirmado', + 'totalAceptado' => 'Total aceptado', + // Preview 'preview' => 'Previsualización de configuraciones', 'preview-conf-bn' => 'Configuración Blanco y Negro', 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..a9d4d901 100644 --- a/ci4/app/Models/Facturas/FacturaLineaModel.php +++ b/ci4/app/Models/Facturas/FacturaLineaModel.php @@ -10,7 +10,7 @@ class FacturaLineaModel extends \App\Models\BaseModel { // Lista de columnas basada en los campos de la tabla, para asignación masiva protected $allowedFields = [ 'factura_id', - 'pedido_impresion_id', + 'pedido_linea_impresion_id', 'pedido_maquetacion_id', 'descripcion', 'cantidad', @@ -21,7 +21,7 @@ class FacturaLineaModel extends \App\Models\BaseModel { 'total', 'data', 'deleted_at', - 'user_update_id' + 'user_updated_id' ]; protected $returnType = "App\Entities\Facturas\FacturaLineaEntity"; @@ -30,4 +30,43 @@ 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_linea_impresion_id AS pedido_linea_impresion_id, t1.pedido_maquetacion_id AS pedido_maquetacion_id, + t1.descripcion AS concepto, t1.cantidad as unidades, t1.precio_unidad AS precio_unidad, t1.iva AS iva, + t1.base AS subtotal, t1.total_iva AS total_iva, t1.total AS total, t1.data AS data, t2.pedido_id AS pedido_id, + t3.total_aceptado AS total_aceptado" + ) + ->join("pedidos_linea t2", "t2.id = t1.pedido_linea_impresion_id", "left") + ->join("presupuestos t3", "t3.id = t2.presupuesto_id", "left") + ->where("t1.factura_id", $factura_id) + ->where("t1.deleted_at", null); + + return $builder; + } + + public function addFacturaPedidoLinea($factura_id, $pedido_linea_id, $cantidad) + { + $data = [ + "factura_id" => $factura_id, + "pedido_linea_id" => $pedido_linea_id, + "cantidad" => $cantidad + ]; + + return $this->db->table("facturas_pedidos_lineas")->insert($data); + } + + public function deleteFacturasLineasPedido($factura_id, $pedido_linea_id, $cantidad){ + + $this->db->table("facturas_pedidos_lineas") + ->where("factura_id", $factura_id) + ->where("pedido_linea_id", $pedido_linea_id) + ->where("cantidad", $cantidad) + ->delete(); + } } \ No newline at end of file diff --git a/ci4/app/Models/Facturas/FacturaModel.php b/ci4/app/Models/Facturas/FacturaModel.php index 94895a80..30e61341 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"); @@ -88,4 +88,15 @@ class FacturaModel extends \App\Models\BaseModel { ->orLike("t1.id", $search) ->groupEnd(); } + + public function getCantidadLineaPedidoFacturada($linea_pedido_id) + { + $builder = $this->db + ->table("facturas_pedidos_lineas t1") + ->select("SUM(t1.cantidad) AS cantidad") + ->where("t1.pedido_linea_id", $linea_pedido_id); + + return $builder->get()->getRow()->cantidad; + } + } \ No newline at end of file diff --git a/ci4/app/Models/Pedidos/PedidoLineaModel.php b/ci4/app/Models/Pedidos/PedidoLineaModel.php index 13308f06..8aee0c2a 100644 --- a/ci4/app/Models/Pedidos/PedidoLineaModel.php +++ b/ci4/app/Models/Pedidos/PedidoLineaModel.php @@ -76,4 +76,40 @@ class PedidoLineaModel extends \App\Models\BaseModel ->orLike("t1.id", $search) ->groupEnd(); } + + + public function obtenerLineasPedidoSinFacturar($cliente_id){ + + $resultaArray = []; + + $builder = $this->db + ->table($this->table . " t1") + ->select("t1.id AS id, t1.pedido_id AS pedido_id, t3.titulo AS titulo, t4.codigo AS tipo_impresion"); + + $builder->join("pedidos t2", "t2.id = t1.pedido_id", "left"); + $builder->join("presupuestos t3", "t3.id = t1.presupuesto_id", "left"); + $builder->join("tipos_presupuestos t4", "t4.id = t3.tipo_impresion_id", "left"); + + $builder->join("facturas_pedidos_lineas fpl", "fpl.pedido_linea_id = t1.id", "left"); + + $builder->where("t3.cliente_id", $cliente_id); + $builder->where("t2.estado", "finalizado"); + + + $builder->where("(`t3`.`tirada` > `fpl`.`cantidad` OR fpl.pedido_linea_id IS NULL)"); + + // Ejecutar la consulta y devolver resultados + $query = $builder->get(); + $data = $query->getResult(); + + foreach($data as $register){ + $item = (object)[ + 'id' => $register->id, + 'text' => '['. lang('Pedidos.pedido') . ' ' . $register->pedido_id . '] ' . $register->titulo . ' - ' . lang('Presupuestos.' . $register->tipo_impresion), + ]; + array_push($resultaArray, $item); + } + + return $resultaArray; + } } \ No newline at end of file diff --git a/ci4/app/Models/Presupuestos/PresupuestoModel.php b/ci4/app/Models/Presupuestos/PresupuestoModel.php index b9e48761..dc8c3ad3 100755 --- a/ci4/app/Models/Presupuestos/PresupuestoModel.php +++ b/ci4/app/Models/Presupuestos/PresupuestoModel.php @@ -142,7 +142,7 @@ class PresupuestoModel extends \App\Models\BaseModel ], "titulo" => [ "label" => "Presupuestos.titulo", - "rules" => "trim|required|max_length[30]", + "rules" => "trim|required|max_length[300]", ], "inc_rei" => [ "label" => "Presupuestos.incRei", @@ -538,7 +538,7 @@ class PresupuestoModel extends \App\Models\BaseModel return $json; } - public function generarLineaPedido($presupuesto_id) + public function generarLineaPedido($presupuesto_id, $forFactura = false, $pedido_id = 0) { $builder = $this->db ->table($this->table . " t1") @@ -565,13 +565,18 @@ class PresupuestoModel extends \App\Models\BaseModel $presupuesto = $presupuesto[0]; // Libro - if($presupuesto->tipo < 10){ + if($presupuesto->tipo < 10 || $presupuesto->tipo==20 || $presupuesto->tipo==21){ if($presupuesto->papel_formato_personalizado == 1){ $presupuesto->tamanio= $presupuesto->papel_formato_ancho . "x" . $presupuesto->papel_formato_alto; } - $presupuesto->concepto = sprintf(lang('Pedidos.lineasTemplates.libro'), - $presupuesto->numero, + if($forFactura){ + $presupuesto->concepto = sprintf(lang('Pedidos.lineasTemplates.pedido'), $pedido_id); + } + else{ + $presupuesto->concepto = sprintf(lang('Pedidos.lineasTemplates.presupuesto'), $presupuesto->numero); + } + $presupuesto->concepto .= sprintf(lang('Pedidos.lineasTemplates.libro'), $presupuesto->unidades, $presupuesto->paginas, $presupuesto->titulo, diff --git a/ci4/app/Views/themes/_commonPartialsBs/_modalConfirmDialog.php b/ci4/app/Views/themes/_commonPartialsBs/_modalConfirmDialog.php index e2b6d8c3..37339425 100755 --- a/ci4/app/Views/themes/_commonPartialsBs/_modalConfirmDialog.php +++ b/ci4/app/Views/themes/_commonPartialsBs/_modalConfirmDialog.php @@ -26,20 +26,34 @@ function asyncConfirmDialog(title, msg, yesCallbackFn, noCallbackFn) { - var $confirmDialog = $("#modalConfirmYesNo"); - $confirmDialog.modal('show'); - $("#labelTitleConfirmDialog").html(title); - $("#labelMsgConfirmDialog").html(msg); - $("#btnYesConfirmDialog").off('click').click(function () { - yesCallbackFn(); - $confirmDialog.modal("hide"); - }); - $("#btnNoConfirmDialog").off('click').click(function () { - noCallbackFn(); - $confirmDialog.modal("hide"); - }); - } + var $confirmDialog = $("#modalConfirmYesNo"); + $confirmDialog.modal('show'); + $("#labelTitleConfirmDialog").html(title); + $("#labelMsgConfirmDialog").html(msg); + $("#btnYesConfirmDialog").off('click').click(function () { + yesCallbackFn(); + $confirmDialog.modal("hide"); + }); + $("#btnNoConfirmDialog").off('click').click(function () { + noCallbackFn(); + $confirmDialog.modal("hide"); + }); +} +function asyncConfirmDialogWithParams(title, msg, yesCallbackFn, noCallbackFn, params) { + var $confirmDialog = $("#modalConfirmYesNo"); + $confirmDialog.modal('show'); + $("#labelTitleConfirmDialog").html(title); + $("#labelMsgConfirmDialog").html(msg); + $("#btnYesConfirmDialog").off('click').click(function () { + yesCallbackFn(params); + $confirmDialog.modal("hide"); + }); + $("#btnNoConfirmDialog").off('click').click(function () { + noCallbackFn(params); + $confirmDialog.modal("hide"); + }); +} endSection() ?> 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..cae8922e --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/facturas/_addPedidosItems.php @@ -0,0 +1,139 @@ +
+
+
+ +

+ +

+ +
+
+
+
+ +
+ +
+ +
+
+ +
+
+
+
+ + +
+
+ +

+ +

+ +
+
+ +
+
+ +
+ +
+ +
+
+ +
+
+
+
+
+ +section('additionalInlineJs') ?> + +$('#pedidoImpresion').select2({ + placeholder: "", + allowClear: true, + ajax: { + url: 'cliente_id) ?>', + type: 'post', + dataType: 'json', + + data: function (params) { + return { + id: 'id', + text: 'nombre', + searchTerm: params.term, + : v + }; + }, + delay: 60, + processResults: function (response) { + + yeniden(response.); + + return { + results: response.menu + }; + }, + + cache: true + } +}); + +$('#addNewPedidoImpresion').on('click', function(){ + var lineaPedido = $('#pedidoImpresion').val(); + if(lineaPedido == null) { + return; + } + $.ajax({ + url: 'id) ?>', + type: 'post', + data: { + lineaPedido: lineaPedido, + : v + }, + success: function(response) { + yeniden(response.); + + // Se actualiza la tabla de lineas de factura + $('#tableOfLineasFactura').DataTable().clearPipeline(); + $('#tableOfLineasFactura').DataTable().ajax.reload(); + // se ajustan el ancho de las columnas + $('#tableOfLineasFactura').DataTable().columns.adjust().draw(); + $('#pedidoImpresion').val(null).trigger('change'); + + } + }); +}); + + + +$('#pedidoMaquetacion').select2({ + placeholder: "", + allowClear: true, + width: '100%' +}); + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/facturas/_facturaCabeceraItems.php b/ci4/app/Views/themes/vuexy/form/facturas/_facturaCabeceraItems.php new file mode 100644 index 00000000..47754d47 --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/facturas/_facturaCabeceraItems.php @@ -0,0 +1,307 @@ +
+ +
+

+ +

+ +
+
+ +
+

estado)?>

+
+
+ +
+ estado === 'borrador') : ?> +
+ + +
+ +
+ + +
+ +
+ +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+ + +
+
+
+ + +
+
+ +
+
+ + +
+
+ +
+
+ + +
+
+ +
+ +
+ +
+
+ + +
+
+ +
+
+ + +
+
+ +
+
+ + +
+
+ +
+
+ + +
+
+ +
+ +
+ +
+
+ + estado === 'validada' && (auth()->user()->inGroup('beta') || auth()->user()->inGroup('admin'))) : ?> + + + + + + + +
+
+ +
+ +
+
+
+
+ + +section('additionalInlineJs') ?> + +$("#fecha_factura_at").flatpickr({ + defaultDate: fecha_factura_at_text ? "'".$facturaEntity->fecha_factura_at_text."'" : 'null' ?>, + dateFormat: "d/m/Y", + locale: { + firstDayOfWeek: 1, + weekdays: { + shorthand: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'], + longhand: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'], + }, + months: { + shorthand: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Оct', 'Nov', 'Dic'], + longhand: ['Enero', 'Febreo', 'Мarzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'], + }, + }, + onChange: function(selectedDates, dateStr, instance) { + estado == 'borrador'): ?> + updateDate('fecha_entrega_at', dateStr); + + } +}); + + +function updateDate(elementId, dateStr) { + var id = id ?>; + + data = { + : v, + }; + var parts = dateStr.split('/'); + var newFormat = parts[2] + '-' + parts[1] + '-' + parts[0]; // Asume dateStr en formato d/m/Y. + + data[elementId] = newFormat; + + var url = ''; + url = url.replace(':id', id ); + + $.ajax({ + url: url, + type: 'POST', + data: data, + success: function(response){ + + if('error' in response){ + + } + } + }); +} + +$('#serie_id').select2({ + allowClear: false, + minimumResultsForSearch: -1, + ajax: { + url: '', + type: 'post', + dataType: 'json', + + data: function(params) { + return { + id: 'id', + text: 'nombre', + searchTerm: params.term, + : v + }; + }, + delay: 60, + processResults: function(response) { + yeniden(response.); + return { + results: response.menu + }; + }, + cache: true + } +}); + +$('#cliente_id').select2({ + allowClear: false, + ajax: { + url: '', + type: 'post', + dataType: 'json', + + data: function(params) { + return { + id: 'id', + text: 'alias', + searchTerm: params.term, + : v + }; + }, + delay: 60, + processResults: function(response) { + yeniden(response.); + return { + results: response.menu + }; + }, + cache: true + } +}); + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/facturas/_facturaLineasItems.php b/ci4/app/Views/themes/vuexy/form/facturas/_facturaLineasItems.php new file mode 100644 index 00000000..09798fba --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/facturas/_facturaLineasItems.php @@ -0,0 +1,327 @@ +
+ +
+

+ +

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
id
Subtotal:
I.V.A.:
Total:
Pendiente de pago:
+ estado =='borrador') : ?> +
+
+ +
+
+ +
+
+
+
+ + +section('additionalInlineJs') ?> + +const actionBtns = function(data) { + + // se comprueba si data es null + if (data.pedido_id === null) { + return ` + +
+
+ + +
+
+ `; + } + else{ + return ` + +
+
+ + +
+
+
+ +
+ `; + } +}; + +var editor_lineas = new $.fn.dataTable.Editor( { + ajax: { + url: "", + headers: { + : v, + }, + }, + table : "#tableOfLineasFactura", + idSrc: 'id', + fields: [ + { + name: "unidades", + + }, { + name: "concepto" + }, { + name: "precio_unidad", + } + ] +} ); + +editor_lineas.on( 'preSubmit', function ( e, d, type ) { + if ( type === 'create'){ + d.data[0]['factura_id'] = id ?>; + } + else if(type === 'edit' ) { + for (v in d.data){ + d.data[v]['factura_id'] = id ?>; + } + } +}); + + +editor_lineas.on( 'postSubmit', function ( e, json, data, action ) { + + yeniden(json.); +}); + +editor_lineas.on( 'submitSuccess', function ( e, json, data, action ) { + + tableLineas.clearPipeline(); + tableLineas.draw(); +}); + + +// Activate an inline edit on click of a table cell +$('#tableOfLineasFactura').on( 'click', 'tbody span.edit', function (e) { + editor_lineas.inline( + tableLineas.cells(this.parentNode.parentNode, '*').nodes(), + { + cancelHtml: '', + cancelTrigger: 'span.cancel', + submitHtml: '', + submitTrigger: 'span.edit', + submit: 'allIfChanged' + } + ); +} ); + + +var tableLineas = $('#tableOfLineasFactura').DataTable({ + processing: true, + serverSide: true, + autoWidth: true, + responsive: true, + scrollX: true, + columns: [ + {data: null, render: actionBtns}, + {data: "id"}, + {data: "pedido_linea_impresion_id"}, + {data: "pedido_maquetacion_id"}, + {data: "pedido_id"}, + {data: "unidades"}, + { + data: "concepto", + render: function (data, type, row, meta) { + + // se convierten a float data.total_aceptado y subtotal + var total_aceptado = parseFloat(row.total_aceptado); + var subtotal = parseFloat(row.subtotal); + + var error_text = ''; + if(total_aceptado != subtotal){ + error_text = 'El total del pedido ('+ total_aceptado + '€) no coincide con la línea ('+ subtotal + '€)'; + } + + return ` +
+ ${data} +
+ +
+ + ${error_text} +
+ +
+ + +
+ `; + } + }, + {data: "precio_unidad"}, + {data: "iva"}, + {data: "subtotal"}, + {data: "total_iva"}, + {data: "total"}, + ], + order: [[1, "asc"]], + dom: 't', + language: { + url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json" + }, + ajax : $.fn.dataTable.pipeline( { + url: 'id) ?>', + method: 'POST', + headers: {'X-Requested-With': 'XMLHttpRequest'}, + async: true, + }), + columnDefs: [ + { + orderable: false, + searchable: false, + targets: [0] + }, + { + visible: false, + targets: [1, 2, 3, 4, 10, 11] + } + + ], + footerCallback: function (row, data, start, end, display) { + var api = this.api(); + + // Remove the formatting to get integer data for summation + var intVal = function (i) { + return typeof i === 'string' ? + i.replace(/[\$,]/g, '')*1 : + typeof i === 'number' ? + i : 0; + }; + + // Total over all pages + var totalSubtotal = api + .column(8) + .data() + .reduce(function (a, b) { + return intVal(a) + intVal(b); + }, 0); + + var totalIVA = api + .column(9) + .data() + .reduce(function (a, b) { + return intVal(a) + intVal(b); + }, 0); + + var totalTotal = api + .column(10) + .data() + .reduce(function (a, b) { + return intVal(a) + intVal(b); + }, 0); + + // Update footer + $('#subtotal-sum').html(totalSubtotal.toFixed(2)); + $('#total-iva-sum').html(totalIVA.toFixed(2)); + $('#total-sum').html(totalTotal.toFixed(2)); + + // Assuming pendiente de pago is totalTotal - totalIVA for this example + var pendientePago = totalTotal ;//- totalIVA; + $('#pendiente-pago').html(pendientePago.toFixed(2)); + } +}); + + +// Delete row +$(document).on('click', '.btn-delete', function(e) { + //$(".btn-remove").attr('data-id', $(this).attr('data-id')); + const dataId = $(this).attr('data-id'); + const row = $(this).closest('tr'); + if ($.isNumeric(dataId)) { + asyncConfirmDialogWithParams( + "Borrar Linea de Factura", + "¿Está seguro de borrar la línea? Esta acción no se puede deshacer.", + deleteConfirmed, null, [dataId, row]) + } +}); + + +function deleteConfirmed(params){ + var factura_linea_id = params[0]; + var row = params[1]; + var url = ''; + url = url.replace(':id', factura_linea_id ); + $.ajax({ + url: url, + method: 'GET', + }).done((data, textStatus, jqXHR) => { + $('#tableOfLineasFactura').DataTable().clearPipeline(); + $('#tableOfLineasFactura').DataTable().row($(row)).invalidate().draw(); + }).fail((jqXHR, textStatus, errorThrown) => { + popErrorAlert(jqXHR.responseJSON.messages.error) + }) +} + +$(document).on('click', '.btn-view_pedido', function(e) { + var pedido_id = $(this).data('id'); + var url = ''; + url = url.replace(':id', pedido_id ); + + window.open(url, '_blank'); +}); + + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/facturas/viewAddFactura.php b/ci4/app/Views/themes/vuexy/form/facturas/viewAddFactura.php index e69de29b..727d7ced 100644 --- a/ci4/app/Views/themes/vuexy/form/facturas/viewAddFactura.php +++ b/ci4/app/Views/themes/vuexy/form/facturas/viewAddFactura.php @@ -0,0 +1,118 @@ +include('themes/_commonPartialsBs/datatables') ?> +include("themes/_commonPartialsBs/select2bs5") ?> +include("themes/_commonPartialsBs/sweetalert") ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +extend('themes/vuexy/main/defaultlayout') ?> + +section("content") ?> +
+
+
+
+

+
+
+ + + getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?> + +
+ +
+
+ + +
+
+ +
+ +
+ +
+
+ + +
+
+ +
+ + +
+ " + /> + "btn btn-secondary float-start"]) ?> +
+
+
+
+ +
+ +endSection() ?> + +section("additionalInlineJs") ?> + +$('#cliente_id').select2({ + allowClear: false, + ajax: { + url: '', + type: 'post', + dataType: 'json', + + data: function(params) { + return { + id: 'id', + text: 'nombre', + searchTerm: params.term, + : v + }; + }, + delay: 60, + processResults: function(response) { + yeniden(response.); + return { + results: response.menu + }; + }, + cache: true + } +}); + + +$('#serie_id').select2({ + allowClear: false, + minimumResultsForSearch: -1, + ajax: { + url: '', + type: 'post', + dataType: 'json', + + data: function(params) { + return { + id: 'id', + text: 'nombre', + searchTerm: params.term, + : v + }; + }, + delay: 60, + processResults: function(response) { + yeniden(response.); + return { + results: response.menu + }; + }, + cache: true + } +}); + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/vuexy/form/facturas/viewFacturaForm.php b/ci4/app/Views/themes/vuexy/form/facturas/viewFacturaForm.php new file mode 100644 index 00000000..4f3cf2cd --- /dev/null +++ b/ci4/app/Views/themes/vuexy/form/facturas/viewFacturaForm.php @@ -0,0 +1,69 @@ +include('themes/_commonPartialsBs/datatables') ?> +include("themes/_commonPartialsBs/select2bs5") ?> +include("themes/_commonPartialsBs/sweetalert") ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +extend('themes/vuexy/main/defaultlayout') ?> + +section("content") ?> +
+
+
+
+

+
+
+ + + getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?> + + + estado =='borrador') : ?> + + + + + +
+ " + /> + "btn btn-secondary float-start"]) ?> +
+
+
+
+ + + +
+ +endSection() ?> + +section("additionalInlineJs") ?> + +endSection() ?> + + +section('css') ?> + "> + "> + + +endSection() ?> + +section('additionalExternalJs') ?> + + + + + + + + + + +endSection() ?> + + diff --git a/ci4/app/Views/themes/vuexy/form/facturas/viewFacturasList.php b/ci4/app/Views/themes/vuexy/form/facturas/viewFacturasList.php index 3ebdfc4b..d92ce5a8 100644 --- a/ci4/app/Views/themes/vuexy/form/facturas/viewFacturasList.php +++ b/ci4/app/Views/themes/vuexy/form/facturas/viewFacturasList.php @@ -49,12 +49,22 @@ const lastColNr = $('#tableOfFacturas').find("tr:first th").length - 1; const actionBtns = function(data) { - return ` + if(data.estado == 'borrador'){ + return ` + +
+ +
+ `; + } + else{ + return `
`; + } }; theTable = $('#tableOfFacturas').DataTable({ @@ -141,8 +151,7 @@ } } }, - { 'data': 'total_presupuesto' }, - { 'data': forma_pago, + { 'data': 'forma_pago', render: function(data, type, row, meta) { switch(data){ case "cheque": @@ -176,14 +185,14 @@ } } }, - { 'data': vencimiento }, + { 'data': 'vencimiento' }, { 'data': actionBtns } ] }); $(document).on('click', '.btn-edit', function(e) { - var url = ''; + var url = ''; url = url.replace(':id', `${$(this).attr('data-id')}` ); window.location.href = url; }); diff --git a/ci4/app/Views/themes/vuexy/form/pedidos/_lineasItems.php b/ci4/app/Views/themes/vuexy/form/pedidos/_lineasItems.php index 9665e763..be7f622a 100644 --- a/ci4/app/Views/themes/vuexy/form/pedidos/_lineasItems.php +++ b/ci4/app/Views/themes/vuexy/form/pedidos/_lineasItems.php @@ -130,7 +130,6 @@ $(document).on('click', '.btn-view', function(e) { var url = ''; url = url.replace(':id', `${$(this).attr('data-id')}` ); - console.log(url); window.open( url, '_blank' // <- This is what makes it open in a new window. diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/_disenioLibroItems.php b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/_disenioLibroItems.php index 66de6299..442b8694 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/_disenioLibroItems.php +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/cliente/_disenioLibroItems.php @@ -16,7 +16,7 @@
- + estado_id == 2): ?> +
+
+ + > +
+
+
diff --git a/ci4/app/Views/themes/vuexy/form/presupuestos/cosidotapablanda/_resumenPresupuestos.js b/ci4/app/Views/themes/vuexy/form/presupuestos/cosidotapablanda/_resumenPresupuestos.js index 6cfb891e..a7351f3f 100644 --- a/ci4/app/Views/themes/vuexy/form/presupuestos/cosidotapablanda/_resumenPresupuestos.js +++ b/ci4/app/Views/themes/vuexy/form/presupuestos/cosidotapablanda/_resumenPresupuestos.js @@ -177,8 +177,8 @@ function updateTotales(updateLP=true, updateServicios=true, updateEnvio=true){ margenEnvios = parseFloat($('#margenEnvios').attr('val')) } - var totalCostes = totalPapel + totalImpresion + totalServicios + totalEnvios - var totalMargenes = margenPapel + margenImpresion + margenServicios + margenEnvios + var totalCostes = parseFloat(totalPapel.toFixed(2)) + parseFloat(totalImpresion.toFixed(2)) + parseFloat(totalServicios.toFixed(2)) + parseFloat(totalEnvios.toFixed(2)) + var totalMargenes = parseFloat(margenPapel.toFixed(2)) + parseFloat(margenImpresion.toFixed(2)) + parseFloat(margenServicios.toFixed(2)) + parseFloat(margenEnvios.toFixed(2)) $('#totalCostes').text((addSeparatorsNF(totalCostes.toFixed(2), ".", ",", ".")) + "€") $('#totalMargenes').text((addSeparatorsNF(totalMargenes.toFixed(2), ".", ",", ".")) + "€") $('#totalCostes').attr('val',(totalCostes).toFixed(2) + '€') @@ -251,11 +251,13 @@ function getValuesResumenForm(){ formResumen += '&total_presupuesto=' + $('#totalDespuesDecuento').attr('val'); formResumen += '&total_precio_unidad=' + $('#precioUnidadPresupuesto').attr('val'); - formResumen += '&total_factor=' + $('#total_factor').text(); - formResumen += '&total_factor_ponderado=' + $('#total_factor_ponderado').text(); + // replace , for . in the values + formResumen += '&total_factor=' + $('#factor').text().replace(/,/g, '.'); + formResumen += '&total_factor_ponderado=' + $('#factor_ponderado').text().replace(/,/g, '.'); if($('#confirmar_presupuesto').prop('checked')){ - formResumen += '&confirmar=1'; + formResumen += '&confirmar=1'; + formResumen += '&total_aceptado=' + $('#totalDespuesDecuento').attr('val'); } return formResumen diff --git a/ci4/app/Views/themes/vuexy/main/menus/facturacion_menu.php b/ci4/app/Views/themes/vuexy/main/menus/facturacion_menu.php index c8c2ef1a..d2a4bc73 100644 --- a/ci4/app/Views/themes/vuexy/main/menus/facturacion_menu.php +++ b/ci4/app/Views/themes/vuexy/main/menus/facturacion_menu.php @@ -12,7 +12,7 @@ if (auth()->user()->inGroup('beta')) {