183 lines
		
	
	
		
			8.4 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
		
		
			
		
	
	
			183 lines
		
	
	
		
			8.4 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/tiposbobina
 | ||
|  |     [ApiController] | ||
|  |     [Authorize] | ||
|  |     public class TiposBobinaController : ControllerBase | ||
|  |     { | ||
|  |         private readonly ITipoBobinaService _tipoBobinaService; | ||
|  |         private readonly ILogger<TiposBobinaController> _logger; | ||
|  | 
 | ||
|  |         public TiposBobinaController(ITipoBobinaService tipoBobinaService, ILogger<TiposBobinaController> logger) | ||
|  |         { | ||
|  |             _tipoBobinaService = tipoBobinaService ?? throw new ArgumentNullException(nameof(tipoBobinaService)); | ||
|  |             _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 TiposBobinaController."); | ||
|  |             return null; | ||
|  |         } | ||
|  | 
 | ||
|  |         // GET: api/tiposbobina | ||
|  |         // Permiso: IB006 (Ver Tipos Bobinas) | ||
|  |         [HttpGet] | ||
|  |         [ProducesResponseType(typeof(IEnumerable<TipoBobinaDto>), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> GetAllTiposBobina([FromQuery] string? denominacion) | ||
|  |         { | ||
|  |             if (!TienePermiso("IB006")) return Forbid(); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var tiposBobina = await _tipoBobinaService.ObtenerTodosAsync(denominacion); | ||
|  |                 return Ok(tiposBobina); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener todos los Tipos de Bobina. Filtro: {Denominacion}", denominacion); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener los tipos de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // GET: api/tiposbobina/{id} | ||
|  |         // Permiso: IB006 (Ver Tipos Bobinas) | ||
|  |         [HttpGet("{id:int}", Name = "GetTipoBobinaById")] | ||
|  |         [ProducesResponseType(typeof(TipoBobinaDto), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> GetTipoBobinaById(int id) | ||
|  |         { | ||
|  |             if (!TienePermiso("IB006")) return Forbid(); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var tipoBobina = await _tipoBobinaService.ObtenerPorIdAsync(id); | ||
|  |                 if (tipoBobina == null) return NotFound(new { message = $"Tipo de bobina con ID {id} no encontrado." }); | ||
|  |                 return Ok(tipoBobina); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener Tipo de Bobina por ID: {Id}", id); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener el tipo de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // POST: api/tiposbobina | ||
|  |         // Permiso: IB007 (Agregar Tipos Bobinas) | ||
|  |         [HttpPost] | ||
|  |         [ProducesResponseType(typeof(TipoBobinaDto), StatusCodes.Status201Created)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> CreateTipoBobina([FromBody] CreateTipoBobinaDto createDto) | ||
|  |         { | ||
|  |             if (!TienePermiso("IB007")) return Forbid(); | ||
|  |             if (!ModelState.IsValid) return BadRequest(ModelState); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (tipoBobinaCreado, error) = await _tipoBobinaService.CrearAsync(createDto, idUsuario.Value); | ||
|  |                 if (error != null) return BadRequest(new { message = error }); | ||
|  |                 if (tipoBobinaCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el tipo de bobina."); | ||
|  |                 return CreatedAtRoute("GetTipoBobinaById", new { id = tipoBobinaCreado.IdTipoBobina }, tipoBobinaCreado); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al crear Tipo de Bobina. Denominación: {Denominacion} por Usuario ID: {UsuarioId}", createDto.Denominacion, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al crear el tipo de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // PUT: api/tiposbobina/{id} | ||
|  |         // Permiso: IB008 (Modificar Tipos Bobinas) | ||
|  |         [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> UpdateTipoBobina(int id, [FromBody] UpdateTipoBobinaDto updateDto) | ||
|  |         { | ||
|  |             if (!TienePermiso("IB008")) return Forbid(); | ||
|  |             if (!ModelState.IsValid) return BadRequest(ModelState); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (exito, error) = await _tipoBobinaService.ActualizarAsync(id, updateDto, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Tipo 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 Tipo de Bobina ID: {Id} por Usuario ID: {UsuarioId}", id, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al actualizar el tipo de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // DELETE: api/tiposbobina/{id} | ||
|  |         // Permiso: IB009 (Eliminar Tipos Bobinas) | ||
|  |         [HttpDelete("{id:int}")] | ||
|  |         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] // Si está en uso | ||
|  |         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> DeleteTipoBobina(int id) | ||
|  |         { | ||
|  |             if (!TienePermiso("IB009")) return Forbid(); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (exito, error) = await _tipoBobinaService.EliminarAsync(id, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Tipo de bobina no encontrado.") return NotFound(new { message = error }); | ||
|  |                     return BadRequest(new { message = error }); // Ej: "En uso" | ||
|  |                 } | ||
|  |                 return NoContent(); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al eliminar Tipo de Bobina ID: {Id} por Usuario ID: {UsuarioId}", id, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al eliminar el tipo de bobina."); | ||
|  |             } | ||
|  |         } | ||
|  |     } | ||
|  | } |