143 lines
6.8 KiB
C#
143 lines
6.8 KiB
C#
|
|
using GestionIntegral.Api.Data;
|
||
|
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||
|
|
using GestionIntegral.Api.Data.Repositories.Suscripciones;
|
||
|
|
using GestionIntegral.Api.Dtos.Suscripciones;
|
||
|
|
using GestionIntegral.Api.Models.Suscripciones;
|
||
|
|
using System.Data;
|
||
|
|
|
||
|
|
namespace GestionIntegral.Api.Services.Suscripciones
|
||
|
|
{
|
||
|
|
public class SuscripcionService : ISuscripcionService
|
||
|
|
{
|
||
|
|
private readonly ISuscripcionRepository _suscripcionRepository;
|
||
|
|
private readonly ISuscriptorRepository _suscriptorRepository;
|
||
|
|
private readonly IPublicacionRepository _publicacionRepository;
|
||
|
|
private readonly DbConnectionFactory _connectionFactory;
|
||
|
|
private readonly ILogger<SuscripcionService> _logger;
|
||
|
|
|
||
|
|
public SuscripcionService(
|
||
|
|
ISuscripcionRepository suscripcionRepository,
|
||
|
|
ISuscriptorRepository suscriptorRepository,
|
||
|
|
IPublicacionRepository publicacionRepository,
|
||
|
|
DbConnectionFactory connectionFactory,
|
||
|
|
ILogger<SuscripcionService> logger)
|
||
|
|
{
|
||
|
|
_suscripcionRepository = suscripcionRepository;
|
||
|
|
_suscriptorRepository = suscriptorRepository;
|
||
|
|
_publicacionRepository = publicacionRepository;
|
||
|
|
_connectionFactory = connectionFactory;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
private async Task<SuscripcionDto?> MapToDto(Suscripcion suscripcion)
|
||
|
|
{
|
||
|
|
if (suscripcion == null) return null;
|
||
|
|
var publicacion = await _publicacionRepository.GetByIdSimpleAsync(suscripcion.IdPublicacion);
|
||
|
|
return new SuscripcionDto
|
||
|
|
{
|
||
|
|
IdSuscripcion = suscripcion.IdSuscripcion,
|
||
|
|
IdSuscriptor = suscripcion.IdSuscriptor,
|
||
|
|
IdPublicacion = suscripcion.IdPublicacion,
|
||
|
|
NombrePublicacion = publicacion?.Nombre ?? "Desconocida",
|
||
|
|
FechaInicio = suscripcion.FechaInicio.ToString("yyyy-MM-dd"),
|
||
|
|
FechaFin = suscripcion.FechaFin?.ToString("yyyy-MM-dd"),
|
||
|
|
Estado = suscripcion.Estado,
|
||
|
|
DiasEntrega = suscripcion.DiasEntrega,
|
||
|
|
Observaciones = suscripcion.Observaciones
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<SuscripcionDto?> ObtenerPorId(int idSuscripcion)
|
||
|
|
{
|
||
|
|
var suscripcion = await _suscripcionRepository.GetByIdAsync(idSuscripcion);
|
||
|
|
if (suscripcion == null)
|
||
|
|
return null;
|
||
|
|
return await MapToDto(suscripcion);
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<IEnumerable<SuscripcionDto>> ObtenerPorSuscriptorId(int idSuscriptor)
|
||
|
|
{
|
||
|
|
var suscripciones = await _suscripcionRepository.GetBySuscriptorIdAsync(idSuscriptor);
|
||
|
|
var dtosTasks = suscripciones.Select(s => MapToDto(s));
|
||
|
|
var dtos = await Task.WhenAll(dtosTasks);
|
||
|
|
return dtos.Where(dto => dto != null)!;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<(SuscripcionDto? Suscripcion, string? Error)> Crear(CreateSuscripcionDto createDto, int idUsuario)
|
||
|
|
{
|
||
|
|
if (await _suscriptorRepository.GetByIdAsync(createDto.IdSuscriptor) == null)
|
||
|
|
return (null, "El suscriptor no existe.");
|
||
|
|
if (await _publicacionRepository.GetByIdSimpleAsync(createDto.IdPublicacion) == null)
|
||
|
|
return (null, "La publicación no existe.");
|
||
|
|
if (createDto.FechaFin.HasValue && createDto.FechaFin.Value < createDto.FechaInicio)
|
||
|
|
return (null, "La fecha de fin no puede ser anterior a la fecha de inicio.");
|
||
|
|
|
||
|
|
var nuevaSuscripcion = new Suscripcion
|
||
|
|
{
|
||
|
|
IdSuscriptor = createDto.IdSuscriptor,
|
||
|
|
IdPublicacion = createDto.IdPublicacion,
|
||
|
|
FechaInicio = createDto.FechaInicio,
|
||
|
|
FechaFin = createDto.FechaFin,
|
||
|
|
Estado = createDto.Estado,
|
||
|
|
DiasEntrega = string.Join(",", createDto.DiasEntrega),
|
||
|
|
Observaciones = createDto.Observaciones,
|
||
|
|
IdUsuarioAlta = idUsuario
|
||
|
|
};
|
||
|
|
|
||
|
|
using var connection = _connectionFactory.CreateConnection();
|
||
|
|
await (connection as System.Data.Common.DbConnection)!.OpenAsync();
|
||
|
|
using var transaction = connection.BeginTransaction();
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var creada = await _suscripcionRepository.CreateAsync(nuevaSuscripcion, transaction);
|
||
|
|
if (creada == null) throw new DataException("Error al crear la suscripción.");
|
||
|
|
|
||
|
|
transaction.Commit();
|
||
|
|
_logger.LogInformation("Suscripción ID {Id} creada por Usuario ID {UserId}.", creada.IdSuscripcion, idUsuario);
|
||
|
|
return (await MapToDto(creada), null);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
try { transaction.Rollback(); } catch { }
|
||
|
|
_logger.LogError(ex, "Error al crear suscripción para suscriptor ID {IdSuscriptor}", createDto.IdSuscriptor);
|
||
|
|
return (null, $"Error interno: {ex.Message}");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task<(bool Exito, string? Error)> Actualizar(int idSuscripcion, UpdateSuscripcionDto updateDto, int idUsuario)
|
||
|
|
{
|
||
|
|
var existente = await _suscripcionRepository.GetByIdAsync(idSuscripcion);
|
||
|
|
if (existente == null) return (false, "Suscripción no encontrada.");
|
||
|
|
|
||
|
|
if (updateDto.FechaFin.HasValue && updateDto.FechaFin.Value < updateDto.FechaInicio)
|
||
|
|
return (false, "La fecha de fin no puede ser anterior a la fecha de inicio.");
|
||
|
|
|
||
|
|
existente.FechaInicio = updateDto.FechaInicio;
|
||
|
|
existente.FechaFin = updateDto.FechaFin;
|
||
|
|
existente.Estado = updateDto.Estado;
|
||
|
|
existente.DiasEntrega = string.Join(",", updateDto.DiasEntrega);
|
||
|
|
existente.Observaciones = updateDto.Observaciones;
|
||
|
|
existente.IdUsuarioMod = idUsuario;
|
||
|
|
existente.FechaMod = DateTime.Now;
|
||
|
|
|
||
|
|
using var connection = _connectionFactory.CreateConnection();
|
||
|
|
await (connection as System.Data.Common.DbConnection)!.OpenAsync();
|
||
|
|
using var transaction = connection.BeginTransaction();
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var actualizado = await _suscripcionRepository.UpdateAsync(existente, transaction);
|
||
|
|
if (!actualizado) throw new DataException("Error al actualizar la suscripción.");
|
||
|
|
|
||
|
|
transaction.Commit();
|
||
|
|
_logger.LogInformation("Suscripción ID {Id} actualizada por Usuario ID {UserId}.", idSuscripcion, idUsuario);
|
||
|
|
return (true, null);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
try { transaction.Rollback(); } catch { }
|
||
|
|
_logger.LogError(ex, "Error al actualizar suscripción ID: {IdSuscripcion}", idSuscripcion);
|
||
|
|
return (false, $"Error interno: {ex.Message}");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|