This commit is contained in:
2025-05-31 10:58:30 -03:00
commit 1cb7645910
48 changed files with 2235 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
namespace OpenCand.API.Config
{
public class FotosSettings
{
public string Path { get; set; } = string.Empty;
public string ApiBasePath { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
namespace OpenCand.API.Controllers
{
[ApiController]
[Route("v1/[controller]")]
[Produces("application/json")]
public class BaseController : Controller
{
}
}

View File

@@ -0,0 +1,41 @@
using Microsoft.AspNetCore.Mvc;
using OpenCand.API.Model;
using OpenCand.API.Services;
using OpenCand.Core.Models;
namespace OpenCand.API.Controllers
{
public class CandidatoController : BaseController
{
private readonly OpenCandService openCandService;
public CandidatoController(OpenCandService openCandService)
{
this.openCandService = openCandService;
}
[HttpGet("search")]
public async Task<CandidatoSearchResult> CandidatoSearch([FromQuery] string q)
{
return await openCandService.SearchCandidatosAsync(q);
}
[HttpGet("{id}")]
public async Task<Candidato> GetCandidatoById([FromRoute] Guid id)
{
return await openCandService.GetCandidatoAsync(id);
}
[HttpGet("{id}/bens")]
public async Task<BemCandidatoResult> GetBensCandidatoById([FromRoute] Guid id)
{
return await openCandService.GetBemCandidatoById(id);
}
[HttpGet("{id}/rede-social")]
public async Task<RedeSocialResult> GetCandidatoRedeSocialById([FromRoute] Guid id)
{
return await openCandService.GetCandidatoRedeSocialById(id);
}
}
}

View File

@@ -0,0 +1,22 @@
using Microsoft.AspNetCore.Mvc;
using OpenCand.API.Services;
using OpenCand.Core.Models;
namespace OpenCand.API.Controllers
{
public class StatsController : BaseController
{
private readonly OpenCandService openCandService;
public StatsController(OpenCandService openCandService)
{
this.openCandService = openCandService;
}
[HttpGet()]
public async Task<OpenCandStats> GetStats()
{
return await openCandService.GetOpenCandStatsAsync();
}
}
}

View File

@@ -0,0 +1,19 @@
using OpenCand.Core.Models;
namespace OpenCand.API.Model
{
public class CandidatoSearchResult
{
public List<Candidato> Candidatos { get; set; }
}
public class BemCandidatoResult
{
public List<BemCandidato> Bens { get; set; }
}
public class RedeSocialResult
{
public List<RedeSocial> RedesSociais { get; set; }
}
}

View File

@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Npgsql" Version="8.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="Dapper" Version="2.1.66" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OpenCand.Core\OpenCand.Core.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.Development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

68
OpenCand.API/Program.cs Normal file
View File

@@ -0,0 +1,68 @@
using Microsoft.Extensions.FileProviders;
using OpenCand.API.Config;
using OpenCand.API.Repository;
using OpenCand.API.Services;
using OpenCand.Repository;
namespace OpenCand.API
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
if (string.IsNullOrEmpty(Environment.ProcessPath))
{
throw new InvalidOperationException("Environment.ProcessPath is not set. Ensure the application is running in a valid environment.");
}
// Add services to the container.
builder.Services.AddControllers();
SetupServices(builder);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
var workingDir = Path.GetDirectoryName(Environment.ProcessPath);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(workingDir, "fotos_cand")),
RequestPath = "/assets/fotos"
});
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseCors(x => x.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials()); // allow credentials
app.Run();
}
private static void SetupServices(WebApplicationBuilder builder)
{
builder.Services.Configure<FotosSettings>(builder.Configuration.GetSection("FotosSettings"));
builder.Services.AddScoped<OpenCandRepository>();
builder.Services.AddScoped<CandidatoRepository>();
builder.Services.AddScoped<BemCandidatoRepository>();
builder.Services.AddScoped<OpenCandService>();
}
}
}

View File

@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:54223",
"sslPort": 44383
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5299",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7051;http://localhost:5299",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,17 @@
using Microsoft.Extensions.Configuration;
using Npgsql;
namespace OpenCand.Repository
{
public abstract class BaseRepository
{
protected string ConnectionString { get; private set; }
protected NpgsqlConnection? Connection { get; private set; }
public BaseRepository(IConfiguration configuration)
{
ConnectionString = configuration["DatabaseSettings:ConnectionString"] ??
throw new ArgumentNullException("Connection string not found in configuration");
}
}
}

View File

@@ -0,0 +1,26 @@
using Dapper;
using Npgsql;
using OpenCand.Core.Models;
namespace OpenCand.Repository
{
public class BemCandidatoRepository : BaseRepository
{
public BemCandidatoRepository(IConfiguration configuration) : base(configuration)
{
}
public async Task<List<BemCandidato>?> GetBemCandidatoAsync(Guid idcandidato)
{
using (var connection = new NpgsqlConnection(ConnectionString))
{
var query = @"
SELECT * FROM bem_candidato
WHERE idcandidato = @idcandidato
ORDER BY ano DESC, ordembem ASC;";
return (await connection.QueryAsync<BemCandidato>(query, new { idcandidato })).AsList();
}
}
}
}

View File

@@ -0,0 +1,61 @@
using Dapper;
using Npgsql;
using OpenCand.Core.Models;
namespace OpenCand.Repository
{
public class CandidatoRepository : BaseRepository
{
public CandidatoRepository(IConfiguration configuration) : base(configuration)
{
}
public async Task<List<Candidato>> SearchCandidatosAsync(string query)
{
using (var connection = new NpgsqlConnection(ConnectionString))
{
return (await connection.QueryAsync<Candidato>(@"
SELECT idcandidato, cpf, nome, datanascimento, email, sexo, estadocivil, escolaridade, ocupacao
FROM candidato
WHERE nome ILIKE '%' || @query || '%' OR
cpf ILIKE '%' || @query || '%' OR
email ILIKE '%' || @query || '%'
LIMIT 10;",
new { query })).AsList();
}
}
public async Task<Candidato?> GetCandidatoAsync(Guid idcandidato)
{
using (var connection = new NpgsqlConnection(ConnectionString))
{
return await connection.QueryFirstOrDefaultAsync<Candidato>(@"
SELECT * FROM candidato
WHERE idcandidato = @idcandidato;",
new { idcandidato });
}
}
public async Task<List<CandidatoMapping>?> GetCandidatoMappingById(Guid idcandidato)
{
using (var connection = new NpgsqlConnection(ConnectionString))
{
var query = @"
SELECT * FROM candidato_mapping
WHERE idcandidato = @idcandidato";
return (await connection.QueryAsync<CandidatoMapping>(query, new { idcandidato })).AsList();
}
}
public async Task<List<RedeSocial>?> GetCandidatoRedeSocialById(Guid idcandidato)
{
using (var connection = new NpgsqlConnection(ConnectionString))
{
var query = @"
SELECT * FROM rede_social
WHERE idcandidato = @idcandidato";
return (await connection.QueryAsync<RedeSocial>(query, new { idcandidato })).AsList();
}
}
}
}

View File

@@ -0,0 +1,29 @@
using Dapper;
using Npgsql;
using OpenCand.Core.Models;
using OpenCand.Repository;
namespace OpenCand.API.Repository
{
public class OpenCandRepository : BaseRepository
{
public OpenCandRepository(IConfiguration configuration) : base(configuration)
{
}
public async Task<OpenCandStats> GetOpenCandStatsAsync()
{
using (var connection = new NpgsqlConnection(ConnectionString))
{
var stats = await connection.QueryFirstOrDefaultAsync<OpenCandStats>(@"
SELECT
(SELECT COUNT(idcandidato) FROM candidato) AS TotalCandidatos,
(SELECT COUNT(*) FROM bem_candidato) AS TotalBemCandidatos,
(SELECT SUM(valor) FROM bem_candidato) AS TotalValorBemCandidatos,
(SELECT COUNT(*) FROM rede_social) AS TotalRedesSociais,
(SELECT COUNT(DISTINCT ano) FROM bem_candidato) AS TotalEleicoes;");
return stats ?? new OpenCandStats();
}
}
}
}

View File

@@ -0,0 +1,98 @@
using Microsoft.Extensions.Options;
using OpenCand.API.Config;
using OpenCand.API.Model;
using OpenCand.API.Repository;
using OpenCand.Core.Models;
using OpenCand.Repository;
namespace OpenCand.API.Services
{
public class OpenCandService
{
private readonly OpenCandRepository openCandRepository;
private readonly CandidatoRepository candidatoRepository;
private readonly BemCandidatoRepository bemCandidatoRepository;
private readonly IConfiguration configuration;
private readonly FotosSettings fotoSettings;
private readonly ILogger<OpenCandService> logger;
public OpenCandService(
OpenCandRepository openCandRepository,
CandidatoRepository candidatoRepository,
BemCandidatoRepository bemCandidatoRepository,
IOptions<FotosSettings> fotoSettings,
IConfiguration configuration,
ILogger<OpenCandService> logger)
{
this.openCandRepository = openCandRepository;
this.candidatoRepository = candidatoRepository;
this.bemCandidatoRepository = bemCandidatoRepository;
this.fotoSettings = fotoSettings.Value;
this.configuration = configuration;
this.logger = logger;
}
public async Task<OpenCandStats> GetOpenCandStatsAsync()
{
return await openCandRepository.GetOpenCandStatsAsync();
}
public async Task<CandidatoSearchResult> SearchCandidatosAsync(string query)
{
return new CandidatoSearchResult()
{
Candidatos = await candidatoRepository.SearchCandidatosAsync(query)
};
}
public async Task<Candidato> GetCandidatoAsync(Guid idcandidato)
{
var result = await candidatoRepository.GetCandidatoAsync(idcandidato);
var eleicoes = await candidatoRepository.GetCandidatoMappingById(idcandidato);
if (result == null)
{
throw new KeyNotFoundException($"Candidato with ID {idcandidato} not found.");
}
if (eleicoes == null || eleicoes.Count == 0)
{
throw new KeyNotFoundException($"CandidatoMapping for ID {idcandidato} not found.");
}
var lastEleicao = eleicoes.OrderByDescending(e => e.Ano).First();
result.FotoUrl = $"{fotoSettings.ApiBasePath}/foto_cand{lastEleicao.Ano}_{lastEleicao.SiglaUF}_div/F{lastEleicao.SiglaUF}{lastEleicao.SqCandidato}_div.jpg";
result.Eleicoes = eleicoes.OrderByDescending(e => e.Ano).ToList();
return result;
}
public async Task<BemCandidatoResult> GetBemCandidatoById(Guid idcandidato)
{
var result = await bemCandidatoRepository.GetBemCandidatoAsync(idcandidato);
if (result == null)
{
result = new List<BemCandidato>();
}
return new BemCandidatoResult()
{
Bens = result.OrderByDescending(r => r.TipoBem).ThenByDescending(r => r.Valor).ToList()
};
}
public async Task<RedeSocialResult> GetCandidatoRedeSocialById(Guid idcandidato)
{
var result = await candidatoRepository.GetCandidatoRedeSocialById(idcandidato);
if (result == null)
{
result = new List<RedeSocial>();
}
return new RedeSocialResult()
{
RedesSociais = result.OrderByDescending(r => r.Ano).ToList()
};
}
}
}

View File

@@ -0,0 +1,16 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"DatabaseSettings": {
"ConnectionString": "Host=localhost;Database=opencand;Username=root;Password=root;Include Error Detail=true;CommandTimeout=300"
},
"FotosSettings": {
"Path": "./foto_cand",
"ApiBasePath": "http://localhost:5299/assets/fotos"
},
"AllowedHosts": "*"
}