using AutoMapper; using CuentasCobrar.CORE.DTOs; using CuentasCobrar.CORE.Entities; using CuentasCobrar.CORE.Exceptions; using CuentasCobrar.CORE.Interfaces; using CuentasCobrar.CORE.QueryFilters; using CuentasCobrar.CORE.ResponseObjects; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System.Net; namespace CuentasCobrar.API.Controllers { [Route("api/[controller]")] [Produces("application/json")] [ApiController] public class FacturaController : ControllerBase { private readonly IFacturaRepo _FacturaRepo; private readonly IPagoContieneFacturaRepo _PagoContieneFacturaRepo; private readonly IMapper _mapper; private readonly IConfiguration _configuration; public FacturaController(IFacturaRepo facturaRepo, IPagoContieneFacturaRepo pagoContieneFacturaRepo, IMapper mapper, IConfiguration configuration) { _FacturaRepo = facturaRepo; _PagoContieneFacturaRepo = pagoContieneFacturaRepo; _mapper = mapper; _configuration = configuration; } /// /// Obtiene todas las facturas /// /// /// Retorna todas las facturas de la base de datos /// [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(IEnumerable))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpGet("obtenerTodos/"), Authorize(Roles = "ADMINISTRADOR,OPERATIVO,CONTADOR")] public async Task Get() { try { var facturas = await _FacturaRepo.Get(); if (facturas == null) { throw new BadRequestException("Hubo un problema al obtener las facturas"); } var facturasDto = _mapper.Map>(facturas); return Ok(facturasDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Obtiene las facturas aplicando los filtros de paginación         ///         ///         /// Retorna las facturas de la base de datos paginadas         /// [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(IEnumerable))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpGet, Authorize(Roles = "ADMINISTRADOR,OPERATIVO,CONTADOR")] public async Task Get([FromQuery] FacturaQueryFilter filters) { try { int NumeroDePagina = _configuration.GetValue("PaginationDefaultConfig:NumeroDePagina"); int RegistrosPorPagina = _configuration.GetValue("PaginationDefaultConfig:RegistrosPorPagina"); filters.NumeroDePagina = filters.NumeroDePagina == 0 ? NumeroDePagina : filters.NumeroDePagina; filters.RegistrosPorPagina = filters.RegistrosPorPagina == 0 ? RegistrosPorPagina : filters.RegistrosPorPagina; var facturas = await _FacturaRepo.Get(filters); if (facturas == null) { throw new BadRequestException("Hubo un problema al obtener los países"); } var FacturasDto = _mapper.Map>(facturas); var metadata = new { facturas.NumeroDePagina, facturas.RegistrosTotales, facturas.RegistrosPorPagina, facturas.PaginasTotales, facturas.HayPaginaSiguiente, facturas.HayPaginaAnterior, facturas.NumeroPaginaSiguiente, facturas.NumeroPaginaAnterior }; Response.Headers.Add("Pagination-Info", JsonConvert.SerializeObject(metadata)); return Ok(FacturasDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Obtiene la factura especificada por su consecutivo         ///         ///         /// Retorna los datos de la factura especificada [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(FacturaDTO))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpGet("{consecutivoFactura}"), Authorize(Roles = "ADMINISTRADOR,OPERATIVO,CONTADOR")] public async Task Get(string consecutivoFactura) { try { var factura = await _FacturaRepo.Get(consecutivoFactura); if (factura == null) { throw new BadRequestException("La factura no existe"); } var FacturaDto = _mapper.Map(factura); return Ok(FacturaDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Agrega una factura         ///         /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpPost, Authorize(Roles = "ADMINISTRADOR,OPERATIVO")] public async Task Post(FacturaDTO facturaDto) { try { var factura = _mapper.Map(facturaDto); bool agregado = await _FacturaRepo.Post(factura); if (agregado == false) { throw new BadRequestException("Hubo un problema al agregar la factura"); } return Ok(agregado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Actualiza la factura especificada por su consecutivo         ///         /// Factura [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpPut, Authorize(Roles = "ADMINISTRADOR,OPERATIVO")] public async Task Put(FacturaDTO facturaDto) { try { var facturaTemp = await _FacturaRepo.Get(facturaDto.Consecutivo); if (facturaTemp == null) { throw new BadRequestException("La factura a modificar no existe"); } var factura = _mapper.Map(facturaDto); bool modificado = await _FacturaRepo.Put(factura); if (modificado == false) { throw new BadRequestException("Hubo un problema al modificar la factura"); } return Ok(modificado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Elimina la factura especificada por su consecutivo         ///         /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpDelete("{consecutivoFactura}"), Authorize(Roles = "ADMINISTRADOR,OPERATIVO")] public async Task Delete(string consecutivoFactura) { try { var facturaTemp = await _FacturaRepo.Get(consecutivoFactura); if (facturaTemp == null) { throw new BadRequestException("La factura a eliminar no existe"); } List facturaConPago = await _PagoContieneFacturaRepo.Get(); facturaConPago = facturaConPago.FindAll(x => x.ConsecutivoFactura == consecutivoFactura); if (facturaConPago != null && facturaConPago.Count > 0) { throw new BadRequestException("La factura no se puede eliminar porque está asociada a un pago"); } bool eliminado = await _FacturaRepo.Delete(consecutivoFactura); if (eliminado == false) { throw new BadRequestException("Hubo un problema al eliminar la factura"); } return Ok(eliminado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } /// /// Genera una nota de crédito /// /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpPost("GenerarNotaCredito/"), Authorize(Roles = "ADMINISTRADOR,OPERATIVO")] public async Task GenerarNotaCredito(FacturaDTO notaCreditoDTO) { try { var facturaTemp = await _FacturaRepo.Get(notaCreditoDTO.ConsecutivoNotaReferencia); if (facturaTemp == null) { throw new BadRequestException("La factura no existe"); } var notaCredito = _mapper.Map(notaCreditoDTO); bool generada = await _FacturaRepo.GenerarNotaCredito(facturaTemp, notaCredito); if (generada == false) { throw new BadRequestException("Hubo un problema al generar la nota de crédito"); } return Ok(generada); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } } }