Un buen negocio o empresa con un numero de empleados considerable siempre va a necesitar un buen sistema de nomina sobre todo para sacar reportes, generar archivos de dispersión de nomina para pagarle a través del banco y sobre todo para generar el timbrado.
Durante las siguientes publicaciones mostraremos como desarrollar un sistema de nomina completo en CodeIgniter 4.x
Primero crearemos la base del proyecto
Creamos el proyecto via composer con el siguiente codigo
Creamos la tabla nomina2023 en mariaDB/MySQL o en el motor de su preferencia
en app/config/database.php cambiamos la configuración de la base de datos default lo dejamos de la siguiente forma, igual si ustedes le quieren poner alguna contraseña por seguridad pueden ponersela
en app/config/app.php modificamos las siguientes variables
public $indexPage = '';
public $defaultLocale = 'es';
public $supportedLocales = ['es'];
Para debugear ponemos este codigo al final del archivo app/config/constants.php
define("ENVIRONMENT","development");
Ahora procedemos a instalar boilerplate el cual nos servirá para instalar la plantilla adminLTE3 con un administrador de usuario/roles/permisos/login
Primero instalamos via composer con el siguiente comando
composer require agungsugiarto/boilerplate
Instalamos Auth que es lo que permitirá logearnos administrar usuarios, permisos y roles
php spark auth:publish
Publish Migration? [y, n]: y
created: Database/Migrations/2017-11-20-223112_create_auth_tables.php
Remember to run `spark migrate -all` to migrate the database.
Publish Models? [y, n]: n
Publish Entities? [y, n]: n
Publish Controller? [y, n]: n
Publish Views? [y, n]: n
Publish Filters? [y, n]: n
Publish Config file? [y, n]: y
created: Config/Auth.php
Publish Language file? [y, n]: n
en app/config/auth.php remplazamos el siguiente codigo
Instalamos, migramos y sembramos boilerplate con el siguiente comando
php spark boilerplate:install
En controller/home.php lo dejamos de la siguiente manera para que siempre nos retorne al admin
<?php
namespace App\Controllers;
class Home extends BaseController
{
public function index()
{
return redirect()->to('/admin');
}
}
En app/config/Boilerplate.php modificamos public $i18n = ‘Indonesian’; a public $i18n = ‘Spanish’; para cambiar el idioma del datable, para el nombre del programa cambiamos public $appName = ‘Boilerplate’; por public $appName = ‘Nomina 2023’;
Tambien modificamos el brand a nuestro antojo yo lo modifique de esta manera
En este apartado vamos a crear nuestro modulo de citas medicas que posteriormente podremos convertir en consulta, a su vez veremos como crear nuestros propios helpers y usarlos
Que es un helper en codeigniter, pues no es mas que funciones o utilerías que nos pueden servir en diferentes partes del sistema
Creamos la tabla para citas
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 08-01-2023 a las 23:44:15
-- Versión del servidor: 10.4.17-MariaDB
-- Versión de PHP: 7.4.15
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `medicalsoft`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `citas`
--
CREATE TABLE `citas` (
`id` int(11) NOT NULL,
`idPaciente` int(11) DEFAULT NULL,
`fechaHora` datetime NOT NULL,
`hastaFechaHora` datetime DEFAULT NULL,
`observaciones` varchar(1024) COLLATE utf8_spanish2_ci NOT NULL,
`created_at` datetime NOT NULL,
`deleted_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`estado` varchar(15) COLLATE utf8_spanish2_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `citas`
--
ALTER TABLE `citas`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `citas`
--
ALTER TABLE `citas`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Y como de costumbre creamos primeramente el archiv CitasModel.php en la carpeta app/models y le ponemos el siguiente código
En este modulo como se vieron el archivo CitasController.php se usaron unas funciones para el formato de las fechas dichas funciones estan en el helper, estas funciones nos sirvieron anteriormente en JCPOS2021, entonces en la carpeta app/Helpers creamos el archivo utilerias_helper.php y metemos el siguiente código
<?php
function strMenuActivo($strMenu1, $strMenu2) {
if ($strMenu1 == $strMenu2) {
$respuesta = 'class="active"';
} else {
$respuesta = "";
}
return $respuesta;
}
//SI LA VARIABLE ESTA VACIA O NO SETA DECLARADA MANDARA CERO SIEMPRE, ES COMO EL VAL DE VISUAL BASIC 6.0
function esCero($value) {
if (empty($value)) {
return "0";
} else {
return $value;
}
}
//FECHA SQL PARA GUARDAR EN BASE DE DATOS
function fechaSQL($fecha) {
return date("Ymd", strtotime($fecha));
}
// CONVIERTE FECHA MYSQLDATETIME A HTML5
function fechaMySQLADateTimeHTML5($fecha) {
return date("Y-m-d", strtotime($fecha)) . "T" . date("H:i:s", strtotime($fecha));
}
function agregarMinutos($fecha, $minutos) {
return date("Y/m/d h:i:s", strtotime($fecha . "+ $minutos minutes"));
/*
$fecha1= new DateTime($fecha);
$fecha1->add(new DateInterval('PT10H30S'));
return $date->format('Y-m-d H:i:s') . "\n";
*
*/
}
//CONVIERTE LA FECHA EN PERIODO
function fechaPeriodo($fecha) {
return date("Ym", strtotime($fecha));
}
//OBTIENE FECHA ACTUAL
function fechaActual() {
return date("Y/m/d");
}
//OBTIENE FECHA HORA ACTUAL
function fechaHoraActual() {
return date("Y-m-d H:i:s ", time());
}
//DIFERENCIA ENTRE MINUTOS
function diferenciaMinutos($fecha_i, $fecha_f) {
$minutos = (strtotime($fecha_i) - strtotime($fecha_f)) / 60;
$minutos = abs($minutos);
$minutos = floor($minutos);
return $minutos;
}
function strSellar($llave, $password, $cadenaOriginal) {
$archivoPem = "/tmp/llave.key.pem";
$comando = "openssl pkcs8 -inform DER -in $llave -passin pass:$password -out $archivoPem";
exec($comando);
$sello = "ok";
//Sellar
$archivo = openssl_pkey_get_private(file_get_contents($archivoPem));
$sig = "";
openssl_sign($cadenaOriginal, $sig, $archivo, OPENSSL_ALGO_SHA256);
$sello = base64_encode($sig);
return $sello;
}
//SOLO DIA
function dia($fecha) {
return date("d", strtotime($fecha));
}
//SOLO MES
function mes($fecha) {
return date("m", strtotime($fecha));
}
//SOLO AÑO
function año($fecha) {
return date("Y", strtotime($fecha));
}
Ahora en app/lenguajes/en/ creamos el archivo citas.php y metemos el siguiente archivo
<?php
$citas["observaciones"] = "Observations";
$citas["nombrePaciente"] = "Patient´s Name";
$citas["fechaHora"] = "Start Date";
$citas["hastaFechaHora"] = "End Date";
$citas["createdAt"] = "Date Creation";
$citas["updateAt"] = "Date Update";
$citas["add"] = "add appointment";
$citas["actions"] = "Acciones";
$citas["estado"] = "status";
$citas["createEdit"] = "add / update appointment";
$citas["seleccionePaciente"] = "Select an Patient";
$citas["title"] = "appointment";
$citas["subtitle"] = "List of appointments";
$citas["msg_delete"] = "The quote has been removed .";
$citas["msg_get_fail"] = "The appointment does not exist or was deleted.";
return $citas;
Ahora en app/lenguajes/es/ creamos el archivo citas.php y metemos el siguiente archivo
<?php
$citas["observaciones"] = "Observaciones";
$citas["nombrePaciente"] = "Nombre Paciente";
$citas["fechaHora"] = "Fecha Inicio Cita";
$citas["obsevaciones"] = "Observaciones";
$citas["hastaFechaHora"] = "Fin Cita";
$citas["createdAt"] = "Fecha Creación";
$citas["updateAt"] = "Fecha de Modificación";
$citas["add"] = "Agregar Cita";
$citas["actions"] = "Acciones";
$citas["estado"] = "Estado";
$citas["createEdit"] = "Crear / Editar Citas";
$citas["seleccionePaciente"] = "Seleccione un paciente";
$citas["title"] = "Citas";
$citas["subtitle"] = "Lista de Citas";
$citas["msg_delete"] = "La cita ha sido eliminada .";
$citas["msg_get_fail"] = "La cita no existe o fue eliminada.";
return $citas;
Luego ya por ultimo creamos las rutas en app/config/routes.php metemos el siguiente codigo
Ya por ultimo creamos un CRUD super básico para las enfermedades
Primero creamos la tabla
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 07-01-2023 a las 17:11:20
-- Versión del servidor: 10.4.17-MariaDB
-- Versión de PHP: 7.4.15
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `medicalsoft`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `enfermedades`
--
CREATE TABLE `enfermedades` (
`id` int(11) NOT NULL,
`descripcion` varchar(256) COLLATE utf8_spanish2_ci NOT NULL,
`created_at` datetime NOT NULL,
`deleted_at` datetime NOT NULL,
`updated_at` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `enfermedades`
--
ALTER TABLE `enfermedades`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `enfermedades`
--
ALTER TABLE `enfermedades`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Creamos el archivo EnfermedadesModel.php en app/models
Ya creamos el CRUD para pacientes, ahora será necesario crear un CRUD para los medicamentos.
Primero creamos la tabla medicamentos, les dejo la exportación desde phpmyadmin
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 06-01-2023 a las 20:37:36
-- Versión del servidor: 10.4.17-MariaDB
-- Versión de PHP: 7.4.15
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `medicalsoft`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `medicamentos`
--
CREATE TABLE `medicamentos` (
`id` int(11) NOT NULL,
`descripcion` varchar(256) COLLATE utf8_spanish2_ci NOT NULL,
`created_at` datetime DEFAULT NULL,
`deleted_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `medicamentos`
--
ALTER TABLE `medicamentos`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `medicamentos`
--
ALTER TABLE `medicamentos`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Creamos el archivo MedicamentosModel.php en app/models/
Ahora veremos como crear el CRUD de pacientes en el framework CodeIgniter 4.0 con los siguientes datos, Nombres, Apellidos, DNI, Correo Electrónico, para ello creamos la siguiente tabla.
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 04-01-2023 a las 18:20:08
-- Versión del servidor: 10.4.17-MariaDB
-- Versión de PHP: 7.4.15
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `medicalsoft`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `pacientes`
--
CREATE TABLE `pacientes` (
`id` int(11) NOT NULL,
`nombres` varchar(256) COLLATE utf8_spanish2_ci DEFAULT NULL,
`apellidos` varchar(256) COLLATE utf8_spanish2_ci DEFAULT NULL,
`dni` varchar(32) COLLATE utf8_spanish2_ci DEFAULT NULL,
`telefono` varchar(16) COLLATE utf8_spanish2_ci DEFAULT NULL,
`correoElectronico` varchar(64) COLLATE utf8_spanish2_ci DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`deleted_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `pacientes`
--
ALTER TABLE `pacientes`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `pacientes`
--
ALTER TABLE `pacientes`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Creamos el archivo PacientesModel.php en la carpeta model para el acceso a la tabla de la base de datos
Creamos el archivo PacientesController.php alli tendremos la funciones para guardar, leer y modificar, creo que no falta decir que va en la carpeta controller
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use \App\Models\PacientesModel;
use \App\Models\BitacoraModel;
use CodeIgniter\API\ResponseTrait;
class PacientesController extends BaseController {
use ResponseTrait;
protected $bitacora;
protected $pacientes;
public function __construct() {
$this->pacientes = new PacientesModel();
$this->bitacora = new BitacoraModel();
helper('menu');
}
public function index() {
if ($this->request->isAJAX()) {
/*
$start = $this->request->getGet('start');
$length = $this->request->getGet('length');
$search = $this->request->getGet('search[value]');
$order = BitacoraModel::ORDERABLE[$this->request->getGet('order[0][column]')];
$dir = $this->request->getGet('order[0][dir]');
*/
$datos = $this->pacientes->select('id,nombres,apellidos,dni,telefono,correoElectronico,created_at,updated_at')->where('deleted_at', null);
// $resultado = $this->bitacora->findAll();
// $this->bitacora->getResource()->countAllResults(),
// $this->bitacora->getResource($search)->countAllResults()
// var_dump($datos);
return \Hermawan\DataTables\DataTable::of($datos)->add('action', function ($row) {
return " <div class=\"btn-group\">
<button class=\"btn btn-warning btnEditarPaciente\" data-toggle=\"modal\" idPaciente=\"$row->id\" data-target=\"#modalAgregarPaciente\"> <i class=\" fa fa-edit \"></i></button>
<button class=\"btn btn-danger btnEliminarPaciente\" idPaciente=\"$row->id\"><i class=\"fa fa-times\"></i></button></div>";
}, 'last')
->toJson();
}
$titulos["title"] = lang('patients.title');
$titulos["subtitle"] = lang('patients.subtitle');
//$data["data"] = $datos;
return view('pacientes', $titulos);
}
/*
* Lee paciente
*/
public function traePaciente() {
$idPaciente = $this->request->getPost("idPaciente");
$datosPaciente = $this->pacientes->find($idPaciente);
echo json_encode($datosPaciente);
}
/*
* Guarda o actualiza paciente
*/
public function guardar() {
helper('auth');
$userName = user()->username;
$idUser = user()->id;
$datos = $this->request->getPost();
if ($datos["idPaciente"] == 0) {
try {
if ($this->pacientes->save($datos) === false) {
$errores = $this->pacientes->errors();
foreach ($errores as $field => $error) {
echo $error . " ";
}
return;
}
$datosBitacora["descripcion"] = "Se guardo el paciente con los siguientes datos: " . json_encode($datos);
$datosBitacora["usuario"] = $userName;
$this->bitacora->save($datosBitacora);
echo "Guardado Correctamente";
} catch (\PHPUnit\Framework\Exception $ex) {
echo "Error al guardar " . $ex->getMessage();
}
} else {
if ($this->pacientes->update($datos["idPaciente"], $datos) == false) {
$errores = $this->pacientes->errors();
foreach ($errores as $field => $error) {
echo $error . " ";
}
return;
} else {
$datosBitacora["descripcion"] = "Se actualizo el paciente con los siguientes datos: " . json_encode($datos);
$datosBitacora["usuario"] = $userName;
$this->bitacora->save($datosBitacora);
echo "Actualizado Correctamente";
return;
}
}
return;
}
public function delete($id) {
if (!$found = $this->pacientes->delete($id)) {
return $this->failNotFound(lang('patients.msg.msg_get_fail'));
}
$infoPaciente = $this->pacientes->find($id);
$datosBitacora["descripcion"] = "Se elimino el paciente que contenia los siguientes datos " . json_encode($infoPaciente);
$this->bitacora->save($datosBitacora);
return $this->respondDeleted($found, lang('patients.msg.msg_delete'));
}
/**
* Trae en formato JSON los pacientes para el select2
* @return type
*/
public function traerPacientesAjax() {
$request = service('request');
$postData = $request->getPost();
$response = array();
// Read new token and assign in $response['token']
$response['token'] = csrf_hash();
if (!isset($postData['searchTerm'])) {
// Fetch record
$pacientes = new PacientesModel();
$listaPacientes = $pacientes->select('id,nombres,apellidos')
->orderBy('nombres')
->findAll(10);
} else {
$searchTerm = $postData['searchTerm'];
// Fetch record
$pacientes = new PacientesModel();
$listaPacientes = $pacientes->select('id,nombres,apellidos')
->where("deleted_at",null)
->like('nombres', $searchTerm)
->orLike('apellidos', $searchTerm)
->orderBy('nombres')
->findAll(10);
}
$data = array();
foreach ($listaPacientes as $paciente) {
$data[] = array(
"id" => $paciente['id'],
"text" => $paciente['nombres'].' '.$paciente['apellidos'],
);
}
$response['data'] = $data;
return $this->response->setJSON($response);
}
}
Ya vimos como guardar los datos de la bitácora, ahora veremos como usar el datatable con server side para mostrar los datos de guardados en la bitácora
Primero creamos el archivo BitacoraModel.php de la siguiente forma en la carpeta app/model/ aunque a estas altura ya debemos tenerlo
Para convertir fácilmente el resultado de la consulta SQL del QUERYBUILDER a formato json que usa datatable instalamos en la terminal el siguiente componente de hermawan usando composer
composer require hermawan/codeigniter4-datatables
Creamos el archivo BitacoraController.php con los siguientes, si observamos en la función index vemos que solo con una linea se crea el json
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use \App\Models\BitacoraModel;
use CodeIgniter\API\ResponseTrait;
class BitacoraController extends BaseController {
use ResponseTrait;
protected $bitacora;
public function __construct() {
$this->bitacora = new BitacoraModel();
helper('menu');
}
public function index() {
if ($this->request->isAJAX()) {
/*
$start = $this->request->getGet('start');
$length = $this->request->getGet('length');
$search = $this->request->getGet('search[value]');
$order = BitacoraModel::ORDERABLE[$this->request->getGet('order[0][column]')];
$dir = $this->request->getGet('order[0][dir]');
*/
$datos = $this->bitacora->select('id,descripcion,usuario,created_at');
// $resultado = $this->bitacora->findAll();
// $this->bitacora->getResource()->countAllResults(),
// $this->bitacora->getResource($search)->countAllResults()
return \Hermawan\DataTables\DataTable::of($datos)->toJson();
}
$titulos["title"] = lang('log.title');
$titulos["subtitle"] = lang('log.subtitle');
//$data["data"] = $datos;
return view('bitacora',$titulos);
}
public function tabla() {
if ($this->request->isAJAX()) {
$start = $this->request->getGet('start');
$length = $this->request->getGet('length');
$search = $this->request->getGet('search[value]');
$order = BitacoraModel::ORDERABLE[$this->request->getGet('order[0][column]')];
$dir = $this->request->getGet('order[0][dir]');
return $this->respond(Collection::datatable(
$this->bitacora->getResource($search)->orderBy($order, $dir)->limit($length, $start)->get()->getResultObject(),
$this->bitacora->getResource()->countAllResults(),
$this->bitacora->getResource($search)->countAllResults()
));
}
}
}
En cualquier sistema es importante tener un log o una bitácora en donde vallamos almacenando lo cambios que vamos realizando en la base de datos, por ejemplo, ir guardando la información que va insertando el usuario a la tabla de clientes, también cuando se elimino y actualizo grabando un timestamp que guarde hasta el segundo exacto de modificación y ya con eso vamos llevando un control
Haremos todo esto en CodeIgniter 4
Empezamos primero creamos la tabla
--
-- Estructura de tabla para la tabla bitacora
CREATE TABLE bitacora (
id bigint(20) NOT NULL,
descripcion text COLLATE utf8_spanish2_ci DEFAULT NULL,
usuario varchar(16) COLLATE utf8_spanish2_ci DEFAULT NULL,
created_at datetime DEFAULT NULL,
deleted_at datetime DEFAULT NULL,
updated_at datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish2_ci;
--
-- Índices para tablas volcadas
--
-- Indices de la tabla bitacora
ALTER TABLE bitacora
ADD PRIMARY KEY (id);
ALTER TABLE bitacora
MODIFY id bigint(20) NOT NULL AUTO_INCREMENT;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Ahora usaremos el modelo para guardar cada vez que se haga un cambio al guardar la configuración del hospital
<?php
namespace agungsugiarto\boilerplate\Controllers\Users;
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;
use App\Models\ConfiguracionesModel;
use App\Models\BitacoraModel;
use agungsugiarto\boilerplate\Controllers\BaseController;
use agungsugiarto\boilerplate\Entities\Collection;
use agungsugiarto\boilerplate\Models\GroupModel;
use CodeIgniter\Config\Services;
class HospitalController extends Controller
{
use ResponseTrait;
/** @var \agungsugiarto\boilerplate\Models\GroupModel */
protected $group;
protected $configuraciones;
protected $bitacora;
public function __construct()
{
$this->group = new GroupModel();
$this->configuraciones = new ConfiguracionesModel();
$this->bitacora = new BitacoraModel();
$autorize = $this->authorize = Services::authorization();
helper('menu');
}
public function index()
{
$datos = $this->configuraciones->where("id",1)->first();
$data["title"] = lang('settings.settings.title');
$data["subtitle"] = lang('settings.settings.title');
$data["data"] = $datos;
return view('configuracionEmpresa/index',$data);
}
public function guardar()
{
helper('auth');
$userName = user()->username ;
$idUser = user()->id ;
$bitacoraDatos["descripcion"] = "Se Modifico las configuracion con los siguientes datos:". json_encode($_POST);
$bitacoraDatos["usuario"] = $userName;
//GUARDA CONFIGURACIONES
$this->configuraciones->update(1,$_POST);
//GUARDAR EN BITACORA
$this->bitacora->save($bitacoraDatos);
// return redirect()->to("/admin/hospital");
return redirect()->back()->with('sweet-success', 'Actualizado Correctamente');
// return redirect()->back()->with('sweet-success','Guardado Correctamente');
}
}
Ya con eso cada vez que se haga un cambio a a configuración nos guardara un registro sobre quien hizo el cambio y también nos servirá para los próximos módulos que se vallan programando.
En la próxima publicación veremos como mostrar los datos en un datatable.
Usamos cookies en nuestro sitio web para brindarle la experiencia más relevante recordando sus preferencias y visitas repetidas. Al hacer clic en "Aceptar", acepta el uso de TODAS las cookies.
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.