From 0abdb7efac77b3c6c8012355e711cf4b71bdb53c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= <“jaimejimenezortega@gmail.com”> Date: Tue, 2 Jan 2024 14:28:59 +0100 Subject: [PATCH 1/2] trabajando en cliente precios --- ci4/app/Config/Routes.php | 7 + ci4/app/Controllers/Clientes/Cliente.php | 22 + .../Clientes/Clienteplantillaprecios.php | 32 +- .../Controllers/Clientes/Clienteprecios.php | 237 ++++++++++ ci4/app/Language/en/ClientePrecios.php | 2 + ci4/app/Language/es/ClientePrecios.php | 2 + .../Models/Clientes/ClientePreciosModel.php | 133 +++++- ci4/app/Models/GoBaseModel.php | 5 +- .../clientes/cliente/_clienteFormItems.php | 404 +++++++++++++++++- 9 files changed, 832 insertions(+), 12 deletions(-) create mode 100755 ci4/app/Controllers/Clientes/Clienteprecios.php diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 2b04d4a1..6668f74a 100755 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -352,6 +352,12 @@ $routes->group('cliente', ['namespace' => 'App\Controllers\Clientes'], function }); $routes->resource('cliente', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Cliente', 'except' => 'show,new,create,update']); +$routes->group('clienteprecios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) { + $routes->post('datatable', 'Clienteprecios::datatable', ['as' => 'dataTableOfClienteprecios']); + $routes->post('datatable_editor', 'Clienteprecios::datatable_editor', ['as' => 'editorOfClienteprecios']); +}); +$routes->resource('clienteprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteprecios', 'except' => 'show,new,create,update']); + $routes->group('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes'], function ($routes) { $routes->get('', 'Clienteplantillaprecios::index', ['as' => 'clienteplantillapreciosList']); @@ -360,6 +366,7 @@ $routes->group('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clien $routes->post('edit/(:num)', 'Clienteplantillaprecios::edit/$1', ['as' => 'updateClienteplantillaprecios']); $routes->get('delete/(:num)', 'Clienteplantillaprecios::delete/$1', ['as' => 'deleteClienteplantillaprecios']); $routes->post('datatable', 'Clienteplantillaprecios::datatable', ['as' => 'dataTableOfClientesplantillaprecios']); + $routes->post('menuitems', 'Clienteplantillaprecios::menuItems', ['as' => 'menuItemsOfClienteplantillaprecios']); }); $routes->resource('clienteplantillaprecios', ['namespace' => 'App\Controllers\Clientes', 'controller' => 'Clienteplantillaprecios', 'except' => 'show,new,create,update']); diff --git a/ci4/app/Controllers/Clientes/Cliente.php b/ci4/app/Controllers/Clientes/Cliente.php index 5d2867a3..5aa05865 100755 --- a/ci4/app/Controllers/Clientes/Cliente.php +++ b/ci4/app/Controllers/Clientes/Cliente.php @@ -231,6 +231,7 @@ class Cliente extends \App\Controllers\GoBaseResourceController //var_dump($clienteEntity); dd(); $this->viewData['clienteEntity'] = $clienteEntity; + $this->viewData['precioTemplate'] = $this->getPrecioTemplate($id); $this->viewData['comunidadAutonomaList'] = $this->getComunidadAutonomaListItems($clienteEntity->comunidad_autonoma_id ?? null); $this->viewData['provinciaList'] = $this->getProvinciaListItems($clienteEntity->provincia_id ?? null); $this->viewData['paisList'] = $this->getPaisListItems($clienteEntity->pais_id ?? null); @@ -438,4 +439,25 @@ class Cliente extends \App\Controllers\GoBaseResourceController return $data; } + + protected function getPrecioTemplate($cliente_id){ + + $modelPreciosCliente = model('App\Models\Clientes\ClientePreciosModel'); + $plantilla_id = $modelPreciosCliente->get_plantilla_precios($cliente_id); + if (is_null($plantilla_id)){ + return []; + } + $modelPlantillaPreciosCliente = model('App\Models\Clientes\ClientePlantillaPreciosModel'); + $plantilla = $modelPlantillaPreciosCliente->find($plantilla_id); + if ($plantilla == false){ + return []; + } + else{ + return (object)array( + "value" => $plantilla_id, + "label" => $plantilla->nombre + ); + } + + } } diff --git a/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php b/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php index ee2564e1..c6fa3ade 100755 --- a/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php +++ b/ci4/app/Controllers/Clientes/Clienteplantillaprecios.php @@ -240,6 +240,36 @@ class Clienteplantillaprecios extends \App\Controllers\GoBaseResourceController } } - + public function menuItems() + { + if ($this->request->isAJAX()) { + $searchStr = goSanitize($this->request->getPost('searchTerm'))[0]; + $reqId = goSanitize($this->request->getPost('id'))[0]; + $reqText = goSanitize($this->request->getPost('text'))[0]; + $onlyActiveOnes = false; + $columns2select = [$reqId ?? 'id', $reqText ?? 'nombre']; + $onlyActiveOnes = false; + try{ + $menu = $this->model->getSelect2MenuItems($columns2select, $columns2select[1], $onlyActiveOnes, $searchStr, true); + $nonItem = new \stdClass; + $nonItem->id = ''; + $nonItem->text = '- ' . lang('Basic.global.None') . ' -'; + array_unshift($menu, $nonItem); + } + catch(Exception $e){ + $menu = []; + } + + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + $data = [ + 'menu' => $menu, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + } else { + return $this->failUnauthorized('Invalid request', 403); + } + } } diff --git a/ci4/app/Controllers/Clientes/Clienteprecios.php b/ci4/app/Controllers/Clientes/Clienteprecios.php new file mode 100755 index 00000000..ad096cb2 --- /dev/null +++ b/ci4/app/Controllers/Clientes/Clienteprecios.php @@ -0,0 +1,237 @@ +viewData['pageTitle'] = lang('ClientesPrecios.plantillaPrecios_module'); + $this->viewData['usingSweetAlert'] = true; + + // Se indica que este controlador trabaja con soft_delete + $this->soft_delete = true; + // Se indica el flag para los ficheros borrados + $this->delete_flag = 1; + + $this->viewData = ['usingServerSideDataTable' => true]; // JJO + + parent::initController($request, $response, $logger); + } + + + public function update($requestedId = null) + { + $requestMethod = $this->request->getMethod(); + + if ($requestMethod === 'post') : + + if ($requestedId == null) : + return; + endif; + + $postData = $this->request->getJSON(); + + $plantilla_id = $postData->plantilla_id ?? -1; + + // Se ha actualizado un registro por lo que no es una plantilla + if($plantilla_id == -1){ + $this->model->clean_plantilla_id($requestedId); + } + else{ + $this->model->copy_from_plantilla($requestedId, $plantilla_id); + } + + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + $data = [ + $csrfTokenName => $newTokenHash + ]; + + return $this->respond($data); + + endif; // ($requestMethod === 'post') + } + + + + + + + public function datatable() + { + 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; + $requestedOrder = $reqData['order']['0']['column'] ?? 0; + $requestedOrder2 = $reqData['order']['1']['column'] ?? $requestedOrder; + $requestedOrder3 = $reqData['order']['2']['column'] ?? $requestedOrder; + $requestedOrder4 = $reqData['order']['3']['column'] ?? $requestedOrder; + $requestedOrder5 = $reqData['order']['4']['column'] ?? $requestedOrder; + $order = ClientePreciosModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 0]; + $order2 = ClientePreciosModel::SORTABLE[$requestedOrder2 >= 0 ? $requestedOrder2 : $requestedOrder]; + $order3 = ClientePreciosModel::SORTABLE[$requestedOrder3 >= 0 ? $requestedOrder3 : $requestedOrder]; + $order4 = ClientePreciosModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder4 : $requestedOrder]; + $order5 = ClientePreciosModel::SORTABLE[$requestedOrder4 >= 0 ? $requestedOrder5 : $requestedOrder]; + $dir = $reqData['order']['0']['dir'] ?? 'asc'; + $dir2 = $reqData['order']['1']['dir'] ?? $dir; + $dir3 = $reqData['order']['2']['dir'] ?? $dir; + $dir4= $reqData['order']['3']['dir'] ?? $dir; + $dir5= $reqData['order']['4']['dir'] ?? $dir; + + $cliente_id = $reqData['cliente_id'] ?? 0; + + $resourceData = $this->model->getResource($cliente_id) + ->orderBy($order, $dir)->orderBy($order2, $dir2)->orderBy($order3, $dir3)->orderBy($order4, $dir4)->orderBy($order5, $dir5) + ->limit($length, $start)->get()->getResultObject(); + return $this->respond(Collection::datatable( + $resourceData, + $this->model->getResource($cliente_id)->countAllResults(), + $this->model->getResource($cliente_id)->countAllResults() + )); + } else { + return $this->failUnauthorized('Invalid request', 403); + } + } + + 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_precios' ) + ->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( 'is_deleted' ), + Field::inst( 'tiempo_min' ) + ->validator( 'Validate::notEmpty',array( + 'message' => lang('ClientePrecios.validation.required')) + ) + ->validator('Validate::numeric', array( + 'message' => lang('ClientePrecios.validation.decimal')) + ), + + Field::inst( 'tiempo_max' ) + ->validator( 'Validate::notEmpty',array( + 'message' => lang('ClientePrecios.validation.required')) + ) + ->validator('Validate::numeric', array( + 'message' => lang('ClientePrecios.validation.decimal')) + ), + + Field::inst( 'precio_hora' ) + ->validator( 'Validate::notEmpty',array( + 'message' => lang('ClientePrecios.validation.required')) + ) + ->validator('Validate::numeric', array( + 'message' => lang('ClientePrecios.validation.decimal')) + ), + + Field::inst( 'margen' ) + ->validator( 'Validate::notEmpty',array( + 'message' => lang('ClientePrecios.validation.required')) + ) + ->validator('Validate::numeric', array( + '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]['cliente_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')); + }) + ->on('postCreate', function ($editor,$id, $values, $row ) { + $this->model->clean_plantilla_id($values['cliente_id']); + }) + ->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); + } + } + +} diff --git a/ci4/app/Language/en/ClientePrecios.php b/ci4/app/Language/en/ClientePrecios.php index 5c14e5b7..c48561eb 100755 --- a/ci4/app/Language/en/ClientePrecios.php +++ b/ci4/app/Language/en/ClientePrecios.php @@ -8,6 +8,8 @@ return [ 'plantillaPrecios_list' => 'List Customer fees templates', 'nombre' => 'Name', 'plantilla_id' => 'Template ID', + 'plantilla' => 'Prices template', + 'convertir2plantilla' => 'Convert to template', 'tipo' => 'Type', 'tipo_maquina' => 'Machine type', 'tipo_impresion' => 'Print type', diff --git a/ci4/app/Language/es/ClientePrecios.php b/ci4/app/Language/es/ClientePrecios.php index f87ace4f..4641a22f 100755 --- a/ci4/app/Language/es/ClientePrecios.php +++ b/ci4/app/Language/es/ClientePrecios.php @@ -8,6 +8,8 @@ return [ 'plantillaPrecios_list' => 'Lista Plantillas tarifas cliente', 'nombre' => 'Nombre', 'plantilla_id' => 'Plantilla ID', + 'plantilla' => 'Plantilla de precios', + 'convertir2plantilla' => 'Convertir a plantilla', 'tipo' => 'Tipo', 'tipo_maquina' => 'Tipo de máquina', 'tipo_impresion' => 'Tipo de impresión', diff --git a/ci4/app/Models/Clientes/ClientePreciosModel.php b/ci4/app/Models/Clientes/ClientePreciosModel.php index 093952cf..8e2b9f44 100644 --- a/ci4/app/Models/Clientes/ClientePreciosModel.php +++ b/ci4/app/Models/Clientes/ClientePreciosModel.php @@ -2,7 +2,7 @@ namespace App\Models\Clientes; -class ClientePlantillaPreciosLineasModel extends \App\Models\GoBaseModel +class ClientePreciosModel extends \App\Models\GoBaseModel { protected $table = "cliente_precios"; @@ -13,6 +13,16 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\GoBaseModel */ protected $useAutoIncrement = true; + const SORTABLE = [ + 0 => "t1.tipo", + 1 => "t1.tipo_maquina", + 2 => "t1.tipo_impresion", + 3 => "t1.tiempo_min", + 4 => "t1.tiempo_max", + 5 => "t1.precio_hora", + 6 => "t1.margen", + + ]; protected $allowedFields = [ "cliente_id", @@ -101,5 +111,126 @@ class ClientePlantillaPreciosLineasModel extends \App\Models\GoBaseModel ], ]; + function clean_plantilla_id($cliente_id = 0){ + $this->db + ->table($this->table . " t1") + ->where('cliente_id', $cliente_id) + ->set('plantilla_id', null) + ->update(); + } + + function delete_values($cliente_id = 0){ + $this->db + ->table($this->table . " t1") + ->where('cliente_id', $cliente_id) + ->delete(); + } + + function copy_from_plantilla($cliente_id = 0, $plantilla_id = 0){ + + $session = session(); + $datetime = (new \CodeIgniter\I18n\Time("now")); + $date_value = $datetime->format('Y-m-d H:i:s'); + + // Se borran los valores existentes + $this->delete_values($cliente_id); + + // Se cargan los valores de la plantilla + $plantillaModel = model('App\Models\Clientes\ClientePlantillaPreciosLineasModel'); + $values = $plantillaModel->getResource($plantilla_id)->get()->getResultObject(); + foreach ($values as $value) { + $this->db + ->table($this->table . " t1") + ->set('cliente_id', $cliente_id) + ->set('plantilla_id', $plantilla_id) + ->set('tipo', $value->tipo) + ->set('tipo_maquina', $value->tipo_maquina) + ->set('tipo_impresion', $value->tipo_impresion) + ->set('tiempo_min', $value->tiempo_min) + ->set('tiempo_max', $value->tiempo_max) + ->set('margen', $value->margen) + ->set('user_updated_id', $session->id_user) + ->set('updated_at', $date_value) + ->insert(); + } + + } + + + /** + * Get resource data. + * + * @param string $search + * + * @return \CodeIgniter\Database\BaseBuilder + */ + public function getResource($cliente_id = -1) + { + $builder = $this->db + ->table($this->table . " t1") + ->select( + "t1.id as id, t1.plantilla_id AS plantilla_id, t1.cliente_id AS cliente_id, + t1.tipo AS tipo, t1.tipo_maquina AS tipo_maquina, t1.tipo_impresion AS tipo_impresion, + t1.tiempo_min AS tiempo_min, t1.tiempo_max AS tiempo_max, t1.precio_hora AS precio_hora, t1.margen AS margen, + t1.user_updated_id AS user_updated_id, t1.updated_at AS updated_at, CONCAT(t2.first_name, ' ', t2.last_name) AS user_updated" + ); + + $builder->join("auth_user t2", "t1.user_updated_id = t2.id_user", "left"); + + $builder->where('t1.is_deleted', 0); + $builder->where('t1.cliente_id', $cliente_id); + + + return $builder; + } + + + public function checkIntervals($data = [], $id_linea = null, $cliente_id = null){ + + helper('general'); + + if(floatval($data["tiempo_min"])>= floatval($data["tiempo_max"])){ + return lang('ClientePrecios.errors.error_tiempo_range'); + } + + $rows = $this->db + ->table($this->table) + ->select("id, tiempo_min, tiempo_max") + ->where("is_deleted", 0) + ->where("tipo", $data["tipo"]) + ->where("tipo_maquina", $data["tipo_maquina"]) + ->where("tipo_impresion", $data["tipo_impresion"]) + ->where("cliente_id", $cliente_id) + ->get()->getResultObject(); + + + foreach ($rows as $row) { + if (!is_null($id_linea)){ + if($row->id == $id_linea){ + continue; + } + } + if(check_overlap(floatval($data["tiempo_min"]), floatval($data["tiempo_max"]), + $row->tiempo_min, $row->tiempo_max)){ + return lang('ClientePrecios.errors.error_tiempo_overlap'); + } + } + + return ""; + } + + public function get_plantilla_precios($cliente_id = -1){ + $value = $this->db + ->table($this->table) + ->select("plantilla_id") + ->where("is_deleted", 0) + ->where("cliente_id", $cliente_id) + ->limit(1)->get()->getResultObject(); + + if(count($value)>0){ + return $value[0]->plantilla_id; + } + return null; + } } diff --git a/ci4/app/Models/GoBaseModel.php b/ci4/app/Models/GoBaseModel.php index bce07f9e..7664ed2b 100755 --- a/ci4/app/Models/GoBaseModel.php +++ b/ci4/app/Models/GoBaseModel.php @@ -181,7 +181,7 @@ abstract class GoBaseModel extends Model { * @param null $searchStr * @return array */ - public function getSelect2MenuItems(array $columns2select = ['id', 'designation'], $resultSorting=null, bool $onlyActiveOnes=true, $searchStr = null) { + public function getSelect2MenuItems(array $columns2select = ['id', 'designation'], $resultSorting=null, bool $onlyActiveOnes=true, $searchStr = null, $isDeleteField=false) { $theseConditionsAreMet = []; @@ -199,6 +199,9 @@ abstract class GoBaseModel extends Model { $theseConditionsAreMet['active'] = true; } } + //JJO + if($isDeleteField) + $theseConditionsAreMet['is_deleted'] = 0; $queryBuilder = $this->db->table($this->table); $queryBuilder->select([$id, $text]); diff --git a/ci4/app/Views/themes/backend/vuexy/form/clientes/cliente/_clienteFormItems.php b/ci4/app/Views/themes/backend/vuexy/form/clientes/cliente/_clienteFormItems.php index b824c23c..ec6ab53f 100755 --- a/ci4/app/Views/themes/backend/vuexy/form/clientes/cliente/_clienteFormItems.php +++ b/ci4/app/Views/themes/backend/vuexy/form/clientes/cliente/_clienteFormItems.php @@ -16,6 +16,18 @@ +