diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index a71c49fa..01b4b1e4 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -401,7 +401,7 @@ $routes->group('tarifasenvios', ['namespace' => 'App\Controllers\Tarifas'], func $routes->post('add', 'Tarifasenvios::add', ['as' => 'createTarifaEnvio']); $routes->post('create', 'Tarifasenvios::create', ['as' => 'ajaxCreateTarifaEnvio']); $routes->put('(:num)/update', 'Tarifasenvios::update/$1', ['as' => 'ajaxUpdateTarifaEnvio']); - $routes->post('(:num)/edit', 'Tarifasenvios::edit/$1', ['as' => 'updateTarifaEnvio']); + $routes->post('edit/(:num)', 'Tarifasenvios::edit/$1', ['as' => 'updateTarifaEnvio']); $routes->post('datatable', 'Tarifasenvios::datatable', ['as' => 'dataTableOfTarifaEnvio']); $routes->post('allmenuitems', 'Tarifasenvios::allItemsSelect', ['as' => 'select2ItemsOfTarifaEnvio']); $routes->post('menuitems', 'Tarifasenvios::menuItems', ['as' => 'menuItemsOfTarifaEnvio']); @@ -410,10 +410,10 @@ $routes->resource('tarifasenvios', ['namespace' => 'App\Controllers\Tarifas', ' $routes->group('tarifasenviosprecios', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) { - $routes->post('datatable', 'Tarifasenvioserecios::datatable', ['as' => 'dataTableOfTarifasEnvioPrecios']); - $routes->post('datatable_editor', 'Tarifasenvioserecios::datatable_editor', ['as' => 'editorOfTarifasEnvioPrecios']); + $routes->post('datatable', 'Tarifasenviosprecios::datatable', ['as' => 'dataTableOfTarifasEnvioPrecios']); + $routes->post('datatable_editor', 'Tarifasenviosprecios::datatable_editor', ['as' => 'editorOfTarifasEnvioPrecios']); }); -$routes->resource('tarifasenviosprecios', ['namespace' => 'App\Controllers\Tarifas', 'controller' => 'Tarifasenvioserecios', 'except' => 'show,new,create,update']); +$routes->resource('tarifasenviosprecios', ['namespace' => 'App\Controllers\Tarifas', 'controller' => 'Tarifasenviosprecios', 'except' => 'show,new,create,update']); $routes->group('tarifasenvioszonas', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) { diff --git a/ci4/app/Controllers/Tarifas/Tarifasenvios.php b/ci4/app/Controllers/Tarifas/Tarifasenvios.php index 15c72682..0eb098b9 100644 --- a/ci4/app/Controllers/Tarifas/Tarifasenvios.php +++ b/ci4/app/Controllers/Tarifas/Tarifasenvios.php @@ -191,12 +191,12 @@ class Tarifasenvios extends \App\Controllers\GoBaseResourceController { $tarifaEnvioEntity->fill($sanitizedData); - $thenRedirect = true; + $thenRedirect = false; endif; if ($noException && $successfulResult) : $id = $tarifaEnvioEntity->id ?? $id; $message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('TarifasEnvios.tarifaEnvio'))]).'.'; - $message .= anchor( "admin/tarifasenvios/{$id}/edit" , lang('Basic.global.continueEditing').'?'); + //$message .= anchor( "admin/tarifasenvios/{$id}/edit" , lang('Basic.global.continueEditing').'?'); $message = ucfirst(str_replace("'", "\'", $message)); if ($thenRedirect) : @@ -215,7 +215,7 @@ class Tarifasenvios extends \App\Controllers\GoBaseResourceController { $this->viewData['tarifaEnvioEntity'] = $tarifaEnvioEntity; $this->viewData['paisList'] = $this->getPaisListItems(); - $this->viewData['formAction'] = route_to('updateTarifaEnvio', $id); + $this->viewData['formAction'] = route_to('updateTarifaEnvio', $id); $this->viewData['boxTitle'] = lang('Basic.global.edit2').' '.lang('TarifasEnvios.moduleTitle').' '.lang('Basic.global.edit3'); @@ -238,8 +238,8 @@ class Tarifasenvios extends \App\Controllers\GoBaseResourceController { $start = $reqData['start'] ?? 0; $length = $reqData['length'] ?? 5; $search = $reqData['search']['value']; - $requestedOrder = $reqData['order']['0']['column'] ?? 1; - $order = TarifaEnvioModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1]; + $requestedOrder = $reqData['order']['0']['column'] ?? 0; + $order = TarifaEnvioModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0]; $dir = $reqData['order']['0']['dir'] ?? 'asc'; $resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); diff --git a/ci4/app/Controllers/Tarifas/Tarifasenvioserecios.php b/ci4/app/Controllers/Tarifas/Tarifasenviosprecios.php similarity index 93% rename from ci4/app/Controllers/Tarifas/Tarifasenvioserecios.php rename to ci4/app/Controllers/Tarifas/Tarifasenviosprecios.php index 16626478..6284a4a4 100644 --- a/ci4/app/Controllers/Tarifas/Tarifasenvioserecios.php +++ b/ci4/app/Controllers/Tarifas/Tarifasenviosprecios.php @@ -17,7 +17,7 @@ use DataTables\Editor, DataTables\Editor\Field; -class Tarifasenvioserecios extends \App\Controllers\GoBaseResourceController { +class Tarifasenviosprecios extends \App\Controllers\GoBaseResourceController { protected $modelName = TarifaEnvioPrecioModel::class; protected $format = 'json'; @@ -268,7 +268,15 @@ class Tarifasenvioserecios extends \App\Controllers\GoBaseResourceController { foreach ($data['data'] as $pkey => $values) { // Si no se quiere borrar... if ($data['data'][$pkey]['is_deleted'] != 1) { - /*Los CP son string... consultar si checkear*/ + $process_data['peso_min'] = $data['data'][$pkey]['peso_min']; + $process_data['peso_max'] = $data['data'][$pkey]['peso_max']; + $process_data['proveedor_id'] = $data['data'][$pkey]['proveedor_id']; + $process_data['tipo_envio'] = $data['data'][$pkey]['tipo_envio']; + $response = $this->model->checkIntervals($process_data, $pkey, $data['data'][$pkey]['zona_envio_id']); + // No se pueden duplicar valores al crear o al editar + if (!empty($response)) { + return $response; + } } } } @@ -325,12 +333,14 @@ class Tarifasenvioserecios extends \App\Controllers\GoBaseResourceController { $order = TarifaEnvioPrecioModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1]; $dir = $reqData['order']['0']['dir'] ?? 'asc'; - $resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); + $zona_envio_id = $reqData['zona_envio_id'] ?? -1; + + $resourceData = $this->model->getResource($search, $zona_envio_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); return $this->respond(Collection::datatable( $resourceData, $this->model->getResource()->countAllResults(), - $this->model->getResource($search)->countAllResults() + $this->model->getResource($search, $zona_envio_id)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); diff --git a/ci4/app/Controllers/Tarifas/Tarifasenvioszonas.php b/ci4/app/Controllers/Tarifas/Tarifasenvioszonas.php index 3efde431..1c3271c2 100644 --- a/ci4/app/Controllers/Tarifas/Tarifasenvioszonas.php +++ b/ci4/app/Controllers/Tarifas/Tarifasenvioszonas.php @@ -10,6 +10,7 @@ use App\Entities\Tarifas\TarifaEnvioZonaEntity; use App\Models\Tarifas\TarifaEnvioModel; use App\Models\Tarifas\TarifaEnvioZonaModel; +use App\Models\Tarifas\TarifaEnvioPrecioModel; use DataTables\Editor, @@ -208,6 +209,43 @@ class Tarifasenvioszonas extends \App\Controllers\GoBaseResourceController { } // end function edit(...) + public function delete($id = null) + { + if (!empty(static::$pluralObjectNameCc) && !empty(static::$singularObjectNameCc)) { + $objName = mb_strtolower(lang(ucfirst(static::$pluralObjectNameCc).'.'.static::$singularObjectNameCc)); + } else { + $objName = lang('Basic.global.record'); + } + + if (!$this->soft_delete){ + + if (!$this->model->delete($id)) { + return $this->failNotFound(lang('Basic.global.deleteError', [$objName])); + } + } + else{ + $datetime = (new \CodeIgniter\I18n\Time("now")); + + $precioModel = new TarifaEnvioPrecioModel(); + $precioResult = $precioModel->removeAllPrecioLineas($id, $datetime, $this->delete_flag); + + $rawResult = $this->model->where('id',$id) + ->set(['deleted_at' => $datetime->format('Y-m-d H:i:s'), + 'is_deleted' => $this->delete_flag]) + ->update(); + + if (!$rawResult && !$precioResult) { + return $this->failNotFound(lang('Basic.global.deleteError', [$objName])); + } + + } + + // $message = lang('Basic.global.deleteSuccess', [$objName]); IMN commented + $message = lang('Basic.global.deleteSuccess', [lang('Basic.global.record')]); + $response = $this->respondDeleted(['id' => $id, 'msg' => $message]); + return $response; + } + public function datatable_editor() { if ($this->request->isAJAX()) { @@ -308,12 +346,14 @@ class Tarifasenvioszonas extends \App\Controllers\GoBaseResourceController { $order = TarifaEnvioZonaModel::SORTABLE[$requestedOrder >= 0 ? $requestedOrder : 0]; $dir = $reqData['order']['0']['dir'] ?? 'asc'; - $resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); + $tarifa_envio_id = $reqData['tarifa_envio_id'] ?? -1; + + $resourceData = $this->model->getResource($search, $tarifa_envio_id)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(); return $this->respond(Collection::datatable( $resourceData, $this->model->getResource()->countAllResults(), - $this->model->getResource($search)->countAllResults() + $this->model->getResource($search, $tarifa_envio_id)->countAllResults() )); } else { return $this->failUnauthorized('Invalid request', 403); diff --git a/ci4/app/Language/en/TarifasEnviosPrecios.php b/ci4/app/Language/en/TarifasEnviosPrecios.php index 1828053a..e58a12c2 100644 --- a/ci4/app/Language/en/TarifasEnviosPrecios.php +++ b/ci4/app/Language/en/TarifasEnviosPrecios.php @@ -3,7 +3,7 @@ return [ - 'a domicilio' => 'Home delivery', + 'aDomicilio' => 'Home delivery', 'cajas' => 'Boxes', 'createdAt' => 'Created At', 'deletedAt' => 'Deleted At', @@ -26,6 +26,8 @@ return [ 'userUpdatedId' => 'User Updated ID', 'validation' => [ 'error_seleccion_zonas' => 'A line from the zones table must be selected before creating a new record.', + 'error_precio_overlap' => 'The range [Min Weight, Max Weight] is overlapped with another one for the selected provider and type.', + 'error_precio_range' => 'The field Min Weight must be lower than the field Max Weight', 'peso_max' => [ 'decimal' => 'The field must contain a decimal number.', 'required' => 'The field is required.', diff --git a/ci4/app/Language/es/TarifasEnviosPrecios.php b/ci4/app/Language/es/TarifasEnviosPrecios.php index a1e020d8..c2af4492 100644 --- a/ci4/app/Language/es/TarifasEnviosPrecios.php +++ b/ci4/app/Language/es/TarifasEnviosPrecios.php @@ -3,7 +3,7 @@ return [ - 'a domicilio' => 'A domicilio', + 'aDomicilio' => 'A domicilio', 'cajas' => 'Cajas', 'createdAt' => 'Created At', 'deletedAt' => 'Deleted At', @@ -26,6 +26,8 @@ return [ 'userUpdatedId' => 'User Updated ID', 'validation' => [ 'error_seleccion_zonas' => 'Debe seleccionar una línea de la tabla zonas antes de crear un registro nuevo.', + 'error_precio_overlap' => 'El rango [Peso Min, Peso Max] se solapa con otro existente para el proveedor y tipo seleccionado.', + 'error_precio_range' => 'El campo Peso Min debe ser menor que el campo Peso Max', 'peso_max' => [ 'decimal' => 'El campo debe contener un número decimal.', 'required' => 'El campo es obligatorio.', diff --git a/ci4/app/Models/Compras/ProveedorModel.php b/ci4/app/Models/Compras/ProveedorModel.php index 4acbc281..45ec3589 100644 --- a/ci4/app/Models/Compras/ProveedorModel.php +++ b/ci4/app/Models/Compras/ProveedorModel.php @@ -207,8 +207,9 @@ class ProveedorModel extends \App\Models\GoBaseModel $builder = $this->db ->table($this->table . " t1") ->select( - "t1.id AS value, t1.nombre AS label") - ->where("tipo_id", $tipoId); + "t1.id AS value, t1.nombre AS label, t1.propiedades AS options") + ->where("tipo_id", $tipoId) + ->orderBy('t1.nombre', 'asc'); return $builder->get()->getResultObject(); } diff --git a/ci4/app/Models/Tarifas/TarifaEnvioPrecioModel.php b/ci4/app/Models/Tarifas/TarifaEnvioPrecioModel.php index d97b96aa..b7cb9f50 100644 --- a/ci4/app/Models/Tarifas/TarifaEnvioPrecioModel.php +++ b/ci4/app/Models/Tarifas/TarifaEnvioPrecioModel.php @@ -116,7 +116,7 @@ class TarifaEnvioPrecioModel extends \App\Models\GoBaseModel * * @return \CodeIgniter\Database\BaseBuilder */ - public function getResource(string $search = "") + public function getResource(string $search = "", $zona_envio_id = -1) { $builder = $this->db ->table($this->table . " t1") @@ -126,7 +126,8 @@ class TarifaEnvioPrecioModel extends \App\Models\GoBaseModel ); $builder->join("tarifas_envios_zonas t2", "t1.zona_envio_id = t2.id", "left"); $builder->join("lg_proveedores t3", "t1.proveedor_id = t3.id", "left"); - + $builder->where("t1.zona_envio_id", $zona_envio_id); + //JJO $builder->where("t1.is_deleted", 0); @@ -148,4 +149,50 @@ class TarifaEnvioPrecioModel extends \App\Models\GoBaseModel ->orLike("t3.nombre", $search) ->groupEnd(); } + + + public function checkIntervals($data = [], $precio_id = null, $zona_id = null){ + + helper('general'); + + if(floatval($data["peso_min"])>= floatval($data["peso_max"])){ + return lang('TarifasEnviosPrecios.validation.error_precio_range'); + } + + $rows = $this->db + ->table($this->table) + ->select("id, proveedor_id, tipo_envio, peso_min, peso_max") + ->where("is_deleted", 0) + ->where("zona_envio_id", $zona_id) + ->get()->getResultObject(); + + + foreach ($rows as $row) { + if (!is_null($precio_id)){ + if($row->id == $precio_id){ + continue; + } + } + if($row->proveedor_id == $data["proveedor_id"] && $row->tipo_envio == $data["tipo_envio"]){ + if(check_overlap(floatval($data["peso_min"]), floatval($data["peso_max"]), + $row->peso_min, $row->peso_max)){ + return lang('TarifasEnviosPrecios.validation.error_precio_overlap'); + } + } + } + + return ""; + } + + public function removeAllPrecioLineas($zona_id = -1, $datetime = null, $delete_flag=1){ + + $builder = $this->db + ->table($this->table) + ->set(['deleted_at' => $datetime->format('Y-m-d H:i:s'), + 'is_deleted' => $delete_flag]) + ->where('zona_envio_id',$zona_id) + ->update(); + + return $builder; + } } diff --git a/ci4/app/Models/Tarifas/TarifaEnvioZonaModel.php b/ci4/app/Models/Tarifas/TarifaEnvioZonaModel.php index f0759b5c..f6c8e6d4 100644 --- a/ci4/app/Models/Tarifas/TarifaEnvioZonaModel.php +++ b/ci4/app/Models/Tarifas/TarifaEnvioZonaModel.php @@ -18,7 +18,7 @@ class TarifaEnvioZonaModel extends \App\Models\GoBaseModel 2 => "t1.importe_fijo", ]; - protected $allowedFields = ["tarifa_envio_id", "cp_inicial", "cp_final", "importe_fijo"]; + protected $allowedFields = ["tarifa_envio_id", "cp_inicial", "cp_final", "importe_fijo", "is_deleted", "deleted_at"]; protected $returnType = "App\Entities\Tarifas\TarifaEnvioZonaEntity"; protected $useTimestamps = true; @@ -88,14 +88,15 @@ class TarifaEnvioZonaModel extends \App\Models\GoBaseModel * * @return \CodeIgniter\Database\BaseBuilder */ - public function getResource(string $search = "") + public function getResource(string $search = "", $tarifa_envio_id=-1) { $builder = $this->db ->table($this->table . " t1") ->select( - "t1.cp_inicial AS cp_inicial, t1.cp_final AS cp_final, t1.importe_fijo AS importe_fijo, t2.id AS tarifa_envio" + "t1.id as id, t1.cp_inicial AS cp_inicial, t1.cp_final AS cp_final, t1.importe_fijo AS importe_fijo, t2.id AS tarifa_envio" ); $builder->join("lg_tarifas_envios t2", "t1.tarifa_envio_id = t2.id", "left"); + $builder->where("t1.tarifa_envio_id", $tarifa_envio_id); //JJO $builder->where("t1.is_deleted", 0); diff --git a/ci4/app/Views/themes/backend/vuexy/form/tarifas/envios/viewTarifaEnvioForm.php b/ci4/app/Views/themes/backend/vuexy/form/tarifas/envios/viewTarifaEnvioForm.php index 8ac1be99..07dfc502 100644 --- a/ci4/app/Views/themes/backend/vuexy/form/tarifas/envios/viewTarifaEnvioForm.php +++ b/ci4/app/Views/themes/backend/vuexy/form/tarifas/envios/viewTarifaEnvioForm.php @@ -48,7 +48,7 @@ - + @@ -81,7 +81,7 @@ - + @@ -127,10 +127,10 @@ // Delete row $(document).on('click', '.btn-delete', function(e) { $(".btn-remove").attr('data-id', $(this).attr('data-id')); - if($(this).closest('table').attr('id').includes('zonas')){ + if($(this).closest('table').attr('id').includes('Zonas')){ $(".btn-remove").attr('table', "zonas"); } - else if($(this).closest('table').attr('id').includes('precios')){ + else if($(this).closest('table').attr('id').includes('Precios')){ $(".btn-remove").attr('table', "precios"); } else{ @@ -234,8 +234,8 @@ dom: '<"mt-4"><"float-end"B><"float-start"l><"mt-4 mb-3"p>', ajax : $.fn.dataTable.pipeline( { url: '', - data: function ( d ) { - d.tarifa_envio_id = id; + data: { + tarifa_envio_id: id, }, method: 'POST', headers: {'X-Requested-With': 'XMLHttpRequest'}, @@ -301,7 +301,11 @@ theTable.row($(row)).invalidate().draw(); popSuccessAlert(data.msg ?? jqXHR.statusText); }).fail((jqXHR, textStatus, errorThrown) => { - popErrorAlert(jqXHR.responseJSON.messages.error) + if(typeof jqXHR.responseJSON.messages != "undefined") + popErrorAlert(jqXHR.responseJSON.messages.error); + else + popErrorAlert(jqXHR.responseJSON.message); + $('#confirm2delete').modal('toggle'); }); } @@ -344,7 +348,8 @@ const lastColNr2 = $('#tableOfPrecios').find("tr:first th").length - 1; "name": "proveedor_id", "type": "select" }, { - name: "tipo_envio" + name: "tipo_envio", + "type": "select" }, { name: "peso_min" }, { @@ -356,9 +361,6 @@ const lastColNr2 = $('#tableOfPrecios').find("tr:first th").length - 1; }, { "name": "zona_envio_id", "type": "hidden" - }, { - "name": "proveedor_id", - "type": "hidden" }, { "name": "deleted_at", "type": "hidden" @@ -369,7 +371,7 @@ const lastColNr2 = $('#tableOfPrecios').find("tr:first th").length - 1; ] } ); - // Generación de la lista de proveedores (id, nombre) para encuadernación + // Generación de la lista de proveedores (id, nombre) const suppliersList = ; editor2.field( 'proveedor_id' ).update( suppliersList ); @@ -384,7 +386,25 @@ const lastColNr2 = $('#tableOfPrecios').find("tr:first th").length - 1; } }); - + + editor2.dependent('proveedor_id', function (val, data, callback, e ) { + + var supplier = suppliersList.find(o => o.value === val); + values = [{label:'', value: "a domicilio"}]; + + if(supplier.options != null) + { + if(supplier.options.includes("cajas")){ + values.push({label:'', value: "cajas"}); + } + if(supplier.options.includes("palets")){ + values.push({label:'', value: "palets"}); + } + } + editor2.field( 'tipo_envio' ).update( values ); + callback(true); + }); + editor2.on( 'postSubmit', function ( e, json, data, action ) { yeniden(json.); @@ -397,7 +417,7 @@ const lastColNr2 = $('#tableOfPrecios').find("tr:first th").length - 1; theTable2.draw(); }); - + var theTable2 = $('#tableOfPrecios').DataTable( { serverSide: true, processing: true, @@ -421,8 +441,21 @@ const lastColNr2 = $('#tableOfPrecios').find("tr:first th").length - 1; async: true, }), columns: [ - { 'data': 'proveedor' }, - { 'data': 'tipo_envio' }, + {'data': 'proveedor_id', + render: function(data, type, row, meta) { + var value = suppliersList.find(element => element.value === data); + return value['label']; + }, + }, + { 'data': 'tipo_envio', "render": function ( data, type, row, meta ) { + if(data=='a domicilio') + return ''; + else if (data=='cajas') + return ''; + else if (data=='palets') + return ''; + } + }, { 'data': 'peso_min' }, { 'data': 'peso_max' }, { 'data': 'precio' }, diff --git a/ci4/app/Views/themes/backend/vuexy/form/tarifas/envios/viewTarifaEnvioList.php b/ci4/app/Views/themes/backend/vuexy/form/tarifas/envios/viewTarifaEnvioList.php index 4d56ae20..fa923f6a 100644 --- a/ci4/app/Views/themes/backend/vuexy/form/tarifas/envios/viewTarifaEnvioList.php +++ b/ci4/app/Views/themes/backend/vuexy/form/tarifas/envios/viewTarifaEnvioList.php @@ -81,7 +81,7 @@ { orderable: false, searchable: false, - targets: [0,lastColNr] + targets: [lastColNr] } ], columns : [ @@ -96,7 +96,7 @@ $(document).on('click', '.btn-edit', function(e) { - window.location.href = `/tarifas/tarifasenvios/edit/${$(this).attr('data-id')}/edit`; + window.location.href = `/tarifas/tarifasenvios/edit/${$(this).attr('data-id')}`; }); $(document).on('click', '.btn-delete', function(e) {