arraglando la tabla tarifas con la forma nueva

This commit is contained in:
Jaime Jimenez
2023-05-11 07:33:06 +02:00
parent ff9bf6a000
commit 3cbf5cf8a8
15 changed files with 819 additions and 177 deletions

View File

@ -0,0 +1,327 @@
<?php
namespace App\Controllers;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
abstract class GoBaseResourceController extends \CodeIgniter\RESTful\ResourceController
{
/**
*
* @var string
*/
public $pageTitle;
/**
* Additional string to display after page title
*
* @var string
*/
public $pageSubTitle;
/**
*
* @var boolean
*/
protected $usePageSubTitle = true;
/**
* Singular noun of primary object
*
* @var string
*/
protected static $singularObjectName;
/**
* Plural form of primary object name
*
* @var string
*/
protected static $pluralObjectName;
/**
* Path for the views directory for the extending view controller
*
* @var string
*/
protected static $viewPath;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var array
*/
protected $helpers = ['session', 'go_common', 'form', 'text'];
/**
* Initializer method.
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param LoggerInterface $logger
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->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 (isset(static::$controllerSlug) && 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['usingSweetAlert'] = true;
$this->viewData['viewPath'] = static::$viewPath;
$this->viewData['currentLocale'] = $this->request->getLocale();
}
/**
* 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']) . '/' . $formActionSuffix . '/' . $action );
}
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 (isset($this->indexRoute) && !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 (isset(static::$controllerSlug) && !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);
}
}
/**
* Delete the designated resource object from the model.
*
* @param int $id
*
* @return array an array
*/
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->model->delete($id)) {
return $this->failNotFound(lang('Basic.global.deleteError', [$objName]));
}
$message = lang('Basic.global.deleteSuccess', [$objName]);
$response = $this->respondDeleted(['id' => $id, 'msg' => $message]);
return $response;
}
/**
* 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;
}
/**
* Custom fail method needed when CSRF token regeneration is on in security settings
* @param string|array $messages
* @param int $status
* @param string|null $code
* @param string $customMessage
* @return mixed
*/
protected function failWithNewToken($messages, int $status = 400, string $code = null, string $customMessage = '') {
if (! is_array($messages))
{
$messages = ['error' => $messages];
}
$response = [
'status' => $status,
'error' => $status,
'messages' => $messages,
csrf_token() => csrf_hash()
];
return $this->respond($response, $status);
}
/**
* Used when a specified resource cannot be found and send back a new CSRF token.
*
* @param string $description
* @param string $code
* @param string $message
*
* @return mixed
*/
public function failNotFoundWithNewToken(string $description = 'Not Found', string $code = null, string $message = '')
{
return $this->failWithNewToken($description, $this->codes['resource_not_found'], $code, $message);
}
/**
* 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());
}
}
}

View File

@ -1,21 +1,27 @@
<?php namespace App\Controllers\Tarifas;
<?php namespace App\Controllers\Tarifas ;
use App\Controllers\GoBaseResourceController;
use App\Models\Collection;
use App\Entities\Tarifas\TarifaacabadoEntity;
use App\Controllers\GoBaseController;
class Tarifaacabado extends GoBaseController {
use App\Models\Tarifas\TarifaacabadoModel;
use \CodeIgniter\API\ResponseTrait;
class Tarifaacabado extends \App\Controllers\GoBaseResourceController {
protected static $primaryModelName = 'App\Models\Tarifas\TarifaacabadoModel';
protected $modelName = TarifaacabadoModel::class;
protected $format = 'json';
protected static $singularObjectNameCc = 'tarifaacabado';
protected static $singularObjectName = 'Tarifaacabado';
protected static $singularObjectNameCc = 'tarifaacabado';
protected static $pluralObjectName = 'Tarifasacabado';
protected static $pluralObjectNameCc = 'tarifasacabado';
protected static $controllerSlug = 'tarifaacabado';
static $viewPath = '';
protected static $viewPath = 'themes/backend/vuexy/form/tarifas/acabado/';
protected $indexRoute = 'tarifaacabadoList';
@ -23,23 +29,29 @@ class Tarifaacabado extends GoBaseController {
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) {
$this->viewData['pageTitle'] = lang('Tarifaacabado.moduleTitle');
self::$viewPath = getenv('theme.path').'form/tarifas/acabado/';
$this->viewData['usingSweetAlert'] = true;
parent::initController($request, $response, $logger);
}
public function index() {
helper('general');
$this->viewData['usingClientSideDataTable'] = true;
$this->viewData['pageSubTitle'] = lang('Basic.global.ManageAllRecords', [lang('Tarifaacabado.tarifaacabado')]);
parent::index();
$viewData = [
'currentModule' => static::$controllerSlug,
'pageSubTitle' => lang('Basic.global.ManageAllRecords', [lang('Tarifaacabado.tarifaacabado')]),
'tarifaacabado_' => new TarifaacabadoEntity(),
'usingServerSideDataTable' => true,
];
$viewData = array_merge($this->viewData, $viewData); // merge any possible values from the parent controller class
return view(static::$viewPath.'viewTarifaacabadoList', $viewData);
}
public function add() {
@ -51,12 +63,13 @@ class Tarifaacabado extends GoBaseController {
$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) ) :
$successfulResult = false; // for now
if ($this->canValidate()) :
try {
@ -71,34 +84,34 @@ class Tarifaacabado extends GoBaseController {
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 .= anchor( "admin/tarifaacabado/{$id}/edit" , 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);
return redirect()->to(route_to( $this->indexRoute ) )->with('sweet-success', $message);
else:
return $this->redirect2listView('successMessage', $message);
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->viewData['successMessage'] = $message;
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['tarifaacabado_'] = isset($sanitizedData) ? new Tarifaacabado($sanitizedData) : new Tarifaacabado();
$this->viewData['tarifaacabado_'] = isset($sanitizedData) ? new TarifaacabadoEntity($sanitizedData) : new TarifaacabadoEntity();
$this->viewData['formAction'] = route_to('createTarifaacabado');
$this->viewData['boxTitle'] = lang('Basic.global.addNew').' '.lang('Tarifaacabado.tarifaacabado').' '.lang('Basic.global.addNewSuffix');
$this->viewData['boxTitle'] = lang('Basic.global.addNew').' '.lang('Tarifaacabado.moduleTitle').' '.lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
@ -114,7 +127,7 @@ class Tarifaacabado extends GoBaseController {
if ($tarifaacabado_ == false) :
$message = lang('Basic.global.notFoundWithIdErr', [mb_strtolower(lang('Tarifaacabado.tarifaacabado')), $id]);
return $this->redirect2listView('errorMessage', $message);
return $this->redirect2listView('sweet-error', $message);
endif;
$requestMethod = $this->request->getMethod();
@ -124,12 +137,13 @@ class Tarifaacabado extends GoBaseController {
$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) ) :
$successfulResult = false; // for now
@ -149,21 +163,21 @@ class Tarifaacabado extends GoBaseController {
$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 .= anchor( "admin/tarifaacabado/{$id}/edit" , 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);
return redirect()->to(route_to( $this->indexRoute ) )->with('sweet-success', $message);
else:
return $this->redirect2listView('successMessage', $message);
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->viewData['successMessage'] = $message;
$this->session->setFlashData('sweet-success', $message);
endif;
endif; // $noException && $successfulResult
@ -171,15 +185,46 @@ class Tarifaacabado extends GoBaseController {
$this->viewData['tarifaacabado_'] = $tarifaacabado_;
$this->viewData['formAction'] = route_to('updateTarifaacabado', $id);
$this->viewData['formAction'] = route_to('updateTarifaacabado', $id);
$this->viewData['boxTitle'] = lang('Basic.global.edit2').' '.lang('Tarifaacabado.tarifaacabado').' '.lang('Basic.global.edit3');
$this->viewData['boxTitle'] = lang('Basic.global.edit2').' '.lang('Tarifaacabado.moduleTitle').' '.lang('Basic.global.edit3');
return $this->displayForm(__METHOD__, $id);
} // end function edit(...)
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;
$search = $reqData['search']['value'];
$requestedOrder = $reqData['order']['0']['column'] ?? 1;
$order = TarifaacabadoModel::SORTABLE[$requestedOrder > 0 ? $requestedOrder : 1];
$dir = $reqData['order']['0']['dir'] ?? 'asc';
$resourceData = $this->model->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject();
foreach ($resourceData as $item) :
if (isset($item->formula_price) && strlen($item->formula_price) > 100) :
$item->formula_price = character_limiter($item->formula_price, 100);
endif;
endforeach;
return $this->respond(Collection::datatable(
$resourceData,
$this->model->getResource()->countAllResults(),
$this->model->getResource($search)->countAllResults()
));
} else {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function allItemsSelect() {
if ($this->request->isAJAX()) {
@ -202,7 +247,7 @@ class Tarifaacabado extends GoBaseController {
return $this->failUnauthorized('Invalid request', 403);
}
}
public function menuItems() {
if ($this->request->isAJAX()) {
$searchStr = goSanitize($this->request->getPost('searchTerm'))[0];
@ -228,5 +273,5 @@ class Tarifaacabado extends GoBaseController {
return $this->failUnauthorized('Invalid request', 403);
}
}
}

View File

@ -39,37 +39,65 @@ class Group extends \App\Controllers\GoBaseController
public function add()
{
helper('form');
$requestMethod = $this->request->getMethod();
$data['title'] = [
'module' => lang("App.group_add_title"),
'page' => lang("App.group_add_subtitle"),
'icon' => 'far fa-plus-square'
];
if ($requestMethod === 'post') :
$data['breadcrumb'] = [
['title' => lang("App.menu_dashboard"), 'route' => "/home", 'active' => false],
['title' => lang("App.group_title"), 'route' => "/usuarios/group", 'active' => false],
['title' => lang("App.group_add_title"), 'route' => "", 'active' => true]
];
$nullIfEmpty = true; // !(phpversion() >= '8.1');
$data['btn_return'] = [
'title' => lang("App.global_come_back"),
'route' => 'usuarios/group',
'class' => 'btn btn-dark mr-1',
'icon' => 'fas fa-angle-left'
];
$postData = $this->request->getPost();
$sanitizedData = $this->sanitized($postData, $nullIfEmpty);
$data['btn_submit'] = [
'title' => lang("App.global_save"),
'route' => '',
'class' => 'btn btn-primary mr-1',
'icon' => 'fas fa-save'
];
echo view(getenv('theme.path').'main/header');
echo view(getenv('theme.path').'form/group/form',$data);
echo view(getenv('theme.path').'main/footer');
$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('Group.userGroup'))]);
$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('Group.userGroup'))]).'.';
$message .= anchor( "admin/user-groups/{$id}/edit" , lang('Basic.global.continueEditing').'?');
$message = ucfirst(str_replace("'", "\'", $message));
if ($thenRedirect) :
if (!empty($this->indexRoute)) :
return redirect()->to(route_to( $this->indexRoute ) )->with('sweet-success', $message);
else:
return $this->redirect2listView('sweet-success', $message);
endif;
else:
$this->viewData['successMessage'] = $message;
endif;
endif; // $noException && $successfulResult
endif; // ($requestMethod === 'post')
$this->viewData['group'] = isset($sanitizedData) ? new UserGroupModel($sanitizedData) : new UserGroupModel();
$this->viewData['formAction'] = route_to('createUserGroup');
$this->viewData['boxTitle'] = lang('Basic.global.addNew').' '.lang('Group.moduleTitle').' '.lang('Basic.global.addNewSuffix');
return $this->displayForm(__METHOD__);
}
//public function edit($id)