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.
		
	
		
			
				
	
	
		
			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.");
 | |
|             }
 | |
|         }
 | |
|     }
 | |
| } |