Ya perdí el hilo de los cambios pero ahi van.
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
using GestionIntegral.Api.Dtos.Contables;
|
||||
using GestionIntegral.Api.Services.Contables;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Contables
|
||||
{
|
||||
[Route("api/notascreditodebito")] // Ruta base
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class NotasCreditoDebitoController : ControllerBase
|
||||
{
|
||||
private readonly INotaCreditoDebitoService _notaService;
|
||||
private readonly ILogger<NotasCreditoDebitoController> _logger;
|
||||
|
||||
// Permisos para Notas C/D (CN001 a CN004)
|
||||
private const string PermisoVer = "CN001";
|
||||
private const string PermisoCrear = "CN002";
|
||||
private const string PermisoModificar = "CN003";
|
||||
private const string PermisoEliminar = "CN004";
|
||||
|
||||
public NotasCreditoDebitoController(INotaCreditoDebitoService notaService, ILogger<NotasCreditoDebitoController> logger)
|
||||
{
|
||||
_notaService = notaService;
|
||||
_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 NotasCreditoDebitoController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/notascreditodebito
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<NotaCreditoDebitoDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||
[FromQuery] string? destino, [FromQuery] int? idDestino,
|
||||
[FromQuery] int? idEmpresa, [FromQuery] string? tipoNota)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var notas = await _notaService.ObtenerTodosAsync(fechaDesde, fechaHasta, destino, idDestino, idEmpresa, tipoNota);
|
||||
return Ok(notas);
|
||||
}
|
||||
|
||||
// GET: api/notascreditodebito/{idNota}
|
||||
[HttpGet("{idNota:int}", Name = "GetNotaCreditoDebitoById")]
|
||||
[ProducesResponseType(typeof(NotaCreditoDebitoDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(int idNota)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var nota = await _notaService.ObtenerPorIdAsync(idNota);
|
||||
if (nota == null) return NotFound(new { message = $"Nota con ID {idNota} no encontrada." });
|
||||
return Ok(nota);
|
||||
}
|
||||
|
||||
// POST: api/notascreditodebito
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(NotaCreditoDebitoDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateNotaDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoCrear)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (dto, error) = await _notaService.CrearAsync(createDto, userId.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al registrar la nota.");
|
||||
|
||||
return CreatedAtRoute("GetNotaCreditoDebitoById", new { idNota = dto.IdNota }, dto);
|
||||
}
|
||||
|
||||
// PUT: api/notascreditodebito/{idNota}
|
||||
[HttpPut("{idNota:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(int idNota, [FromBody] UpdateNotaDto updateDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificar)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _notaService.ActualizarAsync(idNota, updateDto, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Nota no encontrada.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// DELETE: api/notascreditodebito/{idNota}
|
||||
[HttpDelete("{idNota:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(int idNota)
|
||||
{
|
||||
if (!TienePermiso(PermisoEliminar)) return Forbid();
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _notaService.EliminarAsync(idNota, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Nota no encontrada.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using GestionIntegral.Api.Dtos.Contables;
|
||||
using GestionIntegral.Api.Services.Contables;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Contables
|
||||
{
|
||||
[Route("api/pagosdistribuidor")] // Ruta base
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class PagosDistribuidorController : ControllerBase
|
||||
{
|
||||
private readonly IPagoDistribuidorService _pagoService;
|
||||
private readonly ILogger<PagosDistribuidorController> _logger;
|
||||
|
||||
// Permisos para Pagos Distribuidores (CP001 a CP004)
|
||||
private const string PermisoVer = "CP001";
|
||||
private const string PermisoCrear = "CP002";
|
||||
private const string PermisoModificar = "CP003";
|
||||
private const string PermisoEliminar = "CP004";
|
||||
|
||||
public PagosDistribuidorController(IPagoDistribuidorService pagoService, ILogger<PagosDistribuidorController> logger)
|
||||
{
|
||||
_pagoService = pagoService;
|
||||
_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 PagosDistribuidorController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/pagosdistribuidor
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<PagoDistribuidorDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||
[FromQuery] int? idDistribuidor, [FromQuery] int? idEmpresa,
|
||||
[FromQuery] string? tipoMovimiento)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var pagos = await _pagoService.ObtenerTodosAsync(fechaDesde, fechaHasta, idDistribuidor, idEmpresa, tipoMovimiento);
|
||||
return Ok(pagos);
|
||||
}
|
||||
|
||||
// GET: api/pagosdistribuidor/{idPago}
|
||||
[HttpGet("{idPago:int}", Name = "GetPagoDistribuidorById")]
|
||||
[ProducesResponseType(typeof(PagoDistribuidorDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(int idPago)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var pago = await _pagoService.ObtenerPorIdAsync(idPago);
|
||||
if (pago == null) return NotFound(new { message = $"Pago con ID {idPago} no encontrado." });
|
||||
return Ok(pago);
|
||||
}
|
||||
|
||||
// POST: api/pagosdistribuidor
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(PagoDistribuidorDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> Create([FromBody] CreatePagoDistribuidorDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoCrear)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (dto, error) = await _pagoService.CrearAsync(createDto, userId.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al registrar el pago.");
|
||||
|
||||
return CreatedAtRoute("GetPagoDistribuidorById", new { idPago = dto.IdPago }, dto);
|
||||
}
|
||||
|
||||
// PUT: api/pagosdistribuidor/{idPago}
|
||||
[HttpPut("{idPago:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(int idPago, [FromBody] UpdatePagoDistribuidorDto updateDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificar)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _pagoService.ActualizarAsync(idPago, updateDto, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Pago no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// DELETE: api/pagosdistribuidor/{idPago}
|
||||
[HttpDelete("{idPago:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(int idPago)
|
||||
{
|
||||
if (!TienePermiso(PermisoEliminar)) return Forbid();
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _pagoService.EliminarAsync(idPago, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Pago no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Services.Distribucion;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
{
|
||||
[Route("api/controldevoluciones")] // Ruta base
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class ControlDevolucionesController : ControllerBase
|
||||
{
|
||||
private readonly IControlDevolucionesService _controlDevService;
|
||||
private readonly ILogger<ControlDevolucionesController> _logger;
|
||||
|
||||
// Permisos para Control Devoluciones (CD001 a CD003)
|
||||
private const string PermisoVer = "CD001";
|
||||
private const string PermisoCrear = "CD002";
|
||||
private const string PermisoModificar = "CD003";
|
||||
// Asumo que no hay un permiso específico para eliminar, se podría usar CD003 o crear CD004
|
||||
|
||||
public ControlDevolucionesController(IControlDevolucionesService controlDevService, ILogger<ControlDevolucionesController> logger)
|
||||
{
|
||||
_controlDevService = controlDevService;
|
||||
_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 ControlDevolucionesController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/controldevoluciones
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<ControlDevolucionesDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||
[FromQuery] int? idEmpresa)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var controles = await _controlDevService.ObtenerTodosAsync(fechaDesde, fechaHasta, idEmpresa);
|
||||
return Ok(controles);
|
||||
}
|
||||
|
||||
// GET: api/controldevoluciones/{idControl}
|
||||
[HttpGet("{idControl:int}", Name = "GetControlDevolucionesById")]
|
||||
[ProducesResponseType(typeof(ControlDevolucionesDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(int idControl)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var control = await _controlDevService.ObtenerPorIdAsync(idControl);
|
||||
if (control == null) return NotFound(new { message = $"Control de devoluciones con ID {idControl} no encontrado." });
|
||||
return Ok(control);
|
||||
}
|
||||
|
||||
// POST: api/controldevoluciones
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(ControlDevolucionesDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> Create([FromBody] CreateControlDevolucionesDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoCrear)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (dto, error) = await _controlDevService.CrearAsync(createDto, userId.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al registrar el control.");
|
||||
|
||||
return CreatedAtRoute("GetControlDevolucionesById", new { idControl = dto.IdControl }, dto);
|
||||
}
|
||||
|
||||
// PUT: api/controldevoluciones/{idControl}
|
||||
[HttpPut("{idControl:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Update(int idControl, [FromBody] UpdateControlDevolucionesDto updateDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificar)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _controlDevService.ActualizarAsync(idControl, updateDto, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Control de devoluciones no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// DELETE: api/controldevoluciones/{idControl}
|
||||
[HttpDelete("{idControl:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)] // Podría usar PermisoModificar o un permiso de borrado específico
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> Delete(int idControl)
|
||||
{
|
||||
// Asumimos que CD003 (Modificar) también permite eliminar, o se define un permiso específico
|
||||
if (!TienePermiso(PermisoModificar)) return Forbid();
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _controlDevService.EliminarAsync(idControl, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Control de devoluciones no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Services.Distribucion;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
{
|
||||
[Route("api/entradassalidascanilla")] // Ruta base
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class EntradasSalidasCanillaController : ControllerBase
|
||||
{
|
||||
private readonly IEntradaSalidaCanillaService _esCanillaService;
|
||||
private readonly ILogger<EntradasSalidasCanillaController> _logger;
|
||||
|
||||
// Permisos para E/S Canillitas (MC001 a MC005)
|
||||
private const string PermisoVerMovimientos = "MC001";
|
||||
private const string PermisoCrearMovimiento = "MC002";
|
||||
private const string PermisoModificarMovimiento = "MC003";
|
||||
private const string PermisoEliminarMovimiento = "MC004"; // (si no está liquidado)
|
||||
private const string PermisoLiquidar = "MC005"; // Asumo que ver comprobante implica poder liquidar.
|
||||
|
||||
public EntradasSalidasCanillaController(IEntradaSalidaCanillaService esCanillaService, ILogger<EntradasSalidasCanillaController> logger)
|
||||
{
|
||||
_esCanillaService = esCanillaService;
|
||||
_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 EntradasSalidasCanillaController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/entradassalidascanilla
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<EntradaSalidaCanillaDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAll(
|
||||
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||
[FromQuery] int? idPublicacion, [FromQuery] int? idCanilla,
|
||||
[FromQuery] bool? liquidados, [FromQuery] bool? incluirNoLiquidados = true) // incluirNoLiquidados por defecto true para ver todo
|
||||
{
|
||||
if (!TienePermiso(PermisoVerMovimientos)) return Forbid();
|
||||
try
|
||||
{
|
||||
var movimientos = await _esCanillaService.ObtenerTodosAsync(fechaDesde, fechaHasta, idPublicacion, idCanilla, liquidados, incluirNoLiquidados);
|
||||
return Ok(movimientos);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener listado de E/S Canillitas.");
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/entradassalidascanilla/{idParte}
|
||||
[HttpGet("{idParte:int}", Name = "GetEntradaSalidaCanillaById")]
|
||||
[ProducesResponseType(typeof(EntradaSalidaCanillaDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetById(int idParte)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerMovimientos)) return Forbid();
|
||||
var movimiento = await _esCanillaService.ObtenerPorIdAsync(idParte);
|
||||
if (movimiento == null) return NotFound(new { message = $"Movimiento con ID {idParte} no encontrado." });
|
||||
return Ok(movimiento);
|
||||
}
|
||||
|
||||
// PUT: api/entradassalidascanilla/{idParte}
|
||||
[HttpPut("{idParte:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdateMovimiento(int idParte, [FromBody] UpdateEntradaSalidaCanillaDto updateDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificarMovimiento)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _esCanillaService.ActualizarMovimientoAsync(idParte, updateDto, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Movimiento no encontrado." || error == "No se puede modificar un movimiento ya liquidado.")
|
||||
return NotFound(new { message = error }); // Podría ser 404 o 400 dependiendo del error
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// DELETE: api/entradassalidascanilla/{idParte}
|
||||
[HttpDelete("{idParte:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeleteMovimiento(int idParte)
|
||||
{
|
||||
// Permiso base MC004
|
||||
// El servicio ahora usa User (ClaimsPrincipal) para verificar MC006 si es necesario
|
||||
string permisoBaseRequerido = "MC004"; // Asumiendo que esta constante existe o la defines
|
||||
|
||||
if (!TienePermiso(permisoBaseRequerido))
|
||||
{
|
||||
_logger.LogWarning("Acceso denegado a DeleteMovimiento (IDParte: {IdParte}) para Usuario ID {UserId}. Permiso {Permiso} requerido.", idParte, GetCurrentUserId() ?? 0, permisoBaseRequerido);
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized("No se pudo obtener el ID del usuario del token.");
|
||||
|
||||
var (exito, error) = await _esCanillaService.EliminarMovimientoAsync(idParte, userId.Value, User); // Pasar ClaimsPrincipal (User)
|
||||
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Movimiento no encontrado.") return NotFound(new { message = error });
|
||||
// Otros errores como "no tiene permiso para eliminar liquidados" o errores internos.
|
||||
// El servicio podría devolver un código de estado más específico o el controlador interpretarlo.
|
||||
// Por ahora, un BadRequest es genérico para fallos de lógica de negocio o permisos no cumplidos en el servicio.
|
||||
if (error != null && error.Contains("No tiene permiso"))
|
||||
{
|
||||
_logger.LogWarning("Intento fallido de eliminar movimiento ID {IdParte} por Usuario ID {UserId}. Razón: {Error}", idParte, userId, error);
|
||||
return StatusCode(StatusCodes.Status403Forbidden, new { message = error });
|
||||
}
|
||||
return BadRequest(new { message = error ?? "Error desconocido al eliminar." });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// POST: api/entradassalidascanilla/liquidar
|
||||
[HttpPost("liquidar")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> LiquidarMovimientos([FromBody] LiquidarMovimientosCanillaRequestDto liquidarDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoLiquidar)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _esCanillaService.LiquidarMovimientosAsync(liquidarDto, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpPost("bulk")] // Nueva ruta o ajustar la existente y diferenciar por DTO
|
||||
[ProducesResponseType(typeof(IEnumerable<EntradaSalidaCanillaDto>), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> CreateBulkMovimientos([FromBody] CreateBulkEntradaSalidaCanillaDto createBulkDto)
|
||||
{
|
||||
// Mantener PermisoCrearMovimiento = "MC002"
|
||||
if (!TienePermiso(PermisoCrearMovimiento)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (dtos, error) = await _esCanillaService.CrearMovimientosEnLoteAsync(createBulkDto, userId.Value);
|
||||
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (dtos == null || !dtos.Any()) return StatusCode(StatusCodes.Status500InternalServerError, "No se pudo registrar ningún movimiento o hubo un error.");
|
||||
|
||||
// Podrías devolver solo un 201 Created si la lista de DTOs es muy grande
|
||||
// o si no necesitas los detalles de cada uno inmediatamente.
|
||||
// O devolver la lista como se hace aquí.
|
||||
return StatusCode(StatusCodes.Status201Created, dtos);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using GestionIntegral.Api.Dtos.Usuarios;
|
||||
using GestionIntegral.Api.Dtos.Usuarios.Auditoria;
|
||||
using GestionIntegral.Api.Services.Usuarios;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
@@ -141,18 +142,63 @@ namespace GestionIntegral.Api.Controllers.Usuarios
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ToggleHabilitado(int id, [FromBody] bool habilitar)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificarUsuarios)) return Forbid();
|
||||
if (!TienePermiso(PermisoModificarUsuarios)) return Forbid();
|
||||
|
||||
var idAdmin = GetCurrentUserId();
|
||||
if (idAdmin == null) return Unauthorized("Token inválido.");
|
||||
|
||||
var (exito, error) = await _usuarioService.CambiarEstadoHabilitadoAsync(id, habilitar, idAdmin.Value);
|
||||
if (!exito)
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Usuario no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// GET: api/usuarios/{idUsuarioAfectado}/historial
|
||||
[HttpGet("{idUsuarioAfectado:int}/historial")]
|
||||
[ProducesResponseType(typeof(IEnumerable<UsuarioHistorialDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetHistorialDeUsuario(int idUsuarioAfectado, [FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta)
|
||||
{
|
||||
// Necesitas un permiso para ver historial, ej: "AU001" o uno más granular "AU_USR_VIEW_SINGLE"
|
||||
// O si solo SuperAdmin puede ver historiales específicos.
|
||||
if (!TienePermiso("AU001")) // Asumiendo AU001 = Ver Historial de Auditoría (General o Usuarios)
|
||||
{
|
||||
_logger.LogWarning("Acceso denegado a GetHistorialDeUsuario para Usuario ID {UserId}", GetCurrentUserId() ?? 0);
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var usuarioExiste = await _usuarioService.ObtenerPorIdAsync(idUsuarioAfectado);
|
||||
if (usuarioExiste == null)
|
||||
{
|
||||
return NotFound(new { message = $"Usuario con ID {idUsuarioAfectado} no encontrado." });
|
||||
}
|
||||
|
||||
var historial = await _usuarioService.ObtenerHistorialPorUsuarioIdAsync(idUsuarioAfectado, fechaDesde, fechaHasta);
|
||||
return Ok(historial);
|
||||
}
|
||||
|
||||
// GET: api/usuarios/historial (Para todos los usuarios, con filtros)
|
||||
[HttpGet("historial")]
|
||||
[ProducesResponseType(typeof(IEnumerable<UsuarioHistorialDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetTodoElHistorialDeUsuarios(
|
||||
[FromQuery] DateTime? fechaDesde,
|
||||
[FromQuery] DateTime? fechaHasta,
|
||||
[FromQuery] int? idUsuarioModifico,
|
||||
[FromQuery] string? tipoModificacion)
|
||||
{
|
||||
if (!TienePermiso("AU001")) // Mismo permiso general de auditoría
|
||||
{
|
||||
_logger.LogWarning("Acceso denegado a GetTodoElHistorialDeUsuarios para Usuario ID {UserId}", GetCurrentUserId() ?? 0);
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
var historial = await _usuarioService.ObtenerTodoElHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion);
|
||||
return Ok(historial);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user