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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
using GestionIntegral.Api.Dtos;
|
||||
using GestionIntegral.Api.Services;
|
||||
using GestionIntegral.Api.Services.Usuarios;
|
||||
using Microsoft.AspNetCore.Authorization; // Para [Authorize]
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Security.Claims; // Para leer claims del token
|
||||
|
||||
namespace GestionIntegral.Api.Controllers
|
||||
namespace GestionIntegral.Api.Controllers.Usuarios
|
||||
{
|
||||
[Route("api/[controller]")] // Ruta base: /api/auth
|
||||
[ApiController]
|
||||
@@ -0,0 +1,239 @@
|
||||
using GestionIntegral.Api.Dtos.Usuarios;
|
||||
using GestionIntegral.Api.Services.Usuarios;
|
||||
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.Usuarios
|
||||
{
|
||||
[Route("api/[controller]")] // Ruta base: /api/perfiles
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
public class PerfilesController : ControllerBase
|
||||
{
|
||||
private readonly IPerfilService _perfilService;
|
||||
private readonly ILogger<PerfilesController> _logger;
|
||||
|
||||
// Códigos de permiso para Perfiles (PU001-PU004)
|
||||
private const string PermisoVer = "PU001";
|
||||
private const string PermisoCrear = "PU002";
|
||||
private const string PermisoModificar = "PU003";
|
||||
private const string PermisoEliminar = "PU003";
|
||||
private const string PermisoAsignar = "PU004";
|
||||
|
||||
public PerfilesController(IPerfilService perfilService, ILogger<PerfilesController> logger)
|
||||
{
|
||||
_perfilService = perfilService ?? throw new ArgumentNullException(nameof(perfilService));
|
||||
_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 PerfilesController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/perfiles
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<PerfilDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAllPerfiles([FromQuery] string? nombre)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
try
|
||||
{
|
||||
var perfiles = await _perfilService.ObtenerTodosAsync(nombre);
|
||||
return Ok(perfiles);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Perfiles. Filtro: {Nombre}", nombre);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/perfiles/{id}
|
||||
[HttpGet("{id:int}", Name = "GetPerfilById")]
|
||||
[ProducesResponseType(typeof(PerfilDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetPerfilById(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoVer)) return Forbid();
|
||||
try
|
||||
{
|
||||
var perfil = await _perfilService.ObtenerPorIdAsync(id);
|
||||
if (perfil == null) return NotFound(new { message = $"Perfil con ID {id} no encontrado." });
|
||||
return Ok(perfil);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Perfil por ID: {Id}", id);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// POST: api/perfiles
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(PerfilDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> CreatePerfil([FromBody] CreatePerfilDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoCrear)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var idUsuario = GetCurrentUserId(); // Necesario para auditoría si se implementa
|
||||
if (idUsuario == null) return Unauthorized("Token inválido.");
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
var (perfilCreado, error) = await _perfilService.CrearAsync(createDto, idUsuario.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (perfilCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el perfil.");
|
||||
return CreatedAtRoute("GetPerfilById", new { id = perfilCreado.Id }, perfilCreado);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al crear Perfil. Nombre: {Nombre}, UserID: {UsuarioId}", createDto.NombrePerfil, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// PUT: api/perfiles/{id}
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdatePerfil(int id, [FromBody] UpdatePerfilDto updateDto)
|
||||
{
|
||||
// Asumo que PU003 es para modificar el perfil (nombre/descripción)
|
||||
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 _perfilService.ActualizarAsync(id, updateDto, idUsuario.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Perfil no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al actualizar Perfil ID: {Id}, UserID: {UsuarioId}", id, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE: api/perfiles/{id}
|
||||
[HttpDelete("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> DeletePerfil(int id)
|
||||
{
|
||||
// El Excel dice PU003 para eliminar.
|
||||
if (!TienePermiso(PermisoEliminar)) return Forbid();
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized("Token inválido.");
|
||||
|
||||
try
|
||||
{
|
||||
var (exito, error) = await _perfilService.EliminarAsync(id, idUsuario.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Perfil no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al eliminar Perfil ID: {Id}, UserID: {UsuarioId}", id, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
// GET: api/perfiles/{idPerfil}/permisos
|
||||
[HttpGet("{idPerfil:int}/permisos")]
|
||||
[ProducesResponseType(typeof(IEnumerable<PermisoAsignadoDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)] // Si no tiene permiso PU001 o PU004
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetPermisosPorPerfil(int idPerfil)
|
||||
{
|
||||
// Para ver los permisos de un perfil, podría ser PU001 (ver perfil) o PU004 (asignar)
|
||||
if (!TienePermiso(PermisoVer) && !TienePermiso(PermisoAsignar)) return Forbid();
|
||||
|
||||
try
|
||||
{
|
||||
var perfil = await _perfilService.ObtenerPorIdAsync(idPerfil); // Verificar si el perfil existe
|
||||
if (perfil == null)
|
||||
{
|
||||
return NotFound(new { message = $"Perfil con ID {idPerfil} no encontrado." });
|
||||
}
|
||||
|
||||
var permisos = await _perfilService.ObtenerPermisosAsignadosAsync(idPerfil);
|
||||
return Ok(permisos);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener permisos para el Perfil ID: {IdPerfil}", idPerfil);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al obtener los permisos del perfil.");
|
||||
}
|
||||
}
|
||||
|
||||
// PUT: api/perfiles/{idPerfil}/permisos
|
||||
[HttpPut("{idPerfil:int}/permisos")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)] // Si no tiene permiso PU004
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> UpdatePermisosDelPerfil(int idPerfil, [FromBody] ActualizarPermisosPerfilRequestDto request)
|
||||
{
|
||||
if (!TienePermiso(PermisoAsignar)) return Forbid();
|
||||
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
var idUsuario = GetCurrentUserId();
|
||||
if (idUsuario == null) return Unauthorized("Token inválido.");
|
||||
|
||||
try
|
||||
{
|
||||
var (exito, error) = await _perfilService.ActualizarPermisosAsignadosAsync(idPerfil, request, idUsuario.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Perfil no encontrado.") return NotFound(new { message = error });
|
||||
// Otros errores como "permiso inválido"
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al actualizar permisos para Perfil ID: {IdPerfil} por Usuario ID: {UsuarioId}", idPerfil, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al actualizar los permisos del perfil.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
using GestionIntegral.Api.Dtos.Usuarios;
|
||||
using GestionIntegral.Api.Services.Usuarios;
|
||||
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.Usuarios
|
||||
{
|
||||
[Route("api/[controller]")] // Ruta base: /api/permisos
|
||||
[ApiController]
|
||||
[Authorize(Roles = "SuperAdmin")] // Solo SuperAdmin puede gestionar la definición de permisos
|
||||
public class PermisosController : ControllerBase
|
||||
{
|
||||
private readonly IPermisoService _permisoService;
|
||||
private readonly ILogger<PermisosController> _logger;
|
||||
|
||||
public PermisosController(IPermisoService permisoService, ILogger<PermisosController> logger)
|
||||
{
|
||||
_permisoService = permisoService ?? throw new ArgumentNullException(nameof(permisoService));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
// Helper para User ID (aunque en SuperAdmin puede no ser tan crítico para auditoría de *definición* de permisos)
|
||||
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 PermisosController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/permisos
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<PermisoDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetAllPermisos([FromQuery] string? modulo, [FromQuery] string? codAcc)
|
||||
{
|
||||
try
|
||||
{
|
||||
var permisos = await _permisoService.ObtenerTodosAsync(modulo, codAcc);
|
||||
return Ok(permisos);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Permisos. Filtros: Modulo={Modulo}, CodAcc={CodAcc}", modulo, codAcc);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// GET: api/permisos/{id}
|
||||
[HttpGet("{id:int}", Name = "GetPermisoById")]
|
||||
[ProducesResponseType(typeof(PermisoDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> GetPermisoById(int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
var permiso = await _permisoService.ObtenerPorIdAsync(id);
|
||||
if (permiso == null) return NotFound(new { message = $"Permiso con ID {id} no encontrado." });
|
||||
return Ok(permiso);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Permiso por ID: {Id}", id);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// POST: api/permisos
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(PermisoDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> CreatePermiso([FromBody] CreatePermisoDto createDto)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var idUsuario = GetCurrentUserId() ?? 0; // SuperAdmin puede no necesitar auditoría estricta aquí
|
||||
|
||||
try
|
||||
{
|
||||
var (permisoCreado, error) = await _permisoService.CrearAsync(createDto, idUsuario);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (permisoCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el permiso.");
|
||||
return CreatedAtRoute("GetPermisoById", new { id = permisoCreado.Id }, permisoCreado);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al crear Permiso. CodAcc: {CodAcc}, UserID: {UsuarioId}", createDto.CodAcc, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// PUT: api/permisos/{id}
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> UpdatePermiso(int id, [FromBody] UpdatePermisoDto updateDto)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
var idUsuario = GetCurrentUserId() ?? 0;
|
||||
|
||||
try
|
||||
{
|
||||
var (exito, error) = await _permisoService.ActualizarAsync(id, updateDto, idUsuario);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Permiso no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al actualizar Permiso ID: {Id}, UserID: {UsuarioId}", id, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE: api/permisos/{id}
|
||||
[HttpDelete("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||
public async Task<IActionResult> DeletePermiso(int id)
|
||||
{
|
||||
var idUsuario = GetCurrentUserId() ?? 0;
|
||||
|
||||
try
|
||||
{
|
||||
var (exito, error) = await _permisoService.EliminarAsync(id, idUsuario);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Permiso no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error }); // Ej: "En uso"
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al eliminar Permiso ID: {Id}, UserID: {UsuarioId}", id, idUsuario);
|
||||
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using GestionIntegral.Api.Dtos.Usuarios;
|
||||
using GestionIntegral.Api.Services.Usuarios;
|
||||
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.Usuarios
|
||||
{
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
[Authorize] // Requiere autenticación general
|
||||
public class UsuariosController : ControllerBase
|
||||
{
|
||||
private readonly IUsuarioService _usuarioService;
|
||||
private readonly ILogger<UsuariosController> _logger;
|
||||
|
||||
// Permisos para gestión de usuarios (CU001-CU004)
|
||||
private const string PermisoVerUsuarios = "CU001";
|
||||
private const string PermisoAgregarUsuarios = "CU002";
|
||||
private const string PermisoModificarUsuarios = "CU003"; // Asumo que CU003 es para modificar, aunque el Excel dice "Eliminar"
|
||||
private const string PermisoAsignarPerfil = "CU004"; // Este se relaciona con la edición del perfil del usuario
|
||||
|
||||
public UsuariosController(IUsuarioService usuarioService, ILogger<UsuariosController> logger)
|
||||
{
|
||||
_usuarioService = usuarioService;
|
||||
_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;
|
||||
_logger.LogWarning("No se pudo obtener el UserId del token JWT en UsuariosController.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// GET: api/usuarios
|
||||
[HttpGet]
|
||||
[ProducesResponseType(typeof(IEnumerable<UsuarioDto>), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> GetAllUsuarios([FromQuery] string? user, [FromQuery] string? nombre)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerUsuarios)) return Forbid();
|
||||
var usuarios = await _usuarioService.ObtenerTodosAsync(user, nombre);
|
||||
return Ok(usuarios);
|
||||
}
|
||||
|
||||
// GET: api/usuarios/{id}
|
||||
[HttpGet("{id:int}", Name = "GetUsuarioById")]
|
||||
[ProducesResponseType(typeof(UsuarioDto), StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> GetUsuarioById(int id)
|
||||
{
|
||||
if (!TienePermiso(PermisoVerUsuarios)) return Forbid();
|
||||
var usuario = await _usuarioService.ObtenerPorIdAsync(id);
|
||||
if (usuario == null) return NotFound();
|
||||
return Ok(usuario);
|
||||
}
|
||||
|
||||
// POST: api/usuarios
|
||||
[HttpPost]
|
||||
[ProducesResponseType(typeof(UsuarioDto), StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
||||
public async Task<IActionResult> CreateUsuario([FromBody] CreateUsuarioRequestDto createDto)
|
||||
{
|
||||
if (!TienePermiso(PermisoAgregarUsuarios)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
var idUsuarioCreador = GetCurrentUserId();
|
||||
if (idUsuarioCreador == null) return Unauthorized("Token inválido.");
|
||||
|
||||
var (usuarioCreado, error) = await _usuarioService.CrearAsync(createDto, idUsuarioCreador.Value);
|
||||
if (error != null) return BadRequest(new { message = error });
|
||||
if (usuarioCreado == null) return StatusCode(StatusCodes.Status500InternalServerError, "Error al crear el usuario.");
|
||||
|
||||
return CreatedAtRoute("GetUsuarioById", new { id = usuarioCreado.Id }, usuarioCreado);
|
||||
}
|
||||
|
||||
// PUT: api/usuarios/{id}
|
||||
[HttpPut("{id:int}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)] // CU003 o CU004
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> UpdateUsuario(int id, [FromBody] UpdateUsuarioRequestDto updateDto)
|
||||
{
|
||||
// Modificar datos básicos (CU003), reasignar perfil (CU004)
|
||||
if (!TienePermiso(PermisoModificarUsuarios) && !TienePermiso(PermisoAsignarPerfil)) return Forbid();
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
var idUsuarioModificador = GetCurrentUserId();
|
||||
if (idUsuarioModificador == null) return Unauthorized("Token inválido.");
|
||||
|
||||
var (exito, error) = await _usuarioService.ActualizarAsync(id, updateDto, idUsuarioModificador.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Usuario no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// POST: api/usuarios/{id}/set-password
|
||||
[HttpPost("{id:int}/set-password")]
|
||||
[Authorize(Roles = "SuperAdmin")] // Solo SuperAdmin puede resetear claves directamente
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> SetPassword(int id, [FromBody] SetPasswordRequestDto setPasswordDto)
|
||||
{
|
||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
||||
|
||||
var idAdmin = GetCurrentUserId();
|
||||
if (idAdmin == null) return Unauthorized("Token inválido.");
|
||||
|
||||
var (exito, error) = await _usuarioService.SetPasswordAsync(id, setPasswordDto, idAdmin.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Usuario no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
// POST: api/usuarios/{id}/toggle-habilitado
|
||||
[HttpPost("{id:int}/toggle-habilitado")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status403Forbidden)] // Podría ser PermisoModificarUsuarios (CU003)
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<IActionResult> ToggleHabilitado(int id, [FromBody] bool habilitar)
|
||||
{
|
||||
if (!TienePermiso(PermisoModificarUsuarios)) return Forbid();
|
||||
|
||||
var idAdmin = GetCurrentUserId();
|
||||
if (idAdmin == null) return Unauthorized("Token inválido.");
|
||||
|
||||
var (exito, error) = await _usuarioService.CambiarEstadoHabilitadoAsync(id, habilitar, idAdmin.Value);
|
||||
if (!exito)
|
||||
{
|
||||
if (error == "Usuario no encontrado.") return NotFound(new { message = error });
|
||||
return BadRequest(new { message = error });
|
||||
}
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Data.Repositories;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class CanillaRepository : ICanillaRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<CanillaRepository> _logger;
|
||||
|
||||
public CanillaRepository(DbConnectionFactory connectionFactory, ILogger<CanillaRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<(Canilla Canilla, string NombreZona, string NombreEmpresa)>> GetAllAsync(string? nomApeFilter, int? legajoFilter, bool? soloActivos)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder(@"
|
||||
SELECT c.*, z.Nombre AS NombreZona, ISNULL(e.Nombre, 'N/A (Accionista)') AS NombreEmpresa
|
||||
FROM dbo.dist_dtCanillas c
|
||||
INNER JOIN dbo.dist_dtZonas z ON c.Id_Zona = z.Id_Zona
|
||||
LEFT JOIN dbo.dist_dtEmpresas e ON c.Empresa = e.Id_Empresa -- Empresa 0 no tendrá join
|
||||
WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (soloActivos.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(soloActivos.Value ? " AND c.Baja = 0" : " AND c.Baja = 1");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(nomApeFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND c.NomApe LIKE @NomApe");
|
||||
parameters.Add("NomApe", $"%{nomApeFilter}%");
|
||||
}
|
||||
if (legajoFilter.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND c.Legajo = @Legajo");
|
||||
parameters.Add("Legajo", legajoFilter.Value);
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY c.NomApe;");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Canilla, string, string, (Canilla, string, string)>(
|
||||
sqlBuilder.ToString(),
|
||||
(canilla, nombreZona, nombreEmpresa) => (canilla, nombreZona, nombreEmpresa),
|
||||
parameters,
|
||||
splitOn: "NombreZona,NombreEmpresa"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Canillas.");
|
||||
return Enumerable.Empty<(Canilla, string, string)>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(Canilla? Canilla, string? NombreZona, string? NombreEmpresa)> GetByIdAsync(int id)
|
||||
{
|
||||
const string sql = @"
|
||||
SELECT c.*, z.Nombre AS NombreZona, ISNULL(e.Nombre, 'N/A (Accionista)') AS NombreEmpresa
|
||||
FROM dbo.dist_dtCanillas c
|
||||
INNER JOIN dbo.dist_dtZonas z ON c.Id_Zona = z.Id_Zona
|
||||
LEFT JOIN dbo.dist_dtEmpresas e ON c.Empresa = e.Id_Empresa
|
||||
WHERE c.Id_Canilla = @Id";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var result = await connection.QueryAsync<Canilla, string, string, (Canilla, string, string)>(
|
||||
sql,
|
||||
(canilla, nombreZona, nombreEmpresa) => (canilla, nombreZona, nombreEmpresa),
|
||||
new { Id = id },
|
||||
splitOn: "NombreZona,NombreEmpresa"
|
||||
);
|
||||
return result.SingleOrDefault();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Canilla por ID: {IdCanilla}", id);
|
||||
return (null, null, null);
|
||||
}
|
||||
}
|
||||
public async Task<Canilla?> GetByIdSimpleAsync(int id) // Para uso interno del servicio
|
||||
{
|
||||
const string sql = "SELECT * FROM dbo.dist_dtCanillas WHERE Id_Canilla = @Id";
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<Canilla>(sql, new { Id = id });
|
||||
}
|
||||
|
||||
|
||||
public async Task<bool> ExistsByLegajoAsync(int legajo, int? excludeIdCanilla = null)
|
||||
{
|
||||
if (legajo == 0) return false; // Legajo 0 es como nulo, no debería validarse como único
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.dist_dtCanillas WHERE Legajo = @Legajo AND Legajo != 0"); // Excluir legajo 0 de la unicidad
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("Legajo", legajo);
|
||||
|
||||
if (excludeIdCanilla.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id_Canilla != @ExcludeIdCanilla");
|
||||
parameters.Add("ExcludeIdCanilla", excludeIdCanilla.Value);
|
||||
}
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.ExecuteScalarAsync<bool>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en ExistsByLegajoAsync para Canilla con Legajo: {Legajo}", legajo);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Canilla?> CreateAsync(Canilla nuevoCanilla, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
const string sqlInsert = @"
|
||||
INSERT INTO dbo.dist_dtCanillas (Legajo, NomApe, Parada, Id_Zona, Accionista, Obs, Empresa, Baja, FechaBaja)
|
||||
OUTPUT INSERTED.*
|
||||
VALUES (@Legajo, @NomApe, @Parada, @IdZona, @Accionista, @Obs, @Empresa, @Baja, @FechaBaja);";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtCanillas_H
|
||||
(Id_Canilla, Legajo, NomApe, Parada, Id_Zona, Accionista, Obs, Empresa, Baja, FechaBaja, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdCanilla, @Legajo, @NomApe, @Parada, @IdZona, @Accionista, @Obs, @Empresa, @Baja, @FechaBaja, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
var connection = transaction.Connection!;
|
||||
var insertedCanilla = await connection.QuerySingleAsync<Canilla>(sqlInsert, nuevoCanilla, transaction);
|
||||
|
||||
if (insertedCanilla == null) throw new DataException("No se pudo crear el canilla.");
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
insertedCanilla.IdCanilla, insertedCanilla.Legajo, insertedCanilla.NomApe, insertedCanilla.Parada, insertedCanilla.IdZona,
|
||||
insertedCanilla.Accionista, insertedCanilla.Obs, insertedCanilla.Empresa, insertedCanilla.Baja, insertedCanilla.FechaBaja,
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Creado"
|
||||
}, transaction);
|
||||
return insertedCanilla;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(Canilla canillaAActualizar, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var canillaActual = await connection.QuerySingleOrDefaultAsync<Canilla>(
|
||||
"SELECT * FROM dbo.dist_dtCanillas WHERE Id_Canilla = @IdCanilla", new { canillaAActualizar.IdCanilla }, transaction);
|
||||
if (canillaActual == null) throw new KeyNotFoundException("Canilla no encontrado para actualizar.");
|
||||
|
||||
const string sqlUpdate = @"
|
||||
UPDATE dbo.dist_dtCanillas SET
|
||||
Legajo = @Legajo, NomApe = @NomApe, Parada = @Parada, Id_Zona = @IdZona,
|
||||
Accionista = @Accionista, Obs = @Obs, Empresa = @Empresa
|
||||
-- Baja y FechaBaja se manejan por ToggleBajaAsync
|
||||
WHERE Id_Canilla = @IdCanilla;";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtCanillas_H
|
||||
(Id_Canilla, Legajo, NomApe, Parada, Id_Zona, Accionista, Obs, Empresa, Baja, FechaBaja, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdCanilla, @LegajoActual, @NomApeActual, @ParadaActual, @IdZonaActual, @AccionistaActual, @ObsActual, @EmpresaActual, @BajaActual, @FechaBajaActual, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdCanilla = canillaActual.IdCanilla,
|
||||
LegajoActual = canillaActual.Legajo, NomApeActual = canillaActual.NomApe, ParadaActual = canillaActual.Parada, IdZonaActual = canillaActual.IdZona,
|
||||
AccionistaActual = canillaActual.Accionista, ObsActual = canillaActual.Obs, EmpresaActual = canillaActual.Empresa,
|
||||
BajaActual = canillaActual.Baja, FechaBajaActual = canillaActual.FechaBaja, // Registrar estado actual de baja
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Actualizado"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, canillaAActualizar, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> ToggleBajaAsync(int id, bool darDeBaja, DateTime? fechaBaja, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var canillaActual = await connection.QuerySingleOrDefaultAsync<Canilla>(
|
||||
"SELECT * FROM dbo.dist_dtCanillas WHERE Id_Canilla = @IdCanilla", new { IdCanilla = id }, transaction);
|
||||
if (canillaActual == null) throw new KeyNotFoundException("Canilla no encontrado para dar de baja/alta.");
|
||||
|
||||
const string sqlUpdate = "UPDATE dbo.dist_dtCanillas SET Baja = @Baja, FechaBaja = @FechaBaja WHERE Id_Canilla = @IdCanilla;";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtCanillas_H
|
||||
(Id_Canilla, Legajo, NomApe, Parada, Id_Zona, Accionista, Obs, Empresa, Baja, FechaBaja, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdCanilla, @Legajo, @NomApe, @Parada, @IdZona, @Accionista, @Obs, @Empresa, @BajaNueva, @FechaBajaNueva, @Id_Usuario, @FechaMod, @TipoModHist);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
canillaActual.IdCanilla, canillaActual.Legajo, canillaActual.NomApe, canillaActual.Parada, canillaActual.IdZona,
|
||||
canillaActual.Accionista, canillaActual.Obs, canillaActual.Empresa,
|
||||
BajaNueva = darDeBaja, FechaBajaNueva = (darDeBaja ? fechaBaja : null), // FechaBaja solo si se da de baja
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoModHist = (darDeBaja ? "Baja" : "Alta")
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, new { Baja = darDeBaja, FechaBaja = (darDeBaja ? fechaBaja : null), IdCanilla = id }, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class DistribuidorRepository : IDistribuidorRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<DistribuidorRepository> _logger;
|
||||
|
||||
public DistribuidorRepository(DbConnectionFactory connectionFactory, ILogger<DistribuidorRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<(Distribuidor Distribuidor, string? NombreZona)>> GetAllAsync(string? nombreFilter, string? nroDocFilter)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder(@"
|
||||
SELECT d.*, z.Nombre AS NombreZona
|
||||
FROM dbo.dist_dtDistribuidores d
|
||||
LEFT JOIN dbo.dist_dtZonas z ON d.Id_Zona = z.Id_Zona
|
||||
WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(nombreFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND d.Nombre LIKE @Nombre");
|
||||
parameters.Add("Nombre", $"%{nombreFilter}%");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(nroDocFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND d.NroDoc LIKE @NroDoc");
|
||||
parameters.Add("NroDoc", $"%{nroDocFilter}%");
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY d.Nombre;");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Distribuidor, string, (Distribuidor, string?)>(
|
||||
sqlBuilder.ToString(),
|
||||
(dist, zona) => (dist, zona),
|
||||
parameters,
|
||||
splitOn: "NombreZona"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Distribuidores.");
|
||||
return Enumerable.Empty<(Distribuidor, string?)>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(Distribuidor? Distribuidor, string? NombreZona)> GetByIdAsync(int id)
|
||||
{
|
||||
const string sql = @"
|
||||
SELECT d.*, z.Nombre AS NombreZona
|
||||
FROM dbo.dist_dtDistribuidores d
|
||||
LEFT JOIN dbo.dist_dtZonas z ON d.Id_Zona = z.Id_Zona
|
||||
WHERE d.Id_Distribuidor = @Id";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var result = await connection.QueryAsync<Distribuidor, string, (Distribuidor, string?)>(
|
||||
sql,
|
||||
(dist, zona) => (dist, zona),
|
||||
new { Id = id },
|
||||
splitOn: "NombreZona"
|
||||
);
|
||||
return result.SingleOrDefault();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Distribuidor por ID: {IdDistribuidor}", id);
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Distribuidor?> GetByIdSimpleAsync(int id)
|
||||
{
|
||||
const string sql = "SELECT * FROM dbo.dist_dtDistribuidores WHERE Id_Distribuidor = @Id";
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<Distribuidor>(sql, new { Id = id });
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsByNroDocAsync(string nroDoc, int? excludeIdDistribuidor = null)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.dist_dtDistribuidores WHERE NroDoc = @NroDoc");
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("NroDoc", nroDoc);
|
||||
if (excludeIdDistribuidor.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id_Distribuidor != @ExcludeId");
|
||||
parameters.Add("ExcludeId", excludeIdDistribuidor.Value);
|
||||
}
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.ExecuteScalarAsync<bool>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
public async Task<bool> ExistsByNameAsync(string nombre, int? excludeIdDistribuidor = null)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.dist_dtDistribuidores WHERE Nombre = @Nombre");
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("Nombre", nombre);
|
||||
if (excludeIdDistribuidor.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id_Distribuidor != @ExcludeId");
|
||||
parameters.Add("ExcludeId", excludeIdDistribuidor.Value);
|
||||
}
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.ExecuteScalarAsync<bool>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
|
||||
public async Task<bool> IsInUseAsync(int id)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
string[] checkQueries = {
|
||||
"SELECT TOP 1 1 FROM dbo.dist_EntradasSalidas WHERE Id_Distribuidor = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.cue_PagosDistribuidor WHERE Id_Distribuidor = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.dist_PorcPago WHERE Id_Distribuidor = @Id"
|
||||
};
|
||||
foreach (var query in checkQueries)
|
||||
{
|
||||
if (await connection.ExecuteScalarAsync<int?>(query, new { Id = id }) == 1) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public async Task<Distribuidor?> CreateAsync(Distribuidor nuevoDistribuidor, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
const string sqlInsert = @"
|
||||
INSERT INTO dbo.dist_dtDistribuidores (Nombre, Contacto, NroDoc, Id_Zona, Calle, Numero, Piso, Depto, Telefono, Email, Localidad)
|
||||
OUTPUT INSERTED.*
|
||||
VALUES (@Nombre, @Contacto, @NroDoc, @IdZona, @Calle, @Numero, @Piso, @Depto, @Telefono, @Email, @Localidad);";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtDistribuidores_H
|
||||
(Id_Distribuidor, Nombre, Contacto, NroDoc, Id_Zona, Calle, Numero, Piso, Depto, Telefono, Email, Localidad, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdDistribuidor, @Nombre, @Contacto, @NroDoc, @IdZona, @Calle, @Numero, @Piso, @Depto, @Telefono, @Email, @Localidad, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
var connection = transaction.Connection!;
|
||||
var inserted = await connection.QuerySingleAsync<Distribuidor>(sqlInsert, nuevoDistribuidor, transaction);
|
||||
if (inserted == null) throw new DataException("Error al crear distribuidor.");
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
inserted.IdDistribuidor, inserted.Nombre, inserted.Contacto, inserted.NroDoc, inserted.IdZona,
|
||||
inserted.Calle, inserted.Numero, inserted.Piso, inserted.Depto, inserted.Telefono, inserted.Email, inserted.Localidad,
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Creado"
|
||||
}, transaction);
|
||||
return inserted;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(Distribuidor distribuidorAActualizar, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var actual = await connection.QuerySingleOrDefaultAsync<Distribuidor>(
|
||||
"SELECT * FROM dbo.dist_dtDistribuidores WHERE Id_Distribuidor = @IdDistribuidor",
|
||||
new { distribuidorAActualizar.IdDistribuidor }, transaction);
|
||||
if (actual == null) throw new KeyNotFoundException("Distribuidor no encontrado.");
|
||||
|
||||
const string sqlUpdate = @"
|
||||
UPDATE dbo.dist_dtDistribuidores SET
|
||||
Nombre = @Nombre, Contacto = @Contacto, NroDoc = @NroDoc, Id_Zona = @IdZona, Calle = @Calle, Numero = @Numero,
|
||||
Piso = @Piso, Depto = @Depto, Telefono = @Telefono, Email = @Email, Localidad = @Localidad
|
||||
WHERE Id_Distribuidor = @IdDistribuidor;";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtDistribuidores_H
|
||||
(Id_Distribuidor, Nombre, Contacto, NroDoc, Id_Zona, Calle, Numero, Piso, Depto, Telefono, Email, Localidad, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdDistribuidor, @Nombre, @Contacto, @NroDoc, @IdZona, @Calle, @Numero, @Piso, @Depto, @Telefono, @Email, @Localidad, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdDistribuidor = actual.IdDistribuidor, Nombre = actual.Nombre, Contacto = actual.Contacto, NroDoc = actual.NroDoc, IdZona = actual.IdZona,
|
||||
Calle = actual.Calle, Numero = actual.Numero, Piso = actual.Piso, Depto = actual.Depto, Telefono = actual.Telefono, Email = actual.Email, Localidad = actual.Localidad,
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Actualizado"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, distribuidorAActualizar, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var actual = await connection.QuerySingleOrDefaultAsync<Distribuidor>(
|
||||
"SELECT * FROM dbo.dist_dtDistribuidores WHERE Id_Distribuidor = @Id", new { Id = id }, transaction);
|
||||
if (actual == null) throw new KeyNotFoundException("Distribuidor no encontrado.");
|
||||
|
||||
const string sqlDelete = "DELETE FROM dbo.dist_dtDistribuidores WHERE Id_Distribuidor = @Id";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtDistribuidores_H
|
||||
(Id_Distribuidor, Nombre, Contacto, NroDoc, Id_Zona, Calle, Numero, Piso, Depto, Telefono, Email, Localidad, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdDistribuidor, @Nombre, @Contacto, @NroDoc, @IdZona, @Calle, @Numero, @Piso, @Depto, @Telefono, @Email, @Localidad, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdDistribuidor = actual.IdDistribuidor, actual.Nombre, actual.Contacto, actual.NroDoc, actual.IdZona,
|
||||
actual.Calle, actual.Numero, actual.Piso, actual.Depto, actual.Telefono, actual.Email, actual.Localidad,
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Eliminado"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface ICanillaRepository
|
||||
{
|
||||
Task<IEnumerable<(Canilla Canilla, string NombreZona, string NombreEmpresa)>> GetAllAsync(string? nomApeFilter, int? legajoFilter, bool? soloActivos);
|
||||
Task<(Canilla? Canilla, string? NombreZona, string? NombreEmpresa)> GetByIdAsync(int id);
|
||||
Task<Canilla?> GetByIdSimpleAsync(int id); // Para obtener solo la entidad Canilla
|
||||
Task<Canilla?> CreateAsync(Canilla nuevoCanilla, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> UpdateAsync(Canilla canillaAActualizar, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> ToggleBajaAsync(int id, bool darDeBaja, DateTime? fechaBaja, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> ExistsByLegajoAsync(int legajo, int? excludeIdCanilla = null);
|
||||
// IsInUse no es tan directo, ya que las liquidaciones se marcan. Se podría verificar dist_EntradasSalidasCanillas no liquidadas.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface IDistribuidorRepository
|
||||
{
|
||||
Task<IEnumerable<(Distribuidor Distribuidor, string? NombreZona)>> GetAllAsync(string? nombreFilter, string? nroDocFilter);
|
||||
Task<(Distribuidor? Distribuidor, string? NombreZona)> GetByIdAsync(int id);
|
||||
Task<Distribuidor?> GetByIdSimpleAsync(int id); // Para uso interno en el servicio
|
||||
Task<Distribuidor?> CreateAsync(Distribuidor nuevoDistribuidor, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> UpdateAsync(Distribuidor distribuidorAActualizar, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> ExistsByNroDocAsync(string nroDoc, int? excludeIdDistribuidor = null);
|
||||
Task<bool> ExistsByNameAsync(string nombre, int? excludeIdDistribuidor = null);
|
||||
Task<bool> IsInUseAsync(int id); // Verificar en dist_EntradasSalidas, cue_PagosDistribuidor, dist_PorcPago
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface IOtroDestinoRepository
|
||||
{
|
||||
Task<IEnumerable<OtroDestino>> GetAllAsync(string? nombreFilter);
|
||||
Task<OtroDestino?> GetByIdAsync(int id);
|
||||
Task<OtroDestino?> CreateAsync(OtroDestino nuevoDestino, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> UpdateAsync(OtroDestino destinoAActualizar, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null);
|
||||
Task<bool> IsInUseAsync(int id); // Verificar si se usa en dist_SalidasOtrosDestinos
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface IPorcMonCanillaRepository
|
||||
{
|
||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface IPorcPagoRepository {
|
||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface IPrecioRepository
|
||||
{
|
||||
Task<IEnumerable<Precio>> GetByPublicacionIdAsync(int idPublicacion);
|
||||
Task<Precio?> GetByIdAsync(int idPrecio);
|
||||
Task<Precio?> GetActiveByPublicacionAndDateAsync(int idPublicacion, DateTime fecha, IDbTransaction? transaction = null);
|
||||
Task<Precio?> CreateAsync(Precio nuevoPrecio, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> UpdateAsync(Precio precioAActualizar, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> DeleteAsync(int idPrecio, int idUsuario, IDbTransaction transaction);
|
||||
// MODIFICADO: Añadir idUsuarioAuditoria
|
||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
||||
Task<Precio?> GetPreviousActivePriceAsync(int idPublicacion, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface IPubliSeccionRepository
|
||||
{
|
||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface IPublicacionRepository
|
||||
{
|
||||
Task<IEnumerable<(Publicacion Publicacion, string NombreEmpresa)>> GetAllAsync(string? nombreFilter, int? idEmpresaFilter, bool? soloHabilitadas);
|
||||
Task<(Publicacion? Publicacion, string? NombreEmpresa)> GetByIdAsync(int id);
|
||||
Task<Publicacion?> GetByIdSimpleAsync(int id); // Para uso interno del servicio
|
||||
Task<Publicacion?> CreateAsync(Publicacion nuevaPublicacion, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> UpdateAsync(Publicacion publicacionAActualizar, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction); // Borrado físico con historial
|
||||
Task<bool> ExistsByNameAndEmpresaAsync(string nombre, int idEmpresa, int? excludeIdPublicacion = null);
|
||||
Task<bool> IsInUseAsync(int id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface IRecargoZonaRepository
|
||||
{
|
||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class OtroDestinoRepository : IOtroDestinoRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<OtroDestinoRepository> _logger;
|
||||
|
||||
public OtroDestinoRepository(DbConnectionFactory connectionFactory, ILogger<OtroDestinoRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<OtroDestino>> GetAllAsync(string? nombreFilter)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT Id_Destino AS IdDestino, Nombre, Obs FROM dbo.dist_dtOtrosDestinos WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(nombreFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND Nombre LIKE @NombreFilter");
|
||||
parameters.Add("NombreFilter", $"%{nombreFilter}%");
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY Nombre;");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<OtroDestino>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Otros Destinos. Filtro: {Nombre}", nombreFilter);
|
||||
return Enumerable.Empty<OtroDestino>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<OtroDestino?> GetByIdAsync(int id)
|
||||
{
|
||||
const string sql = "SELECT Id_Destino AS IdDestino, Nombre, Obs FROM dbo.dist_dtOtrosDestinos WHERE Id_Destino = @Id";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<OtroDestino>(sql, new { Id = id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Otro Destino por ID: {IdDestino}", id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.dist_dtOtrosDestinos WHERE Nombre = @Nombre");
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("Nombre", nombre);
|
||||
|
||||
if (excludeId.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id_Destino != @ExcludeId");
|
||||
parameters.Add("ExcludeId", excludeId.Value);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var count = await connection.ExecuteScalarAsync<int>(sqlBuilder.ToString(), parameters);
|
||||
return count > 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en ExistsByNameAsync para Otro Destino con nombre: {Nombre}", nombre);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsInUseAsync(int id)
|
||||
{
|
||||
const string sqlCheckSalidas = "SELECT TOP 1 1 FROM dbo.dist_SalidasOtrosDestinos WHERE Id_Destino = @IdDestino";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var inUse = await connection.ExecuteScalarAsync<int?>(sqlCheckSalidas, new { IdDestino = id });
|
||||
return inUse.HasValue && inUse.Value == 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en IsInUseAsync para Otro Destino ID: {IdDestino}", id);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<OtroDestino?> CreateAsync(OtroDestino nuevoDestino, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
const string sqlInsert = @"
|
||||
INSERT INTO dbo.dist_dtOtrosDestinos (Nombre, Obs)
|
||||
OUTPUT INSERTED.Id_Destino AS IdDestino, INSERTED.Nombre, INSERTED.Obs
|
||||
VALUES (@Nombre, @Obs);";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtOtrosDestinos_H (Id_Destino, Nombre, Obs, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdDestino, @Nombre, @Obs, @IdUsuario, @FechaMod, @TipoMod);";
|
||||
|
||||
var connection = transaction.Connection!;
|
||||
var insertedDestino = await connection.QuerySingleAsync<OtroDestino>(sqlInsert, nuevoDestino, transaction);
|
||||
|
||||
if (insertedDestino == null || insertedDestino.IdDestino <= 0)
|
||||
{
|
||||
throw new DataException("No se pudo obtener el ID del otro destino insertado.");
|
||||
}
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdDestino = insertedDestino.IdDestino,
|
||||
insertedDestino.Nombre,
|
||||
insertedDestino.Obs,
|
||||
IdUsuario = idUsuario,
|
||||
FechaMod = DateTime.Now,
|
||||
TipoMod = "Insertada"
|
||||
}, transaction);
|
||||
return insertedDestino;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(OtroDestino destinoAActualizar, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var destinoActual = await connection.QuerySingleOrDefaultAsync<OtroDestino>(
|
||||
"SELECT Id_Destino AS IdDestino, Nombre, Obs FROM dbo.dist_dtOtrosDestinos WHERE Id_Destino = @Id",
|
||||
new { Id = destinoAActualizar.IdDestino }, transaction);
|
||||
|
||||
if (destinoActual == null) throw new KeyNotFoundException($"Otro Destino con ID {destinoAActualizar.IdDestino} no encontrado.");
|
||||
|
||||
const string sqlUpdate = "UPDATE dbo.dist_dtOtrosDestinos SET Nombre = @Nombre, Obs = @Obs WHERE Id_Destino = @IdDestino;";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtOtrosDestinos_H (Id_Destino, Nombre, Obs, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdDestino, @NombreActual, @ObsActual, @IdUsuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdDestino = destinoActual.IdDestino,
|
||||
NombreActual = destinoActual.Nombre,
|
||||
ObsActual = destinoActual.Obs,
|
||||
IdUsuario = idUsuario,
|
||||
FechaMod = DateTime.Now,
|
||||
TipoMod = "Modificada"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, destinoAActualizar, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var destinoActual = await connection.QuerySingleOrDefaultAsync<OtroDestino>(
|
||||
"SELECT Id_Destino AS IdDestino, Nombre, Obs FROM dbo.dist_dtOtrosDestinos WHERE Id_Destino = @Id",
|
||||
new { Id = id }, transaction);
|
||||
|
||||
if (destinoActual == null) throw new KeyNotFoundException($"Otro Destino con ID {id} no encontrado.");
|
||||
|
||||
const string sqlDelete = "DELETE FROM dbo.dist_dtOtrosDestinos WHERE Id_Destino = @Id";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtOtrosDestinos_H (Id_Destino, Nombre, Obs, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdDestino, @Nombre, @Obs, @IdUsuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdDestino = destinoActual.IdDestino,
|
||||
destinoActual.Nombre,
|
||||
destinoActual.Obs,
|
||||
IdUsuario = idUsuario,
|
||||
FechaMod = DateTime.Now,
|
||||
TipoMod = "Eliminada"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Dapper;
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System;
|
||||
using System.Linq;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class PorcMonCanillaRepository : IPorcMonCanillaRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _cf; private readonly ILogger<PorcMonCanillaRepository> _log;
|
||||
public PorcMonCanillaRepository(DbConnectionFactory cf, ILogger<PorcMonCanillaRepository> log) { _cf = cf; _log = log; }
|
||||
|
||||
public async Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction)
|
||||
{
|
||||
const string selectSql = "SELECT * FROM dbo.dist_PorcMonPagoCanilla WHERE Id_Publicacion = @IdPublicacion";
|
||||
var itemsToDelete = await transaction.Connection!.QueryAsync<PorcMonCanilla>(selectSql, new { IdPublicacion = idPublicacion }, transaction);
|
||||
|
||||
if (itemsToDelete.Any())
|
||||
{
|
||||
const string insertHistoricoSql = @"
|
||||
INSERT INTO dbo.dist_PorcMonPagoCanilla_H (Id_PorcMon, Id_Publicacion, Id_Canilla, VigenciaD, VigenciaH, PorcMon, EsPorcentaje, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@Id_PorcMon, @Id_Publicacion, @Id_Canilla, @VigenciaD, @VigenciaH, @PorcMon, @EsPorcentaje, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
foreach (var item in itemsToDelete)
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(insertHistoricoSql, new
|
||||
{
|
||||
Id_PorcMon = item.IdPorcMon, // Mapeo de propiedad a parámetro SQL
|
||||
Id_Publicacion = item.IdPublicacion,
|
||||
Id_Canilla = item.IdCanilla,
|
||||
item.VigenciaD,
|
||||
item.VigenciaH,
|
||||
item.PorcMon,
|
||||
item.EsPorcentaje,
|
||||
Id_Usuario = idUsuarioAuditoria,
|
||||
FechaMod = DateTime.Now,
|
||||
TipoMod = "Eliminado (Cascada)"
|
||||
}, transaction);
|
||||
}
|
||||
}
|
||||
|
||||
const string deleteSql = "DELETE FROM dbo.dist_PorcMonPagoCanilla WHERE Id_Publicacion = @IdPublicacion";
|
||||
try
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(deleteSql, new { IdPublicacion = idPublicacion }, transaction);
|
||||
return true;
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
_log.LogError(e, "Error al eliminar PorcMonCanilla por IdPublicacion: {idPublicacion}", idPublicacion);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using Dapper; using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System;
|
||||
using System.Linq;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class PorcPagoRepository : IPorcPagoRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _cf; private readonly ILogger<PorcPagoRepository> _log;
|
||||
public PorcPagoRepository(DbConnectionFactory cf, ILogger<PorcPagoRepository> log) { _cf = cf; _log = log; }
|
||||
|
||||
public async Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction)
|
||||
{
|
||||
const string selectSql = "SELECT * FROM dbo.dist_PorcPago WHERE Id_Publicacion = @IdPublicacion";
|
||||
var itemsToDelete = await transaction.Connection!.QueryAsync<PorcPago>(selectSql, new { IdPublicacion = idPublicacion }, transaction);
|
||||
|
||||
if (itemsToDelete.Any())
|
||||
{
|
||||
const string insertHistoricoSql = @"
|
||||
INSERT INTO dbo.dist_PorcPago_H (Id_Porcentaje, Id_Publicacion, Id_Distribuidor, VigenciaD, VigenciaH, Porcentaje, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPorcentaje, @IdPublicacion, @IdDistribuidor, @VigenciaD, @VigenciaH, @Porcentaje, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
foreach (var item in itemsToDelete)
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(insertHistoricoSql, new
|
||||
{
|
||||
item.IdPorcentaje, // Mapea a @Id_Porcentaje si usas nombres con _ en SQL
|
||||
item.IdPublicacion,
|
||||
item.IdDistribuidor,
|
||||
item.VigenciaD,
|
||||
item.VigenciaH,
|
||||
item.Porcentaje,
|
||||
Id_Usuario = idUsuarioAuditoria,
|
||||
FechaMod = DateTime.Now,
|
||||
TipoMod = "Eliminado (Cascada)"
|
||||
}, transaction);
|
||||
}
|
||||
}
|
||||
|
||||
const string deleteSql = "DELETE FROM dbo.dist_PorcPago WHERE Id_Publicacion = @IdPublicacion";
|
||||
try
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(deleteSql, new { IdPublicacion = idPublicacion }, transaction);
|
||||
return true;
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
_log.LogError(e, "Error al eliminar PorcPago por IdPublicacion: {idPublicacion}", idPublicacion);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class PrecioRepository : IPrecioRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<PrecioRepository> _logger;
|
||||
|
||||
public PrecioRepository(DbConnectionFactory connectionFactory, ILogger<PrecioRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Precio>> GetByPublicacionIdAsync(int idPublicacion)
|
||||
{
|
||||
const string sql = "SELECT * FROM dbo.dist_Precios WHERE Id_Publicacion = @IdPublicacion ORDER BY VigenciaD DESC";
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Precio>(sql, new { IdPublicacion = idPublicacion });
|
||||
}
|
||||
|
||||
public async Task<Precio?> GetByIdAsync(int idPrecio)
|
||||
{
|
||||
const string sql = "SELECT * FROM dbo.dist_Precios WHERE Id_Precio = @IdPrecio";
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<Precio>(sql, new { IdPrecio = idPrecio });
|
||||
}
|
||||
|
||||
public async Task<Precio?> GetActiveByPublicacionAndDateAsync(int idPublicacion, DateTime fecha, IDbTransaction? transaction = null)
|
||||
{
|
||||
// Obtiene el precio vigente para una publicación en una fecha específica
|
||||
const string sql = @"
|
||||
SELECT TOP 1 * FROM dbo.dist_Precios
|
||||
WHERE Id_Publicacion = @IdPublicacion
|
||||
AND VigenciaD <= @Fecha
|
||||
AND (VigenciaH IS NULL OR VigenciaH >= @Fecha)
|
||||
ORDER BY VigenciaD DESC;"; // Por si hay solapamientos incorrectos, tomar el más reciente
|
||||
|
||||
var cn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||
return await cn.QuerySingleOrDefaultAsync<Precio>(sql, new { IdPublicacion = idPublicacion, Fecha = fecha }, transaction);
|
||||
}
|
||||
|
||||
public async Task<Precio?> GetPreviousActivePriceAsync(int idPublicacion, DateTime vigenciaDNuevo, IDbTransaction transaction)
|
||||
{
|
||||
// Busca el último precio activo antes de la vigenciaD del nuevo precio, que no tenga VigenciaH o cuya VigenciaH sea mayor o igual a la nueva VigenciaD - 1 día
|
||||
// y que no sea el mismo periodo que se está por crear/actualizar (si tuviera un ID).
|
||||
const string sql = @"
|
||||
SELECT TOP 1 *
|
||||
FROM dbo.dist_Precios
|
||||
WHERE Id_Publicacion = @IdPublicacion
|
||||
AND VigenciaD < @VigenciaDNuevo
|
||||
AND VigenciaH IS NULL
|
||||
ORDER BY VigenciaD DESC;";
|
||||
return await transaction.Connection!.QuerySingleOrDefaultAsync<Precio>(sql, new { IdPublicacion = idPublicacion, VigenciaDNuevo = vigenciaDNuevo }, transaction);
|
||||
}
|
||||
|
||||
|
||||
public async Task<Precio?> CreateAsync(Precio nuevoPrecio, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
const string sqlInsert = @"
|
||||
INSERT INTO dbo.dist_Precios (Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo)
|
||||
OUTPUT INSERTED.*
|
||||
VALUES (@IdPublicacion, @VigenciaD, @VigenciaH, @Lunes, @Martes, @Miercoles, @Jueves, @Viernes, @Sabado, @Domingo);";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_Precios_H
|
||||
(Id_Precio, Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPrecio, @IdPublicacion, @VigenciaD, @VigenciaH, @Lunes, @Martes, @Miercoles, @Jueves, @Viernes, @Sabado, @Domingo, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
var inserted = await transaction.Connection!.QuerySingleAsync<Precio>(sqlInsert, nuevoPrecio, transaction);
|
||||
if (inserted == null) throw new DataException("Error al crear precio.");
|
||||
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
inserted.IdPrecio, inserted.IdPublicacion, inserted.VigenciaD, inserted.VigenciaH,
|
||||
inserted.Lunes, inserted.Martes, inserted.Miercoles, inserted.Jueves, inserted.Viernes, inserted.Sabado, inserted.Domingo,
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Creado"
|
||||
}, transaction);
|
||||
return inserted;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(Precio precioAActualizar, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<Precio>(
|
||||
"SELECT * FROM dbo.dist_Precios WHERE Id_Precio = @IdPrecio",
|
||||
new { precioAActualizar.IdPrecio }, transaction);
|
||||
if (actual == null) throw new KeyNotFoundException("Precio no encontrado.");
|
||||
|
||||
const string sqlUpdate = @"
|
||||
UPDATE dbo.dist_Precios SET
|
||||
VigenciaH = @VigenciaH, Lunes = @Lunes, Martes = @Martes, Miercoles = @Miercoles,
|
||||
Jueves = @Jueves, Viernes = @Viernes, Sabado = @Sabado, Domingo = @Domingo
|
||||
-- No se permite cambiar IdPublicacion ni VigenciaD de un registro de precio existente
|
||||
WHERE Id_Precio = @IdPrecio;";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_Precios_H
|
||||
(Id_Precio, Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPrecio, @IdPublicacion, @VigenciaD, @VigenciaH, @Lunes, @Martes, @Miercoles, @Jueves, @Viernes, @Sabado, @Domingo, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
actual.IdPrecio, actual.IdPublicacion, actual.VigenciaD, // VigenciaD actual para el historial
|
||||
VigenciaH = actual.VigenciaH, // VigenciaH actual para el historial
|
||||
Lunes = actual.Lunes, Martes = actual.Martes, Miercoles = actual.Miercoles, Jueves = actual.Jueves,
|
||||
Viernes = actual.Viernes, Sabado = actual.Sabado, Domingo = actual.Domingo, // Precios actuales para el historial
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Actualizado" // O "Cerrado" si solo se actualiza VigenciaH
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, precioAActualizar, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(int idPrecio, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<Precio>(
|
||||
"SELECT * FROM dbo.dist_Precios WHERE Id_Precio = @IdPrecio", new { IdPrecio = idPrecio }, transaction);
|
||||
if (actual == null) throw new KeyNotFoundException("Precio no encontrado para eliminar.");
|
||||
|
||||
const string sqlDelete = "DELETE FROM dbo.dist_Precios WHERE Id_Precio = @IdPrecio";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_Precios_H
|
||||
(Id_Precio, Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPrecio, @IdPublicacion, @VigenciaD, @VigenciaH, @Lunes, @Martes, @Miercoles, @Jueves, @Viernes, @Sabado, @Domingo, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
actual.IdPrecio, actual.IdPublicacion, actual.VigenciaD, actual.VigenciaH,
|
||||
actual.Lunes, actual.Martes, actual.Miercoles, actual.Jueves, actual.Viernes, actual.Sabado, actual.Domingo,
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Eliminado"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete, new { IdPrecio = idPrecio }, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction) // MODIFICADO: Recibe idUsuarioAuditoria
|
||||
{
|
||||
const string selectPrecios = "SELECT * FROM dbo.dist_Precios WHERE Id_Publicacion = @IdPublicacion";
|
||||
var preciosAEliminar = await transaction.Connection!.QueryAsync<Precio>(selectPrecios, new { IdPublicacion = idPublicacion }, transaction);
|
||||
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_Precios_H
|
||||
(Id_Precio, Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPrecio, @IdPublicacion, @VigenciaD, @VigenciaH, @Lunes, @Martes, @Miercoles, @Jueves, @Viernes, @Sabado, @Domingo, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
foreach (var precio in preciosAEliminar)
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
precio.IdPrecio, precio.IdPublicacion, precio.VigenciaD, precio.VigenciaH,
|
||||
precio.Lunes, precio.Martes, precio.Miercoles, precio.Jueves, precio.Viernes, precio.Sabado, precio.Domingo,
|
||||
Id_Usuario = idUsuarioAuditoria, // MODIFICADO: Usar el idUsuarioAuditoria pasado
|
||||
FechaMod = DateTime.Now, TipoMod = "Eliminado (Cascada)"
|
||||
}, transaction);
|
||||
}
|
||||
|
||||
const string sql = "DELETE FROM dbo.dist_Precios WHERE Id_Publicacion = @IdPublicacion";
|
||||
try
|
||||
{
|
||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sql, new { IdPublicacion = idPublicacion }, transaction: transaction);
|
||||
// No necesitamos devolver rowsAffected >= 0 si la lógica del servicio ya valida si debe haber registros
|
||||
return true; // Indica que la operación de borrado (incluyendo 0 filas) se intentó
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al eliminar precios por IdPublicacion: {IdPublicacion}", idPublicacion);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using Dapper;
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System;
|
||||
using System.Linq;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class PubliSeccionRepository : IPubliSeccionRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _cf; private readonly ILogger<PubliSeccionRepository> _log;
|
||||
public PubliSeccionRepository(DbConnectionFactory cf, ILogger<PubliSeccionRepository> log) { _cf = cf; _log = log; }
|
||||
|
||||
public async Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction)
|
||||
{
|
||||
const string selectSql = "SELECT * FROM dbo.dist_dtPubliSecciones WHERE Id_Publicacion = @IdPublicacion";
|
||||
var itemsToDelete = await transaction.Connection!.QueryAsync<PubliSeccion>(selectSql, new { IdPublicacion = idPublicacion }, transaction);
|
||||
|
||||
if (itemsToDelete.Any())
|
||||
{
|
||||
const string insertHistoricoSql = @"
|
||||
INSERT INTO dbo.dist_dtPubliSecciones_H (Id_Seccion, Id_Publicacion, Nombre, Estado, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@Id_Seccion, @Id_Publicacion, @Nombre, @Estado, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
foreach (var item in itemsToDelete)
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(insertHistoricoSql, new
|
||||
{
|
||||
Id_Seccion = item.IdSeccion, // Mapeo de propiedad a parámetro SQL
|
||||
Id_Publicacion = item.IdPublicacion,
|
||||
item.Nombre,
|
||||
item.Estado,
|
||||
Id_Usuario = idUsuarioAuditoria,
|
||||
FechaMod = DateTime.Now,
|
||||
TipoMod = "Eliminado (Cascada)"
|
||||
}, transaction);
|
||||
}
|
||||
}
|
||||
|
||||
const string deleteSql = "DELETE FROM dbo.dist_dtPubliSecciones WHERE Id_Publicacion = @IdPublicacion";
|
||||
try
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(deleteSql, new { IdPublicacion = idPublicacion }, transaction);
|
||||
return true;
|
||||
}
|
||||
catch (System.Exception e)
|
||||
{
|
||||
_log.LogError(e, "Error al eliminar PubliSecciones por IdPublicacion: {idPublicacion}", idPublicacion);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class PublicacionRepository : IPublicacionRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<PublicacionRepository> _logger;
|
||||
|
||||
public PublicacionRepository(DbConnectionFactory connectionFactory, ILogger<PublicacionRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<(Publicacion Publicacion, string NombreEmpresa)>> GetAllAsync(string? nombreFilter, int? idEmpresaFilter, bool? soloHabilitadas)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder(@"
|
||||
SELECT p.*, e.Nombre AS NombreEmpresa
|
||||
FROM dbo.dist_dtPublicaciones p
|
||||
INNER JOIN dbo.dist_dtEmpresas e ON p.Id_Empresa = e.Id_Empresa
|
||||
WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (soloHabilitadas.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(soloHabilitadas.Value ? " AND p.Habilitada = 1" : " AND (p.Habilitada = 0 OR p.Habilitada IS NULL)");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(nombreFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND p.Nombre LIKE @Nombre");
|
||||
parameters.Add("Nombre", $"%{nombreFilter}%");
|
||||
}
|
||||
if (idEmpresaFilter.HasValue && idEmpresaFilter > 0)
|
||||
{
|
||||
sqlBuilder.Append(" AND p.Id_Empresa = @IdEmpresa");
|
||||
parameters.Add("IdEmpresa", idEmpresaFilter.Value);
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY p.Nombre;");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Publicacion, string, (Publicacion, string)>(
|
||||
sqlBuilder.ToString(),
|
||||
(pub, empNombre) => (pub, empNombre),
|
||||
parameters,
|
||||
splitOn: "NombreEmpresa"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todas las Publicaciones.");
|
||||
return Enumerable.Empty<(Publicacion, string)>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(Publicacion? Publicacion, string? NombreEmpresa)> GetByIdAsync(int id)
|
||||
{
|
||||
const string sql = @"
|
||||
SELECT p.*, e.Nombre AS NombreEmpresa
|
||||
FROM dbo.dist_dtPublicaciones p
|
||||
INNER JOIN dbo.dist_dtEmpresas e ON p.Id_Empresa = e.Id_Empresa
|
||||
WHERE p.Id_Publicacion = @Id";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var result = await connection.QueryAsync<Publicacion, string, (Publicacion, string)>(
|
||||
sql,
|
||||
(pub, empNombre) => (pub, empNombre),
|
||||
new { Id = id },
|
||||
splitOn: "NombreEmpresa"
|
||||
);
|
||||
return result.SingleOrDefault();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Publicación por ID: {IdPublicacion}", id);
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
public async Task<Publicacion?> GetByIdSimpleAsync(int id)
|
||||
{
|
||||
const string sql = "SELECT * FROM dbo.dist_dtPublicaciones WHERE Id_Publicacion = @Id";
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<Publicacion>(sql, new { Id = id });
|
||||
}
|
||||
|
||||
|
||||
public async Task<bool> ExistsByNameAndEmpresaAsync(string nombre, int idEmpresa, int? excludeIdPublicacion = null)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.dist_dtPublicaciones WHERE Nombre = @Nombre AND Id_Empresa = @IdEmpresa");
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("Nombre", nombre);
|
||||
parameters.Add("IdEmpresa", idEmpresa);
|
||||
if (excludeIdPublicacion.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id_Publicacion != @ExcludeId");
|
||||
parameters.Add("ExcludeId", excludeIdPublicacion.Value);
|
||||
}
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.ExecuteScalarAsync<bool>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
|
||||
public async Task<bool> IsInUseAsync(int id)
|
||||
{
|
||||
// Verificar en tablas relacionadas: dist_EntradasSalidas, dist_EntradasSalidasCanillas,
|
||||
// dist_Precios, dist_RecargoZona, dist_PorcPago, dist_PorcMonPagoCanilla, dist_dtPubliSecciones,
|
||||
// bob_RegPublicaciones, bob_StockBobinas (donde Id_Publicacion se usa)
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
string[] checkQueries = {
|
||||
"SELECT TOP 1 1 FROM dbo.dist_EntradasSalidas WHERE Id_Publicacion = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.dist_EntradasSalidasCanillas WHERE Id_Publicacion = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.dist_Precios WHERE Id_Publicacion = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.dist_RecargoZona WHERE Id_Publicacion = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.dist_PorcPago WHERE Id_Publicacion = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.dist_PorcMonPagoCanilla WHERE Id_Publicacion = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.dist_dtPubliSecciones WHERE Id_Publicacion = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.bob_RegPublicaciones WHERE Id_Publicacion = @Id",
|
||||
"SELECT TOP 1 1 FROM dbo.bob_StockBobinas WHERE Id_Publicacion = @Id"
|
||||
};
|
||||
foreach (var query in checkQueries)
|
||||
{
|
||||
if (await connection.ExecuteScalarAsync<int?>(query, new { Id = id }) == 1) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public async Task<Publicacion?> CreateAsync(Publicacion nuevaPublicacion, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
// Habilitada por defecto es true si es null en el modelo
|
||||
nuevaPublicacion.Habilitada ??= true;
|
||||
|
||||
const string sqlInsert = @"
|
||||
INSERT INTO dbo.dist_dtPublicaciones (Nombre, Observacion, Id_Empresa, CtrlDevoluciones, Habilitada)
|
||||
OUTPUT INSERTED.*
|
||||
VALUES (@Nombre, @Observacion, @IdEmpresa, @CtrlDevoluciones, @Habilitada);";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtPublicaciones_H
|
||||
(Id_Publicacion, Nombre, Observacion, Id_Empresa, Habilitada, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPublicacion, @Nombre, @Observacion, @IdEmpresa, @Habilitada, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
var connection = transaction.Connection!;
|
||||
var inserted = await connection.QuerySingleAsync<Publicacion>(sqlInsert, nuevaPublicacion, transaction);
|
||||
if (inserted == null) throw new DataException("Error al crear la publicación.");
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
inserted.IdPublicacion, inserted.Nombre, inserted.Observacion, inserted.IdEmpresa,
|
||||
Habilitada = inserted.Habilitada ?? true, // Asegurar que no sea null para el historial
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Creada"
|
||||
}, transaction);
|
||||
return inserted;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(Publicacion publicacionAActualizar, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var actual = await connection.QuerySingleOrDefaultAsync<Publicacion>(
|
||||
"SELECT * FROM dbo.dist_dtPublicaciones WHERE Id_Publicacion = @IdPublicacion",
|
||||
new { publicacionAActualizar.IdPublicacion }, transaction);
|
||||
if (actual == null) throw new KeyNotFoundException("Publicación no encontrada.");
|
||||
|
||||
publicacionAActualizar.Habilitada ??= true; // Asegurar que no sea null
|
||||
|
||||
const string sqlUpdate = @"
|
||||
UPDATE dbo.dist_dtPublicaciones SET
|
||||
Nombre = @Nombre, Observacion = @Observacion, Id_Empresa = @IdEmpresa,
|
||||
CtrlDevoluciones = @CtrlDevoluciones, Habilitada = @Habilitada
|
||||
WHERE Id_Publicacion = @IdPublicacion;";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtPublicaciones_H
|
||||
(Id_Publicacion, Nombre, Observacion, Id_Empresa, Habilitada, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPublicacion, @Nombre, @Observacion, @IdEmpresa, @Habilitada, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdPublicacion = actual.IdPublicacion, Nombre = actual.Nombre, Observacion = actual.Observacion,
|
||||
IdEmpresa = actual.IdEmpresa, Habilitada = actual.Habilitada ?? true,
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Actualizada"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, publicacionAActualizar, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var actual = await connection.QuerySingleOrDefaultAsync<Publicacion>(
|
||||
"SELECT * FROM dbo.dist_dtPublicaciones WHERE Id_Publicacion = @Id", new { Id = id }, transaction);
|
||||
if (actual == null) throw new KeyNotFoundException("Publicación no encontrada.");
|
||||
|
||||
const string sqlDelete = "DELETE FROM dbo.dist_dtPublicaciones WHERE Id_Publicacion = @Id";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_dtPublicaciones_H
|
||||
(Id_Publicacion, Nombre, Observacion, Id_Empresa, Habilitada, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPublicacion, @Nombre, @Observacion, @IdEmpresa, @Habilitada, @Id_Usuario, @FechaMod, @TipoMod);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdPublicacion = actual.IdPublicacion, actual.Nombre, actual.Observacion, actual.IdEmpresa,
|
||||
Habilitada = actual.Habilitada ?? true,
|
||||
Id_Usuario = idUsuario, FechaMod = DateTime.Now, TipoMod = "Eliminada"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// src/Data/Repositories/RecargoZonaRepository.cs
|
||||
using Dapper;
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using GestionIntegral.Api.Models.Distribucion; // Asegúrate que esta directiva using esté presente
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class RecargoZonaRepository : IRecargoZonaRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory; // _cf
|
||||
private readonly ILogger<RecargoZonaRepository> _logger; // _log
|
||||
|
||||
public RecargoZonaRepository(DbConnectionFactory connectionFactory, ILogger<RecargoZonaRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction)
|
||||
{
|
||||
// Obtener recargos para el historial
|
||||
const string selectRecargos = "SELECT * FROM dbo.dist_RecargoZona WHERE Id_Publicacion = @IdPublicacion";
|
||||
var recargosAEliminar = await transaction.Connection!.QueryAsync<RecargoZona>(selectRecargos, new { IdPublicacion = idPublicacion }, transaction);
|
||||
|
||||
// Asume que tienes una tabla dist_RecargoZona_H y un modelo RecargoZonaHistorico
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.dist_RecargoZona_H (Id_Recargo, Id_Publicacion, Id_Zona, VigenciaD, VigenciaH, Valor, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdRecargo, @IdPublicacion, @IdZona, @VigenciaD, @VigenciaH, @Valor, @Id_Usuario, @FechaMod, @TipoMod);"; // Nombres de parámetros corregidos
|
||||
|
||||
foreach (var recargo in recargosAEliminar)
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
// Mapear los campos de 'recargo' a los parámetros de sqlInsertHistorico
|
||||
recargo.IdRecargo, // Usar las propiedades del modelo RecargoZona
|
||||
recargo.IdPublicacion,
|
||||
recargo.IdZona,
|
||||
recargo.VigenciaD,
|
||||
recargo.VigenciaH,
|
||||
recargo.Valor,
|
||||
Id_Usuario = idUsuarioAuditoria, // Este es el parámetro esperado por la query
|
||||
FechaMod = DateTime.Now,
|
||||
TipoMod = "Eliminado (Cascada)"
|
||||
}, transaction);
|
||||
}
|
||||
|
||||
const string sql = "DELETE FROM dbo.dist_RecargoZona WHERE Id_Publicacion = @IdPublicacion";
|
||||
try
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(sql, new { IdPublicacion = idPublicacion }, transaction: transaction);
|
||||
return true; // Se intentó la operación
|
||||
}
|
||||
catch (System.Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al eliminar RecargosZona por IdPublicacion: {IdPublicacion}", idPublicacion);
|
||||
throw; // Re-lanzar para que la transacción padre haga rollback
|
||||
}
|
||||
}
|
||||
// Aquí irían otros métodos CRUD para RecargoZona si se gestionan individualmente.
|
||||
// Por ejemplo, GetByPublicacionId, Create, Update, Delete (para un recargo específico).
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models;
|
||||
using GestionIntegral.Api.Models.Usuarios;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Data
|
||||
namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
||||
{
|
||||
public class AuthRepository : IAuthRepository
|
||||
{
|
||||
@@ -1,6 +1,6 @@
|
||||
using GestionIntegral.Api.Models;
|
||||
using GestionIntegral.Api.Models.Usuarios;
|
||||
|
||||
namespace GestionIntegral.Api.Data
|
||||
namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
||||
{
|
||||
public interface IAuthRepository
|
||||
{
|
||||
@@ -0,0 +1,20 @@
|
||||
using GestionIntegral.Api.Models.Usuarios;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data; // Para IDbTransaction
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
||||
{
|
||||
public interface IPerfilRepository
|
||||
{
|
||||
Task<IEnumerable<Perfil>> GetAllAsync(string? nombreFilter);
|
||||
Task<Perfil?> GetByIdAsync(int id);
|
||||
Task<Perfil?> CreateAsync(Perfil nuevoPerfil, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> UpdateAsync(Perfil perfilAActualizar, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> ExistsByNameAsync(string nombrePerfil, int? excludeId = null);
|
||||
Task<bool> IsInUseAsync(int id);
|
||||
Task<IEnumerable<int>> GetPermisoIdsByPerfilIdAsync(int idPerfil);
|
||||
Task UpdatePermisosByPerfilIdAsync(int idPerfil, IEnumerable<int> nuevosPermisosIds, IDbTransaction transaction);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using GestionIntegral.Api.Models.Usuarios;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
||||
{
|
||||
public interface IPermisoRepository
|
||||
{
|
||||
Task<IEnumerable<Permiso>> GetAllAsync(string? moduloFilter, string? codAccFilter);
|
||||
Task<Permiso?> GetByIdAsync(int id);
|
||||
Task<Permiso?> CreateAsync(Permiso nuevoPermiso, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> UpdateAsync(Permiso permisoAActualizar, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
||||
Task<bool> ExistsByCodAccAsync(string codAcc, int? excludeId = null);
|
||||
Task<bool> IsInUseAsync(int id);
|
||||
Task<IEnumerable<Permiso>> GetPermisosByIdsAsync(IEnumerable<int> ids);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
using GestionIntegral.Api.Models.Usuarios; // Para Usuario
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
||||
{
|
||||
public interface IUsuarioRepository
|
||||
{
|
||||
Task<IEnumerable<Usuario>> GetAllAsync(string? userFilter, string? nombreFilter);
|
||||
Task<Usuario?> GetByIdAsync(int id);
|
||||
Task<Usuario?> GetByUsernameAsync(string username); // Ya existe en IAuthRepository, pero lo duplicamos para cohesión del CRUD
|
||||
Task<Usuario?> CreateAsync(Usuario nuevoUsuario, int idUsuarioCreador, IDbTransaction transaction);
|
||||
Task<bool> UpdateAsync(Usuario usuarioAActualizar, int idUsuarioModificador, IDbTransaction transaction);
|
||||
// DeleteAsync no es común para usuarios, se suelen deshabilitar.
|
||||
// Task<bool> DeleteAsync(int id, int idUsuarioModificador, IDbTransaction transaction);
|
||||
Task<bool> SetPasswordAsync(int userId, string newHash, string newSalt, bool debeCambiarClave, int idUsuarioModificador, IDbTransaction transaction);
|
||||
Task<bool> UserExistsAsync(string username, int? excludeId = null);
|
||||
|
||||
// Para el DTO de listado
|
||||
Task<IEnumerable<(Usuario Usuario, string NombrePerfil)>> GetAllWithProfileNameAsync(string? userFilter, string? nombreFilter);
|
||||
Task<(Usuario? Usuario, string? NombrePerfil)> GetByIdWithProfileNameAsync(int id);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models.Usuarios;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
||||
{
|
||||
public class PerfilRepository : IPerfilRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<PerfilRepository> _logger;
|
||||
|
||||
public PerfilRepository(DbConnectionFactory connectionFactory, ILogger<PerfilRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Perfil>> GetAllAsync(string? nombreFilter)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT id AS Id, perfil AS NombrePerfil, descPerfil AS Descripcion FROM dbo.gral_Perfiles WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(nombreFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND perfil LIKE @NombreFilter");
|
||||
parameters.Add("NombreFilter", $"%{nombreFilter}%");
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY perfil;");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Perfil>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Perfiles. Filtro: {NombreFilter}", nombreFilter);
|
||||
return Enumerable.Empty<Perfil>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Perfil?> GetByIdAsync(int id)
|
||||
{
|
||||
const string sql = "SELECT id AS Id, perfil AS NombrePerfil, descPerfil AS Descripcion FROM dbo.gral_Perfiles WHERE id = @Id";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<Perfil>(sql, new { Id = id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Perfil por ID: {IdPerfil}", id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsByNameAsync(string nombrePerfil, int? excludeId = null)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.gral_Perfiles WHERE perfil = @NombrePerfil");
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("NombrePerfil", nombrePerfil);
|
||||
|
||||
if (excludeId.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND id != @ExcludeId");
|
||||
parameters.Add("ExcludeId", excludeId.Value);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var count = await connection.ExecuteScalarAsync<int>(sqlBuilder.ToString(), parameters);
|
||||
return count > 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en ExistsByNameAsync para Perfil con nombre: {NombrePerfil}", nombrePerfil);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsInUseAsync(int id)
|
||||
{
|
||||
const string sqlCheckUsuarios = "SELECT TOP 1 1 FROM dbo.gral_Usuarios WHERE IdPerfil = @IdPerfil";
|
||||
const string sqlCheckPermisos = "SELECT TOP 1 1 FROM dbo.gral_PermisosPerfiles WHERE idPerfil = @IdPerfil";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var inUsuarios = await connection.ExecuteScalarAsync<int?>(sqlCheckUsuarios, new { IdPerfil = id });
|
||||
if (inUsuarios.HasValue && inUsuarios.Value == 1) return true;
|
||||
|
||||
var inPermisos = await connection.ExecuteScalarAsync<int?>(sqlCheckPermisos, new { IdPerfil = id });
|
||||
return inPermisos.HasValue && inPermisos.Value == 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en IsInUseAsync para Perfil ID: {IdPerfil}", id);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Perfil?> CreateAsync(Perfil nuevoPerfil, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
const string sqlInsert = @"
|
||||
INSERT INTO dbo.gral_Perfiles (perfil, descPerfil)
|
||||
OUTPUT INSERTED.id AS Id, INSERTED.perfil AS NombrePerfil, INSERTED.descPerfil AS Descripcion
|
||||
VALUES (@NombrePerfil, @Descripcion);";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Perfiles_H (idPerfil, perfil, descPerfil, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPerfilHist, @NombrePerfilHist, @DescripcionHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
var connection = transaction.Connection!; // La conexión debe venir de la transacción
|
||||
|
||||
var insertedPerfil = await connection.QuerySingleAsync<Perfil>(
|
||||
sqlInsert,
|
||||
new { nuevoPerfil.NombrePerfil, nuevoPerfil.Descripcion },
|
||||
transaction: transaction);
|
||||
|
||||
if (insertedPerfil == null || insertedPerfil.Id <= 0)
|
||||
{
|
||||
throw new DataException("No se pudo obtener el ID del perfil insertado.");
|
||||
}
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdPerfilHist = insertedPerfil.Id, // Correcto
|
||||
NombrePerfilHist = insertedPerfil.NombrePerfil,
|
||||
DescripcionHist = insertedPerfil.Descripcion,
|
||||
IdUsuarioHist = idUsuario,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Insertada"
|
||||
}, transaction: transaction);
|
||||
|
||||
return insertedPerfil;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(Perfil perfilAActualizar, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
// Obtener el estado actual PARA EL HISTORIAL DENTRO DE LA MISMA TRANSACCIÓN
|
||||
var perfilActual = await connection.QuerySingleOrDefaultAsync<Perfil>(
|
||||
"SELECT id AS Id, perfil AS NombrePerfil, descPerfil AS Descripcion FROM dbo.gral_Perfiles WHERE id = @Id",
|
||||
new { Id = perfilAActualizar.Id },
|
||||
transaction);
|
||||
|
||||
if (perfilActual == null)
|
||||
{
|
||||
// Esto no debería pasar si el servicio verifica la existencia antes, pero es una salvaguarda.
|
||||
throw new KeyNotFoundException($"Perfil con ID {perfilAActualizar.Id} no encontrado para actualizar.");
|
||||
}
|
||||
|
||||
const string sqlUpdate = "UPDATE dbo.gral_Perfiles SET perfil = @NombrePerfil, descPerfil = @Descripcion WHERE id = @Id;";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Perfiles_H (idPerfil, perfil, descPerfil, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPerfilHist, @NombrePerfilHist, @DescripcionHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
// Insertar en historial con los valores ANTES de la modificación
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdPerfilHist = perfilActual.Id,
|
||||
NombrePerfilHist = perfilActual.NombrePerfil,
|
||||
DescripcionHist = perfilActual.Descripcion,
|
||||
IdUsuarioHist = idUsuario,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Modificada"
|
||||
}, transaction: transaction);
|
||||
|
||||
// Actualizar la tabla principal
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, perfilAActualizar, transaction: transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
// Obtener el estado actual PARA EL HISTORIAL DENTRO DE LA MISMA TRANSACCIÓN
|
||||
var perfilActual = await connection.QuerySingleOrDefaultAsync<Perfil>(
|
||||
"SELECT id AS Id, perfil AS NombrePerfil, descPerfil AS Descripcion FROM dbo.gral_Perfiles WHERE id = @Id",
|
||||
new { Id = id },
|
||||
transaction);
|
||||
|
||||
if (perfilActual == null)
|
||||
{
|
||||
throw new KeyNotFoundException($"Perfil con ID {id} no encontrado para eliminar.");
|
||||
}
|
||||
|
||||
const string sqlDelete = "DELETE FROM dbo.gral_Perfiles WHERE id = @Id";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Perfiles_H (idPerfil, perfil, descPerfil, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPerfilHist, @NombrePerfilHist, @DescripcionHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
// Insertar en historial con los valores ANTES de la eliminación
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdPerfilHist = perfilActual.Id,
|
||||
NombrePerfilHist = perfilActual.NombrePerfil,
|
||||
DescripcionHist = perfilActual.Descripcion,
|
||||
IdUsuarioHist = idUsuario,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Eliminada"
|
||||
}, transaction: transaction);
|
||||
|
||||
// Eliminar de la tabla principal
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction: transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
public async Task<IEnumerable<int>> GetPermisoIdsByPerfilIdAsync(int idPerfil)
|
||||
{
|
||||
const string sql = "SELECT idPermiso FROM dbo.gral_PermisosPerfiles WHERE idPerfil = @IdPerfil";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<int>(sql, new { IdPerfil = idPerfil });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener IDs de permisos para el Perfil ID: {IdPerfil}", idPerfil);
|
||||
return Enumerable.Empty<int>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task UpdatePermisosByPerfilIdAsync(int idPerfil, IEnumerable<int> nuevosPermisosIds, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
|
||||
// 1. Eliminar todos los permisos existentes para este perfil (dentro de la transacción)
|
||||
const string sqlDelete = "DELETE FROM dbo.gral_PermisosPerfiles WHERE idPerfil = @IdPerfil";
|
||||
await connection.ExecuteAsync(sqlDelete, new { IdPerfil = idPerfil }, transaction: transaction);
|
||||
|
||||
// 2. Insertar los nuevos permisos (si hay alguno)
|
||||
if (nuevosPermisosIds != null && nuevosPermisosIds.Any())
|
||||
{
|
||||
const string sqlInsert = "INSERT INTO dbo.gral_PermisosPerfiles (idPerfil, idPermiso) VALUES (@IdPerfil, @IdPermiso)";
|
||||
// Dapper puede manejar una lista de objetos para inserciones múltiples
|
||||
var permisosParaInsertar = nuevosPermisosIds.Select(idPermiso => new { IdPerfil = idPerfil, IdPermiso = idPermiso });
|
||||
await connection.ExecuteAsync(sqlInsert, permisosParaInsertar, transaction: transaction);
|
||||
}
|
||||
// No hay tabla _H para gral_PermisosPerfiles directamente en este diseño.
|
||||
// La auditoría de qué usuario cambió los permisos de un perfil se podría registrar
|
||||
// en una tabla de log de acciones más general si fuera necesario, o deducir
|
||||
// indirectamente si la interfaz de usuario solo permite a SuperAdmin hacer esto.
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models.Usuarios;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
||||
{
|
||||
public class PermisoRepository : IPermisoRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<PermisoRepository> _logger;
|
||||
|
||||
public PermisoRepository(DbConnectionFactory connectionFactory, ILogger<PermisoRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Permiso>> GetAllAsync(string? moduloFilter, string? codAccFilter)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT id AS Id, modulo, descPermiso, codAcc FROM dbo.gral_Permisos WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(moduloFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND modulo LIKE @ModuloFilter");
|
||||
parameters.Add("ModuloFilter", $"%{moduloFilter}%");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(codAccFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND codAcc LIKE @CodAccFilter");
|
||||
parameters.Add("CodAccFilter", $"%{codAccFilter}%");
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY modulo, codAcc;");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Permiso>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Permisos. Filtros: Modulo={Modulo}, CodAcc={CodAcc}", moduloFilter, codAccFilter);
|
||||
return Enumerable.Empty<Permiso>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Permiso?> GetByIdAsync(int id)
|
||||
{
|
||||
const string sql = "SELECT id AS Id, modulo, descPermiso, codAcc FROM dbo.gral_Permisos WHERE id = @Id";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<Permiso>(sql, new { Id = id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Permiso por ID: {IdPermiso}", id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsByCodAccAsync(string codAcc, int? excludeId = null)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.gral_Permisos WHERE codAcc = @CodAcc");
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("CodAcc", codAcc);
|
||||
|
||||
if (excludeId.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND id != @ExcludeId");
|
||||
parameters.Add("ExcludeId", excludeId.Value);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var count = await connection.ExecuteScalarAsync<int>(sqlBuilder.ToString(), parameters);
|
||||
return count > 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en ExistsByCodAccAsync para Permiso con codAcc: {CodAcc}", codAcc);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> IsInUseAsync(int id)
|
||||
{
|
||||
const string sqlCheckPermisosPerfiles = "SELECT TOP 1 1 FROM dbo.gral_PermisosPerfiles WHERE idPermiso = @IdPermiso";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var inUse = await connection.ExecuteScalarAsync<int?>(sqlCheckPermisosPerfiles, new { IdPermiso = id });
|
||||
return inUse.HasValue && inUse.Value == 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en IsInUseAsync para Permiso ID: {IdPermiso}", id);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Permiso>> GetPermisosByIdsAsync(IEnumerable<int> ids)
|
||||
{
|
||||
if (ids == null || !ids.Any())
|
||||
{
|
||||
return Enumerable.Empty<Permiso>();
|
||||
}
|
||||
const string sql = "SELECT id AS Id, modulo, descPermiso, codAcc FROM dbo.gral_Permisos WHERE id IN @Ids;";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Permiso>(sql, new { Ids = ids });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener permisos por IDs.");
|
||||
return Enumerable.Empty<Permiso>();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task<Permiso?> CreateAsync(Permiso nuevoPermiso, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
const string sqlInsert = @"
|
||||
INSERT INTO dbo.gral_Permisos (modulo, descPermiso, codAcc)
|
||||
OUTPUT INSERTED.id AS Id, INSERTED.modulo, INSERTED.descPermiso, INSERTED.codAcc
|
||||
VALUES (@Modulo, @DescPermiso, @CodAcc);";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Permisos_H (idPermiso, modulo, descPermiso, codAcc, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPermisoHist, @ModuloHist, @DescPermisoHist, @CodAccHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
var connection = transaction.Connection!;
|
||||
var insertedPermiso = await connection.QuerySingleAsync<Permiso>(
|
||||
sqlInsert,
|
||||
nuevoPermiso,
|
||||
transaction: transaction);
|
||||
|
||||
if (insertedPermiso == null || insertedPermiso.Id <= 0)
|
||||
{
|
||||
throw new DataException("No se pudo obtener el ID del permiso insertado.");
|
||||
}
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdPermisoHist = insertedPermiso.Id,
|
||||
ModuloHist = insertedPermiso.Modulo,
|
||||
DescPermisoHist = insertedPermiso.DescPermiso,
|
||||
CodAccHist = insertedPermiso.CodAcc,
|
||||
IdUsuarioHist = idUsuario,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Insertada"
|
||||
}, transaction: transaction);
|
||||
|
||||
return insertedPermiso;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(Permiso permisoAActualizar, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var permisoActual = await connection.QuerySingleOrDefaultAsync<Permiso>(
|
||||
"SELECT id AS Id, modulo, descPermiso, codAcc FROM dbo.gral_Permisos WHERE id = @Id",
|
||||
new { Id = permisoAActualizar.Id },
|
||||
transaction);
|
||||
|
||||
if (permisoActual == null)
|
||||
{
|
||||
throw new KeyNotFoundException($"Permiso con ID {permisoAActualizar.Id} no encontrado para actualizar.");
|
||||
}
|
||||
|
||||
const string sqlUpdate = @"UPDATE dbo.gral_Permisos
|
||||
SET modulo = @Modulo, descPermiso = @DescPermiso, codAcc = @CodAcc
|
||||
WHERE id = @Id;";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Permisos_H (idPermiso, modulo, descPermiso, codAcc, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPermisoHist, @ModuloHist, @DescPermisoHist, @CodAccHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdPermisoHist = permisoActual.Id,
|
||||
ModuloHist = permisoActual.Modulo,
|
||||
DescPermisoHist = permisoActual.DescPermiso,
|
||||
CodAccHist = permisoActual.CodAcc,
|
||||
IdUsuarioHist = idUsuario,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Modificada"
|
||||
}, transaction: transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, permisoAActualizar, transaction: transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var permisoActual = await connection.QuerySingleOrDefaultAsync<Permiso>(
|
||||
"SELECT id AS Id, modulo, descPermiso, codAcc FROM dbo.gral_Permisos WHERE id = @Id",
|
||||
new { Id = id },
|
||||
transaction);
|
||||
|
||||
if (permisoActual == null)
|
||||
{
|
||||
throw new KeyNotFoundException($"Permiso con ID {id} no encontrado para eliminar.");
|
||||
}
|
||||
|
||||
const string sqlDelete = "DELETE FROM dbo.gral_Permisos WHERE id = @Id";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Permisos_H (idPermiso, modulo, descPermiso, codAcc, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdPermisoHist, @ModuloHist, @DescPermisoHist, @CodAccHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdPermisoHist = permisoActual.Id,
|
||||
ModuloHist = permisoActual.Modulo,
|
||||
DescPermisoHist = permisoActual.DescPermiso,
|
||||
CodAccHist = permisoActual.CodAcc,
|
||||
IdUsuarioHist = idUsuario,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Eliminada"
|
||||
}, transaction: transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction: transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models.Usuarios;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
||||
{
|
||||
public class UsuarioRepository : IUsuarioRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<UsuarioRepository> _logger;
|
||||
|
||||
public UsuarioRepository(DbConnectionFactory connectionFactory, ILogger<UsuarioRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Usuario>> GetAllAsync(string? userFilter, string? nombreFilter)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT * FROM dbo.gral_Usuarios WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(userFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND [User] LIKE @UserParam");
|
||||
parameters.Add("UserParam", $"%{userFilter}%");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(nombreFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND (Nombre LIKE @NombreParam OR Apellido LIKE @NombreParam)");
|
||||
parameters.Add("NombreParam", $"%{nombreFilter}%");
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY [User];");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Usuario>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Usuarios.");
|
||||
return Enumerable.Empty<Usuario>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<(Usuario Usuario, string NombrePerfil)>> GetAllWithProfileNameAsync(string? userFilter, string? nombreFilter)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder(@"
|
||||
SELECT u.*, p.perfil AS NombrePerfil
|
||||
FROM dbo.gral_Usuarios u
|
||||
INNER JOIN dbo.gral_Perfiles p ON u.IdPerfil = p.id
|
||||
WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(userFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND u.[User] LIKE @UserParam");
|
||||
parameters.Add("UserParam", $"%{userFilter}%");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(nombreFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND (u.Nombre LIKE @NombreParam OR u.Apellido LIKE @NombreParam)");
|
||||
parameters.Add("NombreParam", $"%{nombreFilter}%");
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY u.[User];");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Usuario, string, (Usuario, string)>(
|
||||
sqlBuilder.ToString(),
|
||||
(usuario, nombrePerfil) => (usuario, nombrePerfil),
|
||||
parameters,
|
||||
splitOn: "NombrePerfil"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Usuarios con nombre de perfil.");
|
||||
return Enumerable.Empty<(Usuario, string)>();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task<Usuario?> GetByIdAsync(int id)
|
||||
{
|
||||
const string sql = "SELECT * FROM dbo.gral_Usuarios WHERE Id = @Id";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<Usuario>(sql, new { Id = id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Usuario por ID: {UsuarioId}", id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public async Task<(Usuario? Usuario, string? NombrePerfil)> GetByIdWithProfileNameAsync(int id)
|
||||
{
|
||||
const string sql = @"
|
||||
SELECT u.*, p.perfil AS NombrePerfil
|
||||
FROM dbo.gral_Usuarios u
|
||||
INNER JOIN dbo.gral_Perfiles p ON u.IdPerfil = p.id
|
||||
WHERE u.Id = @Id";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var result = await connection.QueryAsync<Usuario, string, (Usuario Usuario, string NombrePerfil)>(
|
||||
sql,
|
||||
(usuario, nombrePerfil) => (usuario, nombrePerfil),
|
||||
new { Id = id },
|
||||
splitOn: "NombrePerfil"
|
||||
);
|
||||
return result.SingleOrDefault();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Usuario por ID con nombre de perfil: {UsuarioId}", id);
|
||||
return (null, null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public async Task<Usuario?> GetByUsernameAsync(string username)
|
||||
{
|
||||
// Esta es la misma que en AuthRepository, si se unifican, se puede eliminar una.
|
||||
const string sql = "SELECT * FROM dbo.gral_Usuarios WHERE [User] = @Username";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<Usuario>(sql, new { Username = username });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Usuario por Username: {Username}", username);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> UserExistsAsync(string username, int? excludeId = null)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.gral_Usuarios WHERE [User] = @Username");
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("Username", username);
|
||||
|
||||
if (excludeId.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id != @ExcludeId");
|
||||
parameters.Add("ExcludeId", excludeId.Value);
|
||||
}
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.ExecuteScalarAsync<bool>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en UserExistsAsync para username: {Username}", username);
|
||||
return true; // Asumir que existe para prevenir duplicados
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Usuario?> CreateAsync(Usuario nuevoUsuario, int idUsuarioCreador, IDbTransaction transaction)
|
||||
{
|
||||
const string sqlInsert = @"
|
||||
INSERT INTO dbo.gral_Usuarios ([User], ClaveHash, ClaveSalt, Habilitada, SupAdmin, Nombre, Apellido, IdPerfil, VerLog, DebeCambiarClave)
|
||||
OUTPUT INSERTED.*
|
||||
VALUES (@User, @ClaveHash, @ClaveSalt, @Habilitada, @SupAdmin, @Nombre, @Apellido, @IdPerfil, @VerLog, @DebeCambiarClave);";
|
||||
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Usuarios_H
|
||||
(IdUsuario, UserNvo, HabilitadaNva, SupAdminNvo, NombreNvo, ApellidoNvo, IdPerfilNvo, DebeCambiarClaveNva, Id_UsuarioMod, FechaMod, TipoMod)
|
||||
VALUES (@IdUsuarioHist, @UserNvoHist, @HabilitadaNvaHist, @SupAdminNvoHist, @NombreNvoHist, @ApellidoNvoHist, @IdPerfilNvoHist, @DebeCambiarClaveNvaHist, @IdUsuarioModHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
var connection = transaction.Connection!;
|
||||
var insertedUsuario = await connection.QuerySingleAsync<Usuario>(sqlInsert, nuevoUsuario, transaction);
|
||||
|
||||
if (insertedUsuario == null) throw new DataException("No se pudo crear el usuario.");
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdUsuarioHist = insertedUsuario.Id,
|
||||
UserNvoHist = insertedUsuario.User,
|
||||
HabilitadaNvaHist = insertedUsuario.Habilitada,
|
||||
SupAdminNvoHist = insertedUsuario.SupAdmin,
|
||||
NombreNvoHist = insertedUsuario.Nombre,
|
||||
ApellidoNvoHist = insertedUsuario.Apellido,
|
||||
IdPerfilNvoHist = insertedUsuario.IdPerfil,
|
||||
DebeCambiarClaveNvaHist = insertedUsuario.DebeCambiarClave,
|
||||
IdUsuarioModHist = idUsuarioCreador,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Creado"
|
||||
}, transaction);
|
||||
|
||||
return insertedUsuario;
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(Usuario usuarioAActualizar, int idUsuarioModificador, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var usuarioActual = await connection.QuerySingleOrDefaultAsync<Usuario>(
|
||||
"SELECT * FROM dbo.gral_Usuarios WHERE Id = @Id", new { usuarioAActualizar.Id }, transaction);
|
||||
|
||||
if (usuarioActual == null) throw new KeyNotFoundException("Usuario no encontrado para actualizar.");
|
||||
|
||||
// User (nombre de usuario) no se actualiza aquí
|
||||
const string sqlUpdate = @"
|
||||
UPDATE dbo.gral_Usuarios SET
|
||||
Habilitada = @Habilitada, SupAdmin = @SupAdmin, Nombre = @Nombre, Apellido = @Apellido,
|
||||
IdPerfil = @IdPerfil, VerLog = @VerLog, DebeCambiarClave = @DebeCambiarClave
|
||||
WHERE Id = @Id;";
|
||||
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Usuarios_H
|
||||
(IdUsuario, UserAnt, UserNvo, HabilitadaAnt, HabilitadaNva, SupAdminAnt, SupAdminNvo,
|
||||
NombreAnt, NombreNvo, ApellidoAnt, ApellidoNvo, IdPerfilAnt, IdPerfilNvo,
|
||||
DebeCambiarClaveAnt, DebeCambiarClaveNva, Id_UsuarioMod, FechaMod, TipoMod)
|
||||
VALUES (@IdUsuarioHist, @UserAntHist, @UserNvoHist, @HabilitadaAntHist, @HabilitadaNvaHist, @SupAdminAntHist, @SupAdminNvoHist,
|
||||
@NombreAntHist, @NombreNvoHist, @ApellidoAntHist, @ApellidoNvoHist, @IdPerfilAntHist, @IdPerfilNvoHist,
|
||||
@DebeCambiarClaveAntHist, @DebeCambiarClaveNvaHist, @IdUsuarioModHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdUsuarioHist = usuarioActual.Id,
|
||||
UserAntHist = usuarioActual.User, UserNvoHist = usuarioAActualizar.User, // Aunque no cambiemos User, lo registramos
|
||||
HabilitadaAntHist = usuarioActual.Habilitada, HabilitadaNvaHist = usuarioAActualizar.Habilitada,
|
||||
SupAdminAntHist = usuarioActual.SupAdmin, SupAdminNvoHist = usuarioAActualizar.SupAdmin,
|
||||
NombreAntHist = usuarioActual.Nombre, NombreNvoHist = usuarioAActualizar.Nombre,
|
||||
ApellidoAntHist = usuarioActual.Apellido, ApellidoNvoHist = usuarioAActualizar.Apellido,
|
||||
IdPerfilAntHist = usuarioActual.IdPerfil, IdPerfilNvoHist = usuarioAActualizar.IdPerfil,
|
||||
DebeCambiarClaveAntHist = usuarioActual.DebeCambiarClave, DebeCambiarClaveNvaHist = usuarioAActualizar.DebeCambiarClave,
|
||||
IdUsuarioModHist = idUsuarioModificador,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Actualizado"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, usuarioAActualizar, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
|
||||
public async Task<bool> SetPasswordAsync(int userId, string newHash, string newSalt, bool debeCambiarClave, int idUsuarioModificador, IDbTransaction transaction)
|
||||
{
|
||||
var connection = transaction.Connection!;
|
||||
var usuarioActual = await connection.QuerySingleOrDefaultAsync<Usuario>(
|
||||
"SELECT * FROM dbo.gral_Usuarios WHERE Id = @Id", new { Id = userId }, transaction);
|
||||
|
||||
if (usuarioActual == null) throw new KeyNotFoundException("Usuario no encontrado para cambiar contraseña.");
|
||||
|
||||
const string sqlUpdate = @"UPDATE dbo.gral_Usuarios
|
||||
SET ClaveHash = @ClaveHash, ClaveSalt = @ClaveSalt, DebeCambiarClave = @DebeCambiarClave
|
||||
WHERE Id = @UserId";
|
||||
const string sqlInsertHistorico = @"
|
||||
INSERT INTO dbo.gral_Usuarios_H
|
||||
(IdUsuario, UserNvo, HabilitadaNva, SupAdminNvo, NombreNvo, ApellidoNvo, IdPerfilNvo,
|
||||
DebeCambiarClaveAnt, DebeCambiarClaveNva, Id_UsuarioMod, FechaMod, TipoMod)
|
||||
VALUES (@IdUsuarioHist, @UserNvoHist, @HabilitadaNvaHist, @SupAdminNvoHist, @NombreNvoHist, @ApellidoNvoHist, @IdPerfilNvoHist,
|
||||
@DebeCambiarClaveAntHist, @DebeCambiarClaveNvaHist, @IdUsuarioModHist, @FechaModHist, @TipoModHist);";
|
||||
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdUsuarioHist = usuarioActual.Id,
|
||||
UserNvoHist = usuarioActual.User, // No cambia el user
|
||||
HabilitadaNvaHist = usuarioActual.Habilitada,
|
||||
SupAdminNvoHist = usuarioActual.SupAdmin,
|
||||
NombreNvoHist = usuarioActual.Nombre,
|
||||
ApellidoNvoHist = usuarioActual.Apellido,
|
||||
IdPerfilNvoHist = usuarioActual.IdPerfil,
|
||||
DebeCambiarClaveAntHist = usuarioActual.DebeCambiarClave, // Estado anterior de este flag
|
||||
DebeCambiarClaveNvaHist = debeCambiarClave, // Nuevo estado de este flag
|
||||
IdUsuarioModHist = idUsuarioModificador,
|
||||
FechaModHist = DateTime.Now,
|
||||
TipoModHist = "Clave Cambiada" // O "Clave Reseteada"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, new
|
||||
{
|
||||
ClaveHash = newHash,
|
||||
ClaveSalt = newSalt,
|
||||
DebeCambiarClave = debeCambiarClave,
|
||||
UserId = userId
|
||||
}, transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
16
Backend/GestionIntegral.Api/Models/Distribucion/Canilla.cs
Normal file
16
Backend/GestionIntegral.Api/Models/Distribucion/Canilla.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class Canilla
|
||||
{
|
||||
public int IdCanilla { get; set; } // Id_Canilla (PK, Identity)
|
||||
public int? Legajo { get; set; } // Legajo (int, NULL)
|
||||
public string NomApe { get; set; } = string.Empty; // NomApe (varchar(100), NOT NULL)
|
||||
public string? Parada { get; set; } // Parada (varchar(150), NULL)
|
||||
public int IdZona { get; set; } // Id_Zona (int, NOT NULL)
|
||||
public bool Accionista { get; set; } // Accionista (bit, NOT NULL)
|
||||
public string? Obs { get; set; } // Obs (varchar(150), NULL)
|
||||
public int Empresa { get; set; } // Empresa (int, NOT NULL, DEFAULT 0)
|
||||
public bool Baja { get; set; } // Baja (bit, NOT NULL, DEFAULT 0)
|
||||
public DateTime? FechaBaja { get; set; } // FechaBaja (datetime2(0), NULL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class CanillaHistorico
|
||||
{
|
||||
public int IdCanilla { get; set; }
|
||||
public int? Legajo { get; set; }
|
||||
public string NomApe { get; set; } = string.Empty;
|
||||
public string? Parada { get; set; }
|
||||
public int IdZona { get; set; }
|
||||
public bool Accionista { get; set; }
|
||||
public string? Obs { get; set; }
|
||||
public int Empresa { get; set; }
|
||||
public bool Baja { get; set; }
|
||||
public DateTime? FechaBaja { get; set; }
|
||||
|
||||
// Campos de Auditoría
|
||||
public int Id_Usuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class Distribuidor
|
||||
{
|
||||
public int IdDistribuidor { get; set; } // Id_Distribuidor (PK, Identity)
|
||||
public string Nombre { get; set; } = string.Empty; // Nombre (varchar(100), NOT NULL)
|
||||
public string? Contacto { get; set; } // Contacto (varchar(100), NULL)
|
||||
public string NroDoc { get; set; } = string.Empty; // NroDoc (varchar(11), NOT NULL)
|
||||
public int? IdZona { get; set; } // Id_Zona (int, NULL) - Puede no tener zona asignada
|
||||
public string? Calle { get; set; }
|
||||
public string? Numero { get; set; }
|
||||
public string? Piso { get; set; }
|
||||
public string? Depto { get; set; }
|
||||
public string? Telefono { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string? Localidad { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class DistribuidorHistorico
|
||||
{
|
||||
public int IdDistribuidor { get; set; } // FK
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
public string? Contacto { get; set; }
|
||||
public string NroDoc { get; set; } = string.Empty;
|
||||
public int? IdZona { get; set; }
|
||||
public string? Calle { get; set; }
|
||||
public string? Numero { get; set; }
|
||||
public string? Piso { get; set; }
|
||||
public string? Depto { get; set; }
|
||||
public string? Telefono { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string? Localidad { get; set; }
|
||||
|
||||
// Campos de Auditoría
|
||||
public int Id_Usuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class OtroDestino
|
||||
{
|
||||
// Columna: Id_Destino (PK, Identity)
|
||||
public int IdDestino { get; set; }
|
||||
|
||||
// Columna: Nombre (varchar(100), NOT NULL)
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
// Columna: Obs (varchar(250), NULL)
|
||||
public string? Obs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class OtroDestinoHistorico
|
||||
{
|
||||
// Columna: Id_Destino (int, FK)
|
||||
public int IdDestino { get; set; }
|
||||
|
||||
// Columna: Nombre (varchar(100), NOT NULL)
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
// Columna: Obs (varchar(250), NULL)
|
||||
public string? Obs { get; set; }
|
||||
|
||||
// Columnas de Auditoría
|
||||
public int IdUsuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty; // "Insertada", "Modificada", "Eliminada"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class PorcMonCanilla // Corresponde a dist_PorcMonPagoCanilla
|
||||
{
|
||||
public int IdPorcMon { get; set; } // Id_PorcMon
|
||||
public int IdPublicacion { get; set; }
|
||||
public int IdCanilla { get; set; }
|
||||
public DateTime VigenciaD { get; set; }
|
||||
public DateTime? VigenciaH { get; set; }
|
||||
public decimal PorcMon { get; set; } // Columna PorcMon en DB
|
||||
public bool EsPorcentaje { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System;
|
||||
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class PorcMonCanillaHistorico
|
||||
{
|
||||
public int Id_PorcMon { get; set; } // Coincide con la columna
|
||||
public int Id_Publicacion { get; set; }
|
||||
public int Id_Canilla { get; set; }
|
||||
public DateTime VigenciaD { get; set; }
|
||||
public DateTime? VigenciaH { get; set; }
|
||||
public decimal PorcMon { get; set; }
|
||||
public bool EsPorcentaje { get; set; }
|
||||
public int Id_Usuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
14
Backend/GestionIntegral.Api/Models/Distribucion/PorcPago.cs
Normal file
14
Backend/GestionIntegral.Api/Models/Distribucion/PorcPago.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class PorcPago // Corresponde a dist_PorcPago
|
||||
{
|
||||
public int IdPorcentaje { get; set; } // Id_Porcentaje
|
||||
public int IdPublicacion { get; set; }
|
||||
public int IdDistribuidor { get; set; }
|
||||
public DateTime VigenciaD { get; set; } // smalldatetime se mapea a DateTime
|
||||
public DateTime? VigenciaH { get; set; }
|
||||
public decimal Porcentaje { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using System;
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class PorcPagoHistorico
|
||||
{
|
||||
public int IdPorcentaje { get; set; } // Id_Porcentaje
|
||||
public int IdPublicacion { get; set; }
|
||||
public int IdDistribuidor { get; set; }
|
||||
public DateTime VigenciaD { get; set; }
|
||||
public DateTime? VigenciaH { get; set; }
|
||||
public decimal Porcentaje { get; set; }
|
||||
public int IdUsuario { get; set; } // Coincide con Id_Usuario en la tabla _H
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
17
Backend/GestionIntegral.Api/Models/Distribucion/Precio.cs
Normal file
17
Backend/GestionIntegral.Api/Models/Distribucion/Precio.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class Precio
|
||||
{
|
||||
public int IdPrecio { get; set; } // Id_Precio (PK, Identity)
|
||||
public int IdPublicacion { get; set; } // Id_Publicacion (FK, NOT NULL)
|
||||
public DateTime VigenciaD { get; set; } // VigenciaD (datetime2(0), NOT NULL)
|
||||
public DateTime? VigenciaH { get; set; } // VigenciaH (datetime2(0), NULL)
|
||||
public decimal? Lunes { get; set; } // Lunes (decimal(14,2), NULL, DEFAULT 0)
|
||||
public decimal? Martes { get; set; }
|
||||
public decimal? Miercoles { get; set; }
|
||||
public decimal? Jueves { get; set; }
|
||||
public decimal? Viernes { get; set; }
|
||||
public decimal? Sabado { get; set; }
|
||||
public decimal? Domingo { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class PrecioHistorico
|
||||
{
|
||||
public int IdPrecio { get; set; } // FK a dist_Precios.Id_Precio
|
||||
public int IdPublicacion { get; set; }
|
||||
public DateTime VigenciaD { get; set; }
|
||||
public DateTime? VigenciaH { get; set; }
|
||||
public decimal? Lunes { get; set; }
|
||||
public decimal? Martes { get; set; }
|
||||
public decimal? Miercoles { get; set; }
|
||||
public decimal? Jueves { get; set; }
|
||||
public decimal? Viernes { get; set; }
|
||||
public decimal? Sabado { get; set; }
|
||||
public decimal? Domingo { get; set; }
|
||||
|
||||
// Campos de Auditoría
|
||||
public int Id_Usuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class PubliSeccion
|
||||
{
|
||||
public int IdSeccion { get; set; } // Id_Seccion
|
||||
public int IdPublicacion { get; set; }
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
public bool Estado { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class PubliSeccionHistorico
|
||||
{
|
||||
public int Id_Seccion { get; set; } // Coincide con la columna
|
||||
public int Id_Publicacion { get; set; }
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
public bool Estado { get; set; }
|
||||
public int Id_Usuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class Publicacion
|
||||
{
|
||||
public int IdPublicacion { get; set; } // Id_Publicacion (PK, Identity)
|
||||
public string Nombre { get; set; } = string.Empty; // Nombre (varchar(50), NOT NULL)
|
||||
public string? Observacion { get; set; } // Observacion (varchar(150), NULL)
|
||||
public int IdEmpresa { get; set; } // Id_Empresa (int, NOT NULL)
|
||||
public bool CtrlDevoluciones { get; set; } // CtrlDevoluciones (bit, NOT NULL, DEFAULT 0)
|
||||
public bool? Habilitada { get; set; } // Habilitada (bit, NULL, DEFAULT 1) - ¡OJO! En la tabla es NULLABLE con DEFAULT 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class PublicacionHistorico
|
||||
{
|
||||
// No hay PK autoincremental explícita en el script de _H
|
||||
public int IdPublicacion { get; set; }
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
public string? Observacion { get; set; }
|
||||
public int IdEmpresa { get; set; }
|
||||
public bool? Habilitada { get; set; } // Coincide con la tabla _H
|
||||
|
||||
// Campos de Auditoría
|
||||
public int Id_Usuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class RecargoZona
|
||||
{
|
||||
public int IdRecargo { get; set; } // Id_Recargo (PK, Identity)
|
||||
public int IdPublicacion { get; set; } // Id_Publicacion (FK, NOT NULL)
|
||||
public int IdZona { get; set; } // Id_Zona (FK, NOT NULL)
|
||||
public DateTime VigenciaD { get; set; } // VigenciaD (datetime2(0), NOT NULL)
|
||||
public DateTime? VigenciaH { get; set; } // VigenciaH (datetime2(0), NULL)
|
||||
public decimal Valor { get; set; } // Valor (decimal(14,2), NOT NULL, DEFAULT 0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace GestionIntegral.Api.Models.Distribucion
|
||||
{
|
||||
public class RecargoZonaHistorico
|
||||
{
|
||||
public int IdRecargo { get; set; }
|
||||
public int IdPublicacion { get; set; }
|
||||
public int IdZona { get; set; }
|
||||
public DateTime VigenciaD { get; set; }
|
||||
public DateTime? VigenciaH { get; set; }
|
||||
public decimal Valor { get; set; }
|
||||
public int IdUsuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class CanillaDto
|
||||
{
|
||||
public int IdCanilla { get; set; }
|
||||
public int? Legajo { get; set; }
|
||||
public string NomApe { get; set; } = string.Empty;
|
||||
public string? Parada { get; set; }
|
||||
public int IdZona { get; set; }
|
||||
public string NombreZona { get; set; } = string.Empty; // Para mostrar en la UI
|
||||
public bool Accionista { get; set; }
|
||||
public string? Obs { get; set; }
|
||||
public int Empresa { get; set; } // Podría traer el nombre de la empresa si es relevante
|
||||
public string NombreEmpresa { get; set;} = string.Empty;
|
||||
public bool Baja { get; set; }
|
||||
public string? FechaBaja { get; set; } // Formato string para la UI
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class CreateCanillaDto
|
||||
{
|
||||
public int? Legajo { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "El nombre y apellido son obligatorios.")]
|
||||
[StringLength(100)]
|
||||
public string NomApe { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(150)]
|
||||
public string? Parada { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "La zona es obligatoria.")]
|
||||
[Range(1, int.MaxValue, ErrorMessage = "Debe seleccionar una zona válida.")]
|
||||
public int IdZona { get; set; }
|
||||
|
||||
[Required]
|
||||
public bool Accionista { get; set; } = false;
|
||||
|
||||
[StringLength(150)]
|
||||
public string? Obs { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "La empresa es obligatoria.")]
|
||||
// Asumimos que Empresa 0 es válido para accionistas según el contexto.
|
||||
// Si Empresa 0 es un placeholder, entonces Range(1, int.MaxValue)
|
||||
public int Empresa { get; set; } = 0; // Default 0 según la tabla
|
||||
|
||||
// Baja y FechaBaja se manejan por una acción separada, no en creación.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class CreateDistribuidorDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre del distribuidor es obligatorio.")]
|
||||
[StringLength(100)]
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(100)]
|
||||
public string? Contacto { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "El número de documento es obligatorio.")]
|
||||
[StringLength(11)] // CUIT/CUIL suele tener 11 dígitos
|
||||
public string NroDoc { get; set; } = string.Empty;
|
||||
|
||||
public int? IdZona { get; set; } // Puede ser nulo si el distribuidor no tiene zona
|
||||
|
||||
[StringLength(30)]
|
||||
public string? Calle { get; set; }
|
||||
[StringLength(8)]
|
||||
public string? Numero { get; set; }
|
||||
[StringLength(3)]
|
||||
public string? Piso { get; set; }
|
||||
[StringLength(4)]
|
||||
public string? Depto { get; set; }
|
||||
[StringLength(40)]
|
||||
public string? Telefono { get; set; }
|
||||
[StringLength(40)]
|
||||
[EmailAddress(ErrorMessage = "Formato de email inválido.")]
|
||||
public string? Email { get; set; }
|
||||
[StringLength(50)]
|
||||
public string? Localidad { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class CreateOtroDestinoDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre del destino es obligatorio.")]
|
||||
[StringLength(100, ErrorMessage = "El nombre no puede exceder los 100 caracteres.")]
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(250, ErrorMessage = "La observación no puede exceder los 250 caracteres.")]
|
||||
public string? Obs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class CreatePrecioDto
|
||||
{
|
||||
[Required(ErrorMessage = "El ID de la publicación es obligatorio.")]
|
||||
public int IdPublicacion { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "La fecha de Vigencia Desde es obligatoria.")]
|
||||
public DateTime VigenciaD { get; set; } // Recibir como DateTime desde el cliente
|
||||
|
||||
// VigenciaH se calculará o se dejará null inicialmente.
|
||||
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Lunes { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Martes { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Miercoles { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Jueves { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Viernes { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Sabado { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Domingo { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class CreatePublicacionDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre de la publicación es obligatorio.")]
|
||||
[StringLength(50)]
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(150)]
|
||||
public string? Observacion { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "La empresa es obligatoria.")]
|
||||
[Range(1, int.MaxValue, ErrorMessage = "Debe seleccionar una empresa válida.")]
|
||||
public int IdEmpresa { get; set; }
|
||||
|
||||
[Required]
|
||||
public bool CtrlDevoluciones { get; set; } = false;
|
||||
|
||||
public bool Habilitada { get; set; } = true; // Default true en UI
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class DistribuidorDto
|
||||
{
|
||||
public int IdDistribuidor { get; set; }
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
public string? Contacto { get; set; }
|
||||
public string NroDoc { get; set; } = string.Empty;
|
||||
public int? IdZona { get; set; }
|
||||
public string? NombreZona { get; set; } // Para mostrar en UI
|
||||
public string? Calle { get; set; }
|
||||
public string? Numero { get; set; }
|
||||
public string? Piso { get; set; }
|
||||
public string? Depto { get; set; }
|
||||
public string? Telefono { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string? Localidad { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class OtroDestinoDto
|
||||
{
|
||||
public int IdDestino { get; set; }
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
public string? Obs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class PrecioDto
|
||||
{
|
||||
public int IdPrecio { get; set; }
|
||||
public int IdPublicacion { get; set; }
|
||||
public string VigenciaD { get; set; } = string.Empty; // string yyyy-MM-dd para la UI
|
||||
public string? VigenciaH { get; set; } // string yyyy-MM-dd para la UI
|
||||
public decimal? Lunes { get; set; }
|
||||
public decimal? Martes { get; set; }
|
||||
public decimal? Miercoles { get; set; }
|
||||
public decimal? Jueves { get; set; }
|
||||
public decimal? Viernes { get; set; }
|
||||
public decimal? Sabado { get; set; }
|
||||
public decimal? Domingo { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class PublicacionDto
|
||||
{
|
||||
public int IdPublicacion { get; set; }
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
public string? Observacion { get; set; }
|
||||
public int IdEmpresa { get; set; }
|
||||
public string NombreEmpresa { get; set; } = string.Empty; // Para mostrar en UI
|
||||
public bool CtrlDevoluciones { get; set; }
|
||||
public bool Habilitada { get; set; } // Simplificamos a bool, el backend manejará el default si es null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class ToggleBajaCanillaDto
|
||||
{
|
||||
[Required]
|
||||
public bool DarDeBaja { get; set; } // True para dar de baja, False para reactivar
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class UpdateCanillaDto
|
||||
{
|
||||
public int? Legajo { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "El nombre y apellido son obligatorios.")]
|
||||
[StringLength(100)]
|
||||
public string NomApe { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(150)]
|
||||
public string? Parada { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "La zona es obligatoria.")]
|
||||
[Range(1, int.MaxValue, ErrorMessage = "Debe seleccionar una zona válida.")]
|
||||
public int IdZona { get; set; }
|
||||
|
||||
[Required]
|
||||
public bool Accionista { get; set; }
|
||||
|
||||
[StringLength(150)]
|
||||
public string? Obs { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "La empresa es obligatoria.")]
|
||||
public int Empresa { get; set; }
|
||||
|
||||
// Baja y FechaBaja se manejan por una acción separada.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class UpdateDistribuidorDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre del distribuidor es obligatorio.")]
|
||||
[StringLength(100)]
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(100)]
|
||||
public string? Contacto { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "El número de documento es obligatorio.")]
|
||||
[StringLength(11)]
|
||||
public string NroDoc { get; set; } = string.Empty;
|
||||
|
||||
public int? IdZona { get; set; }
|
||||
|
||||
[StringLength(30)]
|
||||
public string? Calle { get; set; }
|
||||
[StringLength(8)]
|
||||
public string? Numero { get; set; }
|
||||
[StringLength(3)]
|
||||
public string? Piso { get; set; }
|
||||
[StringLength(4)]
|
||||
public string? Depto { get; set; }
|
||||
[StringLength(40)]
|
||||
public string? Telefono { get; set; }
|
||||
[StringLength(40)]
|
||||
[EmailAddress(ErrorMessage = "Formato de email inválido.")]
|
||||
public string? Email { get; set; }
|
||||
[StringLength(50)]
|
||||
public string? Localidad { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class UpdateOtroDestinoDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre del destino es obligatorio.")]
|
||||
[StringLength(100, ErrorMessage = "El nombre no puede exceder los 100 caracteres.")]
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(250, ErrorMessage = "La observación no puede exceder los 250 caracteres.")]
|
||||
public string? Obs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class UpdatePrecioDto // Para actualizar un IdPrecio específico
|
||||
{
|
||||
// IdPublicacion no se puede cambiar una vez creado el precio (se borraría y crearía uno nuevo)
|
||||
// VigenciaD tampoco se debería cambiar directamente, se maneja creando nuevos periodos.
|
||||
|
||||
[Required(ErrorMessage = "La fecha de Vigencia Hasta es obligatoria si se modifica un periodo existente para cerrarlo.")]
|
||||
public DateTime? VigenciaH { get; set; } // Para cerrar un periodo
|
||||
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Lunes { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Martes { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Miercoles { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Jueves { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Viernes { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Sabado { get; set; }
|
||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||
public decimal? Domingo { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Distribucion
|
||||
{
|
||||
public class UpdatePublicacionDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre de la publicación es obligatorio.")]
|
||||
[StringLength(50)]
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(150)]
|
||||
public string? Observacion { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "La empresa es obligatoria.")]
|
||||
[Range(1, int.MaxValue, ErrorMessage = "Debe seleccionar una empresa válida.")]
|
||||
public int IdEmpresa { get; set; }
|
||||
|
||||
[Required]
|
||||
public bool CtrlDevoluciones { get; set; }
|
||||
|
||||
[Required] // En la actualización, el estado de Habilitada debe ser explícito
|
||||
public bool Habilitada { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class ActualizarPermisosPerfilRequestDto
|
||||
{
|
||||
[Required]
|
||||
[MinLength(0)] // Puede que un perfil no tenga ningún permiso.
|
||||
public List<int> PermisosIds { get; set; } = new List<int>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class CreatePerfilDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre del perfil es obligatorio.")]
|
||||
[StringLength(20, ErrorMessage = "El nombre del perfil no puede exceder los 20 caracteres.")]
|
||||
public string NombrePerfil { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(150, ErrorMessage = "La descripción no puede exceder los 150 caracteres.")]
|
||||
public string? Descripcion { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class CreatePermisoDto
|
||||
{
|
||||
[Required(ErrorMessage = "El módulo es obligatorio.")]
|
||||
[StringLength(50, ErrorMessage = "El módulo no puede exceder los 50 caracteres.")]
|
||||
public string Modulo { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "La descripción del permiso es obligatoria.")]
|
||||
[StringLength(150, ErrorMessage = "La descripción no puede exceder los 150 caracteres.")]
|
||||
public string DescPermiso { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "El código de acceso es obligatorio.")]
|
||||
[StringLength(10, ErrorMessage = "El código de acceso no puede exceder los 10 caracteres.")]
|
||||
// Podrías añadir una RegularExpression si los codAcc tienen un formato específico
|
||||
public string CodAcc { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class CreateUsuarioRequestDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre de usuario es obligatorio.")]
|
||||
[StringLength(20, MinimumLength = 3, ErrorMessage = "El nombre de usuario debe tener entre 3 y 20 caracteres.")]
|
||||
public string User { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "La contraseña es obligatoria.")]
|
||||
[StringLength(50, MinimumLength = 6, ErrorMessage = "La contraseña debe tener al menos 6 caracteres.")]
|
||||
public string Password { get; set; } = string.Empty; // Contraseña en texto plano para la creación
|
||||
|
||||
[Required(ErrorMessage = "El nombre es obligatorio.")]
|
||||
[StringLength(50)]
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "El apellido es obligatorio.")]
|
||||
[StringLength(50)]
|
||||
public string Apellido { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "El perfil es obligatorio.")]
|
||||
[Range(1, int.MaxValue, ErrorMessage = "Debe seleccionar un perfil válido.")]
|
||||
public int IdPerfil { get; set; }
|
||||
|
||||
public bool Habilitada { get; set; } = true;
|
||||
public bool SupAdmin { get; set; } = false;
|
||||
public bool DebeCambiarClave { get; set; } = true; // Por defecto, forzar cambio al primer login
|
||||
|
||||
[StringLength(10)]
|
||||
public string VerLog { get; set; } = "1.0.0.0"; // Valor por defecto
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class PerfilDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string NombrePerfil { get; set; } = string.Empty;
|
||||
public string? Descripcion { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class PermisoAsignadoDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Modulo { get; set; } = string.Empty;
|
||||
public string DescPermiso { get; set; } = string.Empty;
|
||||
public string CodAcc { get; set; } = string.Empty;
|
||||
public bool Asignado { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class PermisoDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string Modulo { get; set; } = string.Empty;
|
||||
public string DescPermiso { get; set; } = string.Empty;
|
||||
public string CodAcc { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class SetPasswordRequestDto
|
||||
{
|
||||
[Required]
|
||||
[StringLength(50, MinimumLength = 6, ErrorMessage = "La nueva contraseña debe tener al menos 6 caracteres.")]
|
||||
public string NewPassword { get; set; } = string.Empty;
|
||||
public bool ForceChangeOnNextLogin { get; set; } = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class UpdatePerfilDto
|
||||
{
|
||||
[Required(ErrorMessage = "El nombre del perfil es obligatorio.")]
|
||||
[StringLength(20, ErrorMessage = "El nombre del perfil no puede exceder los 20 caracteres.")]
|
||||
public string NombrePerfil { get; set; } = string.Empty;
|
||||
|
||||
[StringLength(150, ErrorMessage = "La descripción no puede exceder los 150 caracteres.")]
|
||||
public string? Descripcion { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class UpdatePermisoDto
|
||||
{
|
||||
[Required(ErrorMessage = "El módulo es obligatorio.")]
|
||||
[StringLength(50, ErrorMessage = "El módulo no puede exceder los 50 caracteres.")]
|
||||
public string Modulo { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "La descripción del permiso es obligatoria.")]
|
||||
[StringLength(150, ErrorMessage = "La descripción no puede exceder los 150 caracteres.")]
|
||||
public string DescPermiso { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "El código de acceso es obligatorio.")]
|
||||
[StringLength(10, ErrorMessage = "El código de acceso no puede exceder los 10 caracteres.")]
|
||||
public string CodAcc { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class UpdateUsuarioRequestDto
|
||||
{
|
||||
// User no se puede cambiar usualmente, o requiere un proceso separado.
|
||||
// Si se permite cambiar, añadir validaciones. Por ahora lo omitimos del DTO de update.
|
||||
|
||||
[Required(ErrorMessage = "El nombre es obligatorio.")]
|
||||
[StringLength(50)]
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "El apellido es obligatorio.")]
|
||||
[StringLength(50)]
|
||||
public string Apellido { get; set; } = string.Empty;
|
||||
|
||||
[Required(ErrorMessage = "El perfil es obligatorio.")]
|
||||
[Range(1, int.MaxValue, ErrorMessage = "Debe seleccionar un perfil válido.")]
|
||||
public int IdPerfil { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "El estado Habilitada es obligatorio.")]
|
||||
public bool Habilitada { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "El estado SupAdmin es obligatorio.")]
|
||||
public bool SupAdmin { get; set; }
|
||||
|
||||
[Required(ErrorMessage = "El estado DebeCambiarClave es obligatorio.")]
|
||||
public bool DebeCambiarClave { get; set; }
|
||||
|
||||
[StringLength(10)]
|
||||
public string VerLog { get; set; } = "1.0.0.0";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace GestionIntegral.Api.Dtos.Usuarios
|
||||
{
|
||||
public class UsuarioDto // Para listar y ver detalles
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public string User { get; set; } = string.Empty;
|
||||
public bool Habilitada { get; set; }
|
||||
public bool SupAdmin { get; set; }
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
public string Apellido { get; set; } = string.Empty;
|
||||
public int IdPerfil { get; set; }
|
||||
public string NombrePerfil { get; set; } = string.Empty; // Para mostrar en la UI
|
||||
public bool DebeCambiarClave { get; set; }
|
||||
public string VerLog { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
14
Backend/GestionIntegral.Api/Models/Usuarios/Perfil.cs
Normal file
14
Backend/GestionIntegral.Api/Models/Usuarios/Perfil.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace GestionIntegral.Api.Models.Usuarios
|
||||
{
|
||||
public class Perfil
|
||||
{
|
||||
// Columna: id (PK, Identity)
|
||||
public int Id { get; set; }
|
||||
|
||||
// Columna: perfil (varchar(20), NOT NULL)
|
||||
public string NombrePerfil { get; set; } = string.Empty; // Renombrado de 'perfil' para evitar conflicto
|
||||
|
||||
// Columna: descPerfil (varchar(150), NULL)
|
||||
public string? Descripcion { get; set; } // Renombrado de 'descPerfil'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace GestionIntegral.Api.Models.Usuarios
|
||||
{
|
||||
public class PerfilHistorico
|
||||
{
|
||||
public int IdPerfil { get; set; } // FK a gral_Perfiles.id
|
||||
public string NombrePerfil { get; set; } = string.Empty;
|
||||
public string? Descripcion { get; set; }
|
||||
public int IdUsuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty; // "Insertada", "Modificada", "Eliminada"
|
||||
}
|
||||
}
|
||||
17
Backend/GestionIntegral.Api/Models/Usuarios/Permiso.cs
Normal file
17
Backend/GestionIntegral.Api/Models/Usuarios/Permiso.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace GestionIntegral.Api.Models.Usuarios
|
||||
{
|
||||
public class Permiso
|
||||
{
|
||||
// Columna: id (PK, Identity)
|
||||
public int Id { get; set; }
|
||||
|
||||
// Columna: modulo (varchar(50), NOT NULL)
|
||||
public string Modulo { get; set; } = string.Empty;
|
||||
|
||||
// Columna: descPermiso (varchar(150), NOT NULL)
|
||||
public string DescPermiso { get; set; } = string.Empty;
|
||||
|
||||
// Columna: codAcc (varchar(10), NOT NULL, UNIQUE)
|
||||
public string CodAcc { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace GestionIntegral.Api.Models.Usuarios
|
||||
{
|
||||
public class PermisoHistorico
|
||||
{
|
||||
public int IdHist { get; set; } // PK de la tabla de historial
|
||||
public int IdPermiso { get; set; } // FK a gral_Permisos.id
|
||||
public string Modulo { get; set; } = string.Empty;
|
||||
public string DescPermiso { get; set; } = string.Empty;
|
||||
public string CodAcc { get; set; } = string.Empty;
|
||||
public int IdUsuario { get; set; }
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace GestionIntegral.Api.Models
|
||||
namespace GestionIntegral.Api.Models.Usuarios
|
||||
{
|
||||
public class Usuario
|
||||
{
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace GestionIntegral.Api.Models.Usuarios
|
||||
{
|
||||
public class UsuarioHistorico
|
||||
{
|
||||
public int IdHist { get; set; }
|
||||
public int IdUsuario { get; set; } // FK al usuario modificado
|
||||
|
||||
public string? UserAnt { get; set; }
|
||||
public string UserNvo { get; set; } = string.Empty;
|
||||
|
||||
public bool? HabilitadaAnt { get; set; }
|
||||
public bool HabilitadaNva { get; set; }
|
||||
|
||||
public bool? SupAdminAnt { get; set; }
|
||||
public bool SupAdminNvo { get; set; }
|
||||
|
||||
public string? NombreAnt { get; set; }
|
||||
public string NombreNvo { get; set; } = string.Empty;
|
||||
|
||||
public string? ApellidoAnt { get; set; }
|
||||
public string ApellidoNvo { get; set; } = string.Empty;
|
||||
|
||||
public int? IdPerfilAnt { get; set; }
|
||||
public int IdPerfilNvo { get; set; }
|
||||
|
||||
public bool? DebeCambiarClaveAnt { get; set; }
|
||||
public bool DebeCambiarClaveNva { get; set; }
|
||||
|
||||
public int Id_UsuarioMod { get; set; } // Quién hizo el cambio
|
||||
public DateTime FechaMod { get; set; }
|
||||
public string TipoMod { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,14 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Services;
|
||||
using GestionIntegral.Api.Services.Contables;
|
||||
using GestionIntegral.Api.Services.Distribucion;
|
||||
using GestionIntegral.Api.Data.Repositories.Contables;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Data.Repositories.Impresion;
|
||||
using GestionIntegral.Api.Services.Impresion;
|
||||
using GestionIntegral.Api.Services.Usuarios;
|
||||
using GestionIntegral.Api.Data.Repositories.Usuarios;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
@@ -30,6 +31,26 @@ builder.Services.AddScoped<ITipoBobinaRepository, TipoBobinaRepository>();
|
||||
builder.Services.AddScoped<ITipoBobinaService, TipoBobinaService>();
|
||||
builder.Services.AddScoped<IEstadoBobinaRepository, EstadoBobinaRepository>();
|
||||
builder.Services.AddScoped<IEstadoBobinaService, EstadoBobinaService>();
|
||||
builder.Services.AddScoped<IOtroDestinoRepository, OtroDestinoRepository>();
|
||||
builder.Services.AddScoped<IOtroDestinoService, OtroDestinoService>();
|
||||
builder.Services.AddScoped<IPerfilRepository, PerfilRepository>();
|
||||
builder.Services.AddScoped<IPerfilService, PerfilService>();
|
||||
builder.Services.AddScoped<IPermisoRepository, PermisoRepository>();
|
||||
builder.Services.AddScoped<IPermisoService, PermisoService>();
|
||||
builder.Services.AddScoped<IUsuarioRepository, UsuarioRepository>();
|
||||
builder.Services.AddScoped<IUsuarioService, UsuarioService>();
|
||||
builder.Services.AddScoped<ICanillaRepository, CanillaRepository>();
|
||||
builder.Services.AddScoped<ICanillaService, CanillaService>();
|
||||
builder.Services.AddScoped<IDistribuidorRepository, DistribuidorRepository>();
|
||||
builder.Services.AddScoped<IDistribuidorService, DistribuidorService>();
|
||||
builder.Services.AddScoped<IPublicacionRepository, PublicacionRepository>();
|
||||
builder.Services.AddScoped<IPublicacionService, PublicacionService>();
|
||||
builder.Services.AddScoped<IRecargoZonaRepository, RecargoZonaRepository>();
|
||||
builder.Services.AddScoped<IPorcPagoRepository, PorcPagoRepository>();
|
||||
builder.Services.AddScoped<IPorcMonCanillaRepository, PorcMonCanillaRepository>();
|
||||
builder.Services.AddScoped<IPubliSeccionRepository, PubliSeccionRepository>();
|
||||
builder.Services.AddScoped<IPrecioRepository, PrecioRepository>();
|
||||
builder.Services.AddScoped<IPrecioService, PrecioService>();
|
||||
|
||||
// --- Configuración de Autenticación JWT ---
|
||||
var jwtSettings = builder.Configuration.GetSection("Jwt");
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Services.Distribucion
|
||||
{
|
||||
public class CanillaService : ICanillaService
|
||||
{
|
||||
private readonly ICanillaRepository _canillaRepository;
|
||||
private readonly IZonaRepository _zonaRepository;
|
||||
private readonly IEmpresaRepository _empresaRepository;
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<CanillaService> _logger;
|
||||
|
||||
public CanillaService(
|
||||
ICanillaRepository canillaRepository,
|
||||
IZonaRepository zonaRepository,
|
||||
IEmpresaRepository empresaRepository,
|
||||
DbConnectionFactory connectionFactory,
|
||||
ILogger<CanillaService> logger)
|
||||
{
|
||||
_canillaRepository = canillaRepository;
|
||||
_zonaRepository = zonaRepository;
|
||||
_empresaRepository = empresaRepository;
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
// CORREGIDO: MapToDto ahora acepta una tupla con tipos anulables
|
||||
private CanillaDto? MapToDto((Canilla? Canilla, string? NombreZona, string? NombreEmpresa) data)
|
||||
{
|
||||
if (data.Canilla == null) return null;
|
||||
|
||||
return new CanillaDto
|
||||
{
|
||||
IdCanilla = data.Canilla.IdCanilla,
|
||||
Legajo = data.Canilla.Legajo,
|
||||
NomApe = data.Canilla.NomApe,
|
||||
Parada = data.Canilla.Parada,
|
||||
IdZona = data.Canilla.IdZona,
|
||||
NombreZona = data.NombreZona ?? "N/A", // Manejar null
|
||||
Accionista = data.Canilla.Accionista,
|
||||
Obs = data.Canilla.Obs,
|
||||
Empresa = data.Canilla.Empresa,
|
||||
NombreEmpresa = data.NombreEmpresa ?? "N/A (Accionista)", // Manejar null
|
||||
Baja = data.Canilla.Baja,
|
||||
FechaBaja = data.Canilla.FechaBaja?.ToString("dd/MM/yyyy")
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<CanillaDto>> ObtenerTodosAsync(string? nomApeFilter, int? legajoFilter, bool? soloActivos)
|
||||
{
|
||||
var canillasData = await _canillaRepository.GetAllAsync(nomApeFilter, legajoFilter, soloActivos);
|
||||
// Filtrar nulos y asegurar al compilador que no hay nulos en la lista final
|
||||
return canillasData.Select(MapToDto).Where(dto => dto != null).Select(dto => dto!);
|
||||
}
|
||||
|
||||
public async Task<CanillaDto?> ObtenerPorIdAsync(int id)
|
||||
{
|
||||
var data = await _canillaRepository.GetByIdAsync(id);
|
||||
// MapToDto ahora devuelve CanillaDto? así que esto es correcto
|
||||
return MapToDto(data);
|
||||
}
|
||||
|
||||
public async Task<(CanillaDto? Canilla, string? Error)> CrearAsync(CreateCanillaDto createDto, int idUsuario)
|
||||
{
|
||||
if (createDto.Legajo.HasValue && createDto.Legajo != 0 && await _canillaRepository.ExistsByLegajoAsync(createDto.Legajo.Value))
|
||||
{
|
||||
return (null, "El legajo ingresado ya existe para otro canillita.");
|
||||
}
|
||||
var zona = await _zonaRepository.GetByIdAsync(createDto.IdZona); // GetByIdAsync de Zona ya considera solo activas
|
||||
if (zona == null)
|
||||
{
|
||||
return (null, "La zona seleccionada no es válida o no está activa.");
|
||||
}
|
||||
if (createDto.Empresa != 0) // Solo validar empresa si no es 0
|
||||
{
|
||||
var empresa = await _empresaRepository.GetByIdAsync(createDto.Empresa);
|
||||
if(empresa == null)
|
||||
{
|
||||
return (null, "La empresa seleccionada no es válida.");
|
||||
}
|
||||
}
|
||||
|
||||
// CORREGIDO: Usar directamente el valor booleano
|
||||
if (createDto.Accionista == true && createDto.Empresa != 0)
|
||||
{
|
||||
return (null, "Un canillita accionista no debe tener una empresa asignada (Empresa debe ser 0).");
|
||||
}
|
||||
if (createDto.Accionista == false && createDto.Empresa == 0)
|
||||
{
|
||||
return (null, "Un canillita no accionista debe tener una empresa asignada (Empresa no puede ser 0).");
|
||||
}
|
||||
|
||||
|
||||
var nuevoCanilla = new Canilla
|
||||
{
|
||||
Legajo = createDto.Legajo == 0 ? null : createDto.Legajo,
|
||||
NomApe = createDto.NomApe,
|
||||
Parada = createDto.Parada,
|
||||
IdZona = createDto.IdZona,
|
||||
Accionista = createDto.Accionista,
|
||||
Obs = createDto.Obs,
|
||||
Empresa = createDto.Empresa,
|
||||
Baja = false,
|
||||
FechaBaja = null
|
||||
};
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
|
||||
try
|
||||
{
|
||||
var canillaCreado = await _canillaRepository.CreateAsync(nuevoCanilla, idUsuario, transaction);
|
||||
if (canillaCreado == null) throw new DataException("Error al crear el canillita.");
|
||||
|
||||
transaction.Commit();
|
||||
|
||||
// Para el DTO de respuesta, necesitamos NombreZona y NombreEmpresa
|
||||
string nombreEmpresaParaDto = "N/A (Accionista)";
|
||||
if (canillaCreado.Empresa != 0)
|
||||
{
|
||||
var empresaData = await _empresaRepository.GetByIdAsync(canillaCreado.Empresa);
|
||||
nombreEmpresaParaDto = empresaData?.Nombre ?? "Empresa Desconocida";
|
||||
}
|
||||
|
||||
var dtoCreado = new CanillaDto {
|
||||
IdCanilla = canillaCreado.IdCanilla, Legajo = canillaCreado.Legajo, NomApe = canillaCreado.NomApe,
|
||||
Parada = canillaCreado.Parada, IdZona = canillaCreado.IdZona, NombreZona = zona.Nombre, // Usar nombre de zona ya obtenido
|
||||
Accionista = canillaCreado.Accionista, Obs = canillaCreado.Obs, Empresa = canillaCreado.Empresa,
|
||||
NombreEmpresa = nombreEmpresaParaDto,
|
||||
Baja = canillaCreado.Baja, FechaBaja = null
|
||||
};
|
||||
|
||||
_logger.LogInformation("Canilla ID {IdCanilla} creado por Usuario ID {IdUsuario}.", canillaCreado.IdCanilla, idUsuario);
|
||||
return (dtoCreado, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch {}
|
||||
_logger.LogError(ex, "Error CrearAsync Canilla: {NomApe}", createDto.NomApe);
|
||||
return (null, $"Error interno al crear el canillita: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateCanillaDto updateDto, int idUsuario)
|
||||
{
|
||||
var canillaExistente = await _canillaRepository.GetByIdSimpleAsync(id);
|
||||
if (canillaExistente == null) return (false, "Canillita no encontrado.");
|
||||
|
||||
if (updateDto.Legajo.HasValue && updateDto.Legajo != 0 && await _canillaRepository.ExistsByLegajoAsync(updateDto.Legajo.Value, id))
|
||||
{
|
||||
return (false, "El legajo ingresado ya existe para otro canillita.");
|
||||
}
|
||||
if (await _zonaRepository.GetByIdAsync(updateDto.IdZona) == null) // GetByIdAsync de Zona ya considera solo activas
|
||||
{
|
||||
return (false, "La zona seleccionada no es válida o no está activa.");
|
||||
}
|
||||
if (updateDto.Empresa != 0) // Solo validar empresa si no es 0
|
||||
{
|
||||
var empresa = await _empresaRepository.GetByIdAsync(updateDto.Empresa);
|
||||
if(empresa == null)
|
||||
{
|
||||
return (false, "La empresa seleccionada no es válida.");
|
||||
}
|
||||
}
|
||||
|
||||
// Usar directamente el valor booleano para Accionista
|
||||
if (updateDto.Accionista == true && updateDto.Empresa != 0)
|
||||
{
|
||||
// Al ser 'bool', no puede ser null. La comparación explícita con 'true'/'false' es para claridad.
|
||||
return (false, "Un canillita accionista no debe tener una empresa asignada (Empresa debe ser 0).");
|
||||
}
|
||||
if (updateDto.Accionista == false && updateDto.Empresa == 0)
|
||||
{
|
||||
return (false, "Un canillita no accionista debe tener una empresa asignada (Empresa no puede ser 0).");
|
||||
}
|
||||
|
||||
// Mapear DTO a entidad existente
|
||||
canillaExistente.Legajo = updateDto.Legajo == 0 ? null : updateDto.Legajo;
|
||||
canillaExistente.NomApe = updateDto.NomApe;
|
||||
canillaExistente.Parada = updateDto.Parada;
|
||||
canillaExistente.IdZona = updateDto.IdZona;
|
||||
canillaExistente.Accionista = updateDto.Accionista; // Aquí Accionista ya es bool
|
||||
canillaExistente.Obs = updateDto.Obs;
|
||||
canillaExistente.Empresa = updateDto.Empresa;
|
||||
// Baja y FechaBaja se manejan por ToggleBajaAsync
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
|
||||
try
|
||||
{
|
||||
var actualizado = await _canillaRepository.UpdateAsync(canillaExistente, idUsuario, transaction);
|
||||
if (!actualizado) throw new DataException("Error al actualizar el canillita.");
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("Canilla ID {IdCanilla} actualizado por Usuario ID {IdUsuario}.", id, idUsuario);
|
||||
return (true, null);
|
||||
}
|
||||
catch (KeyNotFoundException) {
|
||||
try { transaction.Rollback(); } catch {}
|
||||
return (false, "Canillita no encontrado durante la actualización.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch {}
|
||||
_logger.LogError(ex, "Error ActualizarAsync Canilla ID: {IdCanilla}", id);
|
||||
return (false, $"Error interno al actualizar el canillita: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(bool Exito, string? Error)> ToggleBajaAsync(int id, bool darDeBaja, int idUsuario)
|
||||
{
|
||||
var canilla = await _canillaRepository.GetByIdSimpleAsync(id);
|
||||
if (canilla == null) return (false, "Canillita no encontrado.");
|
||||
|
||||
if (canilla.Baja == darDeBaja)
|
||||
{
|
||||
return (false, darDeBaja ? "El canillita ya está dado de baja." : "El canillita ya está activo.");
|
||||
}
|
||||
|
||||
DateTime? fechaBaja = darDeBaja ? DateTime.Now : (DateTime?)null;
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var success = await _canillaRepository.ToggleBajaAsync(id, darDeBaja, fechaBaja, idUsuario, transaction);
|
||||
if (!success) throw new DataException("Error al cambiar estado de baja del canillita.");
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("Estado de baja cambiado a {EstadoBaja} para Canilla ID {IdCanilla} por Usuario ID {IdUsuario}.", darDeBaja, id, idUsuario);
|
||||
return (true, null);
|
||||
}
|
||||
catch (KeyNotFoundException) {
|
||||
try { transaction.Rollback(); } catch {}
|
||||
return (false, "Canillita no encontrado durante el cambio de estado de baja.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch {}
|
||||
_logger.LogError(ex, "Error ToggleBajaAsync Canilla ID: {IdCanilla}", id);
|
||||
return (false, $"Error interno al cambiar estado de baja: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// src/Services/Distribucion/DistribuidorService.cs
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Contables;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Services.Distribucion
|
||||
{
|
||||
public class DistribuidorService : IDistribuidorService
|
||||
{
|
||||
private readonly IDistribuidorRepository _distribuidorRepository;
|
||||
private readonly ISaldoRepository _saldoRepository;
|
||||
private readonly IEmpresaRepository _empresaRepository;
|
||||
private readonly IZonaRepository _zonaRepository;
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<DistribuidorService> _logger;
|
||||
|
||||
public DistribuidorService(
|
||||
IDistribuidorRepository distribuidorRepository,
|
||||
ISaldoRepository saldoRepository,
|
||||
IEmpresaRepository empresaRepository,
|
||||
IZonaRepository zonaRepository,
|
||||
DbConnectionFactory connectionFactory,
|
||||
ILogger<DistribuidorService> logger)
|
||||
{
|
||||
_distribuidorRepository = distribuidorRepository;
|
||||
_saldoRepository = saldoRepository;
|
||||
_empresaRepository = empresaRepository;
|
||||
_zonaRepository = zonaRepository;
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private DistribuidorDto? MapToDto((Distribuidor? Distribuidor, string? NombreZona) data)
|
||||
{
|
||||
if (data.Distribuidor == null) return null;
|
||||
|
||||
return new DistribuidorDto
|
||||
{
|
||||
IdDistribuidor = data.Distribuidor.IdDistribuidor,
|
||||
Nombre = data.Distribuidor.Nombre,
|
||||
Contacto = data.Distribuidor.Contacto,
|
||||
NroDoc = data.Distribuidor.NroDoc,
|
||||
IdZona = data.Distribuidor.IdZona,
|
||||
NombreZona = data.NombreZona, // Ya es anulable en el DTO y en la tupla
|
||||
Calle = data.Distribuidor.Calle,
|
||||
Numero = data.Distribuidor.Numero,
|
||||
Piso = data.Distribuidor.Piso,
|
||||
Depto = data.Distribuidor.Depto,
|
||||
Telefono = data.Distribuidor.Telefono,
|
||||
Email = data.Distribuidor.Email,
|
||||
Localidad = data.Distribuidor.Localidad
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<DistribuidorDto>> ObtenerTodosAsync(string? nombreFilter, string? nroDocFilter)
|
||||
{
|
||||
var data = await _distribuidorRepository.GetAllAsync(nombreFilter, nroDocFilter);
|
||||
// Filtrar nulos y asegurar al compilador que no hay nulos en la lista final
|
||||
return data.Select(MapToDto).Where(dto => dto != null).Select(dto => dto!);
|
||||
}
|
||||
|
||||
public async Task<DistribuidorDto?> ObtenerPorIdAsync(int id)
|
||||
{
|
||||
var data = await _distribuidorRepository.GetByIdAsync(id);
|
||||
// MapToDto ahora devuelve DistribuidorDto?
|
||||
return MapToDto(data);
|
||||
}
|
||||
|
||||
public async Task<(DistribuidorDto? Distribuidor, string? Error)> CrearAsync(CreateDistribuidorDto createDto, int idUsuario)
|
||||
{
|
||||
if (await _distribuidorRepository.ExistsByNroDocAsync(createDto.NroDoc))
|
||||
return (null, "El número de documento ya existe para otro distribuidor.");
|
||||
if (await _distribuidorRepository.ExistsByNameAsync(createDto.Nombre))
|
||||
return (null, "El nombre del distribuidor ya existe.");
|
||||
if (createDto.IdZona.HasValue && await _zonaRepository.GetByIdAsync(createDto.IdZona.Value) == null)
|
||||
return (null, "La zona seleccionada no es válida o no está activa.");
|
||||
|
||||
var nuevoDistribuidor = new Distribuidor
|
||||
{
|
||||
Nombre = createDto.Nombre, Contacto = createDto.Contacto, NroDoc = createDto.NroDoc, IdZona = createDto.IdZona,
|
||||
Calle = createDto.Calle, Numero = createDto.Numero, Piso = createDto.Piso, Depto = createDto.Depto,
|
||||
Telefono = createDto.Telefono, Email = createDto.Email, Localidad = createDto.Localidad
|
||||
};
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
|
||||
try
|
||||
{
|
||||
var distribuidorCreado = await _distribuidorRepository.CreateAsync(nuevoDistribuidor, idUsuario, transaction);
|
||||
if (distribuidorCreado == null) throw new DataException("Error al crear el distribuidor.");
|
||||
|
||||
var empresas = await _empresaRepository.GetAllAsync(null, null);
|
||||
foreach (var empresa in empresas)
|
||||
{
|
||||
bool saldoCreado = await _saldoRepository.CreateSaldoInicialAsync("Distribuidores", distribuidorCreado.IdDistribuidor, empresa.IdEmpresa, transaction);
|
||||
if (!saldoCreado)
|
||||
{
|
||||
throw new DataException($"Falló al crear saldo inicial para el distribuidor {distribuidorCreado.IdDistribuidor} en la empresa {empresa.IdEmpresa}.");
|
||||
}
|
||||
}
|
||||
|
||||
transaction.Commit();
|
||||
var dataCompleta = await _distribuidorRepository.GetByIdAsync(distribuidorCreado.IdDistribuidor);
|
||||
_logger.LogInformation("Distribuidor ID {IdDistribuidor} creado por Usuario ID {IdUsuario}.", distribuidorCreado.IdDistribuidor, idUsuario);
|
||||
// MapToDto ahora devuelve DistribuidorDto?
|
||||
return (MapToDto(dataCompleta), null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch {}
|
||||
_logger.LogError(ex, "Error CrearAsync Distribuidor: {Nombre}", createDto.Nombre);
|
||||
return (null, $"Error interno al crear el distribuidor: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateDistribuidorDto updateDto, int idUsuario)
|
||||
{
|
||||
var distribuidorExistente = await _distribuidorRepository.GetByIdSimpleAsync(id);
|
||||
if (distribuidorExistente == null) return (false, "Distribuidor no encontrado.");
|
||||
|
||||
if (await _distribuidorRepository.ExistsByNroDocAsync(updateDto.NroDoc, id))
|
||||
return (false, "El número de documento ya existe para otro distribuidor.");
|
||||
// CORREGIDO: La tupla de retorno para la validación de nombre debe ser (bool, string?)
|
||||
if (await _distribuidorRepository.ExistsByNameAsync(updateDto.Nombre, id))
|
||||
return (false, "El nombre del distribuidor ya existe."); // Antes (null, ...)
|
||||
if (updateDto.IdZona.HasValue && await _zonaRepository.GetByIdAsync(updateDto.IdZona.Value) == null)
|
||||
return (false, "La zona seleccionada no es válida o no está activa.");
|
||||
|
||||
distribuidorExistente.Nombre = updateDto.Nombre; distribuidorExistente.Contacto = updateDto.Contacto;
|
||||
distribuidorExistente.NroDoc = updateDto.NroDoc; distribuidorExistente.IdZona = updateDto.IdZona;
|
||||
distribuidorExistente.Calle = updateDto.Calle; distribuidorExistente.Numero = updateDto.Numero;
|
||||
distribuidorExistente.Piso = updateDto.Piso; distribuidorExistente.Depto = updateDto.Depto;
|
||||
distribuidorExistente.Telefono = updateDto.Telefono; distribuidorExistente.Email = updateDto.Email;
|
||||
distribuidorExistente.Localidad = updateDto.Localidad;
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var actualizado = await _distribuidorRepository.UpdateAsync(distribuidorExistente, idUsuario, transaction);
|
||||
if (!actualizado) throw new DataException("Error al actualizar.");
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("Distribuidor ID {IdDistribuidor} actualizado por Usuario ID {IdUsuario}.", id, idUsuario);
|
||||
return (true, null);
|
||||
}
|
||||
catch (KeyNotFoundException) { try { transaction.Rollback(); } catch {} return (false, "Distribuidor no encontrado."); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch {}
|
||||
_logger.LogError(ex, "Error ActualizarAsync Distribuidor ID: {IdDistribuidor}", id);
|
||||
return (false, $"Error interno: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario)
|
||||
{
|
||||
var distribuidorExistente = await _distribuidorRepository.GetByIdSimpleAsync(id);
|
||||
if (distribuidorExistente == null) return (false, "Distribuidor no encontrado.");
|
||||
|
||||
if (await _distribuidorRepository.IsInUseAsync(id))
|
||||
return (false, "No se puede eliminar. El distribuidor tiene movimientos o configuraciones asociadas.");
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
try
|
||||
{
|
||||
// Lógica para eliminar saldos asociados (si se implementa)
|
||||
// var saldosEliminados = await _saldoRepository.DeleteSaldosByDestinoAsync("Distribuidores", id, transaction);
|
||||
// if (!saldosEliminados) throw new DataException("Error al eliminar saldos del distribuidor.");
|
||||
|
||||
var eliminado = await _distribuidorRepository.DeleteAsync(id, idUsuario, transaction);
|
||||
if (!eliminado) throw new DataException("Error al eliminar.");
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("Distribuidor ID {IdDistribuidor} eliminado por Usuario ID {IdUsuario}.", id, idUsuario);
|
||||
return (true, null);
|
||||
}
|
||||
catch (KeyNotFoundException) { try { transaction.Rollback(); } catch {} return (false, "Distribuidor no encontrado."); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch {}
|
||||
_logger.LogError(ex, "Error EliminarAsync Distribuidor ID: {IdDistribuidor}", id);
|
||||
return (false, $"Error interno: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user