diff --git a/.dockerignore b/.dockerignore index fe1152b..495f5a5 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,30 +1,39 @@ -**/.classpath -**/.dockerignore -**/.env +# === Git and Docker === **/.git **/.gitignore -**/.project -**/.settings -**/.toolstarget -**/.vs -**/.vscode -**/*.*proj.user -**/*.dbmdl -**/*.jfm -**/azds.yaml -**/bin -**/charts -**/docker-compose* +**/.gitattributes +**/.dockerignore **/Dockerfile* -**/node_modules -**/npm-debug.log -**/obj -**/secrets.dev.yaml -**/values.dev.yaml +!src/Jiban.Api/Dockerfile.production +**/docker-compose* +**/.env* +**/secrets.*.yaml + +# === Documentation === LICENSE README.md -!**/.gitignore -!.git/HEAD -!.git/config -!.git/packed-refs -!.git/refs/heads/** \ No newline at end of file +CONTRIBUTING.md +CODE_OF_CONDUCT.md +**/docs +**/*.md + +# === .NET build output === +**/bin/ +**/obj/ +**/TestResults/ +**/out/ +**/coverage/ +**/*.user +**/*.suo +**/*.dbmdl +**/*.log +**/*.tlog + +# === Node / Frontend === +**/node_modules/ +**/dist/ +**/build/ + +# === AppSettings === +**/appsettings.*.json +!**/appsettings.json \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..96833e4 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,32 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: bug +assignees: yanpitangui + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**(please complete the following information):** + - OS: [e.g. iOS] + - Visual Studio Version [e.g. 22] + - .Net SDK Version + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/documentation.md b/.github/ISSUE_TEMPLATE/documentation.md new file mode 100644 index 0000000..f85f5b9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/documentation.md @@ -0,0 +1,12 @@ +--- +name: Documentation suggestion +about: Suggest an improvement to the documentation +title: "[DOCUMENTATION]" +labels: documentation +assignees: '' + +--- + +**Context** + +Please tell us what you think can be improved on the documentation. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..f455865 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FEATURE]" +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..e4ca311 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "nuget" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "daily" diff --git a/.github/workflows/production.yml b/.github/workflows/production.yml new file mode 100644 index 0000000..06baa9c --- /dev/null +++ b/.github/workflows/production.yml @@ -0,0 +1,121 @@ +name: JIBAN EVENT PRODUCTION +on: + workflow_dispatch: + inputs: + name: + description: "Who to greet" + default: "World" + pull_request: + paths-ignore: + - "**.md" + branches: ["main"] + +jobs: + build: + runs-on: ubuntu-latest + env: + DOTNET_CORE_VERSION: 10.0.x + PORTHTTPS: ${{secrets.PORTHTTPS}} + TZ: America/Guayaquil + NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} + outputs: + image-tag: ${{ steps.generate-tag.outputs.image-tag }} + steps: + - name: Set up .NET Core SDK + uses: actions/setup-dotnet@v5.0.0 + with: + dotnet-version: '10.0.x' + + - name: Check out code + uses: actions/checkout@v5.0.0 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3.11.1 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: raulidavid + password: ${{ secrets.JIBANTOKEN }} + + - name: Generate IMAGE_TAG + id: generate-tag + run: | + IMAGE_TAG="ghcr.io/raulidavid/jiban-event:production-v$(date +%Y.%m.%d)-${{ github.run_number }}" + echo "IMAGE_TAG=$IMAGE_TAG" >> $GITHUB_ENV + echo "image-tag=$IMAGE_TAG" >> $GITHUB_OUTPUT + echo "Generated tag: $IMAGE_TAG" + + - name: Rename .nuget.config to nuget.config + run: mv .nuget.config nuget.config + + - name: Configure NuGet + run: | + echo "Configuring NuGet..." + sed -i 's|\${NUGET_TOKEN}|'"${{ secrets.NUGET_TOKEN }}"'|g' nuget.config + + - name: Build and Push Api Image + uses: docker/build-push-action@v5 + with: + context: . + file: src/Jiban.Api/Dockerfile.production + push: true + tags: ${{ env.IMAGE_TAG }} + build-args: | + NUGET_TOKEN=${{ env.NUGET_TOKEN }} + cache-from: type=gha + cache-to: type=gha,mode=max + platforms: linux/amd64 + + - name: Send Email via Amazon SES + if: success() + uses: dawidd6/action-send-mail@v4 + with: + server_address: email-smtp.us-east-1.amazonaws.com + server_port: 465 + username: ${{ secrets.SES_USER }} + password: ${{ secrets.SES_PASS }} + subject: "🚀 PRODUCTION - Nueva imagen generada: ${{ env.IMAGE_TAG }}" + body: | + 🚀 **BUILD EXITOSO - PRODUCTION** + + La imagen Docker ha sido creada y subida exitosamente. + + 📌 **Tag:** `${{ env.IMAGE_TAG }}` + 🏗️ **Plataformas:** `linux/amd64` + 📊 **Branch:** `${{ github.ref_name }}` + 📝 **Commit:** `${{ github.sha }}` + 👤 **Actor:** `${{ github.actor }}` + 🔗 **Workflow:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + + --- + *Generado automáticamente por GitHub Actions* + to: "raul.flores@jiban.ec" + from: "GitHub Actions Production " + + - name: Send Error Email via Amazon SES + if: failure() + uses: dawidd6/action-send-mail@v4 + with: + server_address: email-smtp.us-east-1.amazonaws.com + server_port: 465 + username: ${{ secrets.SES_USER }} + password: ${{ secrets.SES_PASS }} + subject: "❌ PRODUCTION - Error en build: ${{ github.ref_name }}" + body: | + 💥 **BUILD FALLÓ - PRODUCTION** + + Ha ocurrido un error durante el proceso de build. + + 📊 **Branch:** `${{ github.ref_name }}` + 📝 **Commit:** `${{ github.sha }}` + 👤 **Actor:** `${{ github.actor }}` + 🔗 **Ver detalles:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + + Por favor revisa los logs para más detalles. + + --- + *Generado automáticamente por GitHub Actions* + to: "raul.flores@jiban.ec" + from: "GitHub Actions Production " \ No newline at end of file diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml new file mode 100644 index 0000000..0a42c4e --- /dev/null +++ b/.github/workflows/quality.yml @@ -0,0 +1,121 @@ +name: JIBAN EVENT QUALITY + +on: + workflow_dispatch: + inputs: + name: + description: "Who to greet" + default: "World" + push: + paths-ignore: + - '**.md' + branches: [ "develop" ] + +jobs: + build: + runs-on: ubuntu-latest + env: + DOTNET_CORE_VERSION: 10.0.x + PORTHTTPS: "44361" + TZ: America/Guayaquil + NUGET_TOKEN: ${{ secrets.NUGET_TOKEN }} + outputs: + image-tag: ${{ steps.generate-tag.outputs.image-tag }} + steps: + - name: Set up .NET Core SDK + uses: actions/setup-dotnet@v5.0.0 + with: + dotnet-version: '10.0.x' + + - name: Check out code + uses: actions/checkout@v5.0.0 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3.11.1 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: raulidavid + password: ${{ secrets.JIBANTOKEN }} + + - name: Generate IMAGE_TAG + id: generate-tag + run: | + IMAGE_TAG="ghcr.io/raulidavid/jiban-event:quality-v$(date +%Y.%m.%d)-${{ github.run_number }}" + echo "IMAGE_TAG=$IMAGE_TAG" >> $GITHUB_ENV + echo "image-tag=$IMAGE_TAG" >> $GITHUB_OUTPUT + echo "Generated tag: $IMAGE_TAG" + + - name: Rename .nuget.config to nuget.config + run: mv .nuget.config nuget.config + + - name: Configure NuGet + run: | + echo "Configuring NuGet..." + sed -i 's|\${NUGET_TOKEN}|'"${{ secrets.NUGET_TOKEN }}"'|g' nuget.config + + - name: Build and Push Api Image + uses: docker/build-push-action@v5 + with: + context: . + file: src/Jiban.Api/Dockerfile.production + push: true + tags: ${{ env.IMAGE_TAG }} + build-args: | + NUGET_TOKEN=${{ env.NUGET_TOKEN }} + cache-from: type=gha + cache-to: type=gha,mode=max + platforms: linux/amd64 + + - name: Send Email via Amazon SES + if: success() + uses: dawidd6/action-send-mail@v4 + with: + server_address: email-smtp.us-east-1.amazonaws.com + server_port: 465 + username: ${{ secrets.SES_USER }} + password: ${{ secrets.SES_PASS }} + subject: "✅ QUALITY - Nueva imagen generada: ${{ env.IMAGE_TAG }}" + body: | + 🚀 **BUILD EXITOSO - QUALITY** + + La imagen Docker ha sido creada y subida exitosamente. + + 📌 **Tag:** `${{ env.IMAGE_TAG }}` + 📊 **Branch:** `${{ github.ref_name }}` + 📝 **Commit:** `${{ github.sha }}` + 👤 **Actor:** `${{ github.actor }}` + 🔗 **Workflow:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + + --- + *Generado automáticamente por GitHub Actions* + to: "raul.flores@jiban.ec" + from: "GitHub Actions Quality " + + - name: Send Error Email via Amazon SES + if: failure() + uses: dawidd6/action-send-mail@v4 + with: + server_address: email-smtp.us-east-1.amazonaws.com + server_port: 465 + username: ${{ secrets.SES_USER }} + password: ${{ secrets.SES_PASS }} + subject: "❌ QUALITY - Error en build: ${{ github.ref_name }}" + body: | + 💥 **BUILD FALLÓ - QUALITY** + + Ha ocurrido un error durante el proceso de build. + + 📊 **Branch:** `${{ github.ref_name }}` + 📝 **Commit:** `${{ github.sha }}` + 👤 **Actor:** `${{ github.actor }}` + 🔗 **Ver detalles:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + + Por favor revisa los logs para más detalles. + + --- + *Generado automáticamente por GitHub Actions* + to: "raul.flores@jiban.ec" + from: "GitHub Actions Quality " \ No newline at end of file diff --git a/.nuget.config b/.nuget.config new file mode 100644 index 0000000..25ba807 --- /dev/null +++ b/.nuget.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Jiban.Api/Dockerfile b/src/Jiban.Api/Dockerfile deleted file mode 100644 index 530492a..0000000 --- a/src/Jiban.Api/Dockerfile +++ /dev/null @@ -1,30 +0,0 @@ -# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging. - -# This stage is used when running from VS in fast mode (Default for Debug configuration) -FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base -USER $APP_UID -WORKDIR /app -EXPOSE 8080 -EXPOSE 8081 - - -# This stage is used to build the service project -FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build -ARG BUILD_CONFIGURATION=Release -WORKDIR /src -COPY ["Jiban.Api/Jiban.Api.csproj", "Jiban.Api/"] -RUN dotnet restore "./Jiban.Api/Jiban.Api.csproj" -COPY . . -WORKDIR "/src/Jiban.Api" -RUN dotnet build "./Jiban.Api.csproj" -c $BUILD_CONFIGURATION -o /app/build - -# This stage is used to publish the service project to be copied to the final stage -FROM build AS publish -ARG BUILD_CONFIGURATION=Release -RUN dotnet publish "./Jiban.Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false - -# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration) -FROM base AS final -WORKDIR /app -COPY --from=publish /app/publish . -ENTRYPOINT ["dotnet", "Jiban.Api.dll"] \ No newline at end of file diff --git a/src/Jiban.Api/Dockerfile.development b/src/Jiban.Api/Dockerfile.development new file mode 100644 index 0000000..d54c6cf --- /dev/null +++ b/src/Jiban.Api/Dockerfile.development @@ -0,0 +1,54 @@ +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS base + +# Initialize build arguments +ARG PORTHTTPS +ARG JIBANKEYVAULTURL +ARG DOCKERFILE_PATH + +# Display initialized test arguments +RUN echo "PORTHTTPS: ${PORTHTTPS}" && \ + echo "JIBANKEYVAULTURL: ${JIBANKEYVAULTURL}" + +# Set environment variables +ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false \ + TZ=America/Guayaquil \ + PATH="$PATH:/root/.dotnet/tools" + +# Expose the HTTPS port +EXPOSE ${PORTHTTPS} + +# Use bash as the default shell +RUN ln -sf /bin/bash /bin/sh + +# Create directory for secrets store +RUN mkdir /mnt/secrets-store + +# Install dotnet-ef tool globally +RUN dotnet tool install --global dotnet-ef + +# Set the working directory +WORKDIR /src + +# Copy all files to the working directory +COPY . . + +# Update package lists and install required packages +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + tzdata \ + curl \ + iputils-ping \ + telnet \ + vim \ + wget \ + git \ + libfontconfig1 \ + fontforge \ + cabextract \ + apt-utils \ + libgdiplus \ + libc6-dev && \ + rm -rf /var/lib/apt/lists/* + +# Keep the container running +ENTRYPOINT ["tail", "-f", "/dev/null"] \ No newline at end of file diff --git a/src/Jiban.Api/Dockerfile.production b/src/Jiban.Api/Dockerfile.production new file mode 100644 index 0000000..9be4849 --- /dev/null +++ b/src/Jiban.Api/Dockerfile.production @@ -0,0 +1,88 @@ +# Stage 1: Base Runtime Image (Standard Microsoft Debian-based) +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base + +# Initialize environment variables +ARG PORTHTTPS +ARG JIBANKEYVAULTURL +ARG DOCKERFILE_PATH + +ENV PORTHTTPS=${PORTHTTPS} \ + JIBANKEYVAULTURL=${JIBANKEYVAULTURL} \ + DOCKERFILE_PATH=${DOCKERFILE_PATH} \ + DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false \ + DOTNET_RUNNING_IN_CONTAINER=true \ + DOTNET_USE_POLLING_FILE_WATCHER=true \ + TZ=America/Guayaquil + +# Use bash shell for consistency +RUN rm /bin/sh && ln -s /bin/bash /bin/sh + +# Install runtime dependencies with cleanup +RUN apt-get update && apt-get install -y --no-install-recommends \ + tzdata \ + curl \ + iputils-ping \ + telnet \ + libfontconfig1 \ + fontforge \ + cabextract \ + apt-utils \ + libgdiplus \ + libc6-dev \ + fonts-liberation \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* + +WORKDIR /app +EXPOSE ${PORTHTTPS} + +# Stage 2: Build Dependencies (Better caching) +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS restore + +# Use bash shell +RUN rm /bin/sh && ln -s /bin/bash /bin/sh + +WORKDIR /src + +# Copy all source code at once +COPY . . + +# Restore dependencies +RUN dotnet restore "src/Jiban.Api/Jiban.Api.csproj" \ + --verbosity normal + +# Stage 3: Build Application +FROM restore AS build + +WORKDIR "/src/src/Jiban.Api" + +# Build with optimizations for your .NET 10 API +RUN dotnet build "Jiban.Api.csproj" \ + --configuration Release \ + --no-restore \ + --verbosity minimal \ + --nologo + +# Stage 4: Publish Application +FROM build AS publish + +# Publish with optimizations for production +RUN dotnet publish "Jiban.Api.csproj" \ + --configuration Release \ + --no-build \ + --output /app/publish \ + --self-contained false \ + --verbosity minimal \ + --nologo \ + /p:PublishReadyToRun=false \ + /p:PublishSingleFile=false \ + /p:PublishTrimmed=false + +# Stage 5: Final Optimized Image +FROM base AS final + +# Copy published application +COPY --from=publish /app/publish . + +# Use exec form for better signal handling +ENTRYPOINT ["dotnet", "Jiban.Api.dll"] \ No newline at end of file diff --git a/src/Jiban.Api/Program.cs b/src/Jiban.Api/Program.cs index da50894..5e1753a 100644 --- a/src/Jiban.Api/Program.cs +++ b/src/Jiban.Api/Program.cs @@ -1,41 +1,38 @@ -using Jiban.Infrastructure.Configuration; +using Jiban.Domain; using Jiban.AspNetCore; +using Jiban.Infrastructure.Configuration; var builder = WebApplication.CreateBuilder(args); -// VERIFICACIN TEMPORAL +// Optional: show some config values Console.WriteLine($"Entorno actual: {builder.Environment.EnvironmentName}"); -Console.WriteLine($"Redis Hostname: {builder.Configuration["Redis:Hostname"]}"); -Console.WriteLine($"Redis Password: {builder.Configuration["Redis:Password"]}"); +// Ensure IHttpContextAccessor is available (GetDataKeyFromUserNormal needs it) +builder.Services.AddHttpContextAccessor(); + +// expose webHostBuilder for APIs expecting it +var webHostBuilder = builder.WebHost; + +var setup = builder.Services.MultiTenant(webHostBuilder, builder.Configuration); +builder.Services.AddJibanJwtServices(setup.Options); builder.Services.AddJibanRedis(builder.Configuration); +builder.Services.AddJibanAwsServices(builder.Configuration); + builder.Services.AddJibanHostedServices(builder.Configuration); builder.Services.AddInfrastructureServices(builder.Configuration); builder.Services.AddControllers(); - -// Usar OpenAPI nativo de .NET 10 en lugar de Swashbuckle builder.Services.AddOpenApi(); var app = builder.Build(); -// Configure the HTTP request pipeline. -// Swagger UI disponible en Development +// pipeline... if (app.Environment.IsDevelopment()) { app.MapOpenApi(); - app.UseSwaggerUI(options => - { - options.SwaggerEndpoint("/openapi/v1.json", "Jiban API v1"); - }); - - // Mostrar la URL de Swagger en la consola - Console.WriteLine("?? Swagger UI disponible en: https://localhost:56982/swagger"); + app.UseSwaggerUI(options => options.SwaggerEndpoint("/openapi/v1.json", "Jiban API v1")); } app.UseHttpsRedirection(); - app.UseAuthorization(); - app.MapControllers(); - -app.Run(); +app.Run(); \ No newline at end of file diff --git a/src/Jiban.Api/appsettings.Development.json b/src/Jiban.Api/appsettings.Development.json index 4fe8b3b..3ae488a 100644 --- a/src/Jiban.Api/appsettings.Development.json +++ b/src/Jiban.Api/appsettings.Development.json @@ -12,15 +12,20 @@ "Password": "${REDIS_CONNECTION_PASSWORD}" }, "Process": "true", - "Notification:WaitSeconds": "30", + "Notification:WaitSeconds": "120", "Notification:PendingMessagesCount": "10", "Notification:RetryAttempts": "3", "Notification:NewMessagesCount": "10", - "Notification:StartLetterQueue": "evento_ventadigital_cola_inicio_cuenta_pyme", + "Notification:StartLetterQueue": "Notification:StartLetterQueue", "Notification:FinishLetterQueue": "Notification:FinishLetterQueue", - "Notification:DeadLetterQueue": "evento_ventadigital_cola_muertos_cuenta_pyme", + "Notification:DeadLetterQueue": "Notification:DeadLetterQueue", "JAEGER:AGENTHOST": "microk8s.jiban.ec", "JAEGER:AGENTPORT": "30032", "ACTIVITY_SOURCES": "AuthenticationModule", + "TOKEN_EXPIRE": "30", + "TOKENREFRESH_EXPIRE": "3", + "TOKEN_ISSUER": "https://apiqa.jiban.ec:44361", + "TOKEN_AUDIENCE": "https://appqa.jiban.ec", + "SIGNINGKEY": "SmVzdXNFc0VsQ2FtaW5vRGlvc0VzQW1vcg==", "NswagBaseUrl": "https://apiqa.jiban.ec:44361" } \ No newline at end of file diff --git a/src/Jiban.Domain/Jiban.Domain.csproj b/src/Jiban.Domain/Jiban.Domain.csproj index 59d127d..5e1e249 100644 --- a/src/Jiban.Domain/Jiban.Domain.csproj +++ b/src/Jiban.Domain/Jiban.Domain.csproj @@ -7,7 +7,7 @@ - + diff --git a/src/Jiban.Infrastructure/Configuration/InfraestructureExtension.cs b/src/Jiban.Infrastructure/Configuration/InfraestructureExtension.cs index 1556a43..112052a 100644 --- a/src/Jiban.Infrastructure/Configuration/InfraestructureExtension.cs +++ b/src/Jiban.Infrastructure/Configuration/InfraestructureExtension.cs @@ -5,6 +5,8 @@ using Jiban.Infrastructure.Services; using Polly.Extensions.Http; using Polly; +using Jiban.Nswag; +using JibanPermissions.Services; namespace Jiban.Infrastructure.Configuration { @@ -22,7 +24,9 @@ public static IServiceCollection AddJibanHostedServices(this IServiceCollection public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration) { + services.AddScoped(); + services.AddScoped(); services.AddSingleton(); services.AddTransient(); diff --git a/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.Authorize.cs b/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.Authorize.cs index 35ae93f..eb6026c 100644 --- a/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.Authorize.cs +++ b/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.Authorize.cs @@ -1,12 +1,12 @@ - +using Jiban.Nswag; + namespace Jiban.Infrastructure.HostedServices { public partial class ElectronicDocHostedService { - - public async Task AuthorizeDocument() + public async Task SendEmailDocumentsAsync(DocumentEmailRequest documentEmailRequest) { - Console.WriteLine("Autorizar Documento"); + await _electronicDocService.SendEmailDocumentsAsync(documentEmailRequest); } } } \ No newline at end of file diff --git a/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.Constructor.cs b/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.Constructor.cs index d27011c..b28112f 100644 --- a/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.Constructor.cs +++ b/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.Constructor.cs @@ -43,6 +43,7 @@ public partial class ElectronicDocHostedService : BackgroundService private readonly ILogger _logger; private readonly IElectronicDocService _electronicDocService; private readonly ITokenAccessor _tokenAccessor; + private readonly ITokenBuilder _tokenBuilder; private readonly IConfiguration _configuration; private readonly IEventService _eventService; @@ -53,6 +54,7 @@ public ElectronicDocHostedService(ILogger logger, IS _eventService = _serviceScope.ServiceProvider.GetRequiredService(); _electronicDocService = _serviceScope.ServiceProvider.GetRequiredService(); _tokenAccessor = _serviceScope.ServiceProvider.GetRequiredService(); + _tokenBuilder = _serviceScope.ServiceProvider.GetRequiredService(); _configuration = _serviceScope.ServiceProvider.GetRequiredService(); } } diff --git a/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.cs b/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.cs index f5f2a38..31a21a2 100644 --- a/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.cs +++ b/src/Jiban.Infrastructure/HostedServices/ElectronicDocHostedService.cs @@ -1,7 +1,7 @@ using Jiban.BaseCode.PermissionsCode; -using Jiban.Nswag; using Microsoft.Extensions.Logging; using StackExchange.Redis; +using Jiban.Nswag; namespace Jiban.Infrastructure.HostedServices { @@ -430,30 +430,25 @@ private async Task ProcesarMensajePendienteIndividual(StreamEntry mensaje, strin /// /// Procesar el evento que se recibe de la cola Redis /// - /// Modelo con información de la solicitud a procesar - private async Task ProcesarEvento(DocumentEmailRequest eventAuthorizeDocument) + /// Modelo con información de la solicitud a procesar + private async Task ProcesarEvento(DocumentEmailRequest documentEmailRequest) { try { - string identificacionSolicitud = eventAuthorizeDocument.Email.ToString(); - string identificacion = eventAuthorizeDocument.SriDocumentId.ToString(); - _logger.LogInformation("{ProcessingEmoji} Procesando evento - IdSolicitudDetalle: {IdSolicitudDetalle}, Identificacion: {Identificacion}", - JibanConstants.PROCESSING_EMOJI, identificacionSolicitud, identificacion); + _logger.LogInformation("{ProcessingEmoji} Procesando evento - Autorizar Documento", + JibanConstants.PROCESSING_EMOJI); // PROCESAMIENTO REAL DEL EVENTO - _logger.LogInformation("📄 Iniciando procesamiento de documentos electrónicos para: {Identificacion}", identificacion); - - // Usar el servicio de documentos electrónicos - await _electronicDocService.ProcessElectronicDocumentsAsync(identificacion, CancellationToken.None); - - // Aquí puedes agregar tu lógica de negocio específica: - // await ProcesarSolicitudCheques(eventAuthorizeDocument); - // await ProcesarGeneracionDocumentacion(eventAuthorizeDocument); - // await ProcesarActualizacionUsuarioFinal(eventAuthorizeDocument); - - _logger.LogInformation("{SuccessEmoji} Evento procesado exitosamente para IdSolicitudDetalle: {IdSolicitudDetalle}", - JibanConstants.SUCCESS_EMOJI, identificacionSolicitud); + _logger.LogInformation("📄 Iniciando procesamiento de documentos electrónicos para: {Identificacion}", documentEmailRequest.Email); + documentEmailRequest.ProcessingType = ProcessingType.Direct; + var tokenAndRefreshToken = await _tokenBuilder.GenerateTokenAndRefreshTokenAsync(documentEmailRequest.UserId); + _tokenAccessor.SetToken(tokenAndRefreshToken.Token); + await SendEmailDocumentsAsync(documentEmailRequest); + _tokenAccessor.ClearToken(); + + _logger.LogInformation("{SuccessEmoji} Evento procesado exitosamente - Autorizar Documento", + JibanConstants.SUCCESS_EMOJI); } catch (Exception excepcion) { diff --git a/src/Jiban.Infrastructure/Services/ElectronicDocService.cs b/src/Jiban.Infrastructure/Services/ElectronicDocService.cs index 5839aff..80475b3 100644 --- a/src/Jiban.Infrastructure/Services/ElectronicDocService.cs +++ b/src/Jiban.Infrastructure/Services/ElectronicDocService.cs @@ -7,37 +7,28 @@ namespace Jiban.Infrastructure.Services /// public class ElectronicDocService : IElectronicDocService { - private readonly IAccountClient _accountClient; + private readonly ISriClient _sriClient; private readonly ITokenAccessor _tokenAccessor; /// /// Initializes a new instance of the class. /// - /// Client for account-related operations. + /// Client for account-related operations. /// Accessor for managing authentication tokens. - public ElectronicDocService(IAccountClient accountClient, ITokenAccessor tokenAccessor) + public ElectronicDocService(ISriClient sriClient, ITokenAccessor tokenAccessor) { - _accountClient = accountClient; + _sriClient = sriClient; _tokenAccessor = tokenAccessor; } - /// - /// Processes electronic documents for a given identification, handling authentication and account transfer. - /// - /// The identification of the user or entity. - /// Token to monitor for cancellation requests. - public async Task ProcessElectronicDocumentsAsync(string identificacion, CancellationToken cancellationToken) + public async Task SendEmailDocumentsAsync(DocumentEmailRequest documentEmailRequest) { // Assume token is already set by the caller (e.g., the queue/hosted service). // If needed, you could validate it's present: if (string.IsNullOrWhiteSpace(_tokenAccessor.CurrentToken)) throw new InvalidOperationException("JWT token not set in ITokenAccessor."); - // Initiate account transfer using the provided payload. - await _accountClient.AccountTransferCreateAsync(new AccountTransferCreateRequest - { - // Populate payload properties as required. - }, cancellationToken); + await _sriClient.SendEmailDocumentAsync(documentEmailRequest); } } } \ No newline at end of file diff --git a/src/Jiban.Infrastructure/Services/IElectronicDocService.cs b/src/Jiban.Infrastructure/Services/IElectronicDocService.cs index 3920187..7f2fc48 100644 --- a/src/Jiban.Infrastructure/Services/IElectronicDocService.cs +++ b/src/Jiban.Infrastructure/Services/IElectronicDocService.cs @@ -1,7 +1,27 @@ -namespace Jiban.Infrastructure.Services +using Jiban.Nswag; + +namespace Jiban.Infrastructure.Services { + /// + /// Provides functionality for sending electronic documents (for example, SRI documents) + /// to recipients via email. + /// public interface IElectronicDocService { - Task ProcessElectronicDocumentsAsync(string identificacion, CancellationToken cancellationToken); + /// + /// Sends one or more documents described by to the + /// target email address asynchronously. + /// + /// + /// Request object containing the document identifier, document type and recipient email. + /// See for details. + /// + /// A that represents the asynchronous send operation. + /// + /// Implementations should validate the request and surface errors (for example, network + /// or validation failures) by throwing appropriate exceptions or returning error results + /// according to the calling convention used in the project. + /// + Task SendEmailDocumentsAsync(DocumentEmailRequest documentEmailRequest); } } \ No newline at end of file