feat: Implementación CRUD Canillitas, Distribuidores y Precios de Publicación
Backend API:
- Canillitas (`dist_dtCanillas`):
- Implementado CRUD completo (Modelos, DTOs, Repositorio, Servicio, Controlador).
- Lógica para manejo de `Accionista`, `Baja`, `FechaBaja`.
- Auditoría en `dist_dtCanillas_H`.
- Validación de legajo único y lógica de empresa vs accionista.
- Distribuidores (`dist_dtDistribuidores`):
- Implementado CRUD completo (Modelos, DTOs, Repositorio, Servicio, Controlador).
- Auditoría en `dist_dtDistribuidores_H`.
- Creación de saldos iniciales para el nuevo distribuidor en todas las empresas.
- Verificación de NroDoc único y Nombre opcionalmente único.
- Precios de Publicación (`dist_Precios`):
- Implementado CRUD básico (Modelos, DTOs, Repositorio, Servicio, Controlador).
- Endpoints anidados bajo `/publicaciones/{idPublicacion}/precios`.
- Lógica de negocio para cerrar período de precio anterior al crear uno nuevo.
- Lógica de negocio para reabrir período de precio anterior al eliminar el último.
- Auditoría en `dist_Precios_H`.
- Auditoría en Eliminación de Publicaciones:
- Extendido `PublicacionService.EliminarAsync` para eliminar en cascada registros de precios, recargos, porcentajes de pago (distribuidores y canillitas) y secciones de publicación.
- Repositorios correspondientes (`PrecioRepository`, `RecargoZonaRepository`, `PorcPagoRepository`, `PorcMonCanillaRepository`, `PubliSeccionRepository`) actualizados con métodos `DeleteByPublicacionIdAsync` que registran en sus respectivas tablas `_H` (si existen y se implementó la lógica).
- Asegurada la correcta propagación del `idUsuario` para la auditoría en cascada.
- Correcciones de Nulabilidad:
- Ajustados los métodos `MapToDto` y su uso en `CanillaService` y `PublicacionService` para manejar correctamente tipos anulables.
Frontend React:
- Canillitas:
- `canillaService.ts`.
- `CanillaFormModal.tsx` con selectores para Zona y Empresa, y lógica de Accionista.
- `GestionarCanillitasPage.tsx` con filtros, paginación, y acciones (editar, toggle baja).
- Distribuidores:
- `distribuidorService.ts`.
- `DistribuidorFormModal.tsx` con múltiples campos y selector de Zona.
- `GestionarDistribuidoresPage.tsx` con filtros, paginación, y acciones (editar, eliminar).
- Precios de Publicación:
- `precioService.ts`.
- `PrecioFormModal.tsx` para crear/editar períodos de precios (VigenciaD, VigenciaH opcional, precios por día).
- `GestionarPreciosPublicacionPage.tsx` accesible desde la gestión de publicaciones, para listar y gestionar los períodos de precios de una publicación específica.
- Layout:
- Reemplazado el uso de `Grid` por `Box` con Flexbox en `CanillaFormModal`, `GestionarCanillitasPage` (filtros), `DistribuidorFormModal` y `PrecioFormModal` para resolver problemas de tipos y mejorar la consistencia del layout de formularios.
- Navegación:
- Actualizadas las rutas y pestañas para los nuevos módulos y sub-módulos.
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Services.Distribucion;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class CanillasController : ControllerBase
|
||||
{
|
||||
private readonly ICanillaService _canillaService;
|
||||
private readonly ILogger<CanillasController> _logger;
|
||||
|
||||
// Permisos para Canillas (CG001 a CG005)
|
||||
private const string PermisoVer = "CG001";
|
||||
private const string PermisoCrear = "CG002";
|
||||
private const string PermisoModificar = "CG003";
|
||||
// CG004 es para Porcentajes, se manejará en un endpoint específico o en Update si se incluye en DTO
|
||||
private const string PermisoBaja = "CG005"; // Para dar de baja/alta
|
||||
|
||||
public CanillasController(ICanillaService canillaService, ILogger<CanillasController> logger)
|
||||
{
|
||||
_canillaService = canillaService;
|
||||
_logger = 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;
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/canillas
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<CanillaDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAllCanillas([FromQuery] string? nomApe, [FromQuery] int? legajo, [FromQuery] bool? soloActivos = true)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var canillas = await _canillaService.ObtenerTodosAsync(nomApe, legajo, soloActivos);
|
||||
return Ok(canillas);
|
||||
}
|
||||
|
||||
// GET: api/canillas/{id}
|
||||
[HttpGet("{id:int}", Name = "GetCanillaById")]
|
||||
[ProducesResponseType(typeof(CanillaDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetCanillaById(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var canilla = await _canillaService.ObtenerPorIdAsync(id);
|
||||
if (canilla == null) return NotFound();
|
||||
return Ok(canilla);
|
||||
}
|
||||
|
||||
// POST: api/canillas
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(CanillaDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> CreateCanilla([FromBody] CreateCanillaDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoCrear)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized();
|
||||
|
||||
var (canillaCreado, error) = await _canillaService.CrearAsync(createDto, idUsuario.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (canillaCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el canillita.");
|
||||
|
||||
return CreatedAtRoute("GetCanillaById", new { id = canillaCreado.IdCanilla }, canillaCreado);
|
||||
}
|
||||
|
||||
// PUT: api/canillas/{id}
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdateCanilla(int id, [FromBody] UpdateCanillaDto updateDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificar)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _canillaService.ActualizarAsync(id, updateDto, idUsuario.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Canillita no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// POST: api/canillas/{id}/toggle-baja
|
||||
[HttpPost("{id:int}/toggle-baja")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ToggleBajaCanilla(int id, [FromBody] ToggleBajaCanillaDto bajaDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoBaja)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _canillaService.ToggleBajaAsync(id, bajaDto.DarDeBaja, idUsuario.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Canillita no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Services.Distribucion;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class DistribuidoresController : ControllerBase
|
||||
{
|
||||
private readonly IDistribuidorService _distribuidorService;
|
||||
private readonly ILogger<DistribuidoresController> _logger;
|
||||
|
||||
// Permisos para Distribuidores (DG001 a DG005)
|
||||
private const string PermisoVer = "DG001";
|
||||
private const string PermisoCrear = "DG002";
|
||||
private const string PermisoModificar = "DG003";
|
||||
// DG004 es para Porcentajes, se manejará en un endpoint/controlador dedicado
|
||||
private const string PermisoEliminar = "DG005";
|
||||
|
||||
public DistribuidoresController(IDistribuidorService distribuidorService, ILogger<DistribuidoresController> logger)
|
||||
{
|
||||
_distribuidorService = distribuidorService;
|
||||
_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;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<DistribuidorDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAllDistribuidores([FromQuery] string? nombre, [FromQuery] string? nroDoc)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var distribuidores = await _distribuidorService.ObtenerTodosAsync(nombre, nroDoc);
|
||||
return Ok(distribuidores);
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}", Name = "GetDistribuidorById")]
|
||||
[ProducesResponseType(typeof(DistribuidorDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetDistribuidorById(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var distribuidor = await _distribuidorService.ObtenerPorIdAsync(id);
|
||||
if (distribuidor == null) return NotFound();
|
||||
return Ok(distribuidor);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(DistribuidorDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> CreateDistribuidor([FromBody] CreateDistribuidorDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoCrear)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (dto, error) = await _distribuidorService.CrearAsync(createDto, userId.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear.");
|
||||
return CreatedAtRoute("GetDistribuidorById", new { id = dto.IdDistribuidor }, dto);
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdateDistribuidor(int id, [FromBody] UpdateDistribuidorDto updateDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificar)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _distribuidorService.ActualizarAsync(id, updateDto, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Distribuidor no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeleteDistribuidor(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoEliminar)) return Forbid();
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _distribuidorService.EliminarAsync(id, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Distribuidor no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Services.Distribucion;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Controllers.Distribucion
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class PublicacionesController : ControllerBase
|
||||
{
|
||||
private readonly IPublicacionService _publicacionService;
|
||||
private readonly ILogger<PublicacionesController> _logger;
|
||||
|
||||
// Permisos (DP001 a DP006)
|
||||
private const string PermisoVer = "DP001";
|
||||
private const string PermisoCrear = "DP002";
|
||||
private const string PermisoModificar = "DP003";
|
||||
// DP004 (Precios) y DP005 (Recargos) se manejarán en endpoints/controladores dedicados
|
||||
private const string PermisoEliminar = "DP006";
|
||||
// DP007 (Secciones) también se manejará por separado
|
||||
|
||||
public PublicacionesController(IPublicacionService publicacionService, ILogger<PublicacionesController> logger)
|
||||
{
|
||||
_publicacionService = publicacionService;
|
||||
_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;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<PublicacionDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAllPublicaciones([FromQuery] string? nombre, [FromQuery] int? idEmpresa, [FromQuery] bool? soloHabilitadas = true)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var publicaciones = await _publicacionService.ObtenerTodasAsync(nombre, idEmpresa, soloHabilitadas);
|
||||
return Ok(publicaciones);
|
||||
}
|
||||
|
||||
[HttpGet("{id:int}", Name = "GetPublicacionById")]
|
||||
[ProducesResponseType(typeof(PublicacionDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetPublicacionById(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
var publicacion = await _publicacionService.ObtenerPorIdAsync(id);
|
||||
if (publicacion == null) return NotFound();
|
||||
return Ok(publicacion);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(PublicacionDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> CreatePublicacion([FromBody] CreatePublicacionDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoCrear)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (dto, error) = await _publicacionService.CrearAsync(createDto, userId.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (dto == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear.");
|
||||
return CreatedAtRoute("GetPublicacionById", new { id = dto.IdPublicacion }, dto);
|
||||
}
|
||||
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdatePublicacion(int id, [FromBody] UpdatePublicacionDto updateDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificar)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _publicacionService.ActualizarAsync(id, updateDto, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Publicación no encontrada.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpDelete("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeletePublicacion(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoEliminar)) return Forbid();
|
||||
var userId = GetCurrentUserId();
|
||||
if (userId == null) return Unauthorized();
|
||||
|
||||
var (exito, error) = await _publicacionService.EliminarAsync(id, userId.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Publicación no encontrada.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user