Ya perdí el hilo de los cambios pero ahi van.
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
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/canciones
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class CancionesController : ControllerBase
|
||||
{
|
||||
private readonly ICancionService _cancionService;
|
||||
private readonly ILogger<CancionesController> _logger;
|
||||
|
||||
// Asumir permisos para Canciones (ej. RC001-RC004 o usar SS005)
|
||||
private const string PermisoVerCanciones = "SS005";
|
||||
private const string PermisoGestionarCanciones = "SS005";
|
||||
|
||||
public CancionesController(ICancionService cancionService, ILogger<CancionesController> logger)
|
||||
{
|
||||
_cancionService = cancionService;
|
||||
_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 CancionesController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/canciones
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<CancionDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAll([FromQuery] string? tema, [FromQuery] string? interprete, [FromQuery] int? idRitmo)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerCanciones)) return Forbid();
|
||||
var canciones = await _cancionService.ObtenerTodasAsync(tema, interprete, idRitmo);
|
||||
return Ok(canciones);
|
||||
}
|
||||
|
||||
// GET: api/canciones/{id}
|
||||
[HttpGet("{id:int}", Name = "GetCancionById")]
|
||||
[ProducesResponseType(typeof(CancionDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerCanciones)) return Forbid();
|
||||
var cancion = await _cancionService.ObtenerPorIdAsync(id);
|
||||
if (cancion == null) return NotFound(new { message = $"Canción con ID {id} no encontrada." });
|
||||
return Ok(cancion);
|
||||
}
|
||||
|
||||
// POST: api/canciones
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(CancionDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateCancionDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoGestionarCanciones)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (dto, error) = await _cancionService.CrearAsync(createDto, userId.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear la canción.");
|
||||
|
||||
return CreatedAtRoute("GetCancionById", new { id = dto.Id }, dto);
|
||||
}
|
||||
|
||||
// PUT: api/canciones/{id}
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(int id, [FromBody] UpdateCancionDto updateDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoGestionarCanciones)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _cancionService.ActualizarAsync(id, updateDto, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Canción no encontrada.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// DELETE: api/canciones/{id}
|
||||
[HttpDelete("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoGestionarCanciones)) return Forbid();
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _cancionService.EliminarAsync(id, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Canción no encontrada.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using GestionIntegral.Api.Dtos.Radios;
|
||||
using GestionIntegral.Api.Services.Radios;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Radios
|
||||
{
|
||||
[Route("api/radios/listas")] // Ruta base, ej: /api/radios/listas
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class RadioListasController : ControllerBase
|
||||
{
|
||||
private readonly IRadioListaService _radioListaService;
|
||||
private readonly ILogger<RadioListasController> _logger;
|
||||
|
||||
// Asumir permiso general de Radios o uno específico para generar listas
|
||||
private const string PermisoGenerarListas = "SS005"; // Usando el permiso general de la sección Radios
|
||||
|
||||
public RadioListasController(IRadioListaService radioListaService, ILogger<RadioListasController> logger)
|
||||
{
|
||||
_radioListaService = radioListaService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
|
||||
// GetCurrentUserId no es estrictamente necesario aquí si la acción no modifica datos persistentes auditables por usuario.
|
||||
|
||||
// POST: api/radios/listas/generar
|
||||
[HttpPost("generar")]
|
||||
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)] // Devuelve un archivo
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GenerarListaRadio([FromBody] GenerarListaRadioRequestDto requestDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoGenerarListas)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
_logger.LogInformation("Solicitud de generación de lista de radio recibida: {@RequestDto}", requestDto);
|
||||
|
||||
var (fileContents, contentType, fileName, error) = await _radioListaService.GenerarListaRadioAsync(requestDto);
|
||||
|
||||
if (error != null)
|
||||
{
|
||||
_logger.LogWarning("Error al generar lista de radio: {Error}", error);
|
||||
// Devolver un JSON con el error podría ser más útil para el frontend que un simple BadRequest
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
|
||||
if (fileContents == null || fileContents.Length == 0)
|
||||
{
|
||||
_logger.LogWarning("La generación de la lista de radio no produjo contenido.");
|
||||
// Similar al anterior, un JSON con mensaje puede ser mejor
|
||||
return NotFound(new { message = "No se pudo generar la lista, o no hay datos suficientes." });
|
||||
}
|
||||
|
||||
_logger.LogInformation("Lista de radio generada exitosamente: {FileName}", fileName);
|
||||
// Devuelve el archivo ZIP para descarga
|
||||
return File(fileContents, contentType, fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user