138 lines
6.5 KiB
C#
138 lines
6.5 KiB
C#
|
|
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;
|
||
|
|
using Microsoft.AspNetCore.Mvc.ModelBinding; // Para BindRequired
|
||
|
|
|
||
|
|
namespace GestionIntegral.Api.Controllers.Distribucion
|
||
|
|
{
|
||
|
|
[Route("api/entradassalidasdist")] // Ruta base
|
||
|
|
[ApiController]
|
||
|
|
[Authorize]
|
||
|
|
public class EntradasSalidasDistController : ControllerBase
|
||
|
|
{
|
||
|
|
private readonly IEntradaSalidaDistService _esService;
|
||
|
|
private readonly ILogger<EntradasSalidasDistController> _logger;
|
||
|
|
|
||
|
|
// Permisos para Entradas/Salidas Distribuidores (MD001, MD002)
|
||
|
|
// Asumo MD001 para Ver, MD002 para Crear/Modificar/Eliminar
|
||
|
|
private const string PermisoVerMovimientos = "MD001";
|
||
|
|
private const string PermisoGestionarMovimientos = "MD002";
|
||
|
|
|
||
|
|
public EntradasSalidasDistController(IEntradaSalidaDistService esService, ILogger<EntradasSalidasDistController> logger)
|
||
|
|
{
|
||
|
|
_esService = esService;
|
||
|
|
_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 EntradasSalidasDistController.");
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
// GET: api/entradassalidasdist
|
||
|
|
[HttpGet]
|
||
|
|
[ProducesResponseType(typeof(IEnumerable<EntradaSalidaDistDto>), StatusCodes.Status200OK)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
public async Task<IActionResult> GetAll(
|
||
|
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||
|
|
[FromQuery] int? idPublicacion, [FromQuery] int? idDistribuidor,
|
||
|
|
[FromQuery] string? tipoMovimiento)
|
||
|
|
{
|
||
|
|
if (!TienePermiso(PermisoVerMovimientos)) return Forbid();
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var movimientos = await _esService.ObtenerTodosAsync(fechaDesde, fechaHasta, idPublicacion, idDistribuidor, tipoMovimiento);
|
||
|
|
return Ok(movimientos);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Error al obtener listado de Entradas/Salidas Dist.");
|
||
|
|
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// GET: api/entradassalidasdist/{idParte}
|
||
|
|
[HttpGet("{idParte:int}", Name = "GetEntradaSalidaDistById")]
|
||
|
|
[ProducesResponseType(typeof(EntradaSalidaDistDto), StatusCodes.Status200OK)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
public async Task<IActionResult> GetById(int idParte)
|
||
|
|
{
|
||
|
|
if (!TienePermiso(PermisoVerMovimientos)) return Forbid();
|
||
|
|
var movimiento = await _esService.ObtenerPorIdAsync(idParte);
|
||
|
|
if (movimiento == null) return NotFound(new { message = $"Movimiento con ID {idParte} no encontrado." });
|
||
|
|
return Ok(movimiento);
|
||
|
|
}
|
||
|
|
|
||
|
|
// POST: api/entradassalidasdist
|
||
|
|
[HttpPost]
|
||
|
|
[ProducesResponseType(typeof(EntradaSalidaDistDto), StatusCodes.Status201Created)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
public async Task<IActionResult> CreateMovimiento([FromBody] CreateEntradaSalidaDistDto createDto)
|
||
|
|
{
|
||
|
|
if (!TienePermiso(PermisoGestionarMovimientos)) return Forbid();
|
||
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||
|
|
var userId = GetCurrentUserId();
|
||
|
|
if (userId == null) return Unauthorized();
|
||
|
|
|
||
|
|
var (dto, error) = await _esService.CrearMovimientoAsync(createDto, userId.Value);
|
||
|
|
if (error != null) return BadRequest(new { message = error });
|
||
|
|
if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al registrar el movimiento.");
|
||
|
|
|
||
|
|
return CreatedAtRoute("GetEntradaSalidaDistById", new { idParte = dto.IdParte }, dto);
|
||
|
|
}
|
||
|
|
|
||
|
|
// PUT: api/entradassalidasdist/{idParte}
|
||
|
|
[HttpPut("{idParte:int}")]
|
||
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
public async Task<IActionResult> UpdateMovimiento(int idParte, [FromBody] UpdateEntradaSalidaDistDto updateDto)
|
||
|
|
{
|
||
|
|
if (!TienePermiso(PermisoGestionarMovimientos)) return Forbid();
|
||
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||
|
|
var userId = GetCurrentUserId();
|
||
|
|
if (userId == null) return Unauthorized();
|
||
|
|
|
||
|
|
var (exito, error) = await _esService.ActualizarMovimientoAsync(idParte, updateDto, userId.Value);
|
||
|
|
if (!exito)
|
||
|
|
{
|
||
|
|
if (error == "Movimiento no encontrado.") return NotFound(new { message = error });
|
||
|
|
return BadRequest(new { message = error });
|
||
|
|
}
|
||
|
|
return NoContent();
|
||
|
|
}
|
||
|
|
|
||
|
|
// DELETE: api/entradassalidasdist/{idParte}
|
||
|
|
[HttpDelete("{idParte:int}")]
|
||
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
public async Task<IActionResult> DeleteMovimiento(int idParte)
|
||
|
|
{
|
||
|
|
if (!TienePermiso(PermisoGestionarMovimientos)) return Forbid(); // Asumo que el mismo permiso sirve para eliminar
|
||
|
|
var userId = GetCurrentUserId();
|
||
|
|
if (userId == null) return Unauthorized();
|
||
|
|
|
||
|
|
var (exito, error) = await _esService.EliminarMovimientoAsync(idParte, userId.Value);
|
||
|
|
if (!exito)
|
||
|
|
{
|
||
|
|
if (error == "Movimiento no encontrado.") return NotFound(new { message = error });
|
||
|
|
return BadRequest(new { message = error });
|
||
|
|
}
|
||
|
|
return NoContent();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|