| | | 1 | | using FAU.Logica.DTOs; |
| | | 2 | | using FAU.Logica.Services; |
| | | 3 | | using Microsoft.AspNetCore.Authorization; |
| | | 4 | | using Microsoft.AspNetCore.Http; |
| | | 5 | | using Microsoft.AspNetCore.Mvc; |
| | | 6 | | |
| | | 7 | | namespace FAU.API.Controllers; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Gestión de usuarios del sistema |
| | | 11 | | /// </summary> |
| | | 12 | | [ApiController] |
| | | 13 | | [Route("api/[controller]")] |
| | | 14 | | [Authorize(Roles = "Administrador")] |
| | | 15 | | [Produces("application/json")] |
| | | 16 | | public class UsuariosController : ControllerBase |
| | | 17 | | { |
| | | 18 | | private readonly IUsuarioService _usuarioService; |
| | | 19 | | private readonly ILogger<UsuariosController> _logger; |
| | | 20 | | |
| | 20 | 21 | | public UsuariosController( |
| | 20 | 22 | | IUsuarioService usuarioService, |
| | 20 | 23 | | ILogger<UsuariosController> logger) |
| | | 24 | | { |
| | 20 | 25 | | _usuarioService = usuarioService; |
| | 20 | 26 | | _logger = logger; |
| | 20 | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Listar usuarios con filtros y paginación |
| | | 31 | | /// GET /api/usuarios?rolId=&estado=&q=&page=1&pageSize=25 |
| | | 32 | | /// </summary> |
| | | 33 | | [HttpGet] |
| | | 34 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 35 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 36 | | public async Task<IActionResult> GetUsuarios( |
| | | 37 | | [FromQuery] long? rolId, |
| | | 38 | | [FromQuery] string? estado, |
| | | 39 | | [FromQuery] string? q, |
| | | 40 | | [FromQuery] int page = 1, |
| | | 41 | | [FromQuery] int pageSize = 25) |
| | | 42 | | { |
| | | 43 | | try |
| | | 44 | | { |
| | | 45 | | // Validación de parámetros |
| | 6 | 46 | | if (page < 1) page = 1; |
| | 6 | 47 | | if (pageSize < 1) pageSize = 25; |
| | 6 | 48 | | if (pageSize > 100) pageSize = 100; // Límite máximo |
| | | 49 | | |
| | 6 | 50 | | var usuarios = await _usuarioService.GetAllAsync(); |
| | | 51 | | |
| | | 52 | | // Aplicar filtros |
| | 5 | 53 | | var query = usuarios.AsQueryable(); |
| | | 54 | | |
| | 5 | 55 | | if (rolId.HasValue) |
| | | 56 | | { |
| | 1 | 57 | | query = query.Where(u => u.Roles.Any(r => r.Id == rolId.Value)); |
| | | 58 | | } |
| | | 59 | | |
| | 5 | 60 | | if (!string.IsNullOrWhiteSpace(estado)) |
| | | 61 | | { |
| | 1 | 62 | | query = query.Where(u => u.Estado.Equals(estado, StringComparison.OrdinalIgnoreCase)); |
| | | 63 | | } |
| | | 64 | | |
| | 5 | 65 | | if (!string.IsNullOrWhiteSpace(q)) |
| | | 66 | | { |
| | 1 | 67 | | var searchTerm = q.ToLower(); |
| | 1 | 68 | | query = query.Where(u => |
| | 1 | 69 | | u.Username.ToLower().Contains(searchTerm) || |
| | 1 | 70 | | (u.Persona != null && ( |
| | 1 | 71 | | u.Persona.PrimerNombre.ToLower().Contains(searchTerm) || |
| | 1 | 72 | | u.Persona.PrimerApellido.ToLower().Contains(searchTerm) || |
| | 1 | 73 | | (u.Persona.SegundoNombre != null && u.Persona.SegundoNombre.ToLower().Contains(searchTerm)) || |
| | 1 | 74 | | (u.Persona.SegundoApellido != null && u.Persona.SegundoApellido.ToLower().Contains(searchTerm)) |
| | 1 | 75 | | (u.Persona.Email != null && u.Persona.Email.ToLower().Contains(searchTerm)) |
| | 1 | 76 | | )) |
| | 1 | 77 | | ); |
| | | 78 | | } |
| | | 79 | | |
| | 5 | 80 | | var total = query.Count(); |
| | | 81 | | |
| | | 82 | | // Paginación |
| | 5 | 83 | | var usuariosPaginados = query |
| | 5 | 84 | | .Skip((page - 1) * pageSize) |
| | 5 | 85 | | .Take(pageSize) |
| | 5 | 86 | | .ToList() |
| | 14 | 87 | | .Select(u => new |
| | 14 | 88 | | { |
| | 14 | 89 | | id = u.Id, |
| | 14 | 90 | | usuario = u.Username, |
| | 14 | 91 | | nombre = u.Persona != null ? u.Persona.NombreCompleto : "", |
| | 14 | 92 | | email = u.Persona?.Email ?? "", |
| | 14 | 93 | | rol = u.Roles.FirstOrDefault()?.Nombre ?? "", |
| | 14 | 94 | | estado = u.Estado, |
| | 14 | 95 | | ultimoAcceso = u.FechaActualizacion |
| | 14 | 96 | | }) |
| | 5 | 97 | | .ToList(); |
| | | 98 | | |
| | 5 | 99 | | var response = new |
| | 5 | 100 | | { |
| | 5 | 101 | | items = usuariosPaginados, |
| | 5 | 102 | | total = total, |
| | 5 | 103 | | page = page, |
| | 5 | 104 | | pageSize = pageSize, |
| | 5 | 105 | | totalPages = (int)Math.Ceiling((double)total / pageSize) |
| | 5 | 106 | | }; |
| | | 107 | | |
| | 5 | 108 | | return Ok(ApiResponse<object>.SuccessResult(response)); |
| | | 109 | | } |
| | 1 | 110 | | catch (Exception ex) |
| | | 111 | | { |
| | 1 | 112 | | _logger.LogError(ex, "Error al obtener usuarios"); |
| | 1 | 113 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 114 | | } |
| | 6 | 115 | | } |
| | | 116 | | |
| | | 117 | | /// <summary> |
| | | 118 | | /// Obtener detalle de usuario por ID |
| | | 119 | | /// GET /api/usuarios/{id} |
| | | 120 | | /// </summary> |
| | | 121 | | [HttpGet("{id}")] |
| | | 122 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 123 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 124 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 125 | | public async Task<IActionResult> GetUsuario(long id) |
| | | 126 | | { |
| | | 127 | | try |
| | | 128 | | { |
| | 3 | 129 | | var usuario = await _usuarioService.GetByIdAsync(id); |
| | | 130 | | |
| | 2 | 131 | | if (usuario == null) |
| | | 132 | | { |
| | 1 | 133 | | return NotFound(ApiResponse<string>.ErrorResult("Usuario no encontrado")); |
| | | 134 | | } |
| | | 135 | | |
| | 1 | 136 | | var response = new |
| | 1 | 137 | | { |
| | 1 | 138 | | id = usuario.Id, |
| | 1 | 139 | | usuario = usuario.Username, |
| | 1 | 140 | | nombre = usuario.Persona != null ? usuario.Persona.NombreCompleto : "", |
| | 1 | 141 | | email = usuario.Persona?.Email ?? "", |
| | 1 | 142 | | rolId = usuario.Roles.FirstOrDefault()?.Id, |
| | 1 | 143 | | estado = usuario.Estado |
| | 1 | 144 | | }; |
| | | 145 | | |
| | 1 | 146 | | return Ok(ApiResponse<object>.SuccessResult(response)); |
| | | 147 | | } |
| | 1 | 148 | | catch (Exception ex) |
| | | 149 | | { |
| | 1 | 150 | | _logger.LogError(ex, "Error al obtener usuario {Id}", id); |
| | 1 | 151 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 152 | | } |
| | 3 | 153 | | } |
| | | 154 | | |
| | | 155 | | /// <summary> |
| | | 156 | | /// Crear usuario con contraseña temporal |
| | | 157 | | /// POST /api/usuarios |
| | | 158 | | /// </summary> |
| | | 159 | | [HttpPost] |
| | | 160 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status201Created)] |
| | | 161 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 162 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 163 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 164 | | public async Task<IActionResult> CreateUsuario([FromBody] CreateUsuarioRequest request) |
| | | 165 | | { |
| | | 166 | | try |
| | | 167 | | { |
| | | 168 | | // Validaciones |
| | 3 | 169 | | if (string.IsNullOrWhiteSpace(request.Username)) |
| | | 170 | | { |
| | 1 | 171 | | return BadRequest(ApiResponse<string>.ErrorResult("El nombre de usuario es requerido")); |
| | | 172 | | } |
| | | 173 | | |
| | 2 | 174 | | if (string.IsNullOrWhiteSpace(request.Password)) |
| | | 175 | | { |
| | 0 | 176 | | return BadRequest(ApiResponse<string>.ErrorResult("La contraseña es requerida")); |
| | | 177 | | } |
| | | 178 | | |
| | 2 | 179 | | var (success, usuario, error) = await _usuarioService.CreateAsync( |
| | 2 | 180 | | request.Username, |
| | 2 | 181 | | request.Password, |
| | 2 | 182 | | request.PersonaId); |
| | | 183 | | |
| | 2 | 184 | | if (!success) |
| | | 185 | | { |
| | 1 | 186 | | if (error?.Contains("ya existe") == true || error?.Contains("ya está en uso") == true) |
| | | 187 | | { |
| | 1 | 188 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 189 | | } |
| | 0 | 190 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al crear usuario")); |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | // Asignar roles si se especificaron |
| | 1 | 194 | | if (request.RolesIds != null && request.RolesIds.Any()) |
| | | 195 | | { |
| | 4 | 196 | | foreach (var rolId in request.RolesIds) |
| | | 197 | | { |
| | 1 | 198 | | await _usuarioService.AsignarRolAsync(usuario!.Id, rolId); |
| | | 199 | | } |
| | | 200 | | } |
| | | 201 | | |
| | 1 | 202 | | var response = new |
| | 1 | 203 | | { |
| | 1 | 204 | | id = usuario!.Id, |
| | 1 | 205 | | creado = true |
| | 1 | 206 | | }; |
| | | 207 | | |
| | 1 | 208 | | return CreatedAtAction( |
| | 1 | 209 | | nameof(GetUsuario), |
| | 1 | 210 | | new { id = usuario.Id }, |
| | 1 | 211 | | ApiResponse<object>.SuccessResult(response, "Usuario creado exitosamente")); |
| | | 212 | | } |
| | 0 | 213 | | catch (Exception ex) |
| | | 214 | | { |
| | 0 | 215 | | _logger.LogError(ex, "Error al crear usuario"); |
| | 0 | 216 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 217 | | } |
| | 3 | 218 | | } |
| | | 219 | | |
| | | 220 | | /// <summary> |
| | | 221 | | /// Editar usuario (incluye activar/bloquear mediante campo estado) |
| | | 222 | | /// PUT /api/usuarios/{id} |
| | | 223 | | /// </summary> |
| | | 224 | | [HttpPut("{id}")] |
| | | 225 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 226 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 227 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 228 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 229 | | public async Task<IActionResult> UpdateUsuario(long id, [FromBody] UpdateUsuarioRequest request) |
| | | 230 | | { |
| | | 231 | | try |
| | | 232 | | { |
| | 4 | 233 | | var usuario = await _usuarioService.GetByIdAsync(id); |
| | 3 | 234 | | if (usuario == null) |
| | | 235 | | { |
| | 1 | 236 | | return NotFound(ApiResponse<string>.ErrorResult("Usuario no encontrado")); |
| | | 237 | | } |
| | | 238 | | |
| | | 239 | | // Actualizar datos de persona si se proporcionan |
| | 2 | 240 | | if (usuario.Persona != null) |
| | | 241 | | { |
| | 2 | 242 | | if (!string.IsNullOrWhiteSpace(request.Nombre)) |
| | | 243 | | { |
| | | 244 | | // Asumiendo que nombre viene como "Nombre Apellido" |
| | 1 | 245 | | var nombres = request.Nombre.Split(' ', 2); |
| | 1 | 246 | | usuario.Persona.PrimerNombre = nombres[0]; |
| | 1 | 247 | | if (nombres.Length > 1) |
| | | 248 | | { |
| | 1 | 249 | | usuario.Persona.PrimerApellido = nombres[1]; |
| | | 250 | | } |
| | | 251 | | } |
| | | 252 | | |
| | 2 | 253 | | if (!string.IsNullOrWhiteSpace(request.Email)) |
| | | 254 | | { |
| | 1 | 255 | | usuario.Persona.Email = request.Email; |
| | | 256 | | } |
| | | 257 | | } |
| | | 258 | | |
| | | 259 | | // Cambiar rol si se especifica |
| | 2 | 260 | | if (request.RolId.HasValue) |
| | | 261 | | { |
| | | 262 | | // Remover roles actuales |
| | 0 | 263 | | var rolesActuales = usuario.Roles.ToList(); |
| | 0 | 264 | | foreach (var rol in rolesActuales) |
| | | 265 | | { |
| | 0 | 266 | | var (successRemove, errorRemove) = await _usuarioService.RemoverRolAsync(id, rol.Id); |
| | 0 | 267 | | if (!successRemove) |
| | | 268 | | { |
| | 0 | 269 | | return BadRequest(ApiResponse<string>.ErrorResult(errorRemove ?? "Error al remover rol")); |
| | | 270 | | } |
| | | 271 | | } |
| | | 272 | | |
| | | 273 | | // Asignar nuevo rol |
| | 0 | 274 | | var (successRol, errorRol) = await _usuarioService.AsignarRolAsync(id, request.RolId.Value); |
| | 0 | 275 | | if (!successRol) |
| | | 276 | | { |
| | 0 | 277 | | return BadRequest(ApiResponse<string>.ErrorResult(errorRol ?? "Error al asignar rol")); |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | // Recargar usuario para reflejar cambios de roles |
| | 0 | 281 | | usuario = await _usuarioService.GetByIdAsync(id); |
| | 0 | 282 | | if (usuario == null) |
| | | 283 | | { |
| | 0 | 284 | | return NotFound(ApiResponse<string>.ErrorResult("Usuario no encontrado")); |
| | | 285 | | } |
| | | 286 | | } |
| | | 287 | | |
| | | 288 | | // Cambiar estado si se especifica |
| | 2 | 289 | | if (!string.IsNullOrWhiteSpace(request.Estado)) |
| | | 290 | | { |
| | 2 | 291 | | var (successEstado, errorEstado) = await _usuarioService.CambiarEstadoAsync(id, request.Estado); |
| | 2 | 292 | | if (!successEstado) |
| | | 293 | | { |
| | 1 | 294 | | return BadRequest(ApiResponse<string>.ErrorResult(errorEstado ?? "Error al cambiar estado")); |
| | | 295 | | } |
| | | 296 | | } |
| | | 297 | | |
| | 1 | 298 | | var response = new |
| | 1 | 299 | | { |
| | 1 | 300 | | actualizado = true |
| | 1 | 301 | | }; |
| | | 302 | | |
| | 1 | 303 | | return Ok(ApiResponse<object>.SuccessResult(response, "Usuario actualizado exitosamente")); |
| | | 304 | | } |
| | 1 | 305 | | catch (Exception ex) |
| | | 306 | | { |
| | 1 | 307 | | _logger.LogError(ex, "Error al actualizar usuario {Id}", id); |
| | 1 | 308 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 309 | | } |
| | 4 | 310 | | } |
| | | 311 | | |
| | | 312 | | /// <summary> |
| | | 313 | | /// Cambiar contraseña de usuario (también para reset) |
| | | 314 | | /// PATCH /api/usuarios/{id}/password |
| | | 315 | | /// </summary> |
| | | 316 | | [HttpPatch("{id}/password")] |
| | | 317 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 318 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 319 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 320 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 321 | | public async Task<IActionResult> CambiarPassword(long id, [FromBody] CambiarPasswordRequest request) |
| | | 322 | | { |
| | | 323 | | try |
| | | 324 | | { |
| | 4 | 325 | | if (string.IsNullOrWhiteSpace(request.NuevaPassword)) |
| | | 326 | | { |
| | 1 | 327 | | return BadRequest(ApiResponse<string>.ErrorResult("La nueva contraseña es requerida")); |
| | | 328 | | } |
| | | 329 | | |
| | 3 | 330 | | var (success, error) = await _usuarioService.CambiarPasswordAsync(id, request.NuevaPassword); |
| | | 331 | | |
| | 2 | 332 | | if (!success) |
| | | 333 | | { |
| | 1 | 334 | | if (error?.Contains("no encontrado") == true) |
| | | 335 | | { |
| | 1 | 336 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | | 337 | | } |
| | 0 | 338 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al cambiar contraseña")); |
| | | 339 | | } |
| | | 340 | | |
| | 1 | 341 | | var response = new |
| | 1 | 342 | | { |
| | 1 | 343 | | actualizado = true |
| | 1 | 344 | | }; |
| | | 345 | | |
| | 1 | 346 | | return Ok(ApiResponse<object>.SuccessResult(response, "Contraseña actualizada exitosamente")); |
| | | 347 | | } |
| | 1 | 348 | | catch (Exception ex) |
| | | 349 | | { |
| | 1 | 350 | | _logger.LogError(ex, "Error al cambiar contraseña del usuario {Id}", id); |
| | 1 | 351 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 352 | | } |
| | 4 | 353 | | } |
| | | 354 | | } |
| | | 355 | | |