130 lines
		
	
	
		
			6.2 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			130 lines
		
	
	
		
			6.2 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/controldevoluciones")] // Ruta base
 | |
|     [ApiController]
 | |
|     [Authorize]
 | |
|     public class ControlDevolucionesController : ControllerBase
 | |
|     {
 | |
|         private readonly IControlDevolucionesService _controlDevService;
 | |
|         private readonly ILogger<ControlDevolucionesController> _logger;
 | |
| 
 | |
|         // Permisos para Control Devoluciones (CD001 a CD003)
 | |
|         private const string PermisoVer = "CD001";
 | |
|         private const string PermisoCrear = "CD002";
 | |
|         private const string PermisoModificar = "CD003";
 | |
|         // Asumo que no hay un permiso específico para eliminar, se podría usar CD003 o crear CD004
 | |
| 
 | |
|         public ControlDevolucionesController(IControlDevolucionesService controlDevService, ILogger<ControlDevolucionesController> logger)
 | |
|         {
 | |
|             _controlDevService = controlDevService;
 | |
|             _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 ControlDevolucionesController.");
 | |
|             return null;
 | |
|         }
 | |
| 
 | |
|         // GET: api/controldevoluciones
 | |
|         [HttpGet]
 | |
|         [ProducesResponseType(typeof(IEnumerable<ControlDevolucionesDto>), StatusCodes.Status200OK)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         public async Task<IActionResult> GetAll(
 | |
|             [FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
 | |
|             [FromQuery] int? idEmpresa)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoVer)) return Forbid();
 | |
|             var controles = await _controlDevService.ObtenerTodosAsync(fechaDesde, fechaHasta, idEmpresa);
 | |
|             return Ok(controles);
 | |
|         }
 | |
| 
 | |
|         // GET: api/controldevoluciones/{idControl}
 | |
|         [HttpGet("{idControl:int}", Name = "GetControlDevolucionesById")]
 | |
|         [ProducesResponseType(typeof(ControlDevolucionesDto), StatusCodes.Status200OK)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         [ProducesResponseType(StatusCodes.Status404NotFound)]
 | |
|         public async Task<IActionResult> GetById(int idControl)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoVer)) return Forbid();
 | |
|             var control = await _controlDevService.ObtenerPorIdAsync(idControl);
 | |
|             if (control == null) return NotFound(new { message = $"Control de devoluciones con ID {idControl} no encontrado." });
 | |
|             return Ok(control);
 | |
|         }
 | |
| 
 | |
|         // POST: api/controldevoluciones
 | |
|         [HttpPost]
 | |
|         [ProducesResponseType(typeof(ControlDevolucionesDto), StatusCodes.Status201Created)]
 | |
|         [ProducesResponseType(StatusCodes.Status400BadRequest)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         public async Task<IActionResult> Create([FromBody] CreateControlDevolucionesDto createDto)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoCrear)) return Forbid();
 | |
|             if (!ModelState.IsValid) return BadRequest(ModelState);
 | |
|             var userId = GetCurrentUserId();
 | |
|             if (userId == null) return Unauthorized();
 | |
| 
 | |
|             var (dto, error) = await _controlDevService.CrearAsync(createDto, userId.Value);
 | |
|             if (error != null) return BadRequest(new { message = error });
 | |
|             if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al registrar el control.");
 | |
|             
 | |
|             return CreatedAtRoute("GetControlDevolucionesById", new { idControl = dto.IdControl }, dto);
 | |
|         }
 | |
| 
 | |
|         // PUT: api/controldevoluciones/{idControl}
 | |
|         [HttpPut("{idControl:int}")]
 | |
|         [ProducesResponseType(StatusCodes.Status204NoContent)]
 | |
|         [ProducesResponseType(StatusCodes.Status400BadRequest)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)]
 | |
|         [ProducesResponseType(StatusCodes.Status404NotFound)]
 | |
|         public async Task<IActionResult> Update(int idControl, [FromBody] UpdateControlDevolucionesDto updateDto)
 | |
|         {
 | |
|             if (!TienePermiso(PermisoModificar)) return Forbid();
 | |
|             if (!ModelState.IsValid) return BadRequest(ModelState);
 | |
|             var userId = GetCurrentUserId();
 | |
|             if (userId == null) return Unauthorized();
 | |
| 
 | |
|             var (exito, error) = await _controlDevService.ActualizarAsync(idControl, updateDto, userId.Value);
 | |
|             if (!exito)
 | |
|             {
 | |
|                 if (error == "Control de devoluciones no encontrado.") return NotFound(new { message = error });
 | |
|                 return BadRequest(new { message = error });
 | |
|             }
 | |
|             return NoContent();
 | |
|         }
 | |
| 
 | |
|         // DELETE: api/controldevoluciones/{idControl}
 | |
|         [HttpDelete("{idControl:int}")]
 | |
|         [ProducesResponseType(StatusCodes.Status204NoContent)]
 | |
|         [ProducesResponseType(StatusCodes.Status400BadRequest)]
 | |
|         [ProducesResponseType(StatusCodes.Status403Forbidden)] // Podría usar PermisoModificar o un permiso de borrado específico
 | |
|         [ProducesResponseType(StatusCodes.Status404NotFound)]
 | |
|         public async Task<IActionResult> Delete(int idControl)
 | |
|         {
 | |
|             // Asumimos que CD003 (Modificar) también permite eliminar, o se define un permiso específico
 | |
|             if (!TienePermiso(PermisoModificar)) return Forbid(); 
 | |
|             var userId = GetCurrentUserId();
 | |
|             if (userId == null) return Unauthorized();
 | |
| 
 | |
|             var (exito, error) = await _controlDevService.EliminarAsync(idControl, userId.Value);
 | |
|             if (!exito)
 | |
|             {
 | |
|                 if (error == "Control de devoluciones no encontrado.") return NotFound(new { message = error });
 | |
|                 return BadRequest(new { message = error });
 | |
|             }
 | |
|             return NoContent();
 | |
|         }
 | |
|     }
 | |
| } |