Refinamiento de permisos y ajustes en controles. Añade gestión sobre saldos y visualización. Entre otros..
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
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/saldos")]
|
||||
[ApiController]
|
||||
[Authorize] // Requiere autenticación para todos los endpoints
|
||||
public class SaldosController : ControllerBase
|
||||
{
|
||||
private readonly ISaldoService _saldoService;
|
||||
private readonly ILogger<SaldosController> _logger;
|
||||
|
||||
// Define un permiso específico para ver saldos, y otro para ajustarlos (SuperAdmin implícito)
|
||||
private const string PermisoVerSaldos = "CS001"; // Ejemplo: Cuentas Saldos Ver
|
||||
private const string PermisoAjustarSaldos = "CS002"; // Ejemplo: Cuentas Saldos Ajustar (o solo SuperAdmin)
|
||||
|
||||
|
||||
public SaldosController(ISaldoService saldoService, ILogger<SaldosController> logger)
|
||||
{
|
||||
_saldoService = saldoService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private bool TienePermiso(string codAccRequerido)
|
||||
{
|
||||
if (User.IsInRole("SuperAdmin")) return true;
|
||||
return User.HasClaim(c => c.Type == "permission" && c.Value == codAccRequerido);
|
||||
}
|
||||
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 SaldosController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/saldos
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<SaldoGestionDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetSaldosGestion(
|
||||
[FromQuery] string? destino,
|
||||
[FromQuery] int? idDestino,
|
||||
[FromQuery] int? idEmpresa)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerSaldos)) // Usar el nuevo permiso
|
||||
{
|
||||
_logger.LogWarning("Acceso denegado a GetSaldosGestion para Usuario ID {userId}", GetCurrentUserId() ?? 0);
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var saldos = await _saldoService.ObtenerSaldosParaGestionAsync(destino, idDestino, idEmpresa);
|
||||
return Ok(saldos);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener saldos para gestión.");
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener saldos.");
|
||||
}
|
||||
}
|
||||
|
||||
// POST: api/saldos/ajustar
|
||||
[HttpPost("ajustar")]
|
||||
[ProducesResponseType(typeof(SaldoGestionDto), StatusCodes.Status200OK)] // Devuelve el saldo actualizado
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)] // Solo SuperAdmin o con permiso específico
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> AjustarSaldoManualmente([FromBody] AjusteSaldoRequestDto ajusteDto)
|
||||
{
|
||||
// Esta operación debería ser MUY restringida. Solo SuperAdmin o un permiso muy específico.
|
||||
if (!User.IsInRole("SuperAdmin") && !TienePermiso(PermisoAjustarSaldos))
|
||||
{
|
||||
_logger.LogWarning("Intento no autorizado de ajustar saldo por Usuario ID {userId}", GetCurrentUserId() ?? 0);
|
||||
return Forbid("No tiene permisos para realizar ajustes manuales de saldo.");
|
||||
}
|
||||
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized("No se pudo identificar al usuario.");
|
||||
|
||||
try
|
||||
{
|
||||
var (exito, error, saldoActualizado) = await _saldoService.RealizarAjusteManualSaldoAsync(ajusteDto, idUsuario.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error != null && error.Contains("No se encontró un saldo existente"))
|
||||
return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error ?? "Error desconocido al ajustar el saldo." });
|
||||
}
|
||||
return Ok(saldoActualizado);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error crítico al ajustar saldo manualmente.");
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al procesar el ajuste de saldo.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,11 +47,11 @@ namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<CanillaDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAllCanillas([FromQuery] string? nomApe, [FromQuery] int? legajo, [FromQuery] bool? soloActivos = true)
|
||||
public async Task<IActionResult> GetAllCanillas([FromQuery] string? nomApe, [FromQuery] int? legajo, [FromQuery] bool? esAccionista, [FromQuery] bool? soloActivos = true)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var canillas = await _canillaService.ObtenerTodosAsync(nomApe, legajo, soloActivos);
|
||||
return Ok(canillas);
|
||||
var canillitas = await _canillaService.ObtenerTodosAsync(nomApe, legajo, soloActivos, esAccionista); // <<-- Pasa el parámetro
|
||||
return Ok(canillitas);
|
||||
}
|
||||
|
||||
// GET: api/canillas/{id}
|
||||
@@ -117,7 +117,7 @@ namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
public async Task<IActionResult> ToggleBajaCanilla(int id, [FromBody] ToggleBajaCanillaDto bajaDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoBaja)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized();
|
||||
|
||||
|
||||
@@ -47,6 +47,15 @@ namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
return Ok(distribuidores);
|
||||
}
|
||||
|
||||
[HttpGet("dropdown")]
|
||||
[ProducesResponseType(typeof(IEnumerable<DistribuidorDropdownDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAllDropdownDistribuidores()
|
||||
{
|
||||
var distribuidores = await _distribuidorService.GetAllDropdownAsync();
|
||||
return Ok(distribuidores);
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}", Name = "GetDistribuidorById")]
|
||||
[ProducesResponseType(typeof(DistribuidorDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
@@ -59,6 +68,17 @@ namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
return Ok(distribuidor);
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}/lookup", Name = "GetDistribuidorLookupById")]
|
||||
[ProducesResponseType(typeof(DistribuidorLookupDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ObtenerLookupPorIdAsync(int id)
|
||||
{
|
||||
var distribuidor = await _distribuidorService.ObtenerLookupPorIdAsync(id);
|
||||
if (distribuidor == null) return NotFound();
|
||||
return Ok(distribuidor);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(DistribuidorDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
|
||||
@@ -74,6 +74,25 @@ namespace GestionIntegral.Api.Controllers // Ajusta el namespace si es necesario
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/empresas/dropdown
|
||||
[HttpGet("dropdown")]
|
||||
[ProducesResponseType(typeof(IEnumerable<EmpresaDropdownDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetEmpresasDropdown()
|
||||
{
|
||||
try
|
||||
{
|
||||
var empresas = await _empresaService.ObtenerParaDropdown();
|
||||
return Ok(empresas);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todas las Empresas.");
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener las empresas.");
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/empresas/{id}
|
||||
// Permiso Requerido: DE001 (Ver Empresas)
|
||||
[HttpGet("{id:int}", Name = "GetEmpresaById")]
|
||||
@@ -101,6 +120,29 @@ namespace GestionIntegral.Api.Controllers // Ajusta el namespace si es necesario
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}/lookup", Name = "GetEmpresaLookupById")]
|
||||
[ProducesResponseType(typeof(EmpresaDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> ObtenerLookupPorIdAsync(int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var empresa = await _empresaService.ObtenerLookupPorIdAsync(id);
|
||||
if (empresa == null)
|
||||
{
|
||||
return NotFound(new { message = $"Empresa con ID {id} no encontrada." });
|
||||
}
|
||||
return Ok(empresa);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Empresa por ID: {Id}", id);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener la empresa.");
|
||||
}
|
||||
}
|
||||
|
||||
// POST: api/empresas
|
||||
// Permiso Requerido: DE002 (Agregar Empresas)
|
||||
[HttpPost]
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
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.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
{
|
||||
[Route("api/novedadescanilla")] // Ruta base más genérica para las novedades
|
||||
[ApiController]
|
||||
[Authorize] // Todas las acciones requieren autenticación
|
||||
public class NovedadesCanillaController : ControllerBase
|
||||
{
|
||||
private readonly INovedadCanillaService _novedadService;
|
||||
private readonly ILogger<NovedadesCanillaController> _logger;
|
||||
|
||||
public NovedadesCanillaController(INovedadCanillaService novedadService, ILogger<NovedadesCanillaController> logger)
|
||||
{
|
||||
_novedadService = novedadService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// --- Helper para verificar permisos ---
|
||||
private bool TienePermiso(string codAccRequerido)
|
||||
{
|
||||
if (User.IsInRole("SuperAdmin")) return true;
|
||||
return User.HasClaim(c => c.Type == "permission" && c.Value == codAccRequerido);
|
||||
}
|
||||
|
||||
// --- Helper para obtener User ID ---
|
||||
private int? GetCurrentUserId()
|
||||
{
|
||||
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
|
||||
if (int.TryParse(userIdClaim, out int userId))
|
||||
{
|
||||
return userId;
|
||||
}
|
||||
_logger.LogWarning("No se pudo obtener el UserId del token JWT en NovedadesCanillaController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/novedadescanilla/porcanilla/{idCanilla}
|
||||
// Obtiene todas las novedades para un canillita específico, opcionalmente filtrado por fecha.
|
||||
// Permiso: CG001 (Ver Canillas) o CG006 (Gestionar Novedades).
|
||||
// Si CG006 es "Permite la Carga/Modificación", entonces CG001 podría ser más apropiado solo para ver.
|
||||
// Vamos a usar CG001 para ver. Si se quiere más granularidad, se puede crear un permiso "Ver Novedades".
|
||||
[HttpGet("porcanilla/{idCanilla:int}")]
|
||||
[ProducesResponseType(typeof(IEnumerable<NovedadCanillaDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetNovedadesPorCanilla(int idCanilla, [FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta)
|
||||
{
|
||||
if (!TienePermiso("CG001") && !TienePermiso("CG006")) // Necesita al menos uno de los dos
|
||||
{
|
||||
_logger.LogWarning("Acceso denegado a GetNovedadesPorCanilla para el usuario {UserId} y canillita {IdCanilla}", GetCurrentUserId() ?? 0, idCanilla);
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var novedades = await _novedadService.ObtenerPorCanillaAsync(idCanilla, fechaDesde, fechaHasta);
|
||||
return Ok(novedades);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener novedades para Canillita ID: {IdCanilla}", idCanilla);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener las novedades.");
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/novedadescanilla/{idNovedad}
|
||||
// Obtiene una novedad específica por su ID.
|
||||
// Permiso: CG001 o CG006
|
||||
[HttpGet("{idNovedad:int}", Name = "GetNovedadCanillaById")]
|
||||
[ProducesResponseType(typeof(NovedadCanillaDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetNovedadCanillaById(int idNovedad)
|
||||
{
|
||||
if (!TienePermiso("CG001") && !TienePermiso("CG006")) return Forbid();
|
||||
|
||||
try
|
||||
{
|
||||
var novedad = await _novedadService.ObtenerPorIdAsync(idNovedad);
|
||||
if (novedad == null)
|
||||
{
|
||||
return NotFound(new { message = $"Novedad con ID {idNovedad} no encontrada." });
|
||||
}
|
||||
return Ok(novedad);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener NovedadCanilla por ID: {IdNovedad}", idNovedad);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener la novedad.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// POST: api/novedadescanilla
|
||||
// Crea una nueva novedad. El IdCanilla viene en el DTO.
|
||||
// Permiso: CG006 (Permite la Carga/Modificación de Novedades)
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(NovedadCanillaDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> CreateNovedadCanilla([FromBody] CreateNovedadCanillaDto createDto)
|
||||
{
|
||||
if (!TienePermiso("CG006")) return Forbid();
|
||||
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized("No se pudo obtener el ID del usuario del token.");
|
||||
|
||||
try
|
||||
{
|
||||
var (novedadCreada, error) = await _novedadService.CrearAsync(createDto, idUsuario.Value);
|
||||
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (novedadCreada == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear la novedad.");
|
||||
|
||||
// Devuelve la ruta al recurso creado y el recurso mismo
|
||||
return CreatedAtRoute("GetNovedadCanillaById", new { idNovedad = novedadCreada.IdNovedad }, novedadCreada);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al crear NovedadCanilla para Canilla ID: {IdCanilla} por Usuario ID: {UsuarioId}", createDto.IdCanilla, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al crear la novedad.");
|
||||
}
|
||||
}
|
||||
|
||||
// PUT: api/novedadescanilla/{idNovedad}
|
||||
// Actualiza una novedad existente.
|
||||
// Permiso: CG006
|
||||
[HttpPut("{idNovedad:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> UpdateNovedadCanilla(int idNovedad, [FromBody] UpdateNovedadCanillaDto updateDto)
|
||||
{
|
||||
if (!TienePermiso("CG006")) return Forbid();
|
||||
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized("No se pudo obtener el ID del usuario del token.");
|
||||
|
||||
try
|
||||
{
|
||||
var (exito, error) = await _novedadService.ActualizarAsync(idNovedad, updateDto, idUsuario.Value);
|
||||
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Novedad no encontrada.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al actualizar NovedadCanilla ID: {IdNovedad} por Usuario ID: {UsuarioId}", idNovedad, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al actualizar la novedad.");
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE: api/novedadescanilla/{idNovedad}
|
||||
// Elimina una novedad.
|
||||
// Permiso: CG006 (Asumiendo que el mismo permiso para Carga/Modificación incluye eliminación)
|
||||
// Si la eliminación es un permiso separado (ej: CG00X), ajústalo.
|
||||
[HttpDelete("{idNovedad:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> DeleteNovedadCanilla(int idNovedad)
|
||||
{
|
||||
if (!TienePermiso("CG006")) return Forbid();
|
||||
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized("No se pudo obtener el ID del usuario del token.");
|
||||
|
||||
try
|
||||
{
|
||||
var (exito, error) = await _novedadService.EliminarAsync(idNovedad, idUsuario.Value);
|
||||
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Novedad no encontrada.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error }); // Podría ser otro error, como "no se pudo eliminar"
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al eliminar NovedadCanilla ID: {IdNovedad} por Usuario ID: {UsuarioId}", idNovedad, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al eliminar la novedad.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ using GestionIntegral.Api.Data.Repositories.Impresion;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Services.Distribucion;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers
|
||||
{
|
||||
@@ -25,6 +26,7 @@ namespace GestionIntegral.Api.Controllers
|
||||
private readonly IPublicacionRepository _publicacionRepository;
|
||||
private readonly IEmpresaRepository _empresaRepository;
|
||||
private readonly IDistribuidorRepository _distribuidorRepository; // Para obtener el nombre del distribuidor
|
||||
private readonly INovedadCanillaService _novedadCanillaService;
|
||||
|
||||
|
||||
// Permisos
|
||||
@@ -36,22 +38,25 @@ namespace GestionIntegral.Api.Controllers
|
||||
private const string PermisoVerBalanceCuentas = "RR001";
|
||||
private const string PermisoVerReporteTiradas = "RR008";
|
||||
private const string PermisoVerReporteConsumoBobinas = "RR007";
|
||||
|
||||
private const string PermisoVerReporteNovedadesCanillas = "RR004";
|
||||
private const string PermisoVerReporteListadoDistMensual = "RR009";
|
||||
|
||||
public ReportesController(
|
||||
IReportesService reportesService, // <--- CORREGIDO
|
||||
IReportesService reportesService,
|
||||
INovedadCanillaService novedadCanillaService,
|
||||
ILogger<ReportesController> logger,
|
||||
IPlantaRepository plantaRepository,
|
||||
IPublicacionRepository publicacionRepository,
|
||||
IEmpresaRepository empresaRepository,
|
||||
IDistribuidorRepository distribuidorRepository) // Añadido
|
||||
IDistribuidorRepository distribuidorRepository)
|
||||
{
|
||||
_reportesService = reportesService; // <--- CORREGIDO
|
||||
_reportesService = reportesService;
|
||||
_novedadCanillaService = novedadCanillaService;
|
||||
_logger = logger;
|
||||
_plantaRepository = plantaRepository;
|
||||
_publicacionRepository = publicacionRepository;
|
||||
_empresaRepository = empresaRepository;
|
||||
_distribuidorRepository = distribuidorRepository; // Añadido
|
||||
_distribuidorRepository = distribuidorRepository;
|
||||
}
|
||||
|
||||
private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
|
||||
@@ -1457,5 +1462,277 @@ namespace GestionIntegral.Api.Controllers
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al generar el PDF del ticket.");
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/reportes/novedades-canillas
|
||||
// Obtiene los datos para el reporte de novedades de canillitas
|
||||
[HttpGet("novedades-canillas")]
|
||||
[ProducesResponseType(typeof(IEnumerable<NovedadesCanillasReporteDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)] // Si no hay datos
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetReporteNovedadesCanillasData(
|
||||
[FromQuery] int idEmpresa,
|
||||
[FromQuery] DateTime fechaDesde,
|
||||
[FromQuery] DateTime fechaHasta)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerReporteNovedadesCanillas))
|
||||
{
|
||||
_logger.LogWarning("Acceso denegado a GetReporteNovedadesCanillasData. Usuario: {User}", User.Identity?.Name ?? "Desconocido");
|
||||
return Forbid();
|
||||
}
|
||||
|
||||
if (fechaDesde > fechaHasta)
|
||||
{
|
||||
return BadRequest(new { message = "La fecha 'desde' no puede ser posterior a la fecha 'hasta'." });
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var reporteData = await _novedadCanillaService.ObtenerReporteNovedadesAsync(idEmpresa, fechaDesde, fechaHasta);
|
||||
if (reporteData == null || !reporteData.Any())
|
||||
{
|
||||
// Devolver Ok con array vacío en lugar de NotFound para que el frontend pueda manejarlo como "sin datos"
|
||||
return Ok(Enumerable.Empty<NovedadesCanillasReporteDto>());
|
||||
}
|
||||
return Ok(reporteData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al generar datos para el reporte de novedades de canillitas. Empresa: {IdEmpresa}, Desde: {FechaDesde}, Hasta: {FechaHasta}", idEmpresa, fechaDesde, fechaHasta);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, new { message = "Error interno al generar el reporte de novedades." });
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/reportes/novedades-canillas/pdf
|
||||
// Genera el PDF del reporte de novedades de canillitas
|
||||
[HttpGet("novedades-canillas/pdf")]
|
||||
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetReporteNovedadesCanillasPdf(
|
||||
[FromQuery] int idEmpresa,
|
||||
[FromQuery] DateTime fechaDesde,
|
||||
[FromQuery] DateTime fechaHasta)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerReporteNovedadesCanillas)) // RR004
|
||||
{
|
||||
_logger.LogWarning("Acceso denegado a GetReporteNovedadesCanillasPdf. Usuario: {User}", User.Identity?.Name ?? "Desconocido");
|
||||
return Forbid();
|
||||
}
|
||||
if (fechaDesde > fechaHasta)
|
||||
{
|
||||
return BadRequest(new { message = "La fecha 'desde' no puede ser posterior a la fecha 'hasta'." });
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// Obtener datos para AMBOS datasets
|
||||
var novedadesData = await _novedadCanillaService.ObtenerReporteNovedadesAsync(idEmpresa, fechaDesde, fechaHasta);
|
||||
var gananciasData = await _novedadCanillaService.ObtenerReporteGananciasAsync(idEmpresa, fechaDesde, fechaHasta); // << OBTENER DATOS DE GANANCIAS
|
||||
|
||||
// Verificar si hay datos en *alguno* de los datasets necesarios para el reporte
|
||||
if ((novedadesData == null || !novedadesData.Any()) && (gananciasData == null || !gananciasData.Any()))
|
||||
{
|
||||
return NotFound(new { message = "No hay datos para generar el PDF con los parámetros seleccionados." });
|
||||
}
|
||||
|
||||
var empresa = await _empresaRepository.GetByIdAsync(idEmpresa);
|
||||
|
||||
LocalReport report = new LocalReport();
|
||||
string rdlcPath = Path.Combine("Controllers", "Reportes", "RDLC", "ReporteListadoNovedadesCanillas.rdlc");
|
||||
if (!System.IO.File.Exists(rdlcPath))
|
||||
{
|
||||
_logger.LogError("Archivo RDLC no encontrado en la ruta: {RdlcPath}", rdlcPath);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Archivo de definición de reporte no encontrado.");
|
||||
}
|
||||
|
||||
using (var fs = new FileStream(rdlcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
report.LoadReportDefinition(fs);
|
||||
}
|
||||
|
||||
// Nombre del DataSet en RDLC para SP_DistCanillasNovedades (detalles)
|
||||
report.DataSources.Add(new ReportDataSource("DSNovedadesCanillasDetalles", novedadesData ?? new List<NovedadesCanillasReporteDto>()));
|
||||
|
||||
// Nombre del DataSet en RDLC para SP_DistCanillasGanancias (ganancias/resumen)
|
||||
report.DataSources.Add(new ReportDataSource("DSNovedadesCanillas", gananciasData ?? new List<CanillaGananciaReporteDto>()));
|
||||
|
||||
|
||||
var parameters = new List<ReportParameter>
|
||||
{
|
||||
new ReportParameter("NomEmp", empresa?.Nombre ?? "N/A"),
|
||||
new ReportParameter("FechaDesde", fechaDesde.ToString("dd/MM/yyyy")),
|
||||
new ReportParameter("FechaHasta", fechaHasta.ToString("dd/MM/yyyy"))
|
||||
};
|
||||
report.SetParameters(parameters);
|
||||
|
||||
byte[] pdfBytes = report.Render("PDF");
|
||||
string fileName = $"ReporteNovedadesCanillas_Emp{idEmpresa}_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}.pdf";
|
||||
return File(pdfBytes, "application/pdf", fileName);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al generar PDF para el reporte de novedades de canillitas. Empresa: {IdEmpresa}", idEmpresa);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, new { message = $"Error interno al generar el PDF: {ex.Message}" });
|
||||
}
|
||||
}
|
||||
// GET: api/reportes/novedades-canillas-ganancias
|
||||
[HttpGet("novedades-canillas-ganancias")]
|
||||
[ProducesResponseType(typeof(IEnumerable<CanillaGananciaReporteDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetReporteGananciasCanillasData(
|
||||
[FromQuery] int idEmpresa,
|
||||
[FromQuery] DateTime fechaDesde,
|
||||
[FromQuery] DateTime fechaHasta)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerReporteNovedadesCanillas)) return Forbid(); // RR004
|
||||
|
||||
if (fechaDesde > fechaHasta)
|
||||
{
|
||||
return BadRequest(new { message = "La fecha 'desde' no puede ser posterior a la fecha 'hasta'." });
|
||||
}
|
||||
try
|
||||
{
|
||||
var gananciasData = await _novedadCanillaService.ObtenerReporteGananciasAsync(idEmpresa, fechaDesde, fechaHasta);
|
||||
if (gananciasData == null || !gananciasData.Any())
|
||||
{
|
||||
return Ok(Enumerable.Empty<CanillaGananciaReporteDto>());
|
||||
}
|
||||
return Ok(gananciasData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener datos de ganancias para el reporte de novedades. Empresa: {IdEmpresa}", idEmpresa);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, new { message = "Error interno al obtener datos de ganancias." });
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/reportes/listado-distribucion-mensual/diarios
|
||||
[HttpGet("listado-distribucion-mensual/diarios")]
|
||||
[ProducesResponseType(typeof(IEnumerable<ListadoDistCanMensualDiariosDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetListadoDistMensualDiarios(
|
||||
[FromQuery] DateTime fechaDesde,
|
||||
[FromQuery] DateTime fechaHasta,
|
||||
[FromQuery] bool esAccionista)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerReporteListadoDistMensual)) return Forbid();
|
||||
if (fechaDesde > fechaHasta) return BadRequest(new { message = "Fecha Desde no puede ser mayor a Fecha Hasta." });
|
||||
|
||||
var (data, error) = await _reportesService.ObtenerReporteMensualDiariosAsync(fechaDesde, fechaHasta, esAccionista);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
return Ok(data ?? Enumerable.Empty<ListadoDistCanMensualDiariosDto>());
|
||||
}
|
||||
|
||||
[HttpGet("listado-distribucion-mensual/diarios/pdf")]
|
||||
public async Task<IActionResult> GetListadoDistMensualDiariosPdf(
|
||||
[FromQuery] DateTime fechaDesde,
|
||||
[FromQuery] DateTime fechaHasta,
|
||||
[FromQuery] bool esAccionista)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerReporteListadoDistMensual)) return Forbid();
|
||||
if (fechaDesde > fechaHasta) return BadRequest(new { message = "Fecha Desde no puede ser mayor a Fecha Hasta." });
|
||||
|
||||
var (data, error) = await _reportesService.ObtenerReporteMensualDiariosAsync(fechaDesde, fechaHasta, esAccionista);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (data == null || !data.Any()) return NotFound(new { message = "No hay datos para generar el PDF." });
|
||||
|
||||
try
|
||||
{
|
||||
LocalReport report = new LocalReport();
|
||||
string rdlcPath = Path.Combine("Controllers", "Reportes", "RDLC", "ReporteListadoDistribucionCanMensualDiarios.rdlc");
|
||||
if (!System.IO.File.Exists(rdlcPath))
|
||||
{
|
||||
_logger.LogError("Archivo RDLC no encontrado: {Path}", rdlcPath);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, $"Archivo de reporte no encontrado: {Path.GetFileName(rdlcPath)}");
|
||||
}
|
||||
using (var fs = new FileStream(rdlcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
report.LoadReportDefinition(fs);
|
||||
}
|
||||
report.DataSources.Add(new ReportDataSource("DSListadoDistribucionCanMensualDiarios", data));
|
||||
|
||||
var parameters = new List<ReportParameter>
|
||||
{
|
||||
new ReportParameter("FechaDesde", fechaDesde.ToString("dd/MM/yyyy")),
|
||||
new ReportParameter("FechaHasta", fechaHasta.ToString("dd/MM/yyyy")),
|
||||
new ReportParameter("CanAcc", esAccionista ? "1" : "0") // El RDLC espera un Integer para CanAcc
|
||||
};
|
||||
report.SetParameters(parameters);
|
||||
|
||||
byte[] pdfBytes = report.Render("PDF");
|
||||
string tipoDesc = esAccionista ? "Accionistas" : "Canillitas";
|
||||
return File(pdfBytes, "application/pdf", $"ListadoDistMensualDiarios_{tipoDesc}_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}.pdf");
|
||||
}
|
||||
catch (Exception ex) { _logger.LogError(ex, "Error PDF ListadoDistMensualDiarios"); return StatusCode(500, "Error interno."); }
|
||||
}
|
||||
|
||||
|
||||
// GET: api/reportes/listado-distribucion-mensual/publicaciones
|
||||
[HttpGet("listado-distribucion-mensual/publicaciones")]
|
||||
[ProducesResponseType(typeof(IEnumerable<ListadoDistCanMensualPubDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetListadoDistMensualPorPublicacion(
|
||||
[FromQuery] DateTime fechaDesde,
|
||||
[FromQuery] DateTime fechaHasta,
|
||||
[FromQuery] bool esAccionista)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerReporteListadoDistMensual)) return Forbid();
|
||||
if (fechaDesde > fechaHasta) return BadRequest(new { message = "Fecha Desde no puede ser mayor a Fecha Hasta." });
|
||||
|
||||
var (data, error) = await _reportesService.ObtenerReporteMensualPorPublicacionAsync(fechaDesde, fechaHasta, esAccionista);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
return Ok(data ?? Enumerable.Empty<ListadoDistCanMensualPubDto>());
|
||||
}
|
||||
|
||||
[HttpGet("listado-distribucion-mensual/publicaciones/pdf")]
|
||||
public async Task<IActionResult> GetListadoDistMensualPorPublicacionPdf(
|
||||
[FromQuery] DateTime fechaDesde,
|
||||
[FromQuery] DateTime fechaHasta,
|
||||
[FromQuery] bool esAccionista)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerReporteListadoDistMensual)) return Forbid();
|
||||
if (fechaDesde > fechaHasta) return BadRequest(new { message = "Fecha Desde no puede ser mayor a Fecha Hasta." });
|
||||
|
||||
var (data, error) = await _reportesService.ObtenerReporteMensualPorPublicacionAsync(fechaDesde, fechaHasta, esAccionista);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (data == null || !data.Any()) return NotFound(new { message = "No hay datos para generar el PDF." });
|
||||
|
||||
try
|
||||
{
|
||||
LocalReport report = new LocalReport();
|
||||
string rdlcPath = Path.Combine("Controllers", "Reportes", "RDLC", "ReporteListadoDistribucionCanMensual.rdlc");
|
||||
if (!System.IO.File.Exists(rdlcPath))
|
||||
{
|
||||
_logger.LogError("Archivo RDLC no encontrado: {Path}", rdlcPath);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, $"Archivo de reporte no encontrado: {Path.GetFileName(rdlcPath)}");
|
||||
}
|
||||
using (var fs = new FileStream(rdlcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||
{
|
||||
report.LoadReportDefinition(fs);
|
||||
}
|
||||
report.DataSources.Add(new ReportDataSource("DSListadoDistribucionCanMensual", data));
|
||||
|
||||
var parameters = new List<ReportParameter>
|
||||
{
|
||||
new ReportParameter("FechaDesde", fechaDesde.ToString("dd/MM/yyyy")),
|
||||
new ReportParameter("FechaHasta", fechaHasta.ToString("dd/MM/yyyy")),
|
||||
new ReportParameter("CanAcc", esAccionista ? "1" : "0")
|
||||
};
|
||||
report.SetParameters(parameters);
|
||||
|
||||
byte[] pdfBytes = report.Render("PDF");
|
||||
string tipoDesc = esAccionista ? "Accionistas" : "Canillitas";
|
||||
return File(pdfBytes, "application/pdf", $"ListadoDistMensualPub_{tipoDesc}_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}.pdf");
|
||||
}
|
||||
catch (Exception ex) { _logger.LogError(ex, "Error PDF ListadoDistMensualPorPublicacion"); return StatusCode(500, "Error interno."); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user