180 lines
		
	
	
		
			8.3 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
		
		
			
		
	
	
			180 lines
		
	
	
		
			8.3 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; | ||
|  | 
 | ||
|  | namespace GestionIntegral.Api.Controllers.Distribucion | ||
|  | { | ||
|  |     [Route("api/[controller]")] // Ruta base: /api/otrosdestinos
 | ||
|  |     [ApiController] | ||
|  |     [Authorize] | ||
|  |     public class OtrosDestinosController : ControllerBase | ||
|  |     { | ||
|  |         private readonly IOtroDestinoService _otroDestinoService; | ||
|  |         private readonly ILogger<OtrosDestinosController> _logger; | ||
|  | 
 | ||
|  |         // Permisos para Otros Destinos (basado en el Excel OD001-OD004) | ||
|  |         private const string PermisoVer = "OD001"; // Aunque tu Excel dice "Salidas Otros Destinos", lo asumo para la entidad Otros Destinos | ||
|  |         private const string PermisoCrear = "OD002"; // Asumo para la entidad | ||
|  |         private const string PermisoModificar = "OD003"; // Asumo para la entidad | ||
|  |         private const string PermisoEliminar = "OD004"; // Asumo para la entidad | ||
|  | 
 | ||
|  |         public OtrosDestinosController(IOtroDestinoService otroDestinoService, ILogger<OtrosDestinosController> logger) | ||
|  |         { | ||
|  |             _otroDestinoService = otroDestinoService ?? throw new ArgumentNullException(nameof(otroDestinoService)); | ||
|  |             _logger = logger ?? throw new ArgumentNullException(nameof(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() | ||
|  |         { | ||
|  |             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 OtrosDestinosController."); | ||
|  |             return null; | ||
|  |         } | ||
|  | 
 | ||
|  |         // GET: api/otrosdestinos | ||
|  |         [HttpGet] | ||
|  |         [ProducesResponseType(typeof(IEnumerable<OtroDestinoDto>), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> GetAllOtrosDestinos([FromQuery] string? nombre) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoVer)) return Forbid(); | ||
|  |             try | ||
|  |             { | ||
|  |                 var destinos = await _otroDestinoService.ObtenerTodosAsync(nombre); | ||
|  |                 return Ok(destinos); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener todos los Otros Destinos. Filtro: {Nombre}", nombre); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // GET: api/otrosdestinos/{id} | ||
|  |         [HttpGet("{id:int}", Name = "GetOtroDestinoById")] | ||
|  |         [ProducesResponseType(typeof(OtroDestinoDto), StatusCodes.Status200OK)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> GetOtroDestinoById(int id) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoVer)) return Forbid(); | ||
|  |             try | ||
|  |             { | ||
|  |                 var destino = await _otroDestinoService.ObtenerPorIdAsync(id); | ||
|  |                 if (destino == null) return NotFound(new { message = $"Otro Destino con ID {id} no encontrado." }); | ||
|  |                 return Ok(destino); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al obtener Otro Destino por ID: {Id}", id); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // POST: api/otrosdestinos | ||
|  |         [HttpPost] | ||
|  |         [ProducesResponseType(typeof(OtroDestinoDto), StatusCodes.Status201Created)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> CreateOtroDestino([FromBody] CreateOtroDestinoDto 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 (destinoCreado, error) = await _otroDestinoService.CrearAsync(createDto, idUsuario.Value); | ||
|  |                 if (error != null) return BadRequest(new { message = error }); | ||
|  |                 if (destinoCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear."); | ||
|  |                 return CreatedAtRoute("GetOtroDestinoById", new { id = destinoCreado.IdDestino }, destinoCreado); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al crear Otro Destino. Nombre: {Nombre}, UserID: {UsuarioId}", createDto.Nombre, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // PUT: api/otrosdestinos/{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> UpdateOtroDestino(int id, [FromBody] UpdateOtroDestinoDto 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 _otroDestinoService.ActualizarAsync(id, updateDto, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Otro Destino no encontrado.") return NotFound(new { message = error }); | ||
|  |                     return BadRequest(new { message = error }); | ||
|  |                 } | ||
|  |                 return NoContent(); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al actualizar Otro Destino ID: {Id}, UserID: {UsuarioId}", id, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         // DELETE: api/otrosdestinos/{id} | ||
|  |         [HttpDelete("{id:int}")] | ||
|  |         [ProducesResponseType(StatusCodes.Status204NoContent)] | ||
|  |         [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
|  |         [ProducesResponseType(StatusCodes.Status401Unauthorized)] | ||
|  |         [ProducesResponseType(StatusCodes.Status403Forbidden)] | ||
|  |         [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
|  |         [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
|  |         public async Task<IActionResult> DeleteOtroDestino(int id) | ||
|  |         { | ||
|  |             if (!TienePermiso(PermisoEliminar)) return Forbid(); | ||
|  |             var idUsuario = GetCurrentUserId(); | ||
|  |             if (idUsuario == null) return Unauthorized("Token inválido."); | ||
|  | 
 | ||
|  |             try | ||
|  |             { | ||
|  |                 var (exito, error) = await _otroDestinoService.EliminarAsync(id, idUsuario.Value); | ||
|  |                 if (!exito) | ||
|  |                 { | ||
|  |                     if (error == "Otro Destino no encontrado.") return NotFound(new { message = error }); | ||
|  |                     return BadRequest(new { message = error }); | ||
|  |                 } | ||
|  |                 return NoContent(); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 _logger.LogError(ex, "Error al eliminar Otro Destino ID: {Id}, UserID: {UsuarioId}", id, idUsuario); | ||
|  |                 return StatusCode(StatusCodes.Status500InternalServerError, "Error interno."); | ||
|  |             } | ||
|  |         } | ||
|  |     } | ||
|  | } |