< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 180
Coverable lines: 180
Total lines: 262
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 10
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
<Main>$()0%110100%

File(s)

/home/runner/work/Sistema.Liquidacion.BE/Sistema.Liquidacion.BE/FAU.API/Program.cs

#LineLine coverage
 1using System.Text;
 2using FAU.API.Middleware;
 3using FAU.API.Security;
 4using FAU.API.Seeds;
 5using FAU.DataAccess;
 6using FAU.DataAccess.Repositories;
 7using FAU.Entidades.Auditoria;
 8using FAU.Logica.Services;
 9using FAU.Logica.Services.InsumoValidators;
 10using Microsoft.AspNetCore.Authentication.JwtBearer;
 11using Microsoft.AspNetCore.Authorization;
 12using Microsoft.EntityFrameworkCore;
 13using Microsoft.IdentityModel.Tokens;
 14using Microsoft.OpenApi.Models;
 15using Microsoft.AspNetCore.HttpOverrides;
 16using Serilog;
 17
 18// Npgsql 7+ requiere Kind=UTC para timestamptz; habilitar comportamiento legacy para columnas timestamp sin zona
 019AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
 20
 021var builder = WebApplication.CreateBuilder(args);
 22
 23// Log del ambiente y configuración cargada
 024var environment = builder.Environment.EnvironmentName;
 025var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
 26
 027Console.WriteLine("=====================================");
 028Console.WriteLine($"Ambiente: {environment}");
 029Console.WriteLine("=====================================");
 30
 031builder.Services.AddDbContext<ApplicationDbContext>(options =>
 032    options.UseNpgsql(connectionString, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)));
 33
 034Auditoria.IniciarAuditoria(builder.Configuration);
 35
 36// Redirigir ILogger<T> de todos los servicios/controladores hacia Serilog
 037builder.Logging.ClearProviders();
 038builder.Logging.AddSerilog(Log.Logger);
 39
 40// Configuración de JWT
 041var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key no configurada");
 042var jwtIssuer = builder.Configuration["Jwt:Issuer"];
 043var jwtAudience = builder.Configuration["Jwt:Audience"];
 44
 045builder.Services.AddAuthentication(options =>
 046{
 047    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
 048    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
 049})
 050.AddJwtBearer(options =>
 051{
 052    options.RequireHttpsMetadata = false; // En producción debe ser true
 053    options.SaveToken = true;
 054    options.TokenValidationParameters = new TokenValidationParameters
 055    {
 056        ValidateIssuerSigningKey = true,
 057        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
 058        ValidateIssuer = true,
 059        ValidIssuer = jwtIssuer,
 060        ValidateAudience = true,
 061        ValidAudience = jwtAudience,
 062        ValidateLifetime = true,
 063        ClockSkew = TimeSpan.Zero
 064    };
 065});
 66
 067builder.Services.AddAuthorization();
 68
 69// Políticas dinámicas: Permission:xxx
 070builder.Services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>();
 071builder.Services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
 72
 73// HttpContext + Current user context (auditoría)
 074builder.Services.AddHttpContextAccessor();
 075builder.Services.AddScoped<FAU.Logica.Services.ICurrentUserContext, FAU.API.Services.CurrentUserContext>();
 76
 77// Registro de repositorios
 078builder.Services.AddScoped<IUsuarioRepository, UsuarioRepository>();
 079builder.Services.AddScoped<IRolRepository, RolRepository>();
 080builder.Services.AddScoped<IPermisoRepository, PermisoRepository>();
 081builder.Services.AddScoped<IAuditoriaRepository, AuditoriaRepository>();
 082builder.Services.AddScoped<IBancoRepository, BancoRepository>();
 083builder.Services.AddScoped<IPersonalRepository, PersonalRepository>();
 084builder.Services.AddScoped<ITipoBeneficioRepository, TipoBeneficioRepository>();
 085builder.Services.AddScoped<IBeneficioSocialRepository, BeneficioSocialRepository>();
 086builder.Services.AddScoped<IIrpfRepository, IrpfRepository>();
 087builder.Services.AddScoped<IDependienteRepository, DependienteRepository>();
 088builder.Services.AddScoped<ICompensacionRepository, CompensacionRepository>();
 089builder.Services.AddScoped<IParametroLiquidacionRepository, ParametroLiquidacionRepository>();
 090builder.Services.AddScoped<IPeriodosRepository, PeriodosRepository>();
 091builder.Services.AddScoped<INovedadPeriodoRepository, NovedadPeriodoRepository>();
 092builder.Services.AddScoped<ISnapshotsRepository, SnapshotsRepository>();
 093builder.Services.AddScoped<ISubUnidadRepository, SubUnidadRepository>();
 094builder.Services.AddScoped<IMotivoBajaRepository, MotivoBajaRepository>();
 095builder.Services.AddScoped<IForm3100Repository, Form3100Repository>();
 096builder.Services.AddScoped<IDescuentoPersonalRepository, DescuentoPersonalRepository>();
 097builder.Services.AddScoped<IDocumentoRepository, DocumentoRepository>();
 98
 99// Registro de servicios
 0100builder.Services.AddScoped<IAuthService, AuthService>();
 0101builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 0102builder.Services.AddScoped<IRolService, RolService>();
 0103builder.Services.AddScoped<IAuditoriaCatalogoResolver, AuditoriaCatalogoResolver>();
 0104builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 0105builder.Services.AddScoped<IBancoService, BancoService>();
 0106builder.Services.AddScoped<IPersonalService, PersonalService>();
 0107builder.Services.AddScoped<ITipoBeneficioService, TipoBeneficioService>();
 0108builder.Services.AddScoped<IBeneficioSocialService, BeneficioSocialService>();
 0109builder.Services.AddScoped<IDependienteService, DependienteService>();
 0110builder.Services.AddScoped<ICompensacionService, CompensacionService>();
 0111builder.Services.AddScoped<IParametroLiquidacionService, ParametroLiquidacionService>();
 0112builder.Services.AddScoped<IInsumoValidator, LotesCompensacionValidator>();
 0113builder.Services.AddScoped<IInsumoValidator, BeneficiosSocialesValidator>();
 0114builder.Services.AddScoped<IInsumoValidator, NovedadesPeriodoValidator>();
 0115builder.Services.AddScoped<IInsumoValidator, RetroactividadesPendientesValidator>();
 0116builder.Services.AddScoped<IInsumoValidator, TablasReferenciaValidator>();
 0117builder.Services.AddScoped<IInsumoEvaluador, InsumoEvaluador>();
 0118builder.Services.AddScoped<IInsumosPeriodoLoader, InsumosPeriodoLoader>();
 0119builder.Services.AddScoped<IPeriodoService, PeriodoService>();
 0120builder.Services.AddScoped<INovedadPeriodoService, NovedadPeriodoService>();
 0121builder.Services.AddScoped<IPeriodoGuard, PeriodoGuard>();
 0122builder.Services.AddScoped<ILiquidacionService, LiquidacionService>();
 0123builder.Services.AddScoped<IMotorAcumuladoresService, MotorAcumuladoresService>();
 0124builder.Services.AddScoped<ISubUnidadService, SubUnidadService>();
 0125builder.Services.AddScoped<IMotivoBajaService, MotivoBajaService>();
 0126builder.Services.AddScoped<IForm3100Service, Form3100Service>();
 0127builder.Services.AddScoped<IDescuentoPersonalService, DescuentoPersonalService>();
 0128builder.Services.AddScoped<IStorageService, FilesystemStorageService>();
 129
 130// Add services to the container.
 0131builder.Services.AddControllers();
 132
 133// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 0134builder.Services.AddEndpointsApiExplorer();
 0135builder.Services.AddHealthChecks();
 0136builder.Services.AddSwaggerGen(c =>
 0137{
 0138    c.SwaggerDoc("v1", new OpenApiInfo
 0139    {
 0140        Title = "FAU Liquidación API",
 0141        Version = "v1",
 0142        Description = "API para el sistema de liquidación de la FAU"
 0143    });
 0144
 0145    // Configurar Swagger para usar JWT
 0146    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 0147    {
 0148        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 0149        Name = "Authorization",
 0150        In = ParameterLocation.Header,
 0151        Type = SecuritySchemeType.ApiKey,
 0152        Scheme = "Bearer"
 0153    });
 0154
 0155    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 0156    {
 0157        {
 0158            new OpenApiSecurityScheme
 0159            {
 0160                Reference = new OpenApiReference
 0161                {
 0162                    Type = ReferenceType.SecurityScheme,
 0163                    Id = "Bearer"
 0164                }
 0165            },
 0166            Array.Empty<string>()
 0167        }
 0168    });
 0169});
 170
 171// Configuración de CORS (opcional, para desarrollo)
 0172builder.Services.AddCors(options =>
 0173{
 0174    options.AddPolicy("AllowAll", policy =>
 0175    {
 0176        policy.AllowAnyOrigin()
 0177              .AllowAnyMethod()
 0178              .AllowAnyHeader();
 0179    });
 0180});
 181
 0182var app = builder.Build();
 183
 184// Forwarded headers (si está detrás de proxy / ingress)
 0185app.UseForwardedHeaders(new ForwardedHeadersOptions
 0186{
 0187    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
 0188});
 189
 190// Comando de seeding: dotnet run --seed-admin
 191// Crea el primer usuario Administrador y termina sin levantar el servidor HTTP.
 0192if (args.Contains("--seed-admin"))
 193{
 0194    using var scope = app.Services.CreateScope();
 0195    var exitCode = await SuperAdminSeeder.RunAsync(args, scope.ServiceProvider);
 0196    Environment.Exit(exitCode);
 0197    return;
 198}
 199
 200// Validar conexión a la base de datos al inicio
 0201using (var scope = app.Services.CreateScope())
 202{
 0203    var services = scope.ServiceProvider;
 204    try
 205    {
 0206        var context = services.GetRequiredService<ApplicationDbContext>();
 0207        var canConnect = context.Database.CanConnect();
 208
 0209        if (!canConnect)
 210        {
 0211            app.Logger.LogError("No se pudo conectar a la base de datos");
 0212            throw new Exception("No se pudo establecer conexión con la base de datos");
 213        }
 0214    }
 0215    catch (Exception ex)
 216    {
 0217        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0218        throw;
 219    }
 0220}
 221
 222// Validar configuración de Storage:BasePath (no crítica en desarrollo)
 223{
 0224    var storageBasePath = app.Configuration["Storage:BasePath"];
 0225    if (string.IsNullOrWhiteSpace(storageBasePath))
 226    {
 0227        app.Logger.LogWarning("Storage:BasePath no está configurado. La carga/descarga de archivos (Form 3100) no estará
 228    }
 0229    else if (!Directory.Exists(storageBasePath))
 230    {
 0231        app.Logger.LogWarning(
 0232            "Storage:BasePath configurado pero el directorio no existe: {Path}. " +
 0233            "Se creará al subir el primer archivo.",
 0234            storageBasePath);
 235    }
 236    else
 237    {
 0238        app.Logger.LogInformation("Storage:BasePath OK: {Path}", storageBasePath);
 239    }
 240}
 241
 242// Configure the HTTP request pipeline.
 243// Habilitar Swagger en todos los ambientes (útil para Docker)
 0244app.UseSwagger();
 0245app.UseSwaggerUI(c =>
 0246{
 0247    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0248});
 249
 0250app.UseHttpsRedirection();
 251
 0252app.UseCors("AllowAll");
 253
 0254app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0255app.UseMiddleware<LogUserEnricherMiddleware>(); // Enriquece logs con el usuario autenticado
 0256app.UseAuthorization();
 257
 258
 0259app.MapHealthChecks("/health");
 0260app.MapControllers();
 261
 0262app.Run();

Methods/Properties

<Main>$()