206 lines
		
	
	
		
			11 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
		
		
			
		
	
	
			206 lines
		
	
	
		
			11 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
|  | // src/Services/Distribucion/PublicacionService.cs | ||
|  | 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 PublicacionService : IPublicacionService | ||
|  |     { | ||
|  |         private readonly IPublicacionRepository _publicacionRepository; | ||
|  |         private readonly IEmpresaRepository _empresaRepository; | ||
|  |         private readonly DbConnectionFactory _connectionFactory; | ||
|  |         private readonly ILogger<PublicacionService> _logger; | ||
|  |         private readonly IPrecioRepository _precioRepository; | ||
|  |         private readonly IRecargoZonaRepository _recargoZonaRepository; | ||
|  |         private readonly IPorcPagoRepository _porcPagoRepository; | ||
|  |         private readonly IPorcMonCanillaRepository _porcMonCanillaRepository; | ||
|  |         private readonly IPubliSeccionRepository _publiSeccionRepository; | ||
|  | 
 | ||
|  |         public PublicacionService( | ||
|  |             IPublicacionRepository publicacionRepository, | ||
|  |             IEmpresaRepository empresaRepository, | ||
|  |             DbConnectionFactory connectionFactory, | ||
|  |             ILogger<PublicacionService> logger, | ||
|  |             IPrecioRepository precioRepository, | ||
|  |             IRecargoZonaRepository recargoZonaRepository, | ||
|  |             IPorcPagoRepository porcPagoRepository, | ||
|  |             IPorcMonCanillaRepository porcMonCanillaRepository, | ||
|  |             IPubliSeccionRepository publiSeccionRepository) | ||
|  |         { | ||
|  |             _publicacionRepository = publicacionRepository; | ||
|  |             _empresaRepository = empresaRepository; | ||
|  |             _connectionFactory = connectionFactory; | ||
|  |             _logger = logger; | ||
|  |             _precioRepository = precioRepository; | ||
|  |             _recargoZonaRepository = recargoZonaRepository; | ||
|  |             _porcPagoRepository = porcPagoRepository; | ||
|  |             _porcMonCanillaRepository = porcMonCanillaRepository; | ||
|  |             _publiSeccionRepository = publiSeccionRepository; | ||
|  |         } | ||
|  | 
 | ||
|  |         private PublicacionDto? MapToDto((Publicacion? Publicacion, string? NombreEmpresa) data) | ||
|  |         { | ||
|  |             if (data.Publicacion == null) return null; // Si la publicación es null, no se puede mapear | ||
|  | 
 | ||
|  |             return new PublicacionDto | ||
|  |             { | ||
|  |                 IdPublicacion = data.Publicacion.IdPublicacion, | ||
|  |                 Nombre = data.Publicacion.Nombre, | ||
|  |                 Observacion = data.Publicacion.Observacion, | ||
|  |                 IdEmpresa = data.Publicacion.IdEmpresa, | ||
|  |                 NombreEmpresa = data.NombreEmpresa ?? "Empresa Desconocida", // Manejar null para NombreEmpresa | ||
|  |                 CtrlDevoluciones = data.Publicacion.CtrlDevoluciones, | ||
|  |                 Habilitada = data.Publicacion.Habilitada ?? true // Asumir true si es null desde BD | ||
|  |             }; | ||
|  |         } | ||
|  | 
 | ||
|  |         public async Task<IEnumerable<PublicacionDto>> ObtenerTodasAsync(string? nombreFilter, int? idEmpresaFilter, bool? soloHabilitadas) | ||
|  |         { | ||
|  |             var data = await _publicacionRepository.GetAllAsync(nombreFilter, idEmpresaFilter, soloHabilitadas); | ||
|  |             // Filtrar los nulos que MapToDto podría devolver (si alguna tupla tuviera Publicacion null) | ||
|  |             return data.Select(MapToDto).Where(dto => dto != null).Select(dto => dto!); | ||
|  |         } | ||
|  | 
 | ||
|  |         public async Task<PublicacionDto?> ObtenerPorIdAsync(int id) | ||
|  |         { | ||
|  |             var data = await _publicacionRepository.GetByIdAsync(id); | ||
|  |             // MapToDto ahora devuelve PublicacionDto? | ||
|  |             return MapToDto(data); | ||
|  |         } | ||
|  | 
 | ||
|  |         public async Task<(PublicacionDto? Publicacion, string? Error)> CrearAsync(CreatePublicacionDto createDto, int idUsuario) | ||
|  |         { | ||
|  |             if (await _empresaRepository.GetByIdAsync(createDto.IdEmpresa) == null) | ||
|  |                 return (null, "La empresa seleccionada no es válida."); | ||
|  |             if (await _publicacionRepository.ExistsByNameAndEmpresaAsync(createDto.Nombre, createDto.IdEmpresa)) | ||
|  |                 return (null, "Ya existe una publicación con ese nombre para la empresa seleccionada."); | ||
|  | 
 | ||
|  |             var nuevaPublicacion = new Publicacion | ||
|  |             { | ||
|  |                 Nombre = createDto.Nombre, | ||
|  |                 Observacion = createDto.Observacion, | ||
|  |                 IdEmpresa = createDto.IdEmpresa, | ||
|  |                 CtrlDevoluciones = createDto.CtrlDevoluciones, | ||
|  |                 Habilitada = createDto.Habilitada | ||
|  |             }; | ||
|  | 
 | ||
|  |             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 creada = await _publicacionRepository.CreateAsync(nuevaPublicacion, idUsuario, transaction); | ||
|  |                 if (creada == null) throw new DataException("Error al crear publicación."); | ||
|  | 
 | ||
|  |                 transaction.Commit(); | ||
|  |                 var dataCompleta = await _publicacionRepository.GetByIdAsync(creada.IdPublicacion); // Para obtener NombreEmpresa | ||
|  |                 _logger.LogInformation("Publicación ID {Id} creada por Usuario ID {UserId}.", creada.IdPublicacion, idUsuario); | ||
|  |                 // MapToDto ahora devuelve PublicacionDto? | ||
|  |                 return (MapToDto(dataCompleta), null); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 try { transaction.Rollback(); } catch { } | ||
|  |                 _logger.LogError(ex, "Error CrearAsync Publicacion: {Nombre}", createDto.Nombre); | ||
|  |                 return (null, $"Error interno: {ex.Message}"); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         public async Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdatePublicacionDto updateDto, int idUsuario) | ||
|  |         { | ||
|  |             var existente = await _publicacionRepository.GetByIdSimpleAsync(id); | ||
|  |             if (existente == null) return (false, "Publicación no encontrada."); | ||
|  |             if (await _empresaRepository.GetByIdAsync(updateDto.IdEmpresa) == null) | ||
|  |                 return (false, "La empresa seleccionada no es válida."); | ||
|  |             if (await _publicacionRepository.ExistsByNameAndEmpresaAsync(updateDto.Nombre, updateDto.IdEmpresa, id)) | ||
|  |                 return (false, "Ya existe otra publicación con ese nombre para la empresa seleccionada."); | ||
|  | 
 | ||
|  |             existente.Nombre = updateDto.Nombre; existente.Observacion = updateDto.Observacion; | ||
|  |             existente.IdEmpresa = updateDto.IdEmpresa; existente.CtrlDevoluciones = updateDto.CtrlDevoluciones; | ||
|  |             existente.Habilitada = updateDto.Habilitada; | ||
|  | 
 | ||
|  |             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 _publicacionRepository.UpdateAsync(existente, idUsuario, transaction); | ||
|  |                 if (!actualizado) throw new DataException("Error al actualizar."); | ||
|  |                 transaction.Commit(); | ||
|  |                 _logger.LogInformation("Publicación ID {Id} actualizada por Usuario ID {UserId}.", id, idUsuario); | ||
|  |                 return (true, null); | ||
|  |             } | ||
|  |             catch (KeyNotFoundException) { try { transaction.Rollback(); } catch { } return (false, "Publicación no encontrada."); } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 try { transaction.Rollback(); } catch { } | ||
|  |                 _logger.LogError(ex, "Error ActualizarAsync Publicacion ID: {Id}", id); | ||
|  |                 return (false, $"Error interno: {ex.Message}"); | ||
|  |             } | ||
|  |         } | ||
|  | 
 | ||
|  |         public async Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario) // idUsuario es el que realiza la acción | ||
|  |         { | ||
|  |             var existente = await _publicacionRepository.GetByIdSimpleAsync(id); | ||
|  |             if (existente == null) return (false, "Publicación no encontrada."); | ||
|  | 
 | ||
|  |             if (await _publicacionRepository.IsInUseAsync(id)) | ||
|  |             { | ||
|  |                 return (false, "No se puede eliminar. La publicación tiene datos transaccionales o de configuración relacionados."); | ||
|  |             } | ||
|  | 
 | ||
|  |             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 | ||
|  |             { | ||
|  |                 _logger.LogInformation("Iniciando eliminación de dependencias para Publicación ID: {IdPublicacion} por Usuario ID: {idUsuario}", id, idUsuario); | ||
|  | 
 | ||
|  |                 // Pasar idUsuario a los métodos de borrado para auditoría | ||
|  |                 await _precioRepository.DeleteByPublicacionIdAsync(id, idUsuario, transaction); | ||
|  |                 _logger.LogDebug("Precios eliminados para Publicación ID: {IdPublicacion}", id); | ||
|  | 
 | ||
|  |                 await _recargoZonaRepository.DeleteByPublicacionIdAsync(id, idUsuario, transaction); | ||
|  |                 _logger.LogDebug("RecargosZona eliminados para Publicación ID: {IdPublicacion}", id); | ||
|  | 
 | ||
|  |                 await _porcPagoRepository.DeleteByPublicacionIdAsync(id, idUsuario, transaction); | ||
|  |                 _logger.LogDebug("PorcPago eliminados para Publicación ID: {IdPublicacion}", id); | ||
|  | 
 | ||
|  |                 await _porcMonCanillaRepository.DeleteByPublicacionIdAsync(id, idUsuario, transaction); | ||
|  |                 _logger.LogDebug("PorcMonCanilla eliminados para Publicación ID: {IdPublicacion}", id); | ||
|  | 
 | ||
|  |                 await _publiSeccionRepository.DeleteByPublicacionIdAsync(id, idUsuario, transaction); | ||
|  |                 _logger.LogDebug("PubliSecciones eliminadas para Publicación ID: {IdPublicacion}", id); | ||
|  | 
 | ||
|  |                 var eliminado = await _publicacionRepository.DeleteAsync(id, idUsuario, transaction); | ||
|  |                 if (!eliminado) | ||
|  |                 { | ||
|  |                     throw new DataException("Error al eliminar la publicación principal después de sus dependencias."); | ||
|  |                 } | ||
|  | 
 | ||
|  |                 transaction.Commit(); | ||
|  |                 _logger.LogInformation("Publicación ID {Id} y sus dependencias eliminadas por Usuario ID {UserId}.", id, idUsuario); | ||
|  |                 return (true, null); | ||
|  |             } | ||
|  |             catch (KeyNotFoundException knfEx) | ||
|  |             { | ||
|  |                 try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error en Rollback tras KeyNotFoundException."); } | ||
|  |                 _logger.LogWarning(knfEx, "Entidad no encontrada durante la eliminación de Publicación ID {Id}.", id); | ||
|  |                 return (false, "Una entidad relacionada o la publicación misma no fue encontrada durante la eliminación."); | ||
|  |             } | ||
|  |             catch (Exception ex) | ||
|  |             { | ||
|  |                 try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error en Rollback tras excepción general."); } | ||
|  |                 _logger.LogError(ex, "Error EliminarAsync Publicacion ID: {Id}", id); | ||
|  |                 return (false, $"Error interno al eliminar la publicación y sus dependencias: {ex.Message}"); | ||
|  |             } | ||
|  |         } | ||
|  |     } | ||
|  | } |