| | | 1 | | using System.Text; |
| | | 2 | | using FAU.API.Middleware; |
| | | 3 | | using FAU.API.Security; |
| | | 4 | | using FAU.API.Seeds; |
| | | 5 | | using FAU.DataAccess; |
| | | 6 | | using FAU.DataAccess.Repositories; |
| | | 7 | | using FAU.Entidades.Auditoria; |
| | | 8 | | using FAU.Logica.Services; |
| | | 9 | | using FAU.Logica.Services.InsumoValidators; |
| | | 10 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | | 11 | | using Microsoft.AspNetCore.Authorization; |
| | | 12 | | using Microsoft.EntityFrameworkCore; |
| | | 13 | | using Microsoft.IdentityModel.Tokens; |
| | | 14 | | using Microsoft.OpenApi.Models; |
| | | 15 | | using Microsoft.AspNetCore.HttpOverrides; |
| | | 16 | | using Serilog; |
| | | 17 | | |
| | | 18 | | // Npgsql 7+ requiere Kind=UTC para timestamptz; habilitar comportamiento legacy para columnas timestamp sin zona |
| | 0 | 19 | | AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); |
| | | 20 | | |
| | 0 | 21 | | var builder = WebApplication.CreateBuilder(args); |
| | | 22 | | |
| | | 23 | | // Log del ambiente y configuración cargada |
| | 0 | 24 | | var environment = builder.Environment.EnvironmentName; |
| | 0 | 25 | | var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); |
| | | 26 | | |
| | 0 | 27 | | Console.WriteLine("====================================="); |
| | 0 | 28 | | Console.WriteLine($"Ambiente: {environment}"); |
| | 0 | 29 | | Console.WriteLine("====================================="); |
| | | 30 | | |
| | 0 | 31 | | builder.Services.AddDbContext<ApplicationDbContext>(options => |
| | 0 | 32 | | options.UseNpgsql(connectionString, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery))); |
| | | 33 | | |
| | 0 | 34 | | Auditoria.IniciarAuditoria(builder.Configuration); |
| | | 35 | | |
| | | 36 | | // Redirigir ILogger<T> de todos los servicios/controladores hacia Serilog |
| | 0 | 37 | | builder.Logging.ClearProviders(); |
| | 0 | 38 | | builder.Logging.AddSerilog(Log.Logger); |
| | | 39 | | |
| | | 40 | | // Configuración de JWT |
| | 0 | 41 | | var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key no configurada"); |
| | 0 | 42 | | var jwtIssuer = builder.Configuration["Jwt:Issuer"]; |
| | 0 | 43 | | var jwtAudience = builder.Configuration["Jwt:Audience"]; |
| | | 44 | | |
| | 0 | 45 | | builder.Services.AddAuthentication(options => |
| | 0 | 46 | | { |
| | 0 | 47 | | options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; |
| | 0 | 48 | | options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; |
| | 0 | 49 | | }) |
| | 0 | 50 | | .AddJwtBearer(options => |
| | 0 | 51 | | { |
| | 0 | 52 | | options.RequireHttpsMetadata = false; // En producción debe ser true |
| | 0 | 53 | | options.SaveToken = true; |
| | 0 | 54 | | options.TokenValidationParameters = new TokenValidationParameters |
| | 0 | 55 | | { |
| | 0 | 56 | | ValidateIssuerSigningKey = true, |
| | 0 | 57 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)), |
| | 0 | 58 | | ValidateIssuer = true, |
| | 0 | 59 | | ValidIssuer = jwtIssuer, |
| | 0 | 60 | | ValidateAudience = true, |
| | 0 | 61 | | ValidAudience = jwtAudience, |
| | 0 | 62 | | ValidateLifetime = true, |
| | 0 | 63 | | ClockSkew = TimeSpan.Zero |
| | 0 | 64 | | }; |
| | 0 | 65 | | }); |
| | | 66 | | |
| | 0 | 67 | | builder.Services.AddAuthorization(); |
| | | 68 | | |
| | | 69 | | // Políticas dinámicas: Permission:xxx |
| | 0 | 70 | | builder.Services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>(); |
| | 0 | 71 | | builder.Services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>(); |
| | | 72 | | |
| | | 73 | | // HttpContext + Current user context (auditoría) |
| | 0 | 74 | | builder.Services.AddHttpContextAccessor(); |
| | 0 | 75 | | builder.Services.AddScoped<FAU.Logica.Services.ICurrentUserContext, FAU.API.Services.CurrentUserContext>(); |
| | | 76 | | |
| | | 77 | | // Registro de repositorios |
| | 0 | 78 | | builder.Services.AddScoped<IUsuarioRepository, UsuarioRepository>(); |
| | 0 | 79 | | builder.Services.AddScoped<IRolRepository, RolRepository>(); |
| | 0 | 80 | | builder.Services.AddScoped<IPermisoRepository, PermisoRepository>(); |
| | 0 | 81 | | builder.Services.AddScoped<IAuditoriaRepository, AuditoriaRepository>(); |
| | 0 | 82 | | builder.Services.AddScoped<IBancoRepository, BancoRepository>(); |
| | 0 | 83 | | builder.Services.AddScoped<IPersonalRepository, PersonalRepository>(); |
| | 0 | 84 | | builder.Services.AddScoped<ITipoBeneficioRepository, TipoBeneficioRepository>(); |
| | 0 | 85 | | builder.Services.AddScoped<IBeneficioSocialRepository, BeneficioSocialRepository>(); |
| | 0 | 86 | | builder.Services.AddScoped<IIrpfRepository, IrpfRepository>(); |
| | 0 | 87 | | builder.Services.AddScoped<IDependienteRepository, DependienteRepository>(); |
| | 0 | 88 | | builder.Services.AddScoped<ICompensacionRepository, CompensacionRepository>(); |
| | 0 | 89 | | builder.Services.AddScoped<IParametroLiquidacionRepository, ParametroLiquidacionRepository>(); |
| | 0 | 90 | | builder.Services.AddScoped<IPeriodosRepository, PeriodosRepository>(); |
| | 0 | 91 | | builder.Services.AddScoped<INovedadPeriodoRepository, NovedadPeriodoRepository>(); |
| | 0 | 92 | | builder.Services.AddScoped<ISnapshotsRepository, SnapshotsRepository>(); |
| | 0 | 93 | | builder.Services.AddScoped<IUnidadRepository, UnidadRepository>(); |
| | 0 | 94 | | builder.Services.AddScoped<IEscalafonRepository, EscalafonRepository>(); |
| | 0 | 95 | | builder.Services.AddScoped<IGradoRepository, GradoRepository>(); |
| | 0 | 96 | | builder.Services.AddScoped<ISituacionRepository, SituacionRepository>(); |
| | 0 | 97 | | builder.Services.AddScoped<IProgramaRepository, ProgramaRepository>(); |
| | 0 | 98 | | builder.Services.AddScoped<ITipoMovimientoRepository, TipoMovimientoRepository>(); |
| | 0 | 99 | | builder.Services.AddScoped<IMotivoBajaRepository, MotivoBajaRepository>(); |
| | 0 | 100 | | builder.Services.AddScoped<IForm3100Repository, Form3100Repository>(); |
| | 0 | 101 | | builder.Services.AddScoped<IDescuentoPersonalRepository, DescuentoPersonalRepository>(); |
| | 0 | 102 | | builder.Services.AddScoped<IDocumentoRepository, DocumentoRepository>(); |
| | | 103 | | |
| | | 104 | | // Registro de servicios |
| | 0 | 105 | | builder.Services.AddScoped<IAuthService, AuthService>(); |
| | 0 | 106 | | builder.Services.AddScoped<IUsuarioService, UsuarioService>(); |
| | 0 | 107 | | builder.Services.AddScoped<IRolService, RolService>(); |
| | 0 | 108 | | builder.Services.AddScoped<IAuditoriaCatalogoResolver, AuditoriaCatalogoResolver>(); |
| | 0 | 109 | | builder.Services.AddScoped<IAuditoriaService, AuditoriaService>(); |
| | 0 | 110 | | builder.Services.AddScoped<IBancoService, BancoService>(); |
| | 0 | 111 | | builder.Services.AddScoped<IPersonalService, PersonalService>(); |
| | 0 | 112 | | builder.Services.AddScoped<ITipoBeneficioService, TipoBeneficioService>(); |
| | 0 | 113 | | builder.Services.AddScoped<IBeneficioSocialService, BeneficioSocialService>(); |
| | 0 | 114 | | builder.Services.AddScoped<IDependienteService, DependienteService>(); |
| | 0 | 115 | | builder.Services.AddScoped<ICompensacionService, CompensacionService>(); |
| | 0 | 116 | | builder.Services.AddScoped<IParametroLiquidacionService, ParametroLiquidacionService>(); |
| | 0 | 117 | | builder.Services.AddScoped<IInsumoValidator, LotesCompensacionValidator>(); |
| | 0 | 118 | | builder.Services.AddScoped<IInsumoValidator, BeneficiosSocialesValidator>(); |
| | 0 | 119 | | builder.Services.AddScoped<IInsumoValidator, NovedadesPeriodoValidator>(); |
| | 0 | 120 | | builder.Services.AddScoped<IInsumoValidator, RetroactividadesPendientesValidator>(); |
| | 0 | 121 | | builder.Services.AddScoped<IInsumoValidator, TablasReferenciaValidator>(); |
| | 0 | 122 | | builder.Services.AddScoped<IInsumoEvaluador, InsumoEvaluador>(); |
| | 0 | 123 | | builder.Services.AddScoped<IInsumosPeriodoLoader, InsumosPeriodoLoader>(); |
| | 0 | 124 | | builder.Services.AddScoped<IPeriodoService, PeriodoService>(); |
| | 0 | 125 | | builder.Services.AddScoped<INovedadPeriodoService, NovedadPeriodoService>(); |
| | 0 | 126 | | builder.Services.AddScoped<IPeriodoGuard, PeriodoGuard>(); |
| | 0 | 127 | | builder.Services.AddScoped<ILiquidacionService, LiquidacionService>(); |
| | 0 | 128 | | builder.Services.AddScoped<IrpfCalculator>(); |
| | 0 | 129 | | builder.Services.AddScoped<IIrpfService, IrpfService>(); |
| | 0 | 130 | | builder.Services.AddScoped<IMotorAcumuladoresService, MotorAcumuladoresService>(); |
| | 0 | 131 | | builder.Services.AddScoped<IUnidadService, UnidadService>(); |
| | 0 | 132 | | builder.Services.AddScoped<IEscalafonService, EscalafonService>(); |
| | 0 | 133 | | builder.Services.AddScoped<IGradoService, GradoService>(); |
| | 0 | 134 | | builder.Services.AddScoped<ISituacionService, SituacionService>(); |
| | 0 | 135 | | builder.Services.AddScoped<IProgramaService, ProgramaService>(); |
| | 0 | 136 | | builder.Services.AddScoped<ITipoMovimientoService, TipoMovimientoService>(); |
| | 0 | 137 | | builder.Services.AddScoped<IMotivoBajaService, MotivoBajaService>(); |
| | 0 | 138 | | builder.Services.AddScoped<IForm3100Service, Form3100Service>(); |
| | 0 | 139 | | builder.Services.AddScoped<IDescuentoPersonalService, DescuentoPersonalService>(); |
| | 0 | 140 | | builder.Services.AddScoped<IStorageService, FilesystemStorageService>(); |
| | | 141 | | |
| | | 142 | | // Add services to the container. |
| | 0 | 143 | | builder.Services.AddControllers(); |
| | | 144 | | |
| | | 145 | | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle |
| | 0 | 146 | | builder.Services.AddEndpointsApiExplorer(); |
| | 0 | 147 | | builder.Services.AddHealthChecks(); |
| | 0 | 148 | | builder.Services.AddSwaggerGen(c => |
| | 0 | 149 | | { |
| | 0 | 150 | | c.SwaggerDoc("v1", new OpenApiInfo |
| | 0 | 151 | | { |
| | 0 | 152 | | Title = "FAU Liquidación API", |
| | 0 | 153 | | Version = "v1", |
| | 0 | 154 | | Description = "API para el sistema de liquidación de la FAU" |
| | 0 | 155 | | }); |
| | 0 | 156 | | |
| | 0 | 157 | | // Configurar Swagger para usar JWT |
| | 0 | 158 | | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme |
| | 0 | 159 | | { |
| | 0 | 160 | | Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"", |
| | 0 | 161 | | Name = "Authorization", |
| | 0 | 162 | | In = ParameterLocation.Header, |
| | 0 | 163 | | Type = SecuritySchemeType.ApiKey, |
| | 0 | 164 | | Scheme = "Bearer" |
| | 0 | 165 | | }); |
| | 0 | 166 | | |
| | 0 | 167 | | c.AddSecurityRequirement(new OpenApiSecurityRequirement |
| | 0 | 168 | | { |
| | 0 | 169 | | { |
| | 0 | 170 | | new OpenApiSecurityScheme |
| | 0 | 171 | | { |
| | 0 | 172 | | Reference = new OpenApiReference |
| | 0 | 173 | | { |
| | 0 | 174 | | Type = ReferenceType.SecurityScheme, |
| | 0 | 175 | | Id = "Bearer" |
| | 0 | 176 | | } |
| | 0 | 177 | | }, |
| | 0 | 178 | | Array.Empty<string>() |
| | 0 | 179 | | } |
| | 0 | 180 | | }); |
| | 0 | 181 | | }); |
| | | 182 | | |
| | | 183 | | // Configuración de CORS (opcional, para desarrollo) |
| | 0 | 184 | | builder.Services.AddCors(options => |
| | 0 | 185 | | { |
| | 0 | 186 | | options.AddPolicy("AllowAll", policy => |
| | 0 | 187 | | { |
| | 0 | 188 | | policy.AllowAnyOrigin() |
| | 0 | 189 | | .AllowAnyMethod() |
| | 0 | 190 | | .AllowAnyHeader(); |
| | 0 | 191 | | }); |
| | 0 | 192 | | }); |
| | | 193 | | |
| | 0 | 194 | | var app = builder.Build(); |
| | | 195 | | |
| | | 196 | | // Forwarded headers (si está detrás de proxy / ingress) |
| | 0 | 197 | | app.UseForwardedHeaders(new ForwardedHeadersOptions |
| | 0 | 198 | | { |
| | 0 | 199 | | ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto |
| | 0 | 200 | | }); |
| | | 201 | | |
| | | 202 | | // Comando de seeding: dotnet run --seed-admin |
| | | 203 | | // Crea el primer usuario Administrador y termina sin levantar el servidor HTTP. |
| | 0 | 204 | | if (args.Contains("--seed-admin")) |
| | | 205 | | { |
| | 0 | 206 | | using var scope = app.Services.CreateScope(); |
| | 0 | 207 | | var exitCode = await SuperAdminSeeder.RunAsync(args, scope.ServiceProvider); |
| | 0 | 208 | | Environment.Exit(exitCode); |
| | 0 | 209 | | return; |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | // Validar conexión a la base de datos al inicio |
| | 0 | 213 | | using (var scope = app.Services.CreateScope()) |
| | | 214 | | { |
| | 0 | 215 | | var services = scope.ServiceProvider; |
| | | 216 | | try |
| | | 217 | | { |
| | 0 | 218 | | var context = services.GetRequiredService<ApplicationDbContext>(); |
| | 0 | 219 | | var canConnect = context.Database.CanConnect(); |
| | | 220 | | |
| | 0 | 221 | | if (!canConnect) |
| | | 222 | | { |
| | 0 | 223 | | app.Logger.LogError("No se pudo conectar a la base de datos"); |
| | 0 | 224 | | throw new Exception("No se pudo establecer conexión con la base de datos"); |
| | | 225 | | } |
| | 0 | 226 | | } |
| | 0 | 227 | | catch (Exception ex) |
| | | 228 | | { |
| | 0 | 229 | | app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message); |
| | 0 | 230 | | throw; |
| | | 231 | | } |
| | 0 | 232 | | } |
| | | 233 | | |
| | | 234 | | // Validar configuración de Storage:BasePath (no crítica en desarrollo) |
| | | 235 | | { |
| | 0 | 236 | | var storageBasePath = app.Configuration["Storage:BasePath"]; |
| | 0 | 237 | | if (string.IsNullOrWhiteSpace(storageBasePath)) |
| | | 238 | | { |
| | 0 | 239 | | app.Logger.LogWarning("Storage:BasePath no está configurado. La carga/descarga de archivos (Form 3100) no estará |
| | | 240 | | } |
| | 0 | 241 | | else if (!Directory.Exists(storageBasePath)) |
| | | 242 | | { |
| | 0 | 243 | | app.Logger.LogWarning( |
| | 0 | 244 | | "Storage:BasePath configurado pero el directorio no existe: {Path}. " + |
| | 0 | 245 | | "Se creará al subir el primer archivo.", |
| | 0 | 246 | | storageBasePath); |
| | | 247 | | } |
| | | 248 | | else |
| | | 249 | | { |
| | 0 | 250 | | app.Logger.LogInformation("Storage:BasePath OK: {Path}", storageBasePath); |
| | | 251 | | } |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | // Configure the HTTP request pipeline. |
| | | 255 | | // Habilitar Swagger en todos los ambientes (útil para Docker) |
| | 0 | 256 | | app.UseSwagger(); |
| | 0 | 257 | | app.UseSwaggerUI(c => |
| | 0 | 258 | | { |
| | 0 | 259 | | c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1"); |
| | 0 | 260 | | }); |
| | | 261 | | |
| | 0 | 262 | | app.UseHttpsRedirection(); |
| | | 263 | | |
| | 0 | 264 | | app.UseCors("AllowAll"); |
| | | 265 | | |
| | 0 | 266 | | app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization |
| | 0 | 267 | | app.UseMiddleware<LogUserEnricherMiddleware>(); // Enriquece logs con el usuario autenticado |
| | 0 | 268 | | app.UseAuthorization(); |
| | | 269 | | |
| | | 270 | | |
| | 0 | 271 | | app.MapHealthChecks("/health"); |
| | 0 | 272 | | app.MapControllers(); |
| | | 273 | | |
| | 0 | 274 | | app.Run(); |