From 80016b57f58721196465b77e57dc029d43566fd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Jim=C3=A9nez?= Date: Fri, 5 May 2023 13:38:24 +0200 Subject: [PATCH] Integracion de la lista tarifaacabado sacada del Mac.Comit antes del merge para que nacho lo coja y meta el vuexy --- ci4/app/Config/Routes.php | 22 + ci4/app/Controllers/GoBaseController.php | 490 ++++++++++++++++++ ci4/app/Controllers/Tarifas/Tarifaacabado.php | 252 ++++++++- ci4/app/Controllers/Usuarios/Group.php | 4 +- .../Entities/Tarifas/TarifaacabadoEntity.php | 32 ++ ci4/app/Filters/LoginAuthFilter.php | 1 + ci4/app/Language/en/Basic.php | 89 ++++ ci4/app/Language/en/Paises.php | 63 +++ ci4/app/Language/en/Tarifaacabado.php | 82 +++ ci4/app/Language/es/Basic.php | 89 ++++ ci4/app/Language/es/Paises.php | 87 ++++ ci4/app/Language/es/Tarifaaacabado.php | 114 ++++ ci4/app/Models/GoBaseModel.php | 249 +++++++++ ci4/app/Models/Tarifas/TarifaacabadoModel.php | 112 ++++ .../themes/_commonPartialsBs/_alertBoxes.php | 81 +++ .../_commonPartialsBs/_confirm2delete.php | 17 + .../_form_validation_errors.php | 35 ++ .../themes/_commonPartialsBs/datatables.php | 184 +++++++ .../themes/_commonPartialsBs/select2bs5.php | 19 + .../themes/_commonPartialsBs/sweetalert.php | 48 ++ .../acabado/_tarifaacabadoFormItems.php | 70 +++ .../tarifas/acabado/viewTarifaacabadoForm.php | 25 + .../tarifas/acabado/viewTarifaacabadoList.php | 93 ++++ .../backend/focus2/main/defaultlayout.php | 211 ++++++++ .../themes/backend/focus2/main/header.php | 4 +- .../Views/themes/backend/focus2/main/menu.php | 4 +- 26 files changed, 2442 insertions(+), 35 deletions(-) create mode 100644 ci4/app/Controllers/GoBaseController.php create mode 100644 ci4/app/Entities/Tarifas/TarifaacabadoEntity.php create mode 100644 ci4/app/Language/en/Basic.php create mode 100644 ci4/app/Language/en/Paises.php create mode 100644 ci4/app/Language/en/Tarifaacabado.php create mode 100644 ci4/app/Language/es/Basic.php create mode 100644 ci4/app/Language/es/Paises.php create mode 100644 ci4/app/Language/es/Tarifaaacabado.php create mode 100644 ci4/app/Models/GoBaseModel.php create mode 100644 ci4/app/Models/Tarifas/TarifaacabadoModel.php create mode 100644 ci4/app/Views/themes/_commonPartialsBs/_alertBoxes.php create mode 100644 ci4/app/Views/themes/_commonPartialsBs/_confirm2delete.php create mode 100644 ci4/app/Views/themes/_commonPartialsBs/_form_validation_errors.php create mode 100644 ci4/app/Views/themes/_commonPartialsBs/datatables.php create mode 100644 ci4/app/Views/themes/_commonPartialsBs/select2bs5.php create mode 100644 ci4/app/Views/themes/_commonPartialsBs/sweetalert.php create mode 100644 ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/_tarifaacabadoFormItems.php create mode 100644 ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/viewTarifaacabadoForm.php create mode 100644 ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/viewTarifaacabadoList.php create mode 100644 ci4/app/Views/themes/backend/focus2/main/defaultlayout.php diff --git a/ci4/app/Config/Routes.php b/ci4/app/Config/Routes.php index 294e7bd2..3ae7f096 100644 --- a/ci4/app/Config/Routes.php +++ b/ci4/app/Config/Routes.php @@ -32,6 +32,26 @@ $routes->setAutoRoute(true); // We get a performance increase by specifying the default // route since we don't have to scan directories. +$routes->group('', [], function($routes) { + + + + $routes->group('tarifaacabado', ['namespace' => 'App\Controllers\Tarifas'], function ($routes) { + $routes->get('', 'Tarifaacabado::index', ['as' => 'tarifaacabadoList']); + $routes->get('index', 'Tarifaacabado::index', ['as' => 'tarifaacabadoIndex']); + $routes->get('list', 'Tarifaacabado::index', ['as' => 'tarifaacabadoList2']); + $routes->get('add', 'Tarifaacabado::add', ['as' => 'newTarifaacabado']); + $routes->post('add', 'Tarifaacabado::add', ['as' => 'createTarifaacabado']); + $routes->get('edit/(:num)', 'Tarifaacabado::edit/$1', ['as' => 'editTarifaacabado']); + $routes->post('edit/(:num)', 'Tarifaacabado::edit/$1', ['as' => 'updateTarifaacabado']); + $routes->get('delete/(:num)', 'Tarifaacabado::delete/$1', ['as' => 'deleteTarifaacabado']); + $routes->post('allmenuitems', 'Tarifaacabado::allItemsSelect', ['as' => 'select2ItemsOfTarifasacabado']); + $routes->post('menuitems', 'Tarifaacabado::menuItems', ['as' => 'menuItemsOfTarifasacabado']); + }); + + }); + + //WEB ROUTER ------------------------------------------------------ //------------------------------------------------------------------ $routes->get('/', 'Home::index'); @@ -68,3 +88,5 @@ $routes->delete('api/user/(:segment)','Api::user/delete/$1'); if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) { require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php'; } + + diff --git a/ci4/app/Controllers/GoBaseController.php b/ci4/app/Controllers/GoBaseController.php new file mode 100644 index 00000000..04a9709c --- /dev/null +++ b/ci4/app/Controllers/GoBaseController.php @@ -0,0 +1,490 @@ +session = \Config\Services::session(); + + + if ((!isset($this->viewData['pageTitle']) || empty($this->viewData['pageTitle']) ) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) { + $this->viewData['pageTitle'] = ucfirst(static::$pluralObjectName); + } + + /*if ($this->usePageSubTitle) { + $this->pageSubTitle = config('Basics')->appName; + $this->viewData['pageSubTitle'] = ' '.$this->pageSubTitle; + }*/ + $this->viewData['errorMessage'] = $this->session->getFlashdata('errorMessage'); + $this->viewData['successMessage'] = $this->session->getFlashdata('successMessage'); + + if (empty(static::$controllerSlug)) { + $reflect = new \ReflectionClass($this); + $className = $reflect->getShortName(); + $this->viewData['currentModule'] = slugify(convertToSnakeCase(str_replace('Controller','',$className))); + + } else { + $this->viewData['currentModule'] = strtolower(static::$controllerSlug); + } + + $this->viewData['viewPath'] = static::$viewPath; + + if (!empty(static::$primaryModelName)) { + $primaryModel = model(static::$primaryModelName, true); + $this->primaryModel = $primaryModel; + $this->model = &$this->primaryModel; + } + + // Preload any models, libraries, etc, here. + + + // Language Validate + $language = \Config\Services::language(); + $language->setLocale($this->session->lang); + + // Set TimeZone + if(empty($this->session->get('settings'))){ + $settingsModel = new SettingsModel(); + $settings = $settingsModel->select('default_timezone')->first()??[]; + date_default_timezone_set($this->$settings['default_timezone']??'America/Sao_Paulo'); + }else{ + date_default_timezone_set($this->session->get('settings')['default_timezone']??'America/Sao_Paulo'); + } + + // Get notification + if(!empty($this->session->get('token'))) { + $notificationModel = new NotificationModel(); + $pulse = $notificationModel->where('user_recipient',$this->session->get('token'))->where('is_read',false)->countAllResults() ?? 0; + $notification = $notificationModel->select('token,title,is_read,created_at')->where('user_recipient',$this->session->get('token'))->orderBy('created_at','desc')->findAll(5) ?? []; + $this->session->set('notification', $notification); + $this->session->set('pulse', $pulse); + }else{ + $this->session->set('notification', []); + $this->session->set('pulse', 0); + } + + $this->viewData['currentLocale'] = $this->request->getLocale(); + + } + + public function index() { + + helper('text'); + + if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle']) ) && isset(static::$pluralObjectName) && !empty(static::$pluralObjectName)) { + $this->viewData['boxTitle'] = ucfirst(static::$pluralObjectName); + } + + if (isset($this->primaryModel) && isset(static::$singularObjectNameCc) && !empty(static::$singularObjectNameCc) && !isset($this->viewData[(static::$singularObjectNameCc) . 'List'])) { + $this->viewData[(static::$singularObjectNameCc) . 'List'] = $this->primaryModel->asObject()->findAll(); + } + + // if $this->currentView is assigned a view name, use it, otherwise assume the view something like 'viewSingleObjectList' + $viewFilePath = static::$viewPath . (empty($this->currentView) ? 'view' . ucfirst(static::$singularObjectNameCc) . 'List' : $this->currentView); + + echo view($viewFilePath, $this->viewData); + + + } + + /** + * Convenience method to display the form of a module + * @param $forMethod + * @param null $objId + * @return string + */ + protected function displayForm($forMethod, $objId = null) { + + helper('form'); + $this->viewData['usingSelect2'] = true; + + $validation = \Config\Services::validation(); + + $action = str_replace(static::class . '::', '', $forMethod); + $actionSuffix = ' '; + $formActionSuffix = ''; + + if ($action === 'add') { + $actionSuffix = empty(static::$singularObjectName) || stripos(static::$singularObjectName, 'new') === false ? ' a New ' : ' '; + } elseif ($action === 'edit' && $objId != null) { + $formActionSuffix = $objId . '/'; + } + + if (!isset($this->viewData['action'])) { + $this->viewData['action'] = $action; + } + + if (!isset($this->viewData['formAction'])) { + $this->viewData['formAction'] = base_url(strtolower($this->viewData['currentModule']) . '/' . $action . '/' . $formActionSuffix); + } + + if ((!isset($this->viewData['boxTitle']) || empty($this->viewData['boxTitle']) ) && isset(static::$singularObjectName) && !empty(static::$singularObjectName)) { + $this->viewData['boxTitle'] = ucfirst($action) . $actionSuffix . ucfirst(static::$singularObjectName); + } + + $this->viewData['validation'] = $validation; + + $viewFilePath = static::$viewPath . 'view' . ucfirst(static::$singularObjectNameCc) . 'Form'; + + return view($viewFilePath, $this->viewData); + } + + protected function redirect2listView($flashDataKey = null, $flashDataValue = null) { + + if (!empty($this->indexRoute)) { + $uri = base_url(route_to($this->indexRoute)); + } else { + + $reflect = new \ReflectionClass($this); + $className = $reflect->getShortName(); + + $routes = \Config\Services::routes(); + $routesOptions = $routes->getRoutesOptions(); + + if (!empty(static::$controllerSlug)) { + + if (isset($routesOptions[static::$controllerSlug])) { + $namedRoute = $routesOptions[static::$controllerSlug]['as']; + $uri = route_to($namedRoute); + } else { + $getHandlingRoutes = $routes->getRoutes('get'); + + $indexMethod = array_search('\\App\\Controllers\\'.$className.'::index', $getHandlingRoutes); + if ($indexMethod) { + $uri = route_to('App\\Controllers\\'.$className.'::index'); + } else { + $uri = base_url(static::$controllerSlug); + } + } + } else { + $uri = base_url($className); + } + } + + if ($flashDataKey != null && $flashDataValue != null) { + return redirect()->to($uri)->with($flashDataKey, $flashDataValue); + } else { + return redirect()->to($uri); + } + } + + public function delete($requestedId, bool $deletePermanently = true) { + + if (is_string($requestedId)) : + if (is_numeric($requestedId)) : + $id = filter_var($requestedId, FILTER_SANITIZE_NUMBER_INT); + else: + $onlyAlphaNumeric = true; + $fromGetRequest = true; + $idSanitization = goSanitize($requestedId, $onlyAlphaNumeric, $fromGetRequest); // filter_var(trim($requestedId), FILTER_SANITIZE_FULL_SPECIAL_CHARS); + $id = $idSanitization[0]; + endif; + else: + $id = intval($requestedId); + endif; + + if (empty($id) || $id === 0) : + $error = 'Invalid identifier provided to delete the object.'; + endif; + + $rawResult = null; + + if (!isset($error)) : + try { + if ($deletePermanently) : + if (is_numeric($id)) : + $rawResult = $this->primaryModel->delete($id); + else: + $rawResult = $this->primaryModel->where($this->primaryModel->getPrimaryKeyName(), $id)->delete(); + endif; + else: + $rawResult = $this->primaryModel->update($id, ['deleted' => true]); + endif; + } catch (\Exception $e) { + log_message('error', "Exception: Error deleting object named '".(static::$singularObjectName ?? 'unknown')."' with $id :\r\n".$e->getMessage()); + } + endif; + + $ar = $this->primaryModel->db->affectedRows(); + + try { + $dbError = $this->primaryModel->db->error(); + } catch (\Exception $e2) { + if ($e2->getMessage() != "Trying to get property 'errno' of non-object") { + log_message('error', $e2->getCode() . ' : ' . $e2->getMessage()) ; + } + } + if (isset($dbError['code']) && isset($dbError['message'])) { + log_message('error', $dbError['code'].' '.$dbError['message']); + } else { + $dbError = ['code' => '', 'message'=>'']; + } + + $result = ['persisted'=>$ar>0, 'ar'=>$ar, 'persistedId'=>null, 'affectedRows'=>$ar, 'errorCode'=>$dbError['code'], 'error'=>$dbError['message']]; + + $nameOfDeletedObject = static::$singularObjectNameCc; + + if ($ar < 1) : + $errorMessage = lang('Basic.global.deleteError', [$nameOfDeletedObject]); // 'No ' . static::$singularObjectName . ' was deleted now, because it probably had already been deleted.'; + $fdKey = isset($this->viewData['usingSweetAlert'] ) && $this->viewData['usingSweetAlert'] ? 'sweet-error' : 'errorMessage'; + $errorMessage = str_replace("'", "\'", $errorMessage); + return $this->redirect2listView($fdKey, str_replace("'", '', $errorMessage)); + else: + $message = lang('Basic.global.deleteSuccess', [$nameOfDeletedObject]); // 'The ' . static::$singularObjectName . ' was successfully deleted.'; + $fdKey = isset($this->viewData['usingSweetAlert'] ) && $this->viewData['usingSweetAlert'] ? 'sweet-success' : 'successMessage'; + if ($result['affectedRows']>1) : + log_message('warning', "More than one row has been deleted in attempt to delete row for object named '".(static::$singularObjectName ?? 'unknown')."' with id: $id"); + endif; + $message = str_replace("'", "\'", $message); + return $this->redirect2listView($fdKey, $message); + endif; + + } + + /** + * Convenience method to validate form submission + * @return bool + */ + protected function canValidate() + { + + $validationRules = $this->model->validationRules ?? $this->formValidationRules ?? null; + + if ($validationRules == null) { + return true; + } + + $validationErrorMessages = $this->model->validationMessages ?? $this->formValidationErrorMessagess ?? null;; + + if ($validationErrorMessages != null) { + $valid = $this->validate($validationRules, $validationErrorMessages); + } else { + $valid = $this->validate($validationRules); + } + + $this->validationErrors = $valid ? '' : $this->validator->getErrors(); + + /* + // As of version 1.1.5 of CodeIgniter Wizard, the following is replaced by custom validation errors template supported by CodeIgniter 4 + // If you are not using Bootstrap templates, however, you might want to uncomment this block... + $validation = \Config\Services::validation(); + $this->validation = $validation; + if (!$valid) { + $this->viewData['errorMessage'] .= $validation->listErrors(); + } + */ + return $valid; + } + + /** + * Method for post(ed) input sanitization. Override this when you have custom transformation needs, etc. + * @param array|null $postData + * @return array + */ + protected function sanitized(array $postData = null, bool $nullIfEmpty = false) { + if ($postData == null) { + $postData = $this->request->getPost(); + } + $sanitizedData = []; + foreach ($postData as $k => $v) { + if ($k == csrf_token()) { + continue; + } + $sanitizationResult = goSanitize($v, $nullIfEmpty); + $sanitizedData[$k] = $sanitizationResult[0]; + } + return $sanitizedData; + } + + /** + * Convenience method for common exception handling + * @param \Exception $e + */ + protected function dealWithException(\Exception $e) { + // using another try / catch block to prevent to avoid CodeIgniter bug throwing trivial exceptions for querying DB errors + try { + $query = $this->model->db->getLastQuery(); + $queryStr = !is_null($query) ? $query->getQuery() : ''; + $dbError = $this->model->db->error(); + $userFriendlyErrMsg = lang('Basic.global.persistErr1', [static::$singularObjectNameCc]); + if (isset($dbError['code']) && $dbError['code'] == 1062) : + $userFriendlyErrMsg .= PHP_EOL.lang('Basic.global.persistDuplErr', [static::$singularObjectNameCc]); + endif; + // $userFriendlyErrMsg = str_replace("'", "\'", $userFriendlyErrMsg); // Uncomment if experiencing unescaped single quote errors + log_message('error', $userFriendlyErrMsg.PHP_EOL.$e->getMessage().PHP_EOL.$queryStr); + if (isset($dbError['message']) && !empty($dbError['message'])) : + log_message('error', $dbError['code'].' : '.$dbError['message']); + endif; + $this->viewData['errorMessage'] = $userFriendlyErrMsg; + } catch (\Exception $e2) { + log_message('debug', 'You can probably safely ignore this: In attempt to check DB errors, CodeIgniter threw: '.PHP_EOL.$e2->getMessage()); + } + } + + // Collect the queries so something can be done with them later. + public static function collect(Query $query) { + static::$queries[] = $query; + } + + /** + * Class casting + * + * @param string|object $destination + * @param object $sourceObject + * @return object + */ + function cast($destination, $sourceObject) { + if (is_string($destination)) { + $destination = new $destination(); + } + $sourceReflection = new ReflectionObject($sourceObject); + $destinationReflection = new ReflectionObject($destination); + $sourceProperties = $sourceReflection->getProperties(); + foreach ($sourceProperties as $sourceProperty) { + $sourceProperty->setAccessible(true); + $name = $sourceProperty->getName(); + $value = $sourceProperty->getValue($sourceObject); + if ($destinationReflection->hasProperty($name)) { + $propDest = $destinationReflection->getProperty($name); + $propDest->setAccessible(true); + $propDest->setValue($destination, $value); + } else { + $destination->$name = $value; + } + } + return $destination; + } + +} diff --git a/ci4/app/Controllers/Tarifas/Tarifaacabado.php b/ci4/app/Controllers/Tarifas/Tarifaacabado.php index a4c41177..cc85a1f6 100644 --- a/ci4/app/Controllers/Tarifas/Tarifaacabado.php +++ b/ci4/app/Controllers/Tarifas/Tarifaacabado.php @@ -1,35 +1,231 @@ -viewData['pageTitle'] = lang('Tarifaacabado.moduleTitle'); + self::$viewPath = getenv('theme.path').'form/tarifas/acabado/'; + + parent::initController($request, $response, $logger); + + } + + public function index() { + + $this->viewData['usingClientSideDataTable'] = true; + + $this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifaacabado.tarifaacabado')]); + + parent::index(); + + } + + public function add() { + + + + $requestMethod = $this->request->getMethod(); + + if ($requestMethod === 'post') : + + $nullIfEmpty = true; // !(phpversion() >= '8.1'); + + $postData = $this->request->getPost(); + $sanitizedData = $this->sanitized($postData, $nullIfEmpty); + + + $noException = true; + if ($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', [mb_strtolower(lang('Tarifaacabado.tarifaacabado'))]); + $this->session->setFlashdata('formErrors', $this->model->errors()); + endif; + + $thenRedirect = true; // Change this to false if you want your user to stay on the form after submission + endif; + if ($noException && $successfulResult) : + + $id = $this->model->db->insertID(); + + $message = lang('Basic.global.saveSuccess', [mb_strtolower(lang('Tarifaacabado.tarifaacabado'))]).'.'; + $message .= anchor(route_to('editTarifaacabado', $id), lang('Basic.global.continueEditing').'?'); + $message = ucfirst(str_replace("'", "\'", $message)); + + if ($thenRedirect) : + if (!empty($this->indexRoute)) : + return redirect()->to(route_to($this->indexRoute))->with('successMessage', $message); + else: + return $this->redirect2listView('successMessage', $message); + endif; + else: + $this->viewData['successMessage'] = $message; + endif; + + endif; // $noException && $successfulResult + + endif; // ($requestMethod === 'post') + + $this->viewData['tarifaacabado_'] = isset($sanitizedData) ? new Tarifaacabado_($sanitizedData) : new Tarifaacabado_(); + + $this->viewData['formAction'] = route_to('createTarifaacabado'); + + $this->viewData['boxTitle'] = lang('Basic.global.addNew').' '.lang('Tarifaacabado.tarifaacabado').' '.lang('Basic.global.addNewSuffix'); + + + return $this->displayForm(__METHOD__); + } // end function add() + + public function edit($requestedId = null) { + + if ($requestedId == null) : + return $this->redirect2listView(); + endif; + $id = filter_var($requestedId, FILTER_SANITIZE_URL); + $tarifaacabado_ = $this->model->find($id); + + if ($tarifaacabado_ == false) : + $message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Tarifaacabado.tarifaacabado')), $id]); + return $this->redirect2listView('errorMessage', $message); + endif; + + $requestMethod = $this->request->getMethod(); + + if ($requestMethod === 'post') : + + $nullIfEmpty = true; // !(phpversion() >= '8.1'); + + $postData = $this->request->getPost(); + $sanitizedData = $this->sanitized($postData, $nullIfEmpty); + + + + $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('Tarifaacabado.tarifaacabado'))]); + $this->session->setFlashdata('formErrors', $this->model->errors()); + + endif; + + $tarifaacabado_->fill($sanitizedData); + + $thenRedirect = true; + endif; + if ($noException && $successfulResult) : + $id = $tarifaacabado_->id ?? $id; + $message = lang('Basic.global.updateSuccess', [mb_strtolower(lang('Tarifaacabado.tarifaacabado'))]).'.'; + $message .= anchor(route_to('editTarifaacabado', $id), lang('Basic.global.continueEditing').'?'); + $message = ucfirst(str_replace("'", "\'", $message)); + + if ($thenRedirect) : + if (!empty($this->indexRoute)) : + return redirect()->to(route_to($this->indexRoute))->with('successMessage', $message); + else: + return $this->redirect2listView('successMessage', $message); + endif; + else: + $this->viewData['successMessage'] = $message; + endif; + + endif; // $noException && $successfulResult + endif; // ($requestMethod === 'post') + + $this->viewData['tarifaacabado_'] = $tarifaacabado_; + + $this->viewData['formAction'] = route_to('updateTarifaacabado', $id); + + $this->viewData['boxTitle'] = lang('Basic.global.edit2').' '.lang('Tarifaacabado.tarifaacabado').' '.lang('Basic.global.edit3'); + + + return $this->displayForm(__METHOD__, $id); + } // end function edit(...) + + + + public function allItemsSelect() { + if ($this->request->isAJAX()) { + $onlyActiveOnes = true; + $reqVal = $this->request->getPost('val') ?? 'id'; + $menu = $this->model->getAllForMenu($reqVal.', Select a field...', 'Select a field...', $onlyActiveOnes, false); + $nonItem = new \stdClass; + $nonItem->id = ''; + //$nonItem->Select a field... = '- '.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 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 ?? 'Select a field...']; + $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); - public function index() - { - echo 'Tarifa acabado'; - } - - public function delete() - { - + $newTokenHash = csrf_hash(); + $csrfTokenName = csrf_token(); + $data = [ + 'menu' => $menu, + $csrfTokenName => $newTokenHash + ]; + return $this->respond($data); + } else { + return $this->failUnauthorized('Invalid request', 403); + } } - - public function add() - { - - } - - public function edit() - { - - } - + } - \ No newline at end of file diff --git a/ci4/app/Controllers/Usuarios/Group.php b/ci4/app/Controllers/Usuarios/Group.php index 3b61aa07..aa90cc7e 100644 --- a/ci4/app/Controllers/Usuarios/Group.php +++ b/ci4/app/Controllers/Usuarios/Group.php @@ -32,7 +32,7 @@ class Group extends BaseController $data['btn_add'] = [ 'title' => lang("App.group_btn_add"), - 'route' => '/group/add', + 'route' => '/usuarios/group/add', 'class' => 'btn btn-lg btn-primary float-md-right', 'icon' => 'fas fa-plus' ]; @@ -54,7 +54,7 @@ class Group extends BaseController $data['breadcrumb'] = [ ['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false], - ['title' => lang("App.group_title"), 'route' => "/group", 'active' => false], + ['title' => lang("App.group_title"), 'route' => "/usuarios/group", 'active' => false], ['title' => lang("App.group_add_title"), 'route' => "", 'active' => true] ]; diff --git a/ci4/app/Entities/Tarifas/TarifaacabadoEntity.php b/ci4/app/Entities/Tarifas/TarifaacabadoEntity.php new file mode 100644 index 00000000..bb217f9b --- /dev/null +++ b/ci4/app/Entities/Tarifas/TarifaacabadoEntity.php @@ -0,0 +1,32 @@ + null, + "nombre" => null, + "tirada_min" => 0, + "precio_min" => 0, + "tirada_max" => 0, + "precio_max" => null, + "ajuste" => 0, + "formula_price" => null, + "user_created_id" => 1, + "user_update_id" => 1, + "deleted_at" => null, + "created_at" => null, + "updated_at" => null, + ]; + protected $casts = [ + "tirada_min" => "int", + "precio_min" => "float", + "tirada_max" => "int", + "precio_max" => "float", + "ajuste" => "float", + "user_created_id" => "int", + "user_update_id" => "int", + ]; +} diff --git a/ci4/app/Filters/LoginAuthFilter.php b/ci4/app/Filters/LoginAuthFilter.php index 5e5f558e..f74bff93 100644 --- a/ci4/app/Filters/LoginAuthFilter.php +++ b/ci4/app/Filters/LoginAuthFilter.php @@ -140,6 +140,7 @@ class LoginAuthFilter implements FilterInterface 'Migrate', 'Test', + ]; } diff --git a/ci4/app/Language/en/Basic.php b/ci4/app/Language/en/Basic.php new file mode 100644 index 00000000..af3e20a9 --- /dev/null +++ b/ci4/app/Language/en/Basic.php @@ -0,0 +1,89 @@ + [ + 'About' => 'About', + 'AboutSuffix' => '', + 'Action' => 'Action', + 'Cancel' => 'Cancel', + 'ChangePassword' => 'Change Password', + 'Close' => 'Close', + 'Dashboard' => 'Dashboard', + 'Delete' => 'Delete', + 'Error' => 'Error', + 'Groups' => 'Groups', + 'Home' => 'Home', + 'Logout' => 'Logout', + 'ManageAllRecords' => 'Manage All {0} Records', + 'MemberSince' => 'Member since', + 'Members' => 'Members', + 'MoreInfo' => 'More Info', + 'None' => 'None', + 'Permissions' => 'Permissions', + 'Profile' => 'Profile', + 'Roles' => 'Roles', + 'Save' => 'Save', + 'Sections' => 'Sections', + 'SignOut' => 'Sign Out', + 'Success' => 'Success', + 'UserProfile' => 'User Profile', + 'Warning' => 'Warning', + 'add' => 'New', + 'addNew' => 'Add a New', + 'addNewSuffix' => '', + 'allRightsReserved' => 'All rights reserved.', + 'continueEditing' => 'Continue editing', + 'createdWith' => 'created with', + 'createdWithSuffix' => '.', + 'deleteConfirmation' => 'Confirmation to Delete Record', + 'deleteConfirmationButton' => 'Yes, Delete it!', + 'deleteConfirmationCancel' => 'Cancel', + 'deleteConfirmationQuestion' => 'Are you sure you want to delete this record?', + 'deleteError' => 'No {0} was deleted now, because it probably had already been deleted.', + 'deleteExistingFile' => 'Delete existing file', + 'deleteSuccess' => 'The {0} was successfully deleted.', + 'edit' => 'Edit', + 'edit2' => 'Edit', + 'edit3' => '', + 'for' => 'for', + 'forPrefix' => 'for', + 'forSuffix' => '', + 'formErr1' => 'The {0} was not saved due to an erroneous value entered on the form. ', + 'formErr2' => 'Please correct the errors below:', + 'formErrTitle' => 'There are some errors on the form that need to be corrected: ', + 'jsNeedMsg' => 'Either you have turned JavaScript off, or your browser does not support JavaScript which this page needs to function properly.', + 'need2login' => 'To access the members-only area, please sign in.', + 'notFoundWithIdErr' => 'No such {0} ( with identifier {1} ) was found in the database.', + 'persistDuplErr' => 'There already is an existing {0} on our database with the same data.', + 'persistErr1' => 'An error occurred in an attempt to save a new {0} to the database : ', + 'persistErr2' => 'The {0} was not saved because of an error.', + 'persistErr3' => 'An error occurred in an attempt to update the {0} with {1} {2} in the database : ', + 'pleaseSelect' => 'Please select...', + 'pleaseSelectA' => 'Please select a {0}... ', + 'pleaseSelectOne' => 'Please select one...', + 'record' => 'the record', + 'saveSuccess' => 'The {0} was successfully saved ', + 'saveSuccess1' => 'The {0} ', + 'saveSuccess2' => ' was successfully saved ', + 'saveSuccess3Suffix' => '', + 'saveSucessWithId' => ' with {0} {1}', + 'saveSucessWithName' => ' with name {0}', + 'updateFailure' => 'The {0} could not be updated ', + 'updateSuccess' => 'The {0} was successfully updated ', + 'updated' => 'Updated', + 'sweet' => [ + 'deleteConfirmationButton' => 'Yes, Delete it!', + 'sureToDeleteText' => 'This action cannot be undone.', + 'sureToDeleteTitle' => 'Are you sure you want to delete this {0}?', + 'text' => 'This action cannot be undone.', + 'title' => 'Are you sure?', + + ], + + + ], + + +]; \ No newline at end of file diff --git a/ci4/app/Language/en/Paises.php b/ci4/app/Language/en/Paises.php new file mode 100644 index 00000000..4f672819 --- /dev/null +++ b/ci4/app/Language/en/Paises.php @@ -0,0 +1,63 @@ + 'Code', + 'code3' => 'Code3', + 'id' => 'ID', + 'keyErp' => 'Key Erp', + 'moduleTitle' => 'Paises', + 'moneda' => 'Moneda', + 'nombre' => 'Nombre', + 'pais' => 'Pais', + 'paisList' => 'Pais List', + 'paises' => 'Paises', + 'showErp' => 'Show Erp', + 'urlErp' => 'URL Erp', + 'userErp' => 'User Erp', + 'validation' => [ + 'code3' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + + ], + + 'key_erp' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + + ], + + 'url_erp' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + + ], + + 'user_erp' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + + ], + + 'moneda' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + 'required' => 'The {field} field is required.', + + ], + + 'nombre' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + 'required' => 'The {field} field is required.', + + ], + + 'code' => [ + 'is_unique' => 'The {field} field must contain a unique value', + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + 'required' => 'The {field} field is required.', + + ], + + + ], + + +]; \ No newline at end of file diff --git a/ci4/app/Language/en/Tarifaacabado.php b/ci4/app/Language/en/Tarifaacabado.php new file mode 100644 index 00000000..3cd59a9a --- /dev/null +++ b/ci4/app/Language/en/Tarifaacabado.php @@ -0,0 +1,82 @@ + 'A', + 'createdAt' => 'Created At', + 'deletedAt' => 'Deleted At', + 'formulaPrice' => 'Formula Price', + 'id' => 'ID', + 'moduleTitle' => 'Finishing Rates', + 'nombre' => 'Name', + 'precioMax' => 'Price Max', + 'precioMin' => 'Price Min', + 'tarifaacabado' => 'Finishing Rates', + 'tarifaacabadoList' => 'Finishing Rates List', + 'tarifasacabado' => 'Finishing Rates', + 'tiradaMax' => 'Print Max', + 'tiradaMin' => 'Print Min', + 'updatedAt' => 'Updated At', + 'userCreatedId' => 'User ID Created At', + 'userUpdateId' => 'User ID Update At', + 'validation' => [ + 'ajuste' => [ + 'decimal' => 'The {field} field must contain a decimal number.', + 'required' => 'The {field} field is required.', + + ], + + 'formula_price' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + 'required' => 'The {field} field is required.', + + ], + + 'nombre' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + 'required' => 'The {field} field is required.', + + ], + + 'precio_max' => [ + 'decimal' => 'The {field} field must contain a decimal number.', + 'required' => 'The {field} field is required.', + + ], + + 'precio_min' => [ + 'decimal' => 'The {field} field must contain a decimal number.', + 'required' => 'The {field} field is required.', + + ], + + 'tirada_max' => [ + 'integer' => 'The {field} field must contain an integer.', + 'required' => 'The {field} field is required.', + + ], + + 'tirada_min' => [ + 'integer' => 'The {field} field must contain an integer.', + 'required' => 'The {field} field is required.', + + ], + + 'user_created_id' => [ + 'integer' => 'The {field} field must contain an integer.', + 'required' => 'The {field} field is required.', + + ], + + 'user_update_id' => [ + 'integer' => 'The {field} field must contain an integer.', + 'required' => 'The {field} field is required.', + + ], + + + ], + + +]; \ No newline at end of file diff --git a/ci4/app/Language/es/Basic.php b/ci4/app/Language/es/Basic.php new file mode 100644 index 00000000..30bb24db --- /dev/null +++ b/ci4/app/Language/es/Basic.php @@ -0,0 +1,89 @@ + [ + 'About' => 'Acerca', + 'AboutSuffix' => '', + 'Action' => 'Acción', + 'Cancel' => 'Cancelar', + 'ChangePassword' => 'Cambiar contraseña', + 'Close' => 'Cerrar', + 'Dashboard' => 'Panel de control', + 'Delete' => 'Borrar', + 'Error' => 'Error', + 'Groups' => 'Grupos', + 'Home' => 'Inicio', + 'Logout' => 'Salir', + 'ManageAllRecords' => 'Administrar todos {0} los registros', + 'MemberSince' => 'Miembro desde', + 'Members' => 'Miembro', + 'MoreInfo' => 'Mas Info', + 'None' => 'Ninguno', + 'Permissions' => 'Permisos', + 'Profile' => 'Perfil', + 'Roles' => 'Roles', + 'Save' => 'Guardar', + 'Sections' => 'Secciones', + 'SignOut' => 'Desconectar', + 'Success' => 'Éxito', + 'UserProfile' => 'Perfil de usuario', + 'Warning' => 'Advertencia', + 'add' => 'Nuevo', + 'addNew' => 'Añadir nuevo', + 'addNewSuffix' => '', + 'allRightsReserved' => 'Todos los derechos reservados.', + 'continueEditing' => 'Continuar editando', + 'createdWith' => 'creado con', + 'createdWithSuffix' => '.', + 'deleteConfirmation' => 'Confirmacion para Eliminar Registro', + 'deleteConfirmationButton' => 'Si, bórralo!', + 'deleteConfirmationCancel' => 'Cancelar', + 'deleteConfirmationQuestion' => '¿Está seguro de borrar este registro?', + 'deleteError' => 'No se eliminó {0} ahora, porque probablemente ya se había eliminado.', + 'deleteExistingFile' => 'Borrar fichero existente', + 'deleteSuccess' => 'El {0} se eliminó correctamente', + 'edit' => 'Editar', + 'edit2' => 'Editar', + 'edit3' => '', + 'for' => 'para', + 'forPrefix' => 'para', + 'forSuffix' => '', + 'formErr1' => 'El {0} no se guardó debido a un valor erróneo ingresado en el formulario.', + 'formErr2' => 'Por favor corrija los siguientes errores:', + 'formErrTitle' => 'Hay algunos errores en el formulario que deben corregirse:', + 'jsNeedMsg' => 'Ha desactivado JavaScript o su navegador no es compatible con JavaScript, que esta página necesita para funcionar correctamente.', + 'need2login' => 'Para acceder al área exclusiva para miembros, inicie sesión.', + 'notFoundWithIdErr' => 'No se encontró ningún {0} (con identificador {1}) en la base de datos.', + 'persistDuplErr' => 'Ya existe un {0} en nuestra base de datos con los mismos datos.', + 'persistErr1' => 'Se produjo un error al intentar guardar un nuevo {0} en la base de datos:', + 'persistErr2' => 'El {0} no se guardó debido a un error.', + 'persistErr3' => 'Se produjo un error al intentar actualizar {0} con {1} {2} en la base de datos:', + 'pleaseSelect' => 'Por favor seleccione...', + 'pleaseSelectA' => 'Por favor seleccione un {0}... ', + 'pleaseSelectOne' => 'Por favor selecione un...', + 'record' => 'el registro', + 'saveSuccess' => 'El {0} se ha guardado satisfactoriamente', + 'saveSuccess1' => 'El {0} ', + 'saveSuccess2' => ' se ha guardado satisfactoriamente', + 'saveSuccess3Suffix' => '', + 'saveSucessWithId' => ' con {0} {1}', + 'saveSucessWithName' => ' con nombre {0}', + 'updateFailure' => 'El {0} no se pudo actualizar', + 'updateSuccess' => 'El {0} se ha actualizado correctamente', + 'updated' => 'Actualizado', + 'sweet' => [ + 'deleteConfirmationButton' => 'Si, bórralo!', + 'sureToDeleteText' => 'Esta acción no se puede deshacer.', + 'sureToDeleteTitle' => 'Está seguro de borrar {0}?', + 'text' => 'Esta acción no se puede deshacer.', + 'title' => 'Está seguro?', + + ], + + + ], + + +]; \ No newline at end of file diff --git a/ci4/app/Language/es/Paises.php b/ci4/app/Language/es/Paises.php new file mode 100644 index 00000000..8235db84 --- /dev/null +++ b/ci4/app/Language/es/Paises.php @@ -0,0 +1,87 @@ + 'Code', + 'code3' => 'Code3', + 'id' => 'ID', + 'keyErp' => 'Key Erp', + 'moduleTitle' => 'Paises', + 'moneda' => 'Moneda', + 'nombre' => 'Nombre', + 'pais' => 'Pais', + 'paisList' => 'Pais List', + 'paises' => 'Paises', + 'showErp' => 'Show Erp', + 'urlErp' => 'URL Erp', + 'userErp' => 'User Erp', + 'validation' => [ + 'code' => [ + 'is_unique' => 'The {field} field must contain a unique value', + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + 'required' => 'The {field} field is required.', + + ], + + + ], + + 'validation' => [ + 'code3' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + + ], + + + ], + + 'validation' => [ + 'key_erp' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + + ], + + + ], + + 'validation' => [ + 'moneda' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + 'required' => 'The {field} field is required.', + + ], + + + ], + + 'validation' => [ + 'nombre' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + 'required' => 'The {field} field is required.', + + ], + + + ], + + 'validation' => [ + 'url_erp' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + + ], + + + ], + + 'validation' => [ + 'user_erp' => [ + 'max_length' => 'The {field} field cannot exceed {param} characters in length.', + + ], + + + ], + + +]; \ No newline at end of file diff --git a/ci4/app/Language/es/Tarifaaacabado.php b/ci4/app/Language/es/Tarifaaacabado.php new file mode 100644 index 00000000..35bb5601 --- /dev/null +++ b/ci4/app/Language/es/Tarifaaacabado.php @@ -0,0 +1,114 @@ + 'Ajuste', + 'createdAt' => 'Creado en', + 'deletedAt' => 'Borrado en', + 'formulaPrice' => 'Fórmula precio', + 'id' => 'ID', + 'moduleTitle' => 'Tarifas Acabado', + 'nombre' => 'Nombre', + 'precioMax' => 'Precio Max', + 'precioMin' => 'Precio Min', + 'tarifaacabado' => 'Tarifas Acabado', + 'tarifaacabadoList' => 'Lista Tarifas Acabado', + 'tarifasacabado' => 'Tarifas Acabado', + 'tiradaMax' => 'Tirada Max', + 'tiradaMin' => 'Tirada Min', + 'updatedAt' => 'Actualizado en', + 'userCreatedId' => 'ID Usuario "Creado en"', + 'userUpdateId' => 'ID Usuario "Actualizado en"', + 'validation' => [ + 'formula_price' => [ + 'max_length' => 'El campo {field} no puede exceder {param} caracteres en longitud.', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + 'validation' => [ + 'nombre' => [ + 'max_length' => 'El campo {field} no puede exceder {param} caracteres en longitud.', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + 'validation' => [ + 'precio_max' => [ + 'decimal' => 'El campo {field} debe contener un número decimal.', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + 'validation' => [ + 'precio_min' => [ + 'decimal' => 'El campo {field} debe contener un número decimal.', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + 'validation' => [ + 'tirada_max' => [ + 'integer' => 'El campo {field} debe contener un número entero.', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + 'validation' => [ + 'tirada_min' => [ + 'integer' => 'El campo {field} debe contener un número entero.', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + 'validation' => [ + 'user_created_id' => [ + 'integer' => 'El campo {field} debe contener un número entero.', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + 'validation' => [ + 'user_update_id' => [ + 'integer' => 'El campo {field} debe contener un número entero.', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + 'validation' => [ + 'ajuste' => [ + 'decimal' => 'El campo {field} debe contener un número decimal', + 'required' => 'El campo {field} es obligatorio.', + + ], + + + ], + + +]; \ No newline at end of file diff --git a/ci4/app/Models/GoBaseModel.php b/ci4/app/Models/GoBaseModel.php new file mode 100644 index 00000000..bce07f9e --- /dev/null +++ b/ci4/app/Models/GoBaseModel.php @@ -0,0 +1,249 @@ +table; + } + + /** + * Returns the model's DB table name (Alias of getDbTableName() ) + * + * @return string + */ + public function getTableName() { + return $this->table; + } + + /** + * Returns the model's name of primary key in the database + * + * @return string + */ + public function getPrimaryKeyName() { + return $this->primaryKey; + } + + /** + * Returns the number of rows in the database table + * + * @return int + */ + public function getCount() { + $name = $this->table; + $count = $this->db->table($name)->countAll(); + return $count; + } + + /** + * @param string $columns2select + * @param string $resultSorting + * @param bool $onlyActiveOnes + * @param bool $alsoDeletedOnes + * @param array $additionalConditions + * @return array + */ + public function getAllForMenu($columns2select='*', $resultSorting='id', bool $onlyActiveOnes=false, bool $alsoDeletedOnes=true, $additionalConditions = []) { + + $theseConditionsAreMet = []; + + if ($onlyActiveOnes) { + if ( in_array('enabled', $this->allowedFields) ) { + $theseConditionsAreMet['enabled'] = true; + } elseif (in_array('active', $this->allowedFields)) { + $theseConditionsAreMet['active'] = true; + } + } + + // This check is deprecated and left here only for backward compatibility and this method should be overridden in extending classes so as to check if the bound entity class has these attributes + if (!$alsoDeletedOnes) { + if (in_array('deleted_at', $this->allowedFields)) { + $theseConditionsAreMet['deleted_at'] = null; + } + if (in_array('deleted', $this->allowedFields) ) { + $theseConditionsAreMet['deleted'] = false; + } + if (in_array('date_time_deleted', $this->allowedFields)) { + $theseConditionsAreMet['date_time_deleted'] = null; + } + } + + if (!empty($additionalConditions)) { + $theseConditionsAreMet = array_merge($theseConditionsAreMet, $additionalConditions); + } + $queryBuilder = $this->db->table($this->table); + $queryBuilder->select($columns2select); + if (!empty($theseConditionsAreMet)) { + $queryBuilder->where($theseConditionsAreMet); + } + $queryBuilder->orderBy($resultSorting); + $result = $queryBuilder->get()->getResult(); + + return $result; + } + + /** + * + * @param mixed $columns2select either array or string + * @param mixed $sortResultsBy either string or array + * @param bool $onlyActiveOnes + * @param string $select1str e.g. 'Please select one...' + * @param bool $alsoDeletedOnes + * @param array $additionalConditions + * @return array for use in dropdown menus + */ + public function getAllForCiMenu( $columns2select = ['id', 'designation'], $sortResultsBy = 'id', bool $onlyActiveOnes=false, $selectionRequestLabel = 'Please select one...', bool $alsoDeletedOnes = true, $additionalConditions = []) { + + $ciDropDownOptions = []; + + if (is_array($columns2select) && count($columns2select) >= 2) { + + $key = $columns2select[0]; + $val = $columns2select[1]; + + $cols2selectStr = implode(',', $columns2select); + + $valInd = strpos($val, ' AS '); + if ($valInd !== false) { + $val = substr($val, $valInd+4); + } + + } elseif (is_string($columns2select) && strpos($columns2select,',')!==false) { + + $cols2selectStr = $columns2select; + + $arr = explode(",", $columns2select, 2); + $key = trim($arr[0]); + $val = trim($arr[1]); + + } else { + return ['error'=>'Invalid argument for columns/fields to select']; + } + + $resultList = $this->getAllForMenu($cols2selectStr, $sortResultsBy, $onlyActiveOnes, $alsoDeletedOnes, $additionalConditions); + + if ($resultList != false) { + + if (!empty($selectionRequestLabel)) { + $ciDropDownOptions[''] = $selectionRequestLabel; + } + + foreach ($resultList as $res) { + + if (isset($res->$key) && isset($res->$val)) { + $ciDropDownOptions[$res->$key] = $res->$val; + } + } + } + + return $ciDropDownOptions; + } + + /** + * @param array|string[] $columns2select + * @param null $resultSorting + * @param bool|bool $onlyActiveOnes + * @param null $searchStr + * @return array + */ + public function getSelect2MenuItems(array $columns2select = ['id', 'designation'], $resultSorting=null, bool $onlyActiveOnes=true, $searchStr = null) { + + $theseConditionsAreMet = []; + + $id = $columns2select[0].' AS id'; + $text = $columns2select[1].' AS text'; + + if (empty($resultSorting)) { + $resultSorting = $this->getPrimaryKeyName(); + } + + if ($onlyActiveOnes) { + if ( in_array('enabled', $this->allowedFields) ) { + $theseConditionsAreMet['enabled'] = true; + } elseif (in_array('active', $this->allowedFields)) { + $theseConditionsAreMet['active'] = true; + } + } + + $queryBuilder = $this->db->table($this->table); + $queryBuilder->select([$id, $text]); + $queryBuilder->where($theseConditionsAreMet); + if (!empty($searchStr)) { + $queryBuilder->groupStart() + ->like($columns2select[0], $searchStr) + ->orLike($columns2select[1], $searchStr) + ->groupEnd(); + } + $queryBuilder->orderBy($resultSorting); + $result = $queryBuilder->get()->getResult(); + + return $result; + } + + /** + * Custom method allowing you to add a form validation rule to the model on-the-fly + * @param string $fieldName + * @param string $rule + * @param string|null $msg + */ + public function addValidationRule(string $fieldName, string $rule, string $msg = null ) { + if (empty(trim($fieldName)) ||empty(trim($fieldName))) { + return; + } + if (!isset($this->validationRules[$fieldName]) || empty($this->validationRules[$fieldName])) { + $this->validationRules[$fieldName] = substr($rule, 0, 1) == '|' ? substr($rule, 1) : trim($rule); + } else if (isset($this->validationRules[$fieldName]['rules'])) { + $this->validationRules[$fieldName]['rules'] .= substr($rule, 0, 1) == '|' ? trim($rule) : '|' . trim($rule); + } else { + $this->validationRules[$fieldName] .= $rule; + } + if (isset($msg) && !empty(trim($msg))) { + $ruleKey = strtok($rule, '['); + if ($ruleKey === false) { + return; + } + $item = [$ruleKey => "'".$msg."'"]; + if (!isset($this->validationMessages[$fieldName]) || empty(trim($this->validationMessages[$fieldName]))) { + $this->validationMessages[$fieldName] = $item; + } else { + $this->validationMessages[$fieldName][$ruleKey] = "'".$msg."'"; + } + } + } + +} diff --git a/ci4/app/Models/Tarifas/TarifaacabadoModel.php b/ci4/app/Models/Tarifas/TarifaacabadoModel.php new file mode 100644 index 00000000..0e796ef9 --- /dev/null +++ b/ci4/app/Models/Tarifas/TarifaacabadoModel.php @@ -0,0 +1,112 @@ + [ + "label" => "Acabadoes.ajuste", + "rules" => "required|decimal", + ], + "formula_price" => [ + "label" => "Acabadoes.formulaPrice", + "rules" => "trim|required|max_length[1073241]", + ], + "nombre" => [ + "label" => "Acabadoes.nombre", + "rules" => "trim|required|max_length[255]", + ], + "precio_max" => [ + "label" => "Acabadoes.precioMax", + "rules" => "required|decimal", + ], + "precio_min" => [ + "label" => "Acabadoes.precioMin", + "rules" => "required|decimal", + ], + "tirada_max" => [ + "label" => "Acabadoes.tiradaMax", + "rules" => "required|integer", + ], + "tirada_min" => [ + "label" => "Acabadoes.tiradaMin", + "rules" => "required|integer", + ], + "user_created_id" => [ + "label" => "Acabadoes.userCreatedId", + "rules" => "required|integer", + ], + "user_update_id" => [ + "label" => "Acabadoes.userUpdateId", + "rules" => "required|integer", + ], + ]; + + protected $validationMessages = [ + "ajuste" => [ + "decimal" => "Acabadoes.validation.ajuste.decimal", + "required" => "Acabadoes.validation.ajuste.required", + ], + "formula_price" => [ + "max_length" => "Acabadoes.validation.formula_price.max_length", + "required" => "Acabadoes.validation.formula_price.required", + ], + "nombre" => [ + "max_length" => "Acabadoes.validation.nombre.max_length", + "required" => "Acabadoes.validation.nombre.required", + ], + "precio_max" => [ + "decimal" => "Acabadoes.validation.precio_max.decimal", + "required" => "Acabadoes.validation.precio_max.required", + ], + "precio_min" => [ + "decimal" => "Acabadoes.validation.precio_min.decimal", + "required" => "Acabadoes.validation.precio_min.required", + ], + "tirada_max" => [ + "integer" => "Acabadoes.validation.tirada_max.integer", + "required" => "Acabadoes.validation.tirada_max.required", + ], + "tirada_min" => [ + "integer" => "Acabadoes.validation.tirada_min.integer", + "required" => "Acabadoes.validation.tirada_min.required", + ], + "user_created_id" => [ + "integer" => "Acabadoes.validation.user_created_id.integer", + "required" => "Acabadoes.validation.user_created_id.required", + ], + "user_update_id" => [ + "integer" => "Acabadoes.validation.user_update_id.integer", + "required" => "Acabadoes.validation.user_update_id.required", + ], + ]; +} diff --git a/ci4/app/Views/themes/_commonPartialsBs/_alertBoxes.php b/ci4/app/Views/themes/_commonPartialsBs/_alertBoxes.php new file mode 100644 index 00000000..0d26c166 --- /dev/null +++ b/ci4/app/Views/themes/_commonPartialsBs/_alertBoxes.php @@ -0,0 +1,81 @@ +has('message')) { + $successMessage = session('message'); + } + if (session()->has('error')) { + $errorMessage = is_array(session('error')) ? implode(session('error')) : session('error'); + } /* // Uncomment this block if you want the errors listed line by line in the alert + elseif (session()->has('errors')) { + $errorMessage = ''; + } + */ +?> + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ci4/app/Views/themes/_commonPartialsBs/_confirm2delete.php b/ci4/app/Views/themes/_commonPartialsBs/_confirm2delete.php new file mode 100644 index 00000000..8983cc18 --- /dev/null +++ b/ci4/app/Views/themes/_commonPartialsBs/_confirm2delete.php @@ -0,0 +1,17 @@ + diff --git a/ci4/app/Views/themes/_commonPartialsBs/_form_validation_errors.php b/ci4/app/Views/themes/_commonPartialsBs/_form_validation_errors.php new file mode 100644 index 00000000..4984d699 --- /dev/null +++ b/ci4/app/Views/themes/_commonPartialsBs/_form_validation_errors.php @@ -0,0 +1,35 @@ +theme['name'] == 'Bootstrap5') { ?> + + + + + + + + +
+
+
+ +

Please correct the errors below:

+
    + +
  • + +
+
+
+
+ diff --git a/ci4/app/Views/themes/_commonPartialsBs/datatables.php b/ci4/app/Views/themes/_commonPartialsBs/datatables.php new file mode 100644 index 00000000..5f847e33 --- /dev/null +++ b/ci4/app/Views/themes/_commonPartialsBs/datatables.php @@ -0,0 +1,184 @@ + +section('css') ?> + +endSection() ?> + + +section('footerAdditions') ?> +include('themes/_commonPartialsBs/_confirm2delete') ?> +endSection() ?> + + +section('additionalExternalJs') ?> + + + +endSection() ?> + + +section('additionalInlineJs') ?> + + moment.locale('defaultLocale ?>'); + + + // Pipelining function for DataTables. To be used to the `ajax` option of DataTables + $.fn.dataTable.pipeline = function (opts) { + // Configuration options + let conf = $.extend({ + pages: 5, // number of pages to cache + url: '', + method: 'POST', + headers: {'X-Requested-With': 'XMLHttpRequest'} + }, opts); + + // Private variables for storing the cache + let cacheLower = -1; + let cacheUpper = null; + let cacheLastRequest = null; + let cacheLastJson = null; + + return function (request, drawCallback, settings) { + let ajax = false; + let requestStart = request.start; + let drawStart = request.start; + let requestLength = request.length; + let requestEnd = requestStart + requestLength; + + if (settings.clearCache) { + // API requested that the cache be cleared + ajax = true; + settings.clearCache = false; + } else if (cacheLower < 0 || requestStart < cacheLower || requestEnd > cacheUpper) { + // outside cached data - need to make a request + ajax = true; + } else if (JSON.stringify(request.order) !== JSON.stringify(cacheLastRequest.order) || + JSON.stringify(request.columns) !== JSON.stringify(cacheLastRequest.columns) || + JSON.stringify(request.search) !== JSON.stringify(cacheLastRequest.search) + ) { + // properties changed (ordering, columns, searching) + ajax = true; + } + + // Store the request for checking next time around + cacheLastRequest = $.extend(true, {}, request); + + if (ajax) { + // Need data from the server + if (requestStart < cacheLower) { + requestStart = requestStart - (requestLength * (conf.pages - 1)); + + if (requestStart < 0) { + requestStart = 0; + } + } + + cacheLower = requestStart; + cacheUpper = requestStart + (requestLength * conf.pages); + + request.start = requestStart; + request.length = requestLength * conf.pages; + + // Provide the same `data` options as DataTables. + if (typeof conf.data === 'function') { + // As a function it is executed with the data object as an arg + // for manipulation. If an object is returned, it is used as the + // data object to submit + let d = conf.data(request); + if (d) { + $.extend(request, d); + } + } else if ($.isPlainObject(conf.data)) { + // As an object, the data given extends the default + $.extend(request, conf.data); + } + + request. = v; + + return $.ajax({ + "type": conf.method, + "url": conf.url, + "data": request, + "dataType": "json", + "cache": false, + "success": function (json) { + cacheLastJson = $.extend(true, {}, json); + + if (cacheLower != drawStart) { + json.data.splice(0, drawStart - cacheLower); + } + if (requestLength >= -1) { + json.data.splice(requestLength, json.data.length); + } + + drawCallback(json); + + yeniden(json.token); + }, + error: function (jqXHR, textStatus, errorThrown) { + + $('.dataTables_processing').hide(); + const theData = jqXHR.responseJSON; + drawCallback(theData); + Toast.fire({ + icon: 'error', + title: errorThrown, + }); + } + }); + } else { + let json = $.extend(true, {}, cacheLastJson); + json.draw = request.draw; // Update the echo for each response + json.data.splice(0, requestStart - cacheLower); + json.data.splice(requestLength, json.data.length); + + drawCallback(json); + } + } + }; + + // Register an API method that will empty the pipelined data, forcing an Ajax + // fetch on the next draw (i.e. `table.clearPipeline().draw()`) + $.fn.dataTable.Api.register('clearPipeline()', function () { + return this.iterator('table', function (settings) { + settings.clearCache = true; + }); + }); + + + + let lastColNr = $(".using-data-table").find("tr:first th").length - 1; + theTable = $('.using-data-table').DataTable({ + "responsive": true, + "paging": true, + "lengthMenu": [ 5, 10, 25, 50, 75, 100, 250, 500, 1000, 2500 ], + "pageLength": 10, + "lengthChange": true, + "searching": true, + "ordering": true, + "info": true, + "autoWidth": true, + "scrollX": true, + "stateSave": true, + "language": { + url: "//cdn.datatables.net/plug-ins/1.10.25/i18n/languages[$currentLocale] ?? config('Basics')->i18n ?>.json" + }, + "columnDefs": [ + { + orderable: false, + searchable: false, + targets: [0,lastColNr] + } + ] + }); + + + + $('#confirm2delete').on('show.bs.modal', function (e) { + $(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href')); + }); + + + function toggleAllCheckboxes($cssClass, $io=null) { + $('.'+$cssClass).prop('checked', $io); + } +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/_commonPartialsBs/select2bs5.php b/ci4/app/Views/themes/_commonPartialsBs/select2bs5.php new file mode 100644 index 00000000..c5afb660 --- /dev/null +++ b/ci4/app/Views/themes/_commonPartialsBs/select2bs5.php @@ -0,0 +1,19 @@ + +section('css') ?> + + +endSection() ?> + + +section('additionalExternalJs') ?> + +endSection() ?> + +section('additionalInlineJs') ?> + + $('.select2bs').select2({ + theme: "bootstrap-5", + allowClear: false, + }); + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/_commonPartialsBs/sweetalert.php b/ci4/app/Views/themes/_commonPartialsBs/sweetalert.php new file mode 100644 index 00000000..c522221b --- /dev/null +++ b/ci4/app/Views/themes/_commonPartialsBs/sweetalert.php @@ -0,0 +1,48 @@ + +section('css') ?> + +endSection() ?> + + + + +section('additionalExternalJs') ?> + +endSection() ?> + + + +section('additionalInlineJs') ?> + +var Toast = Swal.mixin({ + toast: true, + position: 'top-end', + showConfirmButton: false, + timer: 6000, + timerProgressBar: true, + onOpen: (toast) => { + toast.addEventListener('mouseenter', Swal.stopTimer) + toast.addEventListener('mouseleave', Swal.resumeTimer) + } + }); + + + Toast.fire({ + icon: 'success', + title: '' + }); + + + Toast.fire({ + icon: 'warning', + title: '' + }); + + + Toast.fire({ + icon: 'error', + title: '' + }); + + +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/_tarifaacabadoFormItems.php b/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/_tarifaacabadoFormItems.php new file mode 100644 index 00000000..337f2a9c --- /dev/null +++ b/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/_tarifaacabadoFormItems.php @@ -0,0 +1,70 @@ +
+
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ +
\ No newline at end of file diff --git a/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/viewTarifaacabadoForm.php b/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/viewTarifaacabadoForm.php new file mode 100644 index 00000000..200566e6 --- /dev/null +++ b/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/viewTarifaacabadoForm.php @@ -0,0 +1,25 @@ +include("Themes/_commonPartialsBs/select2bs5") ?> +extend("Themes/" . config("Basics")->theme["name"] . "/AdminLayout/defaultLayout") ?> +section("content") ?> +
+
+
+
+

+
+
+ +
+ + getErrors()) ? $validation->listErrors("bootstrap_style") : "" ?> + +
+ +
+
+
+
+endSection() ?> diff --git a/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/viewTarifaacabadoList.php b/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/viewTarifaacabadoList.php new file mode 100644 index 00000000..5be01606 --- /dev/null +++ b/ci4/app/Views/themes/backend/focus2/form/tarifas/acabado/viewTarifaacabadoList.php @@ -0,0 +1,93 @@ +include('themes/_commonPartialsBs/datatables') ?> +extend('themes/backend/focus2/main/defaultlayout') ?> + +section('content'); ?> +
+
+ +
+
+

+ 'btn btn-primary float-end']); ?> +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ id ?> + + nombre) || strlen($item->nombre) < 51 ? esc($item->nombre) : character_limiter(esc($item->nombre), 50) ?> + + tirada_min) ?> + + precio_min) ?> + + tirada_max) ?> + + precio_max) ?> + + ajuste) ?> + + formula_price) || strlen($item->formula_price) < 51 ? esc($item->formula_price) : character_limiter(esc($item->formula_price), 50) ?> + + user_created_id) ?> + + user_update_id) ?> + + deleted_at) ? '' : date('d/m/Y H:m:s', strtotime($item->deleted_at)) ?> + + created_at) ? '' : date('d/m/Y H:m:s', strtotime($item->created_at)) ?> + + updated_at) ? '' : date('d/m/Y H:m:s', strtotime($item->updated_at)) ?> + + id), lang('Basic.global.edit'), ['class'=>'btn btn-sm btn-warning btn-edit me-1', 'data-id'=>$item->id,]); ?> + 'btn btn-sm btn-danger btn-delete ms-1', 'data-href'=>route_to('deleteTarifaacabado', $item->id), 'data-bs-toggle'=>'modal', 'data-bs-target'=>'#confirm2delete']); ?> +
+
+ +
+
+
+ +endSection() ?> \ No newline at end of file diff --git a/ci4/app/Views/themes/backend/focus2/main/defaultlayout.php b/ci4/app/Views/themes/backend/focus2/main/defaultlayout.php new file mode 100644 index 00000000..650d7436 --- /dev/null +++ b/ci4/app/Views/themes/backend/focus2/main/defaultlayout.php @@ -0,0 +1,211 @@ +get('settings'); +$picture = session()->get('picture'); +$pulse = session()->get('pulse'); +$notification = session()->get('notification'); +?> + + + + + + + + <?= lang("App.dashboard_title") ?> - <?= $settings['title']??'' ?> + + + + + + + + + + + + + + + +
+
+
+
+
+
+
+ +
+ + + +
+
+ +
+
+ + + +
+
+ renderSection('content') ?> +
+
--> +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + renderSection('footerAdditions') ?> + + + + + + renderSection('additionalExternalJs') ?> + + + + + \ No newline at end of file diff --git a/ci4/app/Views/themes/backend/focus2/main/header.php b/ci4/app/Views/themes/backend/focus2/main/header.php index 1743cb60..52edb1c8 100644 --- a/ci4/app/Views/themes/backend/focus2/main/header.php +++ b/ci4/app/Views/themes/backend/focus2/main/header.php @@ -38,9 +38,7 @@ $notification = session()->get('notification');