Merge branch 'main' into 'add/ajustar_margen'

Mergeados UserModel's y eliminadas referencias a App\Models\UserModel a favor...

See merge request jjimenez/safekat!654
This commit is contained in:
2025-04-04 15:03:45 +00:00
13 changed files with 155 additions and 268 deletions

View File

@ -13,8 +13,7 @@ declare(strict_types=1);
namespace Config; namespace Config;
use App\Entities\Usuarios\UsersEntity; use App\Models\Usuarios\UserModel;
use App\Models\UserModel;
use CodeIgniter\Shield\Authentication\Authenticators\JWT; use CodeIgniter\Shield\Authentication\Authenticators\JWT;
use CodeIgniter\Shield\Authentication\Passwords\ValidationRules; use CodeIgniter\Shield\Authentication\Passwords\ValidationRules;
use CodeIgniter\Shield\Config\Auth as ShieldAuth; use CodeIgniter\Shield\Config\Auth as ShieldAuth;

View File

@ -384,7 +384,7 @@ class Cliente extends \App\Controllers\BaseResourceController
{ {
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Users.user'))])]; $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Users.user'))])];
if (!is_null($selId)) : if (!is_null($selId)) :
$userModel = model('App\Models\UserModel'); $userModel = model('App\Models\Usuarios\UserModel');
$selOption = $userModel->where('id', $selId)->findColumn('first_name'); $selOption = $userModel->where('id', $selId)->findColumn('first_name');
if (!empty($selOption)) : if (!empty($selOption)) :
@ -414,7 +414,7 @@ class Cliente extends \App\Controllers\BaseResourceController
{ {
$data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Users.user'))])]; $data = ['' => lang('Basic.global.pleaseSelectA', [mb_strtolower(lang('Users.user'))])];
if (!is_null($selId)) : if (!is_null($selId)) :
$userModel = model('App\Models\UserModel'); $userModel = model('App\Models\Usuarios\UserModel');
$selOption = $userModel->where('id', $selId)->findColumn('last_name'); $selOption = $userModel->where('id', $selId)->findColumn('last_name');
if (!empty($selOption)) : if (!empty($selOption)) :

View File

@ -5,12 +5,10 @@ use App\Models\Chat\ChatDeparmentModel;
use App\Models\Chat\ChatDeparmentUserModel; use App\Models\Chat\ChatDeparmentUserModel;
use App\Models\Usuarios\GroupModel; use App\Models\Usuarios\GroupModel;
use App\Models\UserModel; use App\Models\Usuarios\UserModel;
use App\Models\Usuarios\GroupsUsersModel; use App\Models\Usuarios\GroupsUsersModel;
use App\Models\Collection; use App\Models\Collection;
use CodeIgniter\Shield\Entities\User;
use function PHPUnit\Framework\isNull;
class Users extends \App\Controllers\GoBaseController class Users extends \App\Controllers\GoBaseController
{ {
@ -89,8 +87,6 @@ class Users extends \App\Controllers\GoBaseController
// Marcar el username como NULL // Marcar el username como NULL
$sanitizedData = $this->sanitized($postData, true); $sanitizedData = $this->sanitized($postData, true);
$email = $sanitizedData['email'];
unset($sanitizedData['email']);
$noException = true; $noException = true;
@ -102,7 +98,7 @@ class Users extends \App\Controllers\GoBaseController
try { try {
// The Email is unique // The Email is unique
if ($this->user_model->isEmailUnique($email)) { if ($this->user_model->isEmailUnique($sanitizedData['email'])) {
// Crear el usuario si pasa la validación // Crear el usuario si pasa la validación
$user = new \CodeIgniter\Shield\Entities\User([ $user = new \CodeIgniter\Shield\Entities\User([
@ -111,6 +107,8 @@ class Users extends \App\Controllers\GoBaseController
'last_name' => $sanitizedData['last_name'], 'last_name' => $sanitizedData['last_name'],
'cliente_id' => $sanitizedData['cliente_id'], 'cliente_id' => $sanitizedData['cliente_id'],
'comments' => $sanitizedData['comments'], 'comments' => $sanitizedData['comments'],
'email' => $sanitizedData['email'],
'password' => $sanitizedData['password'],
'status' => $sanitizedData['status'] ?? 0, 'status' => $sanitizedData['status'] ?? 0,
'active' => $sanitizedData['active'] ?? 0, 'active' => $sanitizedData['active'] ?? 0,
]); ]);

View File

@ -225,7 +225,7 @@ class Facturas extends \App\Controllers\BaseResourceController
['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true] ['title' => lang("Facturas.facturaList"), 'route' => route_to('facturasList'), 'active' => true]
]; ];
$userModel = model('App\Models\UserModel'); $userModel = model('App\Models\Usuarios\UserModel');
$factura->created_by = $userModel->getFullName($factura->user_created_id); $factura->created_by = $userModel->getFullName($factura->user_created_id);
$factura->updated_by = $userModel->getFullName($factura->user_updated_id); $factura->updated_by = $userModel->getFullName($factura->user_updated_id);
$factura->created_at_footer = $factura->created_at ? date(' H:i d/m/Y', strtotime($factura->created_at)) : ''; $factura->created_at_footer = $factura->created_at ? date(' H:i d/m/Y', strtotime($factura->created_at)) : '';

View File

@ -583,7 +583,7 @@ class Pedido extends \App\Controllers\BaseResourceController
$pedidoEntity->fecha_encuadernado_text = $pedidoEntity->fecha_encuadernado ? date('d/m/Y', strtotime($pedidoEntity->fecha_encuadernado)) : ''; $pedidoEntity->fecha_encuadernado_text = $pedidoEntity->fecha_encuadernado ? date('d/m/Y', strtotime($pedidoEntity->fecha_encuadernado)) : '';
$pedidoEntity->fecha_entrega_externo_text = $pedidoEntity->fecha_entrega_externo ? date('d/m/Y', strtotime($pedidoEntity->fecha_entrega_externo)) : ''; $pedidoEntity->fecha_entrega_externo_text = $pedidoEntity->fecha_entrega_externo ? date('d/m/Y', strtotime($pedidoEntity->fecha_entrega_externo)) : '';
$userModel = model('App\Models\UserModel'); $userModel = model('App\Models\Usuarios\UserModel');
$pedidoEntity->created_by = $userModel->getFullName($pedidoEntity->user_created_id); $pedidoEntity->created_by = $userModel->getFullName($pedidoEntity->user_created_id);
$pedidoEntity->updated_by = $userModel->getFullName($pedidoEntity->user_updated_id); $pedidoEntity->updated_by = $userModel->getFullName($pedidoEntity->user_updated_id);
$pedidoEntity->created_at_footer = $pedidoEntity->created_at ? date(' H:i d/m/Y', strtotime($pedidoEntity->created_at)) : ''; $pedidoEntity->created_at_footer = $pedidoEntity->created_at ? date(' H:i d/m/Y', strtotime($pedidoEntity->created_at)) : '';

View File

@ -651,8 +651,8 @@ class Presupuestoadmin extends \App\Controllers\BaseResourceController
$data['resumen']['iva_reducido'] = $presupuesto->iva_reducido; $data['resumen']['iva_reducido'] = $presupuesto->iva_reducido;
$data['created_by'] = model('App\Models\UserModel')->getFullName($presupuesto->user_created_id); $data['created_by'] = model('App\Models\Usuarios\UserModel')->getFullName($presupuesto->user_created_id);
$data['updated_by'] = model('App\Models\UserModel')->getFullName($presupuesto->user_update_id); $data['updated_by'] = model('App\Models\Usuarios\UserModel')->getFullName($presupuesto->user_update_id);
$data['created_at'] = date(' H:i d/m/Y', strtotime($presupuesto->created_at)); $data['created_at'] = date(' H:i d/m/Y', strtotime($presupuesto->created_at));
$data['updated_at'] = date(' H:i d/m/Y', strtotime($presupuesto->updated_at)); $data['updated_at'] = date(' H:i d/m/Y', strtotime($presupuesto->updated_at));

View File

@ -3,7 +3,7 @@
namespace App\Controllers; namespace App\Controllers;
use App\Models\UserModel; use App\Models\Usuarios\UserModel;
class Profile extends BaseController class Profile extends BaseController
{ {

View File

@ -109,7 +109,7 @@ class Ticketcontroller extends \App\Controllers\BaseResourceController
$message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.'; $message = lang('Basic.global.saveSuccess', [lang('Basic.global.record')]) . '.';
$userModel = new \App\Models\UserModel(); $userModel = new \App\Models\Usuarios\UserModel();
$this->sendMail(lang('Tickets.newTicket'), lang('Tickets.newTicketBody') . base_url(route_to('editTicket', $id)), $userModel->find($sanitizedData['user_soporte_id'])->email); $this->sendMail(lang('Tickets.newTicket'), lang('Tickets.newTicketBody') . base_url(route_to('editTicket', $id)), $userModel->find($sanitizedData['user_soporte_id'])->email);
@ -198,7 +198,7 @@ class Ticketcontroller extends \App\Controllers\BaseResourceController
} }
// envio de correos // envio de correos
$userModel = new \App\Models\UserModel(); $userModel = new \App\Models\Usuarios\UserModel();
if ($oldUserSupport != $sanitizedData['user_soporte_id']) { if ($oldUserSupport != $sanitizedData['user_soporte_id']) {
$this->sendMail(lang('Tickets.asgignToChanged'), lang('Tickets.asgignToChangedBody') . base_url(route_to('editTicket', $id)), $userModel->find($sanitizedData['user_soporte_id'])->email); $this->sendMail(lang('Tickets.asgignToChanged'), lang('Tickets.asgignToChangedBody') . base_url(route_to('editTicket', $id)), $userModel->find($sanitizedData['user_soporte_id'])->email);
} }
@ -382,15 +382,15 @@ class Ticketcontroller extends \App\Controllers\BaseResourceController
$supportUsers = array( $supportUsers = array(
array( array(
'id' => $defatulSoporteUserId, 'id' => $defatulSoporteUserId,
'name' => model('App\Models\UserModel')->getFullName($defatulSoporteUserId) 'name' => model('App\Models\Usuarios\UserModel')->getFullName($defatulSoporteUserId)
), ),
array( array(
'id' => 2, 'id' => 2,
'name' => model('App\Models\UserModel')->getFullName(2) 'name' => model('App\Models\Usuarios\UserModel')->getFullName(2)
), ),
array( array(
'id' => 1, 'id' => 1,
'name' => model('App\Models\UserModel')->getFullName(1) 'name' => model('App\Models\Usuarios\UserModel')->getFullName(1)
), ),
); );

View File

@ -1,11 +1,10 @@
<?php <?php
namespace App\Entities\Usuarios; namespace App\Entities\Usuarios;
use App\Entities\Chat\ChatNotificationEntity;
use App\Models\ChatNotification; use App\Models\ChatNotification;
use CodeIgniter\Entity; use CodeIgniter\Shield\Entities\User;
class UserEntity extends \CodeIgniter\Entity\Entity class UserEntity extends User
{ {
protected $attributes = [ protected $attributes = [
"id" => null, "id" => null,
@ -20,7 +19,6 @@ class UserEntity extends \CodeIgniter\Entity\Entity
"created_at" => null, "created_at" => null,
"updated_at" => null, "updated_at" => null,
"deleted_at" => null, "deleted_at" => null,
]; ];
protected $casts = [ protected $casts = [
"id" => "int", "id" => "int",
@ -73,4 +71,6 @@ class UserEntity extends \CodeIgniter\Entity\Entity
$m = model(ChatNotification::class); $m = model(ChatNotification::class);
return $m->where('user_id',$this->attributes['id'])->findAll() ?? []; return $m->where('user_id',$this->attributes['id'])->findAll() ?? [];
} }
} }

View File

@ -1,30 +0,0 @@
<?php
namespace App\Entities\Usuarios;
use CodeIgniter\Shield\Entities\User;
class UsersEntity extends User
{
protected $attributes = [
'first_name' => null,
'last_name'=> null,
'cliente_id' => null,
'comments' => null,
];
protected $casts = [
"cliente_id" => "int",
];
public function getFullName()
{
$firstName = trim($this->attributes["first_name"] ?? "");
$lastName = trim($this->attributes["last_name"] ?? "");
$fullName = $firstName . ' ' . $lastName;
$fullName = trim($fullName); // In case first name is empty, this will remove the leading space
// Use the username attribute if the full name is still empty after trimming
return $fullName ?: $this->attributes["username"];
}
}

View File

@ -23,7 +23,7 @@ class ClienteUsuariosModel extends ShieldUserModel
]; ];
protected $allowedFields = ["id", "first_name", "last_name", "email"]; protected $allowedFields = ["id", "first_name", "last_name", "email"];
protected $returnType = "App\Entities\Usuarios\UsersEntity"; protected $returnType = "App\Entities\Usuarios\UserEntity";
protected $useTimestamps = true; protected $useTimestamps = true;
protected $useSoftDeletes = false; protected $useSoftDeletes = false;

View File

@ -1,153 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Models;
use App\Entities\Usuarios\UsersEntity;
use CodeIgniter\Shield\Authentication\Traits\HasAccessTokens;
use CodeIgniter\Shield\Models\UserModel as ShieldUserModel;
class UserModel extends ShieldUserModel
{
use HasAccessTokens;
protected function initialize(): void
{
parent::initialize();
$this->allowedFields = [
...$this->allowedFields,
'first_name', // Añadido
'last_name', // Añadido
'cliente_id', // Añadido
'comments', // Añadido
];
}
const SORTABLE = [
0 => "t1.id",
1 => "t1.first_name",
2 => "t1.last_name",
3 => "t2.secret",
4 => "t3.nombre",
5 => "t1.last_active",
];
protected $returnType = UsersEntity::class;
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [
"first_name" => "required|trim|max_length[150]",
"last_name" => "required|trim|max_length[150]",
"email" => "required|valid_email|max_length[150]",
'new_pwd' => 'permit_empty|min_length[8]',
'new_pwd_confirm' => 'permit_empty|required_with[new_pwd]|matches[new_pwd]',
"comments" => "permit_empty|trim|max_length[512]"
];
protected $validationMessages = [
'first_name' => [
"max_length" => "Users.validation.first_name.max_length",
"required" => "Users.validation.first_name.required"
],
'last_name' => [
"max_length" => "Users.validation.last_name.max_length",
"required" => "Users.validation.last_name.required"
],
'new_pwd' => [
'min_length' => "App.profile_rules_password_m"
],
'new_pwd_confirm' => [
'matches' => "App.profile_rules_password_confirm_m"
],
'comments' => [
"max_length" => "Users.validation.last_name.max_length",
],
'email' => [
"required" => "Users.validation.email.required",
"valid_email" => "Users.validation.email.valid_email",
"max_length" => "Users.validation.email.max_length"
]
];
public function getResource($search = [])
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id as id, t1.first_name AS first_name, t1.last_name AS last_name,
t2.secret AS email, t1.last_active AS last_active, t3.nombre AS cliente"
);
$builder->join("auth_identities t2", "t1.id = t2.user_id", "left");
$builder->join("clientes t3", "t1.cliente_id = t3.id", "left");
$builder->where('t1.deleted_at', null)->groupBy("t1.id");
if (empty($search))
return $builder;
else {
$builder->groupStart();
foreach ($search as $col_search) {
$column = self::SORTABLE[$col_search[0]];
$value = $col_search[2];
$builder->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%");
}
$builder->groupEnd();
return $builder;
}
}
public function getComerciales()
{
$builder = $this->db
->table("users" . " t1")
->select(
"t1.id AS id, CONCAT(t1.first_name, ' ', t1.last_name) AS name"
);
$builder->where('t1.deleted_at', null);
$builder->where("t2.group", "comercial");
$builder->join("auth_groups_users t2", "t1.id = t2.user_id", "left");
return $builder->get()->getResult();
}
public function getFullName($id=0){
$builder = $this->db
->table("users" . " t1")
->select(
"CONCAT(t1.first_name, ' ', t1.last_name) AS name"
);
$builder->where('t1.deleted_at', null);
$builder->where('t1.id', $id);
return $builder->get()->getRow()->name;
}
// Método para comprobar si el email ya está registrado
public function isEmailUnique($email)
{
$builder = $this->db
->table("auth_identities t1") // La tabla correcta
->select("t1.secret AS email")
->where('secret', $email);
// Obtener resultados
$result = $builder->get()->getRow();
// Devuelve true si no se encuentra el correo (es único), false en caso contrario
return $result === null;
}
}

View File

@ -1,81 +1,154 @@
<?php <?php
declare(strict_types=1);
namespace App\Models\Usuarios; namespace App\Models\Usuarios;
class UserModel extends \App\Models\BaseModel use CodeIgniter\Shield\Authentication\Traits\HasAccessTokens;
use CodeIgniter\Shield\Models\UserModel as ShieldUserModel;
use App\Entities\Usuarios\UserEntity;
class UserModel extends ShieldUserModel
{ {
protected $table = "users"; use HasAccessTokens;
/** protected function initialize(): void
* Whether primary key uses auto increment. {
* parent::initialize();
* @var bool
*/
protected $useAutoIncrement = true;
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $primaryKey = "id"; $this->allowedFields = [
...$this->allowedFields,
'first_name', // Añadido
'last_name', // Añadido
'cliente_id', // Añadido
'comments', // Añadido
];
}
protected $allowedFields = [ const SORTABLE = [
"username", 0 => "t1.id",
"first_name", 1 => "t1.first_name",
"last_name", 2 => "t1.last_name",
"client_id", 3 => "t2.secret",
"status", 4 => "t3.nombre",
"status_message", 5 => "t1.last_active",
"active",
"comments",
"last_active",
"created_at",
"updated_at",
"deleted_at",
]; ];
protected $returnType = "App\Entities\Usuarios\UserEntity";
public static $labelField = "first_name"; protected $returnType = UserEntity::class;
protected $useSoftDeletes = true;
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [ protected $validationRules = [
"first_name" => [ "first_name" => [
"label" => "Users.firstName", "label" => "Users.firstName",
"rules" => "trim|max_length[150]", "rules" => "required|trim|max_length[150]",
], ],
"last_name" => [ "last_name" => [
"label" => "Users.lastName", "label" => "Users.lastName",
"rules" => "trim|max_length[150]", "rules" => "required|trim|max_length[150]",
], ],
'new_pwd' => 'permit_empty|min_length[8]',
'new_pwd_confirm' => 'permit_empty|required_with[new_pwd]|matches[new_pwd]',
"comments" => "permit_empty|trim|max_length[512]"
]; ];
protected $validationMessages = [ protected $validationMessages = [
"first_name" => [ 'first_name' => [
"max_length" => "Users.validation.first_name.max_length", "max_length" => "Users.validation.first_name.max_length",
"required" => "Users.validation.first_name.required", "required" => "Users.validation.first_name.required"
], ],
"last_name" => [ 'last_name' => [
"max_length" => "Users.validation.last_name.max_length", "max_length" => "Users.validation.last_name.max_length",
"required" => "Users.validation.last_name.required", "required" => "Users.validation.last_name.required"
], ],
'new_pwd' => [
'min_length' => "App.profile_rules_password_m"
],
'new_pwd_confirm' => [
'matches' => "App.profile_rules_password_confirm_m"
],
'comments' => [
"max_length" => "Users.validation.last_name.max_length",
]
]; ];
public function getGroupsTitles($user_token){ public function getResource($search = [])
{
$builder = $this->db
->table($this->table . " t1")
->select(
"t1.id as id, t1.first_name AS first_name, t1.last_name AS last_name,
t2.secret AS email, t1.last_active AS last_active, t3.nombre AS cliente"
);
$sql = 'SELECT `auth_groups`.`title` FROM `auth_groups` $builder->join("auth_identities t2", "t1.id = t2.user_id", "left");
JOIN `group_user` ON `auth_groups`.`token` = `group_user`.`token_group` $builder->join("clientes t3", "t1.cliente_id = t3.id", "left");
JOIN `auth_user` ON `auth_user`.`token` = `group_user`.`token_user`
WHERE `auth_user`.`token` = \''. $user_token . '\'';
$builder->where('t1.deleted_at', null)->groupBy("t1.id");
$query = $this->db->query($sql); if (empty($search))
$result = $query->getResultObject(); return $builder;
$data = []; else {
foreach($result as $r){ $builder->groupStart();
array_push($data, $r->title); foreach ($search as $col_search) {
$column = self::SORTABLE[$col_search[0]];
$value = $col_search[2];
$builder->where("LOWER(CONVERT($column USING utf8)) COLLATE utf8_general_ci LIKE", "%" . strtolower($value) . "%");
}
$builder->groupEnd();
return $builder;
} }
return implode(',', $data); }
public function getComerciales()
{
$builder = $this->db
->table("users" . " t1")
->select(
"t1.id AS id, CONCAT(t1.first_name, ' ', t1.last_name) AS name"
);
$builder->where('t1.deleted_at', null);
$builder->where("t2.group", "comercial");
$builder->join("auth_groups_users t2", "t1.id = t2.user_id", "left");
return $builder->get()->getResult();
} }
public function getFullName($id=0){
$builder = $this->db
->table("users" . " t1")
->select(
"CONCAT(t1.first_name, ' ', t1.last_name) AS name"
);
$builder->where('t1.deleted_at', null);
$builder->where('t1.id', $id);
return $builder->get()->getRow()->name;
}
// Método para comprobar si el email ya está registrado
public function isEmailUnique($email)
{
$builder = $this->db
->table("auth_identities t1") // La tabla correcta
->select("t1.secret AS email")
->where('secret', $email);
// Obtener resultados
$result = $builder->get()->getRow();
// Devuelve true si no se encuentra el correo (es único), false en caso contrario
return $result === null;
}
} }