125 lines
		
	
	
		
			5.6 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			125 lines
		
	
	
		
			5.6 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| using GestionIntegral.Api.Dtos.Radios;
 | |
| using GestionIntegral.Api.Services.Radios;
 | |
| using Microsoft.AspNetCore.Authorization;
 | |
| using Microsoft.AspNetCore.Mvc;
 | |
| using Microsoft.Extensions.Logging;
 | |
| using System.Collections.Generic;
 | |
| using System.Security.Claims;
 | |
| using System.Threading.Tasks;
 | |
| 
 | |
| namespace GestionIntegral.Api.Controllers.Radios
 | |
| {
 | |
|     [Route("api/[controller]")] // Ruta base: /api/ritmos
 | |
|     [ApiController]
 | |
|     [Authorize] // Proteger todos los endpoints
 | |
|     public class RitmosController : ControllerBase
 | |
|     {
 | |
|         private readonly IRitmoService _ritmoService;
 | |
|         private readonly ILogger<RitmosController> _logger;
 | |
| 
 | |
|         // Asumir códigos de permiso para Ritmos (ej. RR001-RR004)
 | |
|         // O usar permisos más genéricos de "Gestión Radios" si no hay específicos
 | |
|         private const string PermisoVerRitmos = "SS005"; // Usando el de acceso a la sección radios por ahora
 | |
|         private const string PermisoGestionarRitmos = "SS005"; // Idem para crear/mod/elim
 | |
| 
 | |
|         public RitmosController(IRitmoService ritmoService, ILogger<RitmosController> logger)
 | |
|         {
 | |
|             _ritmoService = ritmoService;
 | |
|             _logger = logger;
 | |
|         }
 | |
| 
 | |
|         private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
 | |
|         private int? GetCurrentUserId()
 | |
|         {
 | |
|             if (int.TryParse(User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub"), out int userId)) return userId;
 | |
|             _logger.LogWarning("No se pudo obtener el UserId del token JWT en RitmosController.");
 | |
|             return null;
 | |
|         }
 | |
| 
 | |
|         // GET: api/ritmos
 | |
|         [HttpGet]
 | |
|         [ProducesResponseType(typeof(IEnumerable<RitmoDto>), StatusCodes.Status200OK)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         public async Task<IActionResult> GetAll([FromQuery] string? nombre)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoVerRitmos)) return Forbid();
 | |
|             var ritmos = await _ritmoService.ObtenerTodosAsync(nombre);
 | |
|             return Ok(ritmos);
 | |
|         }
 | |
| 
 | |
|         // GET: api/ritmos/{id}
 | |
|         [HttpGet("{id:int}", Name = "GetRitmoById")]
 | |
|         [ProducesResponseType(typeof(RitmoDto), StatusCodes.Status200OK)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         [ProducesResponseType(StatusCodes.Status404NotFound)]
 | |
|         public async Task<IActionResult> GetById(int id)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoVerRitmos)) return Forbid();
 | |
|             var ritmo = await _ritmoService.ObtenerPorIdAsync(id);
 | |
|             if (ritmo == null) return NotFound(new { message = $"Ritmo con ID {id} no encontrado." });
 | |
|             return Ok(ritmo);
 | |
|         }
 | |
| 
 | |
|         // POST: api/ritmos
 | |
|         [HttpPost]
 | |
|         [ProducesResponseType(typeof(RitmoDto), StatusCodes.Status201Created)]
 | |
|         [ProducesResponseType(StatusCodes.Status400BadRequest)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         public async Task<IActionResult> Create([FromBody] CreateRitmoDto createDto)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoGestionarRitmos)) return Forbid();
 | |
|             if (!ModelState.IsValid) return BadRequest(ModelState);
 | |
|             var userId = GetCurrentUserId(); // Aunque no se use en el repo sin historial, es bueno tenerlo
 | |
|             if (userId == null) return Unauthorized();
 | |
| 
 | |
|             var (dto, error) = await _ritmoService.CrearAsync(createDto, userId.Value);
 | |
|             if (error != null) return BadRequest(new { message = error });
 | |
|             if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el ritmo.");
 | |
|             
 | |
|             return CreatedAtRoute("GetRitmoById", new { id = dto.Id }, dto);
 | |
|         }
 | |
| 
 | |
|         // PUT: api/ritmos/{id}
 | |
|         [HttpPut("{id:int}")]
 | |
|         [ProducesResponseType(StatusCodes.Status204NoContent)]
 | |
|         [ProducesResponseType(StatusCodes.Status400BadRequest)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         [ProducesResponseType(StatusCodes.Status404NotFound)]
 | |
|         public async Task<IActionResult> Update(int id, [FromBody] UpdateRitmoDto updateDto)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoGestionarRitmos)) return Forbid();
 | |
|             if (!ModelState.IsValid) return BadRequest(ModelState);
 | |
|             var userId = GetCurrentUserId();
 | |
|             if (userId == null) return Unauthorized();
 | |
| 
 | |
|             var (exito, error) = await _ritmoService.ActualizarAsync(id, updateDto, userId.Value);
 | |
|             if (!exito)
 | |
|             {
 | |
|                 if (error == "Ritmo no encontrado.") return NotFound(new { message = error });
 | |
|                 return BadRequest(new { message = error });
 | |
|             }
 | |
|             return NoContent();
 | |
|         }
 | |
| 
 | |
|         // DELETE: api/ritmos/{id}
 | |
|         [HttpDelete("{id:int}")]
 | |
|         [ProducesResponseType(StatusCodes.Status204NoContent)]
 | |
|         [ProducesResponseType(StatusCodes.Status400BadRequest)] // Si está en uso
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         [ProducesResponseType(StatusCodes.Status404NotFound)]
 | |
|         public async Task<IActionResult> Delete(int id)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoGestionarRitmos)) return Forbid();
 | |
|             var userId = GetCurrentUserId();
 | |
|             if (userId == null) return Unauthorized();
 | |
| 
 | |
|             var (exito, error) = await _ritmoService.EliminarAsync(id, userId.Value);
 | |
|             if (!exito)
 | |
|             {
 | |
|                 if (error == "Ritmo no encontrado.") return NotFound(new { message = error });
 | |
|                 return BadRequest(new { message = error }); // Ej: "En uso"
 | |
|             }
 | |
|             return NoContent();
 | |
|         }
 | |
|     }
 | |
| } |