185 lines
		
	
	
		
			8.6 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
		
		
			
		
	
	
			185 lines
		
	
	
		
			8.6 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
|  | using GestionIntegral.Api.Dtos.Impresion; | ||
|  | using GestionIntegral.Api.Services.Impresion; | ||
|  | 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.Impresion | ||
|  | { | ||
|  |     [Route("api/[controller]")] // Ruta base: /api/estadosbobina
 | ||
|  |     [ApiController] | ||
|  |     [Authorize] | ||
|  |     public class EstadosBobinaController : ControllerBase | ||
|  |     { | ||
|  |         private readonly IEstadoBobinaService _estadoBobinaService; | ||
|  |         private readonly ILogger<EstadosBobinaController> _logger; | ||
|  | 
 | ||
|  |         // Asumiendo códigos de permiso para Estados de Bobina | ||
|  |         private const string PermisoVer = "IB010"; | ||
|  |         private const string PermisoCrear = "IB011"; | ||
|  |         private const string PermisoModificar = "IB012"; | ||
|  |         private const string PermisoEliminar = "IB013"; | ||
|  | 
 | ||
|  |         public EstadosBobinaController(IEstadoBobinaService estadoBobinaService, ILogger<EstadosBobinaController> logger) | ||
|  |         { | ||
|  |             _estadoBobinaService = estadoBobinaService ?? throw new ArgumentNullException(nameof(estadoBobinaService)); | ||
|  |             _logger = logger ?? throw new ArgumentNullException(nameof(logger)); | ||
|  |         } | ||
|  | 
 | ||
|  |         // --- Helper para permisos --- | ||
|  |         private bool TienePermiso(string codAccRequerido) | ||
|  |         { | ||
|  |             if (User.IsInRole("SuperAdmin")) return true; | ||
|  |             return User.HasClaim(c => c.Type == "permission" && c.Value == codAccRequerido); | ||
|  |         } | ||
|  | 
 | ||
|  |         // --- Helper para 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 EstadosBobinaController."); | ||
|  |             return null; | ||
|  |         } | ||
|  | 
 | ||
|  |         // GET: api/estadosbobina | ||
|  |         [HttpGet] | ||
|  |         [ProducesResponseType(typeof(IEnumerable<EstadoBobinaDto>), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> GetAllEstadosBobina([FromQuery] string? denominacion) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoVer)) return Forbid(); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var estados = await _estadoBobinaService.ObtenerTodosAsync(denominacion); | ||
|  |                 return Ok(estados); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener todos los Estados de Bobina. Filtro: {Denominacion}", denominacion); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener los estados de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // GET: api/estadosbobina/{id} | ||
|  |         [HttpGet("{id:int}", Name = "GetEstadoBobinaById")] | ||
|  |         [ProducesResponseType(typeof(EstadoBobinaDto), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> GetEstadoBobinaById(int id) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoVer)) return Forbid(); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var estado = await _estadoBobinaService.ObtenerPorIdAsync(id); | ||
|  |                 if (estado == null) return NotFound(new { message = $"Estado de bobina con ID {id} no encontrado." }); | ||
|  |                 return Ok(estado); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener Estado de Bobina por ID: {Id}", id); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener el estado de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // POST: api/estadosbobina | ||
|  |         [HttpPost] | ||
|  |         [ProducesResponseType(typeof(EstadoBobinaDto), StatusCodes.Status201Created)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> CreateEstadoBobina([FromBody] CreateEstadoBobinaDto createDto) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoCrear)) return Forbid(); | ||
|  |             if (!ModelState.IsValid) return BadRequest(ModelState); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (estadoCreado, error) = await _estadoBobinaService.CrearAsync(createDto, idUsuario.Value); | ||
|  |                 if (error != null) return BadRequest(new { message = error }); | ||
|  |                 if (estadoCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el estado de bobina."); | ||
|  |                 return CreatedAtRoute("GetEstadoBobinaById", new { id = estadoCreado.IdEstadoBobina }, estadoCreado); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al crear Estado de Bobina. Denominación: {Denominacion} por Usuario ID: {UsuarioId}", createDto.Denominacion, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al crear el estado de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // PUT: api/estadosbobina/{id} | ||
|  |         [HttpPut("{id:int}")] | ||
|  |         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> UpdateEstadoBobina(int id, [FromBody] UpdateEstadoBobinaDto updateDto) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoModificar)) return Forbid(); | ||
|  |             if (!ModelState.IsValid) return BadRequest(ModelState); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (exito, error) = await _estadoBobinaService.ActualizarAsync(id, updateDto, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Estado de bobina no encontrado.") return NotFound(new { message = error }); | ||
|  |                     return BadRequest(new { message = error }); | ||
|  |                 } | ||
|  |                 return NoContent(); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al actualizar Estado de Bobina ID: {Id} por Usuario ID: {UsuarioId}", id, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al actualizar el estado de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // DELETE: api/estadosbobina/{id} | ||
|  |         [HttpDelete("{id:int}")] | ||
|  |         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] // Si está en uso o es estado base | ||
|  |         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> DeleteEstadoBobina(int id) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoEliminar)) return Forbid(); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (exito, error) = await _estadoBobinaService.EliminarAsync(id, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Estado de bobina no encontrado.") return NotFound(new { message = error }); | ||
|  |                     // Otros errores (en uso, estado base) | ||
|  |                     return BadRequest(new { message = error }); | ||
|  |                 } | ||
|  |                 return NoContent(); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al eliminar Estado de Bobina ID: {Id} por Usuario ID: {UsuarioId}", id, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al eliminar el estado de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  |     } | ||
|  | } |