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 ClienteController : ControllerBase { private readonly IClienteRepo _clienteRepo; private readonly IMapper _mapper; private readonly IConfiguration _configuration; public ClienteController(IClienteRepo clienteRepo, IMapper mapper, IConfiguration configuration) { _clienteRepo = clienteRepo; _mapper = mapper; _configuration = configuration; } ///         /// Obtiene todos los clientes         ///         ///         /// Retorna todos las clientes 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 clientes = await _clienteRepo.Get(); if (clientes == null) { throw new BadRequestException("Hubo un problema al obtener los clientes"); } var ClientesDto = _mapper.Map>(clientes); return Ok(ClientesDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Obtiene los clientes aplicando los filtros de paginación y de cliente         ///         ///         /// Retorna las clientes de la base de datos paginados         /// [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] ClienteQueryFilter 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 clientes = await _clienteRepo.Get(filters); if (clientes == null) { throw new BadRequestException("Hubo un problema al obtener los clientes"); } var clientesDto = _mapper.Map>(clientes); var metadata = new { clientes.NumeroDePagina, clientes.RegistrosTotales, clientes.RegistrosPorPagina, clientes.PaginasTotales, clientes.HayPaginaSiguiente, clientes.HayPaginaAnterior, clientes.NumeroPaginaSiguiente, clientes.NumeroPaginaAnterior }; Response.Headers.Add("Pagination-Info", JsonConvert.SerializeObject(metadata)); return Ok(clientesDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Obtiene el cliente especificado por su id         ///         ///         /// Retorna los datos del banco específicado [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(ClienteDTO))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpGet("{noIdentificacion}"), Authorize(Roles = "ADMINISTRADOR,OPERATIVO,CONTADOR")] public async Task Get(string noIdentificacion) { try { var cliente = await _clienteRepo.Get(noIdentificacion); if (cliente == null) { throw new BadRequestException("El cliente no existe"); } var clienteDto = _mapper.Map(cliente); return Ok(clienteDto); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Agrega un cliente         ///         /// [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(ClienteDTO clienteDto) { try { var cliente = _mapper.Map(clienteDto); var clienteTemp = await _clienteRepo.Get(cliente.NoIdentificacion); if (clienteTemp != null) { throw new BadRequestException("El cliente ingresado ya existe"); } var agregado = await _clienteRepo.Post(cliente); if (agregado == false) { throw new BadRequestException("Hubo un problema al agregar el cliente"); } return Ok(agregado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Actualiza el cliente especificado por su id         ///         ///         /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpPut("{noIdentificacion}"), Authorize(Roles = "ADMINISTRADOR,OPERATIVO")] public async Task Put(string noIdentificacion, ClienteDTO clienteDto) { try { var clienteTemp = await _clienteRepo.Get(noIdentificacion); if (clienteTemp == null) { throw new BadRequestException("El cliente a modificar no existe"); } var cliente = _mapper.Map(clienteDto); bool modificado = await _clienteRepo.Put(noIdentificacion, cliente); if (modificado == false) { throw new BadRequestException("Hubo un problema al modificar el cliente"); } return Ok(modificado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } ///         /// Elimina el cliente especificado por su id         ///         /// [ProducesResponseType((int)HttpStatusCode.OK)] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(ExceptionResponse))] [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(ExceptionResponse))] [HttpDelete("{noIdentificacion}"), Authorize(Roles = "ADMINISTRADOR,OPERATIVO")] public async Task Delete(string noIdentificacion) { try { var clienteTemp = await _clienteRepo.Get(noIdentificacion); if (clienteTemp == null) { throw new BadRequestException("El cliente a eliminar no existe"); } bool eliminado = await _clienteRepo.Delete(noIdentificacion); if (eliminado == false) { throw new BadRequestException("Hubo un problema al eliminar el cliente"); } return Ok(eliminado); } catch (Exception ex) { if (ex.GetType() != typeof(BadRequestException)) { throw new InternalErrorException("Hubo un problema en el servidor"); } else { throw; } } } } }