144 lines
6.9 KiB
C#
144 lines
6.9 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/publicaciones/{idPublicacion}/precios")] // Anidado bajo publicaciones
|
||
|
|
[ApiController]
|
||
|
|
[Authorize]
|
||
|
|
public class PreciosController : ControllerBase
|
||
|
|
{
|
||
|
|
private readonly IPrecioService _precioService;
|
||
|
|
private readonly ILogger<PreciosController> _logger;
|
||
|
|
|
||
|
|
// Permiso DP004 para gestionar precios
|
||
|
|
private const string PermisoGestionarPrecios = "DP004";
|
||
|
|
|
||
|
|
public PreciosController(IPrecioService precioService, ILogger<PreciosController> logger)
|
||
|
|
{
|
||
|
|
_precioService = precioService;
|
||
|
|
_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;
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
// GET: api/publicaciones/{idPublicacion}/precios
|
||
|
|
[HttpGet]
|
||
|
|
[ProducesResponseType(typeof(IEnumerable<PrecioDto>), StatusCodes.Status200OK)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
public async Task<IActionResult> GetPreciosPorPublicacion(int idPublicacion)
|
||
|
|
{
|
||
|
|
// Para ver precios, se podría usar el permiso de ver publicaciones (DP001) o el de gestionar precios (DP004)
|
||
|
|
if (!TienePermiso("DP001") && !TienePermiso(PermisoGestionarPrecios)) return Forbid();
|
||
|
|
|
||
|
|
var precios = await _precioService.ObtenerPorPublicacionIdAsync(idPublicacion);
|
||
|
|
return Ok(precios);
|
||
|
|
}
|
||
|
|
|
||
|
|
// GET: api/publicaciones/{idPublicacion}/precios/{idPrecio}
|
||
|
|
// Este endpoint es más para obtener un precio específico para editarlo, no tanto para el listado.
|
||
|
|
// El anterior es más útil para mostrar todos los periodos de una publicación.
|
||
|
|
[HttpGet("{idPrecio:int}", Name = "GetPrecioById")]
|
||
|
|
[ProducesResponseType(typeof(PrecioDto), StatusCodes.Status200OK)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
public async Task<IActionResult> GetPrecioById(int idPublicacion, int idPrecio)
|
||
|
|
{
|
||
|
|
if (!TienePermiso("DP001") && !TienePermiso(PermisoGestionarPrecios)) return Forbid();
|
||
|
|
var precio = await _precioService.ObtenerPorIdAsync(idPrecio);
|
||
|
|
if (precio == null || precio.IdPublicacion != idPublicacion) return NotFound(); // Asegurar que el precio pertenece a la publicación
|
||
|
|
return Ok(precio);
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
// POST: api/publicaciones/{idPublicacion}/precios
|
||
|
|
[HttpPost]
|
||
|
|
[ProducesResponseType(typeof(PrecioDto), StatusCodes.Status201Created)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
public async Task<IActionResult> CreatePrecio(int idPublicacion, [FromBody] CreatePrecioDto createDto)
|
||
|
|
{
|
||
|
|
if (!TienePermiso(PermisoGestionarPrecios)) return Forbid();
|
||
|
|
if (idPublicacion != createDto.IdPublicacion)
|
||
|
|
return BadRequest(new { message = "El ID de publicación en la ruta no coincide con el del cuerpo de la solicitud." });
|
||
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||
|
|
|
||
|
|
var userId = GetCurrentUserId();
|
||
|
|
if (userId == null) return Unauthorized();
|
||
|
|
|
||
|
|
var (dto, error) = await _precioService.CrearAsync(createDto, userId.Value);
|
||
|
|
if (error != null) return BadRequest(new { message = error });
|
||
|
|
if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el período de precio.");
|
||
|
|
|
||
|
|
// La ruta para "GetPrecioById" necesita ambos IDs
|
||
|
|
return CreatedAtRoute("GetPrecioById", new { idPublicacion = dto.IdPublicacion, idPrecio = dto.IdPrecio }, dto);
|
||
|
|
}
|
||
|
|
|
||
|
|
// PUT: api/publicaciones/{idPublicacion}/precios/{idPrecio}
|
||
|
|
[HttpPut("{idPrecio:int}")]
|
||
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
public async Task<IActionResult> UpdatePrecio(int idPublicacion, int idPrecio, [FromBody] UpdatePrecioDto updateDto)
|
||
|
|
{
|
||
|
|
if (!TienePermiso(PermisoGestionarPrecios)) return Forbid();
|
||
|
|
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||
|
|
var userId = GetCurrentUserId();
|
||
|
|
if (userId == null) return Unauthorized();
|
||
|
|
|
||
|
|
// Verificar que el precio que se intenta actualizar pertenece a la publicación de la ruta
|
||
|
|
var precioExistente = await _precioService.ObtenerPorIdAsync(idPrecio);
|
||
|
|
if (precioExistente == null || precioExistente.IdPublicacion != idPublicacion)
|
||
|
|
{
|
||
|
|
return NotFound(new { message = "Período de precio no encontrado para esta publicación."});
|
||
|
|
}
|
||
|
|
|
||
|
|
var (exito, error) = await _precioService.ActualizarAsync(idPrecio, updateDto, userId.Value);
|
||
|
|
if (!exito)
|
||
|
|
{
|
||
|
|
// El servicio ya devuelve "Período de precio no encontrado." si es el caso
|
||
|
|
return BadRequest(new { message = error });
|
||
|
|
}
|
||
|
|
return NoContent();
|
||
|
|
}
|
||
|
|
|
||
|
|
// DELETE: api/publicaciones/{idPublicacion}/precios/{idPrecio}
|
||
|
|
[HttpDelete("{idPrecio:int}")]
|
||
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||
|
|
public async Task<IActionResult> DeletePrecio(int idPublicacion, int idPrecio)
|
||
|
|
{
|
||
|
|
if (!TienePermiso(PermisoGestionarPrecios)) return Forbid();
|
||
|
|
var userId = GetCurrentUserId();
|
||
|
|
if (userId == null) return Unauthorized();
|
||
|
|
|
||
|
|
var precioExistente = await _precioService.ObtenerPorIdAsync(idPrecio);
|
||
|
|
if (precioExistente == null || precioExistente.IdPublicacion != idPublicacion)
|
||
|
|
{
|
||
|
|
return NotFound(new { message = "Período de precio no encontrado para esta publicación."});
|
||
|
|
}
|
||
|
|
|
||
|
|
var (exito, error) = await _precioService.EliminarAsync(idPrecio, userId.Value);
|
||
|
|
if (!exito)
|
||
|
|
{
|
||
|
|
return BadRequest(new { message = error });
|
||
|
|
}
|
||
|
|
return NoContent();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|