Feat: Implementa ABM y anulación de ajustes manuales
Este commit introduce la funcionalidad completa para la gestión de ajustes manuales (créditos/débitos) en la cuenta corriente de un suscriptor, cerrando un requerimiento clave detectado en el análisis del flujo de trabajo manual. Backend: - Se añade la tabla `susc_Ajustes` para registrar movimientos manuales. - Se crean el Modelo, DTOs, Repositorio y Servicio (`AjusteService`) para el ABM completo de los ajustes. - Se implementa la lógica para anular ajustes que se encuentren en estado "Pendiente", registrando el usuario y fecha de anulación para mantener la trazabilidad. - Se integra la lógica de aplicación de ajustes pendientes en el `FacturacionService`, afectando el `ImporteFinal` de la factura generada. - Se añaden los nuevos endpoints en `AjustesController` para crear, listar y anular ajustes. Frontend: - Se crea el componente `CuentaCorrienteSuscriptorTab` para mostrar el historial de ajustes de un cliente. - Se desarrolla el modal `AjusteFormModal` que permite a los usuarios registrar nuevos créditos o débitos. - Se integra una nueva pestaña "Cuenta Corriente / Ajustes" en la vista de gestión de un suscriptor. - Se añade la funcionalidad de "Anular" en la tabla de ajustes, permitiendo a los usuarios corregir errores antes del ciclo de facturación.
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Suscripciones;
|
||||
using GestionIntegral.Api.Data.Repositories.Usuarios;
|
||||
using GestionIntegral.Api.Dtos.Suscripciones;
|
||||
using GestionIntegral.Api.Models.Suscripciones;
|
||||
using System.Data;
|
||||
|
||||
namespace GestionIntegral.Api.Services.Suscripciones
|
||||
{
|
||||
public class AjusteService : IAjusteService
|
||||
{
|
||||
private readonly IAjusteRepository _ajusteRepository;
|
||||
private readonly ISuscriptorRepository _suscriptorRepository;
|
||||
private readonly IUsuarioRepository _usuarioRepository;
|
||||
private readonly DbConnectionFactory _connectionFactory;
|
||||
private readonly ILogger<AjusteService> _logger;
|
||||
|
||||
public AjusteService(
|
||||
IAjusteRepository ajusteRepository,
|
||||
ISuscriptorRepository suscriptorRepository,
|
||||
IUsuarioRepository usuarioRepository,
|
||||
DbConnectionFactory connectionFactory,
|
||||
ILogger<AjusteService> logger)
|
||||
{
|
||||
_ajusteRepository = ajusteRepository;
|
||||
_suscriptorRepository = suscriptorRepository;
|
||||
_usuarioRepository = usuarioRepository;
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private async Task<AjusteDto?> MapToDto(Ajuste ajuste)
|
||||
{
|
||||
if (ajuste == null) return null;
|
||||
var usuario = await _usuarioRepository.GetByIdAsync(ajuste.IdUsuarioAlta);
|
||||
return new AjusteDto
|
||||
{
|
||||
IdAjuste = ajuste.IdAjuste,
|
||||
IdSuscriptor = ajuste.IdSuscriptor,
|
||||
TipoAjuste = ajuste.TipoAjuste,
|
||||
Monto = ajuste.Monto,
|
||||
Motivo = ajuste.Motivo,
|
||||
Estado = ajuste.Estado,
|
||||
IdFacturaAplicado = ajuste.IdFacturaAplicado,
|
||||
FechaAlta = ajuste.FechaAlta.ToString("yyyy-MM-dd HH:mm"),
|
||||
NombreUsuarioAlta = usuario != null ? $"{usuario.Nombre} {usuario.Apellido}" : "N/A"
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<AjusteDto>> ObtenerAjustesPorSuscriptor(int idSuscriptor)
|
||||
{
|
||||
var ajustes = await _ajusteRepository.GetAjustesPorSuscriptorAsync(idSuscriptor);
|
||||
var dtosTasks = ajustes.Select(a => MapToDto(a));
|
||||
var dtos = await Task.WhenAll(dtosTasks);
|
||||
return dtos.Where(dto => dto != null)!;
|
||||
}
|
||||
|
||||
public async Task<(AjusteDto? Ajuste, string? Error)> CrearAjusteManual(CreateAjusteDto createDto, int idUsuario)
|
||||
{
|
||||
var suscriptor = await _suscriptorRepository.GetByIdAsync(createDto.IdSuscriptor);
|
||||
if (suscriptor == null)
|
||||
{
|
||||
return (null, "El suscriptor especificado no existe.");
|
||||
}
|
||||
|
||||
var nuevoAjuste = new Ajuste
|
||||
{
|
||||
IdSuscriptor = createDto.IdSuscriptor,
|
||||
TipoAjuste = createDto.TipoAjuste,
|
||||
Monto = createDto.Monto,
|
||||
Motivo = createDto.Motivo,
|
||||
IdUsuarioAlta = idUsuario
|
||||
};
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
await (connection as System.Data.Common.DbConnection)!.OpenAsync();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var ajusteCreado = await _ajusteRepository.CreateAsync(nuevoAjuste, transaction);
|
||||
if (ajusteCreado == null) throw new DataException("Error al crear el registro de ajuste.");
|
||||
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("Ajuste manual ID {IdAjuste} creado para Suscriptor ID {IdSuscriptor} por Usuario ID {IdUsuario}", ajusteCreado.IdAjuste, ajusteCreado.IdSuscriptor, idUsuario);
|
||||
|
||||
var dto = await MapToDto(ajusteCreado);
|
||||
return (dto, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch { }
|
||||
_logger.LogError(ex, "Error al crear ajuste manual para Suscriptor ID {IdSuscriptor}", createDto.IdSuscriptor);
|
||||
return (null, "Error interno al registrar el ajuste.");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(bool Exito, string? Error)> AnularAjuste(int idAjuste, int idUsuario)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
await (connection as System.Data.Common.DbConnection)!.OpenAsync();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var ajuste = await _ajusteRepository.GetByIdAsync(idAjuste);
|
||||
if (ajuste == null) return (false, "Ajuste no encontrado.");
|
||||
if (ajuste.Estado != "Pendiente") return (false, $"No se puede anular un ajuste en estado '{ajuste.Estado}'.");
|
||||
|
||||
var exito = await _ajusteRepository.AnularAjusteAsync(idAjuste, idUsuario, transaction);
|
||||
if (!exito) throw new DataException("No se pudo anular el ajuste.");
|
||||
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("Ajuste ID {IdAjuste} anulado por Usuario ID {IdUsuario}", idAjuste, idUsuario);
|
||||
return (true, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch { }
|
||||
_logger.LogError(ex, "Error al anular ajuste ID {IdAjuste}", idAjuste);
|
||||
return (false, "Error interno al anular el ajuste.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user