| | | 1 | | using FAU.Logica.DTOs; |
| | | 2 | | using FAU.Logica.Services; |
| | | 3 | | using FAU.Entidades; |
| | | 4 | | using Microsoft.AspNetCore.Authorization; |
| | | 5 | | using Microsoft.AspNetCore.Http; |
| | | 6 | | using Microsoft.AspNetCore.Mvc; |
| | | 7 | | |
| | | 8 | | namespace FAU.API.Controllers; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Gestión de roles del sistema |
| | | 12 | | /// </summary> |
| | | 13 | | [ApiController] |
| | | 14 | | [Route("api/[controller]")] |
| | | 15 | | [Produces("application/json")] |
| | | 16 | | public class RolesController : ControllerBase |
| | | 17 | | { |
| | | 18 | | private readonly IRolService _rolService; |
| | | 19 | | private readonly ILogger<RolesController> _logger; |
| | | 20 | | |
| | 11 | 21 | | public RolesController( |
| | 11 | 22 | | IRolService rolService, |
| | 11 | 23 | | ILogger<RolesController> logger) |
| | | 24 | | { |
| | 11 | 25 | | _rolService = rolService; |
| | 11 | 26 | | _logger = logger; |
| | 11 | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Listar todos los roles con sus permisos |
| | | 31 | | /// GET /api/roles |
| | | 32 | | /// </summary> |
| | | 33 | | [HttpGet] |
| | | 34 | | [FAU.API.Security.RequirePermission(PermisoEnum.VerRoles)] |
| | | 35 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 36 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 37 | | public async Task<IActionResult> GetRoles() |
| | | 38 | | { |
| | | 39 | | try |
| | | 40 | | { |
| | 2 | 41 | | var roles = await _rolService.GetAllAsync(); |
| | | 42 | | |
| | 3 | 43 | | var rolesDto = roles.Select(r => new |
| | 3 | 44 | | { |
| | 3 | 45 | | id = r.Id, |
| | 3 | 46 | | nombre = r.Nombre, |
| | 3 | 47 | | descripcion = r.Descripcion, |
| | 3 | 48 | | permisos = r.Permisos.Select(p => new { |
| | 3 | 49 | | id = p.Id, |
| | 3 | 50 | | nombre = p.Nombre, |
| | 3 | 51 | | descripcion = p.Descripcion |
| | 3 | 52 | | }).ToList() |
| | 3 | 53 | | }).ToList(); |
| | | 54 | | |
| | 1 | 55 | | var response = rolesDto; |
| | | 56 | | |
| | 1 | 57 | | return Ok(ApiResponse<object>.SuccessResult(response)); |
| | | 58 | | } |
| | 1 | 59 | | catch (Exception ex) |
| | | 60 | | { |
| | 1 | 61 | | _logger.LogError(ex, "Error al obtener roles"); |
| | 1 | 62 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 63 | | } |
| | 2 | 64 | | } |
| | | 65 | | |
| | | 66 | | /// <summary> |
| | | 67 | | /// Crear rol con permisos |
| | | 68 | | /// POST /api/roles |
| | | 69 | | /// </summary> |
| | | 70 | | [HttpPost] |
| | | 71 | | [FAU.API.Security.RequirePermission(PermisoEnum.CrearRoles)] |
| | | 72 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status201Created)] |
| | | 73 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 74 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 75 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 76 | | public async Task<IActionResult> CreateRol([FromBody] CreateRolRequest request) |
| | | 77 | | { |
| | | 78 | | try |
| | | 79 | | { |
| | | 80 | | // Validaciones |
| | 3 | 81 | | if (string.IsNullOrWhiteSpace(request.Nombre)) |
| | | 82 | | { |
| | 1 | 83 | | return BadRequest(ApiResponse<string>.ErrorResult("El nombre del rol es requerido")); |
| | | 84 | | } |
| | | 85 | | |
| | 2 | 86 | | var (success, rol, error) = await _rolService.CreateAsync( |
| | 2 | 87 | | request.Nombre, |
| | 2 | 88 | | request.Descripcion); |
| | | 89 | | |
| | 2 | 90 | | if (!success) |
| | | 91 | | { |
| | 1 | 92 | | if (error?.Contains("ya existe") == true) |
| | | 93 | | { |
| | 1 | 94 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 95 | | } |
| | 0 | 96 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al crear rol")); |
| | | 97 | | } |
| | | 98 | | |
| | | 99 | | // Asignar permisos si se especificaron |
| | 1 | 100 | | if (request.PermisosIds != null && request.PermisosIds.Any()) |
| | | 101 | | { |
| | 8 | 102 | | foreach (var permisoId in request.PermisosIds) |
| | | 103 | | { |
| | 3 | 104 | | await _rolService.AsignarPermisoAsync(rol!.Id, permisoId); |
| | | 105 | | } |
| | | 106 | | } |
| | | 107 | | |
| | 1 | 108 | | var response = new |
| | 1 | 109 | | { |
| | 1 | 110 | | id = rol!.Id, |
| | 1 | 111 | | creado = true |
| | 1 | 112 | | }; |
| | | 113 | | |
| | 1 | 114 | | return CreatedAtAction( |
| | 1 | 115 | | nameof(GetRol), |
| | 1 | 116 | | new { id = rol.Id }, |
| | 1 | 117 | | ApiResponse<object>.SuccessResult(response, "Rol creado exitosamente")); |
| | | 118 | | } |
| | 0 | 119 | | catch (Exception ex) |
| | | 120 | | { |
| | 0 | 121 | | _logger.LogError(ex, "Error al crear rol"); |
| | 0 | 122 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 123 | | } |
| | 3 | 124 | | } |
| | | 125 | | |
| | | 126 | | /// <summary> |
| | | 127 | | /// Obtener rol por ID |
| | | 128 | | /// GET /api/roles/{id} |
| | | 129 | | /// </summary> |
| | | 130 | | [HttpGet("{id}")] |
| | | 131 | | [FAU.API.Security.RequirePermission(PermisoEnum.VerRoles)] |
| | | 132 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 133 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 134 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 135 | | public async Task<IActionResult> GetRol(long id) |
| | | 136 | | { |
| | | 137 | | try |
| | | 138 | | { |
| | 3 | 139 | | var rol = await _rolService.GetByIdAsync(id); |
| | | 140 | | |
| | 2 | 141 | | if (rol == null) |
| | | 142 | | { |
| | 1 | 143 | | return NotFound(ApiResponse<string>.ErrorResult("Rol no encontrado")); |
| | | 144 | | } |
| | | 145 | | |
| | 1 | 146 | | var response = new |
| | 1 | 147 | | { |
| | 1 | 148 | | id = rol.Id, |
| | 1 | 149 | | nombre = rol.Nombre, |
| | 1 | 150 | | descripcion = rol.Descripcion, |
| | 1 | 151 | | permisos = rol.Permisos.Select(p => new { |
| | 1 | 152 | | id = p.Id, |
| | 1 | 153 | | nombre = p.Nombre, |
| | 1 | 154 | | descripcion = p.Descripcion |
| | 1 | 155 | | }).ToList() |
| | 1 | 156 | | }; |
| | | 157 | | |
| | 1 | 158 | | return Ok(ApiResponse<object>.SuccessResult(response)); |
| | | 159 | | } |
| | 1 | 160 | | catch (Exception ex) |
| | | 161 | | { |
| | 1 | 162 | | _logger.LogError(ex, "Error al obtener rol {Id}", id); |
| | 1 | 163 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 164 | | } |
| | 3 | 165 | | } |
| | | 166 | | |
| | | 167 | | /// <summary> |
| | | 168 | | /// Editar rol (nombre y permisos) |
| | | 169 | | /// PUT /api/roles/{id} |
| | | 170 | | /// </summary> |
| | | 171 | | [HttpPut("{id}")] |
| | | 172 | | [FAU.API.Security.RequirePermission(PermisoEnum.ActualizarRoles)] |
| | | 173 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 174 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 175 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 176 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 177 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 178 | | public async Task<IActionResult> UpdateRol(long id, [FromBody] UpdateRolRequest request) |
| | | 179 | | { |
| | | 180 | | try |
| | | 181 | | { |
| | 3 | 182 | | if (id != request.Id) |
| | | 183 | | { |
| | 1 | 184 | | return BadRequest(ApiResponse<string>.ErrorResult("El ID del rol no coincide")); |
| | | 185 | | } |
| | | 186 | | |
| | | 187 | | // Verificar que el rol existe |
| | 2 | 188 | | var rolExistente = await _rolService.GetByIdAsync(id); |
| | 2 | 189 | | if (rolExistente == null) |
| | | 190 | | { |
| | 1 | 191 | | return NotFound(ApiResponse<string>.ErrorResult("Rol no encontrado")); |
| | | 192 | | } |
| | | 193 | | |
| | | 194 | | // Actualizar nombre si se proporciona |
| | 1 | 195 | | if (!string.IsNullOrWhiteSpace(request.Nombre)) |
| | | 196 | | { |
| | 1 | 197 | | var (success, rol, error) = await _rolService.UpdateAsync( |
| | 1 | 198 | | request.Id, |
| | 1 | 199 | | request.Nombre, |
| | 1 | 200 | | request.Descripcion); |
| | | 201 | | |
| | 1 | 202 | | if (!success) |
| | | 203 | | { |
| | 0 | 204 | | if (error?.Contains("ya existe") == true) |
| | | 205 | | { |
| | 0 | 206 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 207 | | } |
| | 0 | 208 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al actualizar rol")); |
| | | 209 | | } |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | // Actualizar permisos si se especifican |
| | 1 | 213 | | if (request.PermisosIds != null) |
| | | 214 | | { |
| | 3 | 215 | | var permisosActuales = rolExistente.Permisos.Select(p => p.Id).ToList(); |
| | 1 | 216 | | var permisosNuevos = request.PermisosIds; |
| | | 217 | | |
| | | 218 | | // Remover permisos que ya no están en la lista |
| | 6 | 219 | | foreach (var permisoId in permisosActuales) |
| | | 220 | | { |
| | 2 | 221 | | if (!permisosNuevos.Contains(permisoId)) |
| | | 222 | | { |
| | 1 | 223 | | await _rolService.RemoverPermisoAsync(request.Id, permisoId); |
| | | 224 | | } |
| | | 225 | | } |
| | | 226 | | |
| | | 227 | | // Agregar permisos nuevos |
| | 6 | 228 | | foreach (var permisoId in permisosNuevos) |
| | | 229 | | { |
| | 2 | 230 | | if (!permisosActuales.Contains(permisoId)) |
| | | 231 | | { |
| | 1 | 232 | | await _rolService.AsignarPermisoAsync(request.Id, permisoId); |
| | | 233 | | } |
| | | 234 | | } |
| | 1 | 235 | | } |
| | | 236 | | |
| | 1 | 237 | | var response = new |
| | 1 | 238 | | { |
| | 1 | 239 | | actualizado = true |
| | 1 | 240 | | }; |
| | | 241 | | |
| | 1 | 242 | | return Ok(ApiResponse<object>.SuccessResult(response, "Rol actualizado exitosamente")); |
| | | 243 | | } |
| | 0 | 244 | | catch (Exception ex) |
| | | 245 | | { |
| | 0 | 246 | | _logger.LogError(ex, "Error al actualizar rol {Id}", id); |
| | 0 | 247 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 248 | | } |
| | 3 | 249 | | } |
| | | 250 | | } |
| | | 251 | | |
| | | 252 | | |