< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 190
Coverable lines: 190
Total lines: 272
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<IUnidadRepository, UnidadRepository>();
 094builder.Services.AddScoped<IEscalafonRepository, EscalafonRepository>();
 095builder.Services.AddScoped<IGradoRepository, GradoRepository>();
 096builder.Services.AddScoped<ISituacionRepository, SituacionRepository>();
 097builder.Services.AddScoped<IProgramaRepository, ProgramaRepository>();
 098builder.Services.AddScoped<ITipoMovimientoRepository, TipoMovimientoRepository>();
 099builder.Services.AddScoped<IMotivoBajaRepository, MotivoBajaRepository>();
 0100builder.Services.AddScoped<IForm3100Repository, Form3100Repository>();
 0101builder.Services.AddScoped<IDescuentoPersonalRepository, DescuentoPersonalRepository>();
 0102builder.Services.AddScoped<IDocumentoRepository, DocumentoRepository>();
 103
 104// Registro de servicios
 0105builder.Services.AddScoped<IAuthService, AuthService>();
 0106builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 0107builder.Services.AddScoped<IRolService, RolService>();
 0108builder.Services.AddScoped<IAuditoriaCatalogoResolver, AuditoriaCatalogoResolver>();
 0109builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 0110builder.Services.AddScoped<IBancoService, BancoService>();
 0111builder.Services.AddScoped<IPersonalService, PersonalService>();
 0112builder.Services.AddScoped<ITipoBeneficioService, TipoBeneficioService>();
 0113builder.Services.AddScoped<IBeneficioSocialService, BeneficioSocialService>();
 0114builder.Services.AddScoped<IDependienteService, DependienteService>();
 0115builder.Services.AddScoped<ICompensacionService, CompensacionService>();
 0116builder.Services.AddScoped<IParametroLiquidacionService, ParametroLiquidacionService>();
 0117builder.Services.AddScoped<IInsumoValidator, LotesCompensacionValidator>();
 0118builder.Services.AddScoped<IInsumoValidator, BeneficiosSocialesValidator>();
 0119builder.Services.AddScoped<IInsumoValidator, NovedadesPeriodoValidator>();
 0120builder.Services.AddScoped<IInsumoValidator, RetroactividadesPendientesValidator>();
 0121builder.Services.AddScoped<IInsumoValidator, TablasReferenciaValidator>();
 0122builder.Services.AddScoped<IInsumoEvaluador, InsumoEvaluador>();
 0123builder.Services.AddScoped<IInsumosPeriodoLoader, InsumosPeriodoLoader>();
 0124builder.Services.AddScoped<IPeriodoService, PeriodoService>();
 0125builder.Services.AddScoped<INovedadPeriodoService, NovedadPeriodoService>();
 0126builder.Services.AddScoped<IPeriodoGuard, PeriodoGuard>();
 0127builder.Services.AddScoped<ILiquidacionService, LiquidacionService>();
 0128builder.Services.AddScoped<IMotorAcumuladoresService, MotorAcumuladoresService>();
 0129builder.Services.AddScoped<IUnidadService, UnidadService>();
 0130builder.Services.AddScoped<IEscalafonService, EscalafonService>();
 0131builder.Services.AddScoped<IGradoService, GradoService>();
 0132builder.Services.AddScoped<ISituacionService, SituacionService>();
 0133builder.Services.AddScoped<IProgramaService, ProgramaService>();
 0134builder.Services.AddScoped<ITipoMovimientoService, TipoMovimientoService>();
 0135builder.Services.AddScoped<IMotivoBajaService, MotivoBajaService>();
 0136builder.Services.AddScoped<IForm3100Service, Form3100Service>();
 0137builder.Services.AddScoped<IDescuentoPersonalService, DescuentoPersonalService>();
 0138builder.Services.AddScoped<IStorageService, FilesystemStorageService>();
 139
 140// Add services to the container.
 0141builder.Services.AddControllers();
 142
 143// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 0144builder.Services.AddEndpointsApiExplorer();
 0145builder.Services.AddHealthChecks();
 0146builder.Services.AddSwaggerGen(c =>
 0147{
 0148    c.SwaggerDoc("v1", new OpenApiInfo
 0149    {
 0150        Title = "FAU Liquidación API",
 0151        Version = "v1",
 0152        Description = "API para el sistema de liquidación de la FAU"
 0153    });
 0154
 0155    // Configurar Swagger para usar JWT
 0156    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 0157    {
 0158        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 0159        Name = "Authorization",
 0160        In = ParameterLocation.Header,
 0161        Type = SecuritySchemeType.ApiKey,
 0162        Scheme = "Bearer"
 0163    });
 0164
 0165    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 0166    {
 0167        {
 0168            new OpenApiSecurityScheme
 0169            {
 0170                Reference = new OpenApiReference
 0171                {
 0172                    Type = ReferenceType.SecurityScheme,
 0173                    Id = "Bearer"
 0174                }
 0175            },
 0176            Array.Empty<string>()
 0177        }
 0178    });
 0179});
 180
 181// Configuración de CORS (opcional, para desarrollo)
 0182builder.Services.AddCors(options =>
 0183{
 0184    options.AddPolicy("AllowAll", policy =>
 0185    {
 0186        policy.AllowAnyOrigin()
 0187              .AllowAnyMethod()
 0188              .AllowAnyHeader();
 0189    });
 0190});
 191
 0192var app = builder.Build();
 193
 194// Forwarded headers (si está detrás de proxy / ingress)
 0195app.UseForwardedHeaders(new ForwardedHeadersOptions
 0196{
 0197    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
 0198});
 199
 200// Comando de seeding: dotnet run --seed-admin
 201// Crea el primer usuario Administrador y termina sin levantar el servidor HTTP.
 0202if (args.Contains("--seed-admin"))
 203{
 0204    using var scope = app.Services.CreateScope();
 0205    var exitCode = await SuperAdminSeeder.RunAsync(args, scope.ServiceProvider);
 0206    Environment.Exit(exitCode);
 0207    return;
 208}
 209
 210// Validar conexión a la base de datos al inicio
 0211using (var scope = app.Services.CreateScope())
 212{
 0213    var services = scope.ServiceProvider;
 214    try
 215    {
 0216        var context = services.GetRequiredService<ApplicationDbContext>();
 0217        var canConnect = context.Database.CanConnect();
 218
 0219        if (!canConnect)
 220        {
 0221            app.Logger.LogError("No se pudo conectar a la base de datos");
 0222            throw new Exception("No se pudo establecer conexión con la base de datos");
 223        }
 0224    }
 0225    catch (Exception ex)
 226    {
 0227        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0228        throw;
 229    }
 0230}
 231
 232// Validar configuración de Storage:BasePath (no crítica en desarrollo)
 233{
 0234    var storageBasePath = app.Configuration["Storage:BasePath"];
 0235    if (string.IsNullOrWhiteSpace(storageBasePath))
 236    {
 0237        app.Logger.LogWarning("Storage:BasePath no está configurado. La carga/descarga de archivos (Form 3100) no estará
 238    }
 0239    else if (!Directory.Exists(storageBasePath))
 240    {
 0241        app.Logger.LogWarning(
 0242            "Storage:BasePath configurado pero el directorio no existe: {Path}. " +
 0243            "Se creará al subir el primer archivo.",
 0244            storageBasePath);
 245    }
 246    else
 247    {
 0248        app.Logger.LogInformation("Storage:BasePath OK: {Path}", storageBasePath);
 249    }
 250}
 251
 252// Configure the HTTP request pipeline.
 253// Habilitar Swagger en todos los ambientes (útil para Docker)
 0254app.UseSwagger();
 0255app.UseSwaggerUI(c =>
 0256{
 0257    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0258});
 259
 0260app.UseHttpsRedirection();
 261
 0262app.UseCors("AllowAll");
 263
 0264app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0265app.UseMiddleware<LogUserEnricherMiddleware>(); // Enriquece logs con el usuario autenticado
 0266app.UseAuthorization();
 267
 268
 0269app.MapHealthChecks("/health");
 0270app.MapControllers();
 271
 0272app.Run();

Methods/Properties

<Main>$()