diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index d4ac0ff..64a4cb3 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -6,7 +6,7 @@ Este PR implementa la **solución completa para el problema de crashes de Railwa ### 🎯 **Problema Solucionado** - ❌ **Problema**: Aplicación crashes en Railway después de exactamente 2 minutos -- ❌ **Problema**: Botones y funcionalidades del admin dashboard no operativas +- ❌ **Problema**: Botones y funcionalidades del admin dashboard no operativas - ❌ **Problema**: Templates genéricos en lugar de específicos - ❌ **Problema**: Configuración de despliegue incompleta @@ -88,7 +88,7 @@ Este PR implementa la **solución completa para el problema de crashes de Railwa - [ ] Variables de entorno configuradas en Railway - [ ] `RAILWAY_TOKEN` configurado en GitHub Secrets -### **Post-merge Actions** +### **Post-merge Actions** 1. **Auto-deploy** se activará automáticamente en `main` 2. **Health check** validará despliegue exitoso 3. **Monitoring** confirmará estabilidad post-deploy @@ -134,4 +134,4 @@ Este PR implementa la **solución completa para el problema de crashes de Railwa --- -**🎉 Este PR convierte NeuroBank FastAPI en una aplicación bancaria de nivel empresarial con despliegue automático y funcionalidad completa!** \ No newline at end of file +**🎉 Este PR convierte NeuroBank FastAPI en una aplicación bancaria de nivel empresarial con despliegue automático y funcionalidad completa!** diff --git a/.github/workflows/ci-cd-fixed.yml b/.github/workflows/ci-cd-fixed.yml index e16fcea..1959998 100644 --- a/.github/workflows/ci-cd-fixed.yml +++ b/.github/workflows/ci-cd-fixed.yml @@ -38,21 +38,21 @@ jobs: if: github.event.inputs.skip_tests != 'true' steps: - uses: actions/checkout@v4 - + - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - + - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - + - name: Run tests with coverage run: | python -m pytest --cov=app --cov-report=xml --cov-report=html - + - name: Upload coverage reports uses: actions/upload-artifact@v4 if: always() @@ -67,27 +67,27 @@ jobs: if: github.event.inputs.skip_tests != 'true' steps: - uses: actions/checkout@v4 - + - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - + - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt pip install bandit safety - + - name: Run Bandit security scan run: | bandit -r app/ -f json -o bandit-report.json --skip B101 || true - + - name: Run Safety vulnerability scan run: | pip freeze > current-requirements.txt safety scan --json --output safety-report.json --continue-on-error || true - + - name: Upload security reports uses: actions/upload-artifact@v4 if: always() @@ -101,15 +101,15 @@ jobs: needs: [test, security] runs-on: ubuntu-latest if: | - always() && + always() && github.event.inputs.force_deploy == 'true' && - (github.event.inputs.skip_tests == 'true' || + (github.event.inputs.skip_tests == 'true' || (needs.test.result == 'success' && needs.security.result == 'success')) - + steps: - name: Checkout uses: actions/checkout@v4 - + - name: Emergency deployment warning if: github.event.inputs.skip_tests == 'true' run: | @@ -119,39 +119,39 @@ jobs: echo "🚨 This should only be used in emergency situations!" echo "🚨 Make sure to run full testing after deployment!" echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" - + - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - + - name: Configure AWS credentials via OIDC uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ env.AWS_ROLE_ARN }} aws-region: ${{ env.AWS_REGION }} role-session-name: GitHubActions-Fixed-${{ github.run_id }} - + - name: Verify AWS connection run: | echo "🔍 Verifying AWS OIDC connection..." aws sts get-caller-identity echo "✅ AWS connection verified!" - + - name: Setup SAM CLI uses: aws-actions/setup-sam@v2 with: use-installer: true - + - name: Create ECR repository if not exists run: | aws ecr describe-repositories --repository-names ${{ env.ECR_REPOSITORY }} --region ${{ env.AWS_REGION }} || \ aws ecr create-repository --repository-name ${{ env.ECR_REPOSITORY }} --region ${{ env.AWS_REGION }} - + - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@v2 - + - name: Build and push Docker image env: ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} @@ -161,7 +161,7 @@ jobs: docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY:latest docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest - + - name: Deploy to AWS Lambda run: | sam build --region ${{ env.AWS_REGION }} @@ -170,4 +170,4 @@ jobs: --capabilities CAPABILITY_IAM \ --region ${{ env.AWS_REGION }} \ --parameter-overrides ApiKey=${{ secrets.API_KEY || 'emergency-deploy-key' }} - echo "🎉 Emergency deployment completed!" \ No newline at end of file + echo "🎉 Emergency deployment completed!" diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml index f7aad88..fb2ad03 100644 --- a/.github/workflows/ci-cd.yml +++ b/.github/workflows/ci-cd.yml @@ -39,30 +39,30 @@ env: jobs: test: runs-on: ubuntu-latest - + # ✅ Variables de entorno para tests env: API_KEY: "NeuroBankDemo2025-SecureKey-ForTestingOnly" ENVIRONMENT: "testing" CI: "true" - + steps: - uses: actions/checkout@v4 - + - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - + - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - + - name: Run tests with coverage run: | python -m pytest --cov=app --cov-report=xml --cov-report=html - + - name: Upload coverage to Codecov uses: codecov/codecov-action@v4 if: always() @@ -71,40 +71,40 @@ jobs: security: runs-on: ubuntu-latest - + # ✅ Variables de entorno para security checks env: API_KEY: "NeuroBankDemo2025-SecureKey-ForTestingOnly" ENVIRONMENT: "testing" CI: "true" - + steps: - uses: actions/checkout@v4 - + - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - + - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - + - name: Install security tools run: pip install bandit safety pytest-cov - + - name: Run Bandit (exclude tests from assert checking) run: | bandit -r app/ -f json -o bandit-report.json --skip B101 || true echo "Bandit scan completed - check bandit-report.json for details" - + - name: Run Safety scan run: | pip freeze > current-requirements.txt safety scan --json --output safety-report.json --continue-on-error || true echo "Safety scan completed - check safety-report.json for details" - + - name: Upload security reports as artifacts uses: actions/upload-artifact@v4 if: always() @@ -118,7 +118,7 @@ jobs: needs: [test, security] runs-on: ubuntu-latest if: github.ref == 'refs/heads/main' - + steps: - name: Check deployment readiness run: | @@ -157,14 +157,14 @@ jobs: runs-on: ubuntu-latest # Solo deployar cuando el usuario lo active manualmente con workflow_dispatch if: | - (github.event_name == 'workflow_dispatch' && - github.event.inputs.deploy_to_aws == 'true' && + (github.event_name == 'workflow_dispatch' && + github.event.inputs.deploy_to_aws == 'true' && github.ref == 'refs/heads/main') - + steps: - name: Checkout uses: actions/checkout@v4 - + - name: Verify OIDC prerequisites run: | echo "🚀 Starting OIDC-secured deployment process..." @@ -172,7 +172,7 @@ jobs: echo "📦 ECR Repository: ${{ env.ECR_REPOSITORY }}" develop echo "🔑 Checking AWS Credentials..." - + # Verify secrets are available (without exposing them) if [ -z "${{ secrets.AWS_ACCESS_KEY_ID }}" ]; then echo "❌ AWS_ACCESS_KEY_ID is missing" @@ -180,7 +180,7 @@ jobs: else echo "✅ AWS_ACCESS_KEY_ID is available" fi - + if [ -z "${{ secrets.AWS_SECRET_ACCESS_KEY }}" ]; then echo "❌ AWS_SECRET_ACCESS_KEY is missing" exit 1 @@ -189,7 +189,7 @@ jobs: echo "� AWS Role ARN: ${{ env.AWS_ROLE_ARN }}" echo "🏗️ Using secure OIDC authentication ✨" - + # Verify AWS Account ID is available if [ -z "${{ secrets.AWS_ACCOUNT_ID }}" ]; then echo "❌ AWS_ACCOUNT_ID secret is missing" @@ -199,7 +199,7 @@ jobs: echo "✅ AWS_ACCOUNT_ID is configured" main fi - + if [ -z "${{ secrets.API_KEY }}" ]; then echo "⚠️ API_KEY is missing - using default" else @@ -209,47 +209,47 @@ jobs: echo "✅ API_KEY is configured" main fi - + - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - + - name: Configure AWS credentials via OIDC uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ env.AWS_ROLE_ARN }} aws-region: ${{ env.AWS_REGION }} role-session-name: GitHubActions-${{ github.run_id }} - + - name: Debug AWS identity run: | echo "🧪 Testing AWS OIDC connection..." aws sts get-caller-identity echo "✅ AWS OIDC connection successful!" - + - name: Test AWS connection run: | echo "🧪 Testing AWS connection..." aws sts get-caller-identity echo "✅ AWS connection successful!" - + - name: Setup SAM CLI uses: aws-actions/setup-sam@v2 with: use-installer: true - + - name: Create ECR repository if not exists run: | echo "📦 Ensuring ECR repository exists..." aws ecr describe-repositories --repository-names ${{ env.ECR_REPOSITORY }} --region ${{ env.AWS_REGION }} || \ aws ecr create-repository --repository-name ${{ env.ECR_REPOSITORY }} --region ${{ env.AWS_REGION }} echo "✅ ECR repository ready" - + - name: Login to Amazon ECR id: login-ecr uses: aws-actions/amazon-ecr-login@v2 - + - name: Build, tag, and push image to Amazon ECR env: ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} @@ -262,7 +262,7 @@ jobs: docker tag $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG $ECR_REGISTRY/$ECR_REPOSITORY:latest docker push $ECR_REGISTRY/$ECR_REPOSITORY:latest echo "✅ Docker image pushed successfully!" - + - name: Deploy to AWS Lambda run: | echo "🚀 Starting SAM deployment..." diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4857afd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,68 @@ +name: CI + +on: + pull_request: + branches: [ "**" ] + push: + branches: [ "feature/**", "fix/**", "chore/**" ] + +jobs: + test-and-lint: + runs-on: ubuntu-latest + defaults: + run: + working-directory: . + steps: + - uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Cache pip + uses: actions/cache@v4 + with: + path: ~/.cache/pip + key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }} + restore-keys: ${{ runner.os }}-pip- + + - name: Install deps (root + services) + run: | + pip install -U pip wheel + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + for svc in trading_ai_system/ingestion_service trading_ai_system/inference_service trading_ai_system/control_service; do + if [ -f "$svc/requirements.txt" ]; then pip install -r "$svc/requirements.txt"; fi + done + pip install pytest flake8 + + - name: Lint + run: flake8 . + + - name: Test + run: | + if [ -d tests ]; then pytest -q; else echo "No tests dir"; fi + + build-check: + name: Docker build (no push) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + service: + - { name: ingestion_service, path: trading_ai_system/ingestion_service } + - { name: inference_service, path: trading_ai_system/inference_service } + - { name: control_service, path: trading_ai_system/control_service } + steps: + - uses: actions/checkout@v4 + - name: Check context exists + id: ctx + run: | + if [ -d "${{ matrix.service.path }}" ] && [ -f "${{ matrix.service.path }}/Dockerfile" ]; then + echo "exists=true" >> $GITHUB_OUTPUT + else + echo "exists=false" >> $GITHUB_OUTPUT + fi + - name: Build ${{ matrix.service.name }} + if: steps.ctx.outputs.exists == 'true' + run: docker build -t neurobank/${{ matrix.service.name }}:ci ${{ matrix.service.path }} diff --git a/.github/workflows/deploy-prod-ecs.yml b/.github/workflows/deploy-prod-ecs.yml new file mode 100644 index 0000000..b061fc9 --- /dev/null +++ b/.github/workflows/deploy-prod-ecs.yml @@ -0,0 +1,94 @@ +name: Deploy Prod (ECS) + +on: + # Solo ejecutable manualmente + workflow_dispatch: + inputs: + tag: + description: "Tag de release (prod-YYYY.MM.DD-XX)" + required: true + confirm: + description: "Confirmar deploy a PRODUCCIÓN (ECS)" + required: true + default: "no" + type: choice + options: ["no", "yes"] + +env: + AWS_REGION: ${{ secrets.AWS_REGION }} + AWS_ACCOUNT_ID: ${{ secrets.AWS_ACCOUNT_ID }} + ECR_REGISTRY: ${{ secrets.AWS_ACCOUNT_ID }}.dkr.ecr.${{ secrets.AWS_REGION }}.amazonaws.com + +jobs: + build-and-push: + runs-on: ubuntu-latest + if: github.event_name == 'workflow_dispatch' && inputs.confirm == 'yes' && secrets.AWS_ACCOUNT_ID != '' && secrets.AWS_OIDC_ROLE_ARN != '' + permissions: + id-token: write + contents: read + strategy: + fail-fast: false + matrix: + service: + - { name: api-gateway, path: . } # Ajusta si API tiene Dockerfile propio en raíz/otra ruta + - { name: ingestion, path: trading_ai_system/ingestion_service } + - { name: inference, path: trading_ai_system/inference_service } + - { name: control, path: trading_ai_system/control_service } + steps: + - uses: actions/checkout@v4 + + - name: Configure AWS credentials (OIDC) + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ secrets.AWS_OIDC_ROLE_ARN }} # IAM Role con trust para GitHub + aws-region: ${{ env.AWS_REGION }} + + - name: Login to ECR + id: ecr + uses: aws-actions/amazon-ecr-login@v2 + + - name: Build & Push ${{ matrix.service.name }} + run: | + IMAGE=${{ env.ECR_REGISTRY }}/neurobank/${{ matrix.service.name }}:${{ inputs.tag }} + docker build -t "$IMAGE" ${{ matrix.service.path }} + docker push "$IMAGE" + + deploy-ecs: + needs: build-and-push + runs-on: ubuntu-latest + if: github.event_name == 'workflow_dispatch' && inputs.confirm == 'yes' + permissions: + id-token: write + contents: read + strategy: + fail-fast: false + matrix: + svc: + - { ecs_service: api-gateway-svc, taskdef: trading_ai_system/ecs/api-gateway-task.json, container: api-gateway, image_repo: neurobank/api-gateway } + - { ecs_service: ingestion-svc, taskdef: trading_ai_system/ecs/ingestion-service-task.json, container: ingestion, image_repo: neurobank/ingestion } + - { ecs_service: inference-svc, taskdef: trading_ai_system/ecs/inference-service-task.json, container: inference, image_repo: neurobank/inference } + - { ecs_service: control-svc, taskdef: trading_ai_system/ecs/control-service-task.json, container: control, image_repo: neurobank/control } + steps: + - uses: actions/checkout@v4 + + - name: Configure AWS credentials (OIDC) + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ secrets.AWS_OIDC_ROLE_ARN }} + aws-region: ${{ env.AWS_REGION }} + + - name: Render Task Definition + id: taskdef + uses: aws-actions/amazon-ecs-render-task-definition@v1 + with: + task-definition: ${{ matrix.svc.taskdef }} + container-name: ${{ matrix.svc.container }} + image: ${{ env.ECR_REGISTRY }}/${{ matrix.svc.image_repo }}:${{ inputs.tag }} + + - name: Deploy to ECS + uses: aws-actions/amazon-ecs-deploy-task-definition@v2 + with: + task-definition: ${{ steps.taskdef.outputs.task-definition }} + service: ${{ matrix.svc.ecs_service }} + cluster: neurobank-prod + wait-for-service-stability: true diff --git a/.github/workflows/deploy-staging-railway.yml b/.github/workflows/deploy-staging-railway.yml new file mode 100644 index 0000000..4f38e6a --- /dev/null +++ b/.github/workflows/deploy-staging-railway.yml @@ -0,0 +1,50 @@ +name: Deploy Staging (Railway) + +on: + # Solo ejecutable manualmente + workflow_dispatch: + inputs: + confirm: + description: "Confirmar deploy a Railway STAGING" + required: true + default: "no" + type: choice + options: ["no", "yes"] + +concurrency: + group: staging-railway + cancel-in-progress: true + +jobs: + deploy: + runs-on: ubuntu-latest + # Ejecutar solo si se invoca manualmente y hay token + if: github.event_name == 'workflow_dispatch' && inputs.confirm == 'yes' && secrets.RAILWAY_TOKEN != '' + env: + RAILWAY_TOKEN: ${{ secrets.RAILWAY_TOKEN }} + steps: + - uses: actions/checkout@v4 + + - name: Setup Node (Railway CLI) + uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install Railway CLI + run: npm i -g @railway/cli + + - name: Auth + run: railway login --token "$RAILWAY_TOKEN" + + # Si tienes railway.toml en la raíz con todos los servicios: + - name: Deploy API Gateway + run: railway up --service api-gateway --yes + + - name: Deploy Ingestion + run: railway up --service ingestion-service --yes + + - name: Deploy Inference + run: railway up --service inference-service --yes + + - name: Deploy Control + run: railway up --service control-service --yes diff --git a/.github/workflows/ecs-taskdef-api.json b/.github/workflows/ecs-taskdef-api.json new file mode 100644 index 0000000..e11efc6 --- /dev/null +++ b/.github/workflows/ecs-taskdef-api.json @@ -0,0 +1,39 @@ +{ + "family": "api-gateway-task", + "networkMode": "awsvpc", + "requiresCompatibilities": ["FARGATE"], + "cpu": "512", + "memory": "1024", + "executionRoleArn": "arn:aws:iam:::role/ecsTaskExecutionRole", + "taskRoleArn": "arn:aws:iam:::role/ecsTaskAppRole", + "containerDefinitions": [ + { + "name": "api-gateway", + "image": ".dkr.ecr..amazonaws.com/neurobank/api-gateway:latest", + "portMappings": [{ "containerPort": 8000, "protocol": "tcp" }], + "environment": [ + { "name": "ENVIRONMENT", "value": "production" }, + { "name": "LOG_LEVEL", "value": "INFO" }, + { "name": "OTEL_SERVICE_NAME", "value": "api_gateway" } + ], + "secrets": [ + { "name": "SECRET_KEY", "valueFrom": "arn:aws:ssm:::parameter/neurobank/secret_key" }, + { "name": "API_KEY", "valueFrom": "arn:aws:ssm:::parameter/neurobank/api_key" } + ], + "logConfiguration": { + "logDriver": "awslogs", + "options": { + "awslogs-group": "/ecs/api-gateway", + "awslogs-region": "", + "awslogs-stream-prefix": "ecs" + } + } + }, + { + "name": "otel-collector", + "image": "otel/opentelemetry-collector:latest", + "command": ["--config=/etc/otelcol-config.yaml"], + "essential": false + } + ] +} diff --git a/.github/workflows/infra-terraform.yml b/.github/workflows/infra-terraform.yml new file mode 100644 index 0000000..4c3e9e1 --- /dev/null +++ b/.github/workflows/infra-terraform.yml @@ -0,0 +1,38 @@ +name: Infra (Terraform) + +on: + workflow_dispatch: + push: + paths: + - "infra/**.tf" + +jobs: + terraform: + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + AWS_REGION: ${{ secrets.AWS_REGION }} + steps: + - uses: actions/checkout@v4 + - uses: hashicorp/setup-terraform@v3 + with: + terraform_version: 1.9.5 + + - name: AWS Credentials (OIDC) + uses: aws-actions/configure-aws-credentials@v4 + with: + role-to-assume: ${{ secrets.AWS_OIDC_ROLE_ARN }} + aws-region: ${{ env.AWS_REGION }} + + - name: Terraform Init/Plan + working-directory: infra + run: | + terraform init + terraform plan -out=tfplan + + - name: Terraform Apply (manual gate) + if: github.event_name == 'workflow_dispatch' + working-directory: infra + run: terraform apply -auto-approve tfplan diff --git a/.github/workflows/production-pipeline.yml b/.github/workflows/production-pipeline.yml index 8c26e19..9fb28b5 100644 --- a/.github/workflows/production-pipeline.yml +++ b/.github/workflows/production-pipeline.yml @@ -2,158 +2,26 @@ name: 🚀 Production Pipeline - NeuroBank FastAPI Banking System on: push: - branches: [ main ] + branches: [ "main" ] pull_request: - branches: [ main ] - workflow_dispatch: - inputs: - deploy_to_railway: - description: 'Deploy to Railway (only for testing)' - required: false - default: false - type: boolean - deploy_to_vercel: - description: 'Deploy to Vercel (only for testing)' - required: false - default: false - type: boolean - -# Add permissions for CodeQL/SARIF upload -permissions: - contents: read - security-events: write - actions: read - -env: - PYTHON_VERSION: "3.11" - NODE_VERSION: "18" + branches: [ "main" ] jobs: - # ============================================================================ - # 1. CODE QUALITY & SECURITY ANALYSIS - # ============================================================================ - code-quality: - name: 🔍 Code Quality & Security Analysis + build-and-scan: runs-on: ubuntu-latest - steps: - - name: 📥 Checkout Repository - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - name: 🐍 Setup Python ${{ env.PYTHON_VERSION }} - uses: actions/setup-python@v4 - with: - python-version: ${{ env.PYTHON_VERSION }} - cache: 'pip' - - - name: 📦 Install Dependencies - run: | - python -m pip install --upgrade pip - pip install -r requirements.txt - pip install flake8 black isort bandit safety pylint - - - name: 🎨 Code Formatting Check (Black) - run: black --check --diff . - - - name: 📋 Import Sorting Check (isort) - run: isort --check-only --diff . - - - name: 🔬 Linting Analysis (Flake8) - run: flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics - - - name: 🛡️ Security Vulnerability Scan (Bandit) - run: bandit -r . -f json -o bandit-report.json || true - - - name: 🔒 Dependency Security Check (Safety) - run: safety check --json --output safety-report.json || true - - - name: 📊 Upload Security Reports - uses: actions/upload-artifact@v4 - with: - name: security-reports - path: | - bandit-report.json - safety-report.json - - # ============================================================================ - # 2. COMPREHENSIVE TESTING SUITE - # ============================================================================ - testing: - name: 🧪 Comprehensive Testing Suite - runs-on: ubuntu-latest - needs: code-quality - strategy: - matrix: - python-version: ["3.10", "3.11", "3.12"] - - services: - postgres: - image: postgres:15 - env: - POSTGRES_PASSWORD: testpassword - POSTGRES_USER: testuser - POSTGRES_DB: neurobank_test - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - ports: - - 5432:5432 - - steps: - - name: 📥 Checkout Repository - uses: actions/checkout@v4 - - - name: 🐍 Setup Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 - with: - python-version: ${{ matrix.python-version }} - cache: 'pip' - - - name: 📦 Install Testing Dependencies - run: | - python -m pip install --upgrade pip - pip install -r requirements.txt - pip install pytest pytest-cov pytest-asyncio httpx - - - name: 🗄️ Setup Test Database - env: - DATABASE_URL: postgresql://testuser:testpassword@localhost:5432/neurobank_test - run: | - echo "Database setup for testing environment" - # Add your database migration commands here if needed - - name: 🧪 Run Unit Tests with Coverage - env: - DATABASE_URL: postgresql://testuser:testpassword@localhost:5432/neurobank_test - SECRET_KEY: test-secret-key-for-github-actions - ENVIRONMENT: testing - run: | - pytest --cov=app --cov-report=xml --cov-report=html --cov-report=term-missing -v - - - name: 📊 Upload Coverage Reports - uses: codecov/codecov-action@v3 - with: - file: ./coverage.xml - flags: unittests - name: codecov-umbrella - fail_ci_if_error: false - - # ============================================================================ - # 3. DOCKER BUILD & VULNERABILITY SCANNING - # ============================================================================ - docker-security: - name: 🐳 Docker Security & Build Validation - runs-on: ubuntu-latest - needs: [code-quality, testing] steps: - name: 📥 Checkout Repository uses: actions/checkout@v4 - name: 🔧 Set up Docker Buildx uses: docker/setup-buildx-action@v3 + with: + install: true + use: true + + - name: 🧰 Set up Docker QEMU (para builds multi-arch, opcional) + uses: docker/setup-qemu-action@v3 - name: 🏗️ Build Docker Image uses: docker/build-push-action@v5 @@ -183,310 +51,6 @@ jobs: severity: 'CRITICAL,HIGH' exit-code: '0' - - name: 📤 Upload Trivy Scan Results - uses: github/codeql-action/upload-sarif@v3 - if: always() - continue-on-error: true - with: - sarif_file: 'trivy-results.sarif' - - # ============================================================================ - # 3.1. DOCKER CLOUD BUILD & PUSH - # ============================================================================ - docker-cloud-build: - name: 🌐 Docker Cloud Build & Push - runs-on: ubuntu-latest - needs: [code-quality, testing] - steps: - - name: 📥 Checkout Repository - uses: actions/checkout@v4 - - - name: 🔐 Log in to Docker Hub - uses: docker/login-action@v3 - with: - username: neiland - password: ${{ secrets.DOCKER_PAT }} - - - name: ☁️ Set up Docker Buildx with Cloud - uses: docker/setup-buildx-action@v3 - with: - driver: cloud - endpoint: "neiland/neurobank-fastapi-docker-cloud" - install: true - - - name: 🏗️ Build and Push to Docker Hub - uses: docker/build-push-action@v6 - with: - context: . - tags: "neiland/neurobank-fastapi:latest,neiland/neurobank-fastapi:${{ github.sha }}" - # For pull requests, export results to the build cache. - # Otherwise, push to a registry. - outputs: ${{ github.event_name == 'pull_request' && 'type=cacheonly' || 'type=registry' }} - cache-from: type=registry,ref=neiland/neurobank-fastapi:buildcache - cache-to: type=registry,ref=neiland/neurobank-fastapi:buildcache,mode=max - - # ============================================================================ - # 4. FRONTEND ASSET OPTIMIZATION - # ============================================================================ - frontend-optimization: - name: 🎨 Frontend Assets & Performance - runs-on: ubuntu-latest - steps: - - name: 📥 Checkout Repository - uses: actions/checkout@v4 - - - name: 🟢 Setup Node.js ${{ env.NODE_VERSION }} - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - cache: 'npm' - - - name: 📦 Install Frontend Dependencies - run: | - npm install -g uglify-js clean-css-cli html-minifier-terser - # Add any additional frontend build tools - - - name: ⚡ Optimize Static Assets - run: | - echo "Optimizing JavaScript files..." - find app/static/js -name "*.js" -not -name "*.min.js" -exec uglifyjs {} -o {}.min.js \; - - echo "Optimizing CSS files..." - find app/static/css -name "*.css" -not -name "*.min.css" -exec cleancss {} -o {}.min.css \; - - echo "Static asset optimization completed" - - - name: 📊 Generate Asset Report - run: | - echo "Asset optimization report generated" - find app/static -name "*.min.*" -exec ls -lh {} \; - - # ============================================================================ - # 5. PRE-DEPLOYMENT VALIDATION - # ============================================================================ - pre-deployment: - name: 🚨 Pre-Deployment Validation - runs-on: ubuntu-latest - needs: [docker-security, docker-cloud-build, frontend-optimization] - steps: - - name: 📥 Checkout Repository - uses: actions/checkout@v4 - - - name: 🐍 Setup Python ${{ env.PYTHON_VERSION }} - uses: actions/setup-python@v4 - with: - python-version: ${{ env.PYTHON_VERSION }} - cache: 'pip' - - - name: 📦 Install Dependencies - run: | - python -m pip install --upgrade pip - pip install -r requirements.txt - - - name: 🔍 Configuration Validation - run: | - echo "Validating Vercel configuration..." - if [ ! -f "vercel.json" ]; then - echo "❌ vercel.json not found!" - exit 1 - fi - - echo "Validating Vercel API directory..." - if [ ! -d "api" ]; then - echo "❌ api/ directory not found!" - exit 1 - fi - - echo "✅ All Vercel configuration files validated successfully!" - - - name: 🏥 Health Check Endpoint Test - run: | - echo "Testing application startup..." - python -c " - import uvicorn - from app.main import app - print('✅ Application imports successfully') - print('✅ FastAPI app configuration validated') - " - - # ============================================================================ - # 6. VERCEL DEPLOYMENT (Production Only) - # ============================================================================ - vercel-deployment: - name: 🚀 Vercel Production Deployment - runs-on: ubuntu-latest - needs: [pre-deployment] - if: (github.ref == 'refs/heads/main' && github.event_name == 'push') || github.event.inputs.deploy_to_vercel == 'true' - environment: - name: production - url: ${{ steps.deploy.outputs.url }} - - steps: - - name: 📥 Checkout Repository - uses: actions/checkout@v4 - - - name: 🟢 Setup Node.js for Vercel CLI - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - - - name: 🚀 Deploy to Vercel - id: deploy - env: - VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }} - VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }} - VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }} - run: | - echo "🚀 Starting Vercel deployment process..." - - # Install Vercel CLI - echo "📦 Installing Vercel CLI..." - npm install -g vercel - - # Verify installation - echo "🔍 Verifying Vercel CLI installation..." - vercel --version + - name: ✅ Summary + run: echo "✅ Docker image built and scanned successfully." - # Authenticate with Vercel - echo "🔐 Authenticating with Vercel..." - if [ -z "$VERCEL_TOKEN" ]; then - echo "❌ VERCEL_TOKEN environment variable is not set" - exit 1 - fi - - # Set Vercel token as environment variable - export VERCEL_TOKEN="$VERCEL_TOKEN" - echo "✅ Vercel token configured via environment variable" - - # Verify authentication by attempting a simple command with token - if ! vercel whoami --token "$VERCEL_TOKEN"; then - echo "❌ Vercel authentication failed" - exit 1 - fi - - echo "✅ Successfully authenticated with Vercel" - - # Link to project (if needed) - echo "🔗 Linking to Vercel project..." - if [ -n "$VERCEL_PROJECT_ID" ]; then - vercel link --project "$VERCEL_PROJECT_ID" --yes --token "$VERCEL_TOKEN" || true - fi - - # Deploy to Vercel - echo "🚀 Deploying application to Vercel..." - if ! vercel --prod --yes --token "$VERCEL_TOKEN"; then - echo "❌ Vercel deployment failed" - exit 1 - fi - - echo "✅ Vercel deployment initiated successfully!" - - # Get deployment URL - echo "🔗 Getting deployment URL..." - sleep 10 - DEPLOYMENT_URL=$(vercel ls --token "$VERCEL_TOKEN" | grep "https://" | head -n 1 | awk '{print $2}') - if [ -n "$DEPLOYMENT_URL" ]; then - echo "url=$DEPLOYMENT_URL" >> $GITHUB_OUTPUT - echo "✅ Deployment URL: $DEPLOYMENT_URL" - else - echo "⚠️ Could not retrieve deployment URL" - fi - - - name: 🏥 Post-Deployment Health Check - run: | - echo "⏳ Waiting for deployment to stabilize..." - sleep 60 - - # Try to get the deployment URL from Vercel - DEPLOYMENT_URL=$(vercel ls --token "$VERCEL_TOKEN" 2>/dev/null | grep "https://" | head -n 1 | awk '{print $2}' || echo "") - - if [ -n "$DEPLOYMENT_URL" ]; then - echo "🔍 Checking Vercel deployment health at: $DEPLOYMENT_URL" - - # Health check - if curl -f -s "$DEPLOYMENT_URL/api/health" > /dev/null 2>&1; then - echo "✅ Health check passed!" - else - echo "⚠️ Health check failed, but deployment may still be initializing" - fi - - # Check main application - if curl -f -s "$DEPLOYMENT_URL/" > /dev/null 2>&1; then - echo "✅ Main application accessible" - else - echo "⚠️ Main application not yet accessible" - fi - else - echo "⚠️ Could not determine deployment URL for health checks" - fi - - echo "✅ Vercel deployment process completed!" - - - name: 📢 Deployment Notification - if: always() - run: | - echo "🚀 NeuroBank FastAPI Banking System" - echo "📊 Deployment Status: ${{ job.status }}" - echo "🌟 Branch: ${{ github.ref }}" - echo "👤 Author: ${{ github.actor }}" - echo "🔗 Commit: ${{ github.sha }}" - echo "✅ Deployment notification completed" - - # ============================================================================ - # 7. POST-DEPLOYMENT MONITORING - # ============================================================================ - post-deployment-monitoring: - name: 📊 Post-Deployment Monitoring - runs-on: ubuntu-latest - needs: [vercel-deployment] - if: github.ref == 'refs/heads/main' && github.event_name == 'push' - - steps: - - name: 📥 Checkout Repository - uses: actions/checkout@v4 - - - name: 🔍 Comprehensive Health Monitoring - run: | - echo "🏥 Comprehensive health monitoring initiated..." - - # Wait for deployment stabilization - sleep 60 - - echo "✅ Monitoring health endpoints..." - echo "✅ Validating database connections..." - echo "✅ Checking API response times..." - echo "✅ Validating admin dashboard functionality..." - - echo "📊 All monitoring checks completed successfully!" - - - name: 📈 Performance Metrics Collection - run: | - echo "📊 Collecting performance metrics..." - echo "⚡ Response time analysis completed" - echo "💾 Memory usage within normal parameters" - echo "🔄 Database connection pool healthy" - - # ============================================================================ - # 8. CLEANUP & ARTIFACT MANAGEMENT - # ============================================================================ - cleanup: - name: 🧹 Cleanup & Artifact Management - runs-on: ubuntu-latest - needs: [post-deployment-monitoring] - if: always() - - steps: - - name: 📊 Workflow Summary - run: | - echo "🎉 NeuroBank FastAPI Banking System Pipeline Completed!" - echo "📋 Summary of completed stages:" - echo " ✅ Code Quality & Security Analysis" - echo " ✅ Comprehensive Testing Suite" - echo " ✅ Docker Security & Build Validation" - echo " ✅ Frontend Asset Optimization" - echo " ✅ Pre-Deployment Validation" - echo " ✅ Vercel Production Deployment" - echo " ✅ Post-Deployment Monitoring" - echo "" - echo "🚀 Banking application successfully deployed to Vercel!" - echo "🌟 All admin panel functionalities validated and operational" \ No newline at end of file diff --git a/.gitignore b/.gitignore index b421d8d..79ff3e1 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,12 @@ Thumbs.db bandit-report.json safety-report.json .env.local +NeuroBank-FastAPI-Toolkit-1 + +NeuroBank-FastAPI-Toolkit-1 + +NeuroBank-FastAPI-Toolkit-1 + +node_modules/ + +node_modules/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..f787ca2 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,32 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: end-of-file-fixer + - id: trailing-whitespace + - id: check-yaml + exclude: template.yaml + - id: check-json + - id: check-added-large-files + + - repo: https://github.com/psf/black + rev: 24.10.0 + hooks: + - id: black + + - repo: https://github.com/pycqa/isort + rev: 5.13.2 + hooks: + - id: isort + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.6.8 + hooks: + - id: ruff + args: ["--fix", "--exit-non-zero-on-fix"] + + - repo: https://github.com/pre-commit/mirrors-mypy + rev: v1.11.2 + hooks: + - id: mypy + additional_dependencies: [] diff --git a/.prettierrc.yaml b/.prettierrc.yaml new file mode 100644 index 0000000..1b4bb91 --- /dev/null +++ b/.prettierrc.yaml @@ -0,0 +1,10 @@ +printWidth: 100 +tabWidth: 2 +useTabs: false +singleQuote: false +trailingComma: "none" +bracketSpacing: true +overrides: + - files: "*.yml" + options: + tabWidth: 2 diff --git a/AWS_OIDC_SETUP.md b/AWS_OIDC_SETUP.md index a2f63b3..2d3fb76 100644 --- a/AWS_OIDC_SETUP.md +++ b/AWS_OIDC_SETUP.md @@ -20,7 +20,7 @@ API_KEY = tu-api-key-para-la-app (opcional) - ARN: `arn:aws:iam::120242956739:oidc-provider/token.actions.githubusercontent.com` - Audience: `sts.amazonaws.com` -2. **IAM Role**: `GitHubActionsOIDCRole` +2. **IAM Role**: `GitHubActionsOIDCRole` - ARN: `arn:aws:iam::120242956739:role/GitHubActionsOIDCRole` - Trust policy configurada para: `Neiland85/NeuroBank-FastAPI-Toolkit` - Permisos para ECR, Lambda, CloudFormation @@ -34,7 +34,7 @@ API_KEY = tu-api-key-para-la-app (opcional) 1. **Push automático** ejecuta solo **tests** y **security scans** 2. **Deployment requiere confirmación manual**: - Ve a GitHub Actions en tu repositorio - - Selecciona "CI/CD Pipeline" + - Selecciona "CI/CD Pipeline" - Haz clic en "Run workflow" - Selecciona "true" para desplegar a AWS 3. **No deployments automáticos** - total control del usuario @@ -105,7 +105,7 @@ aws cloudformation describe-stacks --stack-name neurobank-api --region eu-west-1 # Ver logs de Lambda aws logs tail /aws/lambda/NeuroBank-Function --region eu-west-1 --follow -# Listar versiones en ECR +# Listar versiones en ECR aws ecr list-images --repository-name neurobank-fastapi --region eu-west-1 # Verificar el rol OIDC @@ -118,7 +118,7 @@ aws iam list-open-id-connect-providers ## 🔄 Workflow Jobs 1. **test**: Pytest con coverage -2. **security**: Bandit + Safety scanning +2. **security**: Bandit + Safety scanning 3. **deployment-check**: Verifica configuración OIDC 4. **build-and-deploy**: Deployment completo a AWS diff --git a/DEVELOPMENT_GUIDE_OPTIMIZED.md b/DEVELOPMENT_GUIDE_OPTIMIZED.md index c189817..29e3e9e 100644 --- a/DEVELOPMENT_GUIDE_OPTIMIZED.md +++ b/DEVELOPMENT_GUIDE_OPTIMIZED.md @@ -8,16 +8,16 @@ ### **1.1 Crear Workspace Base** ``` -Crea un nuevo workspace FastAPI para un sistema bancario llamado "NeuroBank FastAPI Banking Toolkit". -Incluye: estructura modular con app/, routers/, services/, tests/, configuración Docker, -Railway deployment, GitHub Actions CI/CD, pytest con coverage, black+isort, bandit security, +Crea un nuevo workspace FastAPI para un sistema bancario llamado "NeuroBank FastAPI Banking Toolkit". +Incluye: estructura modular con app/, routers/, services/, tests/, configuración Docker, +Railway deployment, GitHub Actions CI/CD, pytest con coverage, black+isort, bandit security, y documentación completa. Usa Python 3.11, FastAPI moderna, y JWT authentication. ``` ### **1.2 Configuración de Desarrollo Profesional** ``` -Configura VS Code workspace profesional con: extensiones recomendadas (Python, Docker, GitHub), -settings.json optimizado, tasks.json para comandos frecuentes, launch.json para debugging, +Configura VS Code workspace profesional con: extensiones recomendadas (Python, Docker, GitHub), +settings.json optimizado, tasks.json para comandos frecuentes, launch.json para debugging, .gitignore completo, requirements.txt con todas las dependencias, y .env template. ``` diff --git a/DEVELOPMENT_ROADMAP.md b/DEVELOPMENT_ROADMAP.md index 15c9345..69ba2cc 100644 --- a/DEVELOPMENT_ROADMAP.md +++ b/DEVELOPMENT_ROADMAP.md @@ -4,7 +4,7 @@ ### **🎯 Sprint Goals** - ✅ **Infrastructure Monitoring**: CloudWatch dashboards y alertas -- ✅ **Operational Excellence**: Scripts de deployment y troubleshooting +- ✅ **Operational Excellence**: Scripts de deployment y troubleshooting - ✅ **Documentation**: Guías completas para operations - 🔄 **Security Enhancements**: Advanced monitoring y threat detection @@ -76,7 +76,7 @@ class BankingTransaction(BaseModel): amount: Decimal currency: str = "USD" timestamp: datetime - + # Caching implementation @cache(ttl=300) # 5 minutes cache async def get_account_balance(account_id: str): @@ -179,7 +179,7 @@ async def get_account_balance(account_id: str): ### **🏆 Major Releases** - **v1.1**: ✅ Production Infrastructure Complete -- **v1.2**: 🔄 Monitoring & Operations Excellence +- **v1.2**: 🔄 Monitoring & Operations Excellence - **v1.3**: 🎯 Advanced Security & Compliance - **v2.0**: 🚀 Microservices Architecture diff --git a/DOCKER_HUB_READY.md b/DOCKER_HUB_READY.md index d1c504d..78b4ca2 100644 --- a/DOCKER_HUB_READY.md +++ b/DOCKER_HUB_READY.md @@ -3,7 +3,7 @@ ## ✅ Configuration Status - **Docker Hub Token**: Generated and configured -- **GitHub Variables**: DOCKER_USER set to 'neiland' +- **GitHub Variables**: DOCKER_USER set to 'neiland' - **GitHub Secrets**: DOCKER_PAT configured with access token - **Permissions**: Read, Write, Delete access to Docker Hub - **Token Expiration**: Never diff --git a/Dockerfile b/Dockerfile index 8517ba8..76b7d85 100644 --- a/Dockerfile +++ b/Dockerfile @@ -47,4 +47,4 @@ HEALTHCHECK --interval=30s --timeout=30s --start-period=10s --retries=3 \ CMD sh -c 'curl -f http://localhost:$PORT/health || exit 1' # Comando optimizado para Railway con puerto dinámico -CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port $PORT --workers 1 --loop uvloop --timeout-keep-alive 120 --access-log"] \ No newline at end of file +CMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port $PORT --workers 1 --loop uvloop --timeout-keep-alive 120 --access-log"] diff --git a/FINAL_WORKFLOW_STATUS.md b/FINAL_WORKFLOW_STATUS.md index 521c369..23f53dd 100644 --- a/FINAL_WORKFLOW_STATUS.md +++ b/FINAL_WORKFLOW_STATUS.md @@ -19,7 +19,7 @@ api_key # ❌ Antes: Campo obligatorio api_key: str = os.getenv("API_KEY") -# ✅ Después: Campo opcional para tests +# ✅ Después: Campo opcional para tests api_key: Optional[str] = os.getenv("API_KEY") ``` @@ -76,20 +76,20 @@ print(s.api_key) # ✅ "test_secure_key_for_testing_only_not_production" ### **❌ Estado Inicial:** - Pydantic v1 imports ❌ -- API_KEY siempre obligatorio ❌ +- API_KEY siempre obligatorio ❌ - Tests fallan sin API_KEY ❌ - No compatibilidad CI/CD ❌ ### **✅ Estado Después Primer Fix:** - Pydantic v2 compatible ✅ -- API_KEY siempre obligatorio ❌ +- API_KEY siempre obligatorio ❌ - Tests fallan sin API_KEY ❌ - ValidationError en CI/CD ❌ ### **🎯 Estado Final (Ambos Fixes):** - Pydantic v2 compatible ✅ - API_KEY opcional en tests ✅ -- Tests pasan sin API_KEY ✅ +- Tests pasan sin API_KEY ✅ - CI/CD compatible ✅ - Producción segura ✅ @@ -123,7 +123,7 @@ feat/railway-deployment-optimization: **El proyecto ahora puede:** - 🧪 Ejecutar tests en CI/CD sin configuración previa -- 🚂 Deployar en Railway con configuración segura +- 🚂 Deployar en Railway con configuración segura - 🔒 Mantener validación estricta en producción - 🛠️ Funcionar en desarrollo local diff --git a/GITHUB_ACTIONS_FIX.md b/GITHUB_ACTIONS_FIX.md index 798e4c2..1ab0214 100644 --- a/GITHUB_ACTIONS_FIX.md +++ b/GITHUB_ACTIONS_FIX.md @@ -16,26 +16,26 @@ on: jobs: test: runs-on: ubuntu-latest - + # ✅ AÑADIR ESTAS VARIABLES DE ENTORNO env: API_KEY: "NeuroBankDemo2025-SecureKey-ForTestingOnly" ENVIRONMENT: "testing" CI: "true" - + steps: - uses: actions/checkout@v4 - + - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11' - + - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - + - name: Run tests run: | python -m pytest --cov=app --cov-report=xml --cov-report=html diff --git a/GIT_COMMANDS_HOTFIX.md b/GIT_COMMANDS_HOTFIX.md index 29e9668..13483ca 100644 --- a/GIT_COMMANDS_HOTFIX.md +++ b/GIT_COMMANDS_HOTFIX.md @@ -49,7 +49,7 @@ git commit -m "🚀 HOTFIX: Railway deployment crash resolution & complete funct - Export functionality (CSV/Excel/PDF) operational ✅ Performance Optimizations: -- uvloop integration for 40% async performance boost +- uvloop integration for 40% async performance boost - Single worker configuration prevents Railway memory conflicts - Extended timeouts (120s) for heavy operations - Health checks every 30s with retry logic @@ -153,7 +153,7 @@ BASE_URL="https://your-app-name.railway.app" echo "🌐 Testing URLs:" echo "Health: ${BASE_URL}/health" echo "Dashboard: ${BASE_URL}/backoffice/" -echo "Transactions: ${BASE_URL}/backoffice/admin/transactions" +echo "Transactions: ${BASE_URL}/backoffice/admin/transactions" echo "Users: ${BASE_URL}/backoffice/admin/users" echo "Reports: ${BASE_URL}/backoffice/admin/reports" echo "API Docs: ${BASE_URL}/docs" @@ -166,7 +166,7 @@ echo "API Docs: ${BASE_URL}/docs" ### **Expected Results After Deploy:** - ✅ **Uptime**: 99.9%+ (no more 2-minute crashes) - ✅ **Response Time**: < 2 seconds average -- ✅ **Memory Usage**: Stable < 512MB +- ✅ **Memory Usage**: Stable < 512MB - ✅ **Error Rate**: < 0.1% - ✅ **Functionality**: All buttons operational - ✅ **JavaScript**: 100% interactive features working @@ -180,7 +180,7 @@ echo "API Docs: ${BASE_URL}/docs" # Check Railway logs railway logs --tail -# Monitor resource usage +# Monitor resource usage railway status # Restart if needed @@ -193,7 +193,7 @@ railway variables ### **🚨 Emergency Contacts** ``` Railway Dashboard: https://railway.app/dashboard -GitHub Repository: https://github.com/Neiland85/NeuroBank-FastAPI-Toolkit +GitHub Repository: https://github.com/Neiland85/NeuroBank-FastAPI-Toolkit Project Documentation: See README.md ``` diff --git a/HOTFIX_PR_DESCRIPTION.md b/HOTFIX_PR_DESCRIPTION.md index 7ae6d39..909891f 100644 --- a/HOTFIX_PR_DESCRIPTION.md +++ b/HOTFIX_PR_DESCRIPTION.md @@ -10,7 +10,7 @@ ### **🚂 Railway Optimization** - **railway.json**: Configuración completa con health checks, restart policies y timeouts optimizados -- **Dockerfile**: Single worker + uvloop + performance enhancements específicos para Railway +- **Dockerfile**: Single worker + uvloop + performance enhancements específicos para Railway - **start.sh**: Script de inicio inteligente con pre-validaciones y auto-configuración - **Health Checks**: Endpoint `/health` robusto con métricas Railway-specific @@ -31,28 +31,28 @@ ## 🎪 **Funcionalidades Ahora 100% Operativas** ### **💳 Panel Transacciones** (`/backoffice/admin/transactions`) -✅ **Búsqueda instantánea** por referencia, usuario, monto -✅ **Filtros avanzados** por estado, tipo, rango de fechas -✅ **Paginación completa** con navegación fluida -✅ **Exportar CSV/Excel** con datos reales -✅ **Modal de detalles** con información completa +✅ **Búsqueda instantánea** por referencia, usuario, monto +✅ **Filtros avanzados** por estado, tipo, rango de fechas +✅ **Paginación completa** con navegación fluida +✅ **Exportar CSV/Excel** con datos reales +✅ **Modal de detalles** con información completa ✅ **Botones de acción** (Ver, Editar, Marcar, Procesar) ### **👥 Panel Usuarios** (`/backoffice/admin/users`) -✅ **Búsqueda inteligente** por nombre, email, ID -✅ **Filtros dinámicos** por estado y tipo de cuenta -✅ **Cards de usuario** con avatares y métricas -✅ **Acciones CRUD** (Ver perfil, Editar, Bloquear) -✅ **Exportación** de listas de usuarios +✅ **Búsqueda inteligente** por nombre, email, ID +✅ **Filtros dinámicos** por estado y tipo de cuenta +✅ **Cards de usuario** con avatares y métricas +✅ **Acciones CRUD** (Ver perfil, Editar, Bloquear) +✅ **Exportación** de listas de usuarios ✅ **Estadísticas en tiempo real** ### **📈 Panel Reportes** (`/backoffice/admin/reports`) -✅ **4 Gráficos Chart.js** interactivos (Línea, Dona, Barras, Área) -✅ **Métricas animadas** (Ingresos, Crecimiento, Transacciones, Usuarios) -✅ **Selector temporal** (Hoy, Semana, Mes, Trimestre, Año, Custom) -✅ **Análisis de riesgo** con alertas y contadores -✅ **Top usuarios** por volumen de transacciones -✅ **Exportación múltiple** (PDF, Excel, CSV) +✅ **4 Gráficos Chart.js** interactivos (Línea, Dona, Barras, Área) +✅ **Métricas animadas** (Ingresos, Crecimiento, Transacciones, Usuarios) +✅ **Selector temporal** (Hoy, Semana, Mes, Trimestre, Año, Custom) +✅ **Análisis de riesgo** con alertas y contadores +✅ **Top usuarios** por volumen de transacciones +✅ **Exportación múltiple** (PDF, Excel, CSV) ✅ **Programación de reportes** automáticos --- @@ -79,7 +79,7 @@ ### **APIs Funcionales:** - `GET /backoffice/api/metrics` → Métricas dashboard -- `GET /backoffice/api/transactions/search` → Búsqueda de transacciones +- `GET /backoffice/api/transactions/search` → Búsqueda de transacciones - `GET /backoffice/api/system-health` → Estado del sistema - `GET /health` → Health check para Railway @@ -88,18 +88,18 @@ ## 📊 **Resultados Esperados** ### **Antes del Hotfix:** -❌ Crash después de 2 minutos -❌ Botones sin funcionalidad -❌ Templates genéricos sin interactividad -❌ APIs no conectadas con frontend -❌ JavaScript no operativo +❌ Crash después de 2 minutos +❌ Botones sin funcionalidad +❌ Templates genéricos sin interactividad +❌ APIs no conectadas con frontend +❌ JavaScript no operativo ### **Después del Hotfix:** -✅ **Estabilidad 24/7** sin crashes -✅ **Botones 100% funcionales** en todos los paneles -✅ **JavaScript interactivo** completamente operativo -✅ **APIs respondiendo** correctamente -✅ **Navegación fluida** entre secciones +✅ **Estabilidad 24/7** sin crashes +✅ **Botones 100% funcionales** en todos los paneles +✅ **JavaScript interactivo** completamente operativo +✅ **APIs respondiendo** correctamente +✅ **Navegación fluida** entre secciones ✅ **Performance optimizado** para demos profesionales --- @@ -150,15 +150,15 @@ git push origin main ## 🏆 **Impacto del Hotfix** ### **Para Recruiters/Demos:** -✅ **Aplicación estable** para demos profesionales -✅ **Funcionalidad completa** visible y operativa -✅ **UI profesional** con interactividad real -✅ **Performance óptimo** sin lag ni crashes +✅ **Aplicación estable** para demos profesionales +✅ **Funcionalidad completa** visible y operativa +✅ **UI profesional** con interactividad real +✅ **Performance óptimo** sin lag ni crashes ### **Para Development:** -✅ **Base sólida** para features futuras -✅ **Monitoring robusto** para detección temprana -✅ **Escalabilidad** preparada para crecimiento +✅ **Base sólida** para features futuras +✅ **Monitoring robusto** para detección temprana +✅ **Escalabilidad** preparada para crecimiento ✅ **Mantenimiento** simplificado con scripts automatizados --- @@ -169,7 +169,7 @@ git push origin main - [ ] `/health` responde status 200 con JSON completo - [ ] Dashboard principal carga sin errores de JavaScript - [ ] Panel transacciones: búsqueda encuentra resultados -- [ ] Panel usuarios: filtros funcionan correctamente +- [ ] Panel usuarios: filtros funcionan correctamente - [ ] Panel reportes: gráficos renderizan sin errores - [ ] No crashes después de 10 minutos de uso - [ ] Memory usage estable en Railway metrics diff --git a/HOTFIX_RAILWAY_CRASH.md b/HOTFIX_RAILWAY_CRASH.md index d2e49b4..aba04cd 100644 --- a/HOTFIX_RAILWAY_CRASH.md +++ b/HOTFIX_RAILWAY_CRASH.md @@ -122,7 +122,7 @@ railway logs ## 📈 **MONITOREO POST-DEPLOY** ### **Métricas Clave a Monitorear:** -- **Uptime**: Debe ser 99.9%+ +- **Uptime**: Debe ser 99.9%+ - **Memory Usage**: Estable < 512MB - **Response Time**: < 2 segundos promedio - **Error Rate**: < 0.1% diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..51ee3d7 --- /dev/null +++ b/Makefile @@ -0,0 +1,39 @@ +# Makefile — NeuroBank CI/CD utilities + +AWS_REGION ?= eu-west-1 +AWS_ACCOUNT_ID ?= 000000000000 +ECR_REGISTRY := $(AWS_ACCOUNT_ID).dkr.ecr.$(AWS_REGION).amazonaws.com +TAG := $(shell date +prod-%Y.%m.%d-%H%M) + +.PHONY: help setup lint test build release-prod aws-login + +help: + @echo "Available targets:" + @echo " setup Install dependencies" + @echo " lint Run flake8 + black" + @echo " test Run pytest" + @echo " build Build docker images" + @echo " release-prod Create tag + push (triggers ECS deploy)" + @echo " aws-login Authenticate docker to AWS ECR" + +setup: + pip install -r requirements.txt + +lint: + flake8 . || true + black --check . || true + +test: + pytest -q || echo "⚠️ No tests found" + +build: + @echo "Building local images..." + docker build -t neurobank-api:latest -f docker/Dockerfile.api . + +aws-login: + aws ecr get-login-password --region $(AWS_REGION) | \ + docker login --username AWS --password-stdin $(ECR_REGISTRY) + +release-prod: + git tag -a $(TAG) -m "Release $(TAG)" + git push origin $(TAG) diff --git a/Makefile.deploy b/Makefile.deploy new file mode 100644 index 0000000..13d0386 --- /dev/null +++ b/Makefile.deploy @@ -0,0 +1,12 @@ +AWS_REGION ?= eu-west-1 +AWS_ACCOUNT_ID ?= 000000000000 +ECR = $(AWS_ACCOUNT_ID).dkr.ecr.$(AWS_REGION).amazonaws.com + +login: + aws ecr get-login-password --region $(AWS_REGION) | docker login --username AWS --password-stdin $(ECR) + +build-all: + docker build -t $(ECR)/neurobank/api-gateway:local . + docker build -t $(ECR)/neurobank/ingestion:local trading_ai_system/ingestion_service + docker build -t $(ECR)/neurobank/inference:local trading_ai_system/inference_service + docker build -t $(ECR)/neurobank/control:local trading_ai_system/control_service diff --git a/NeuroBank-FastAPI-Toolkit b/NeuroBank-FastAPI-Toolkit new file mode 160000 index 0000000..00fadb5 --- /dev/null +++ b/NeuroBank-FastAPI-Toolkit @@ -0,0 +1 @@ +Subproject commit 00fadb5889a0f15d6116383a5a782a6ae415991b diff --git a/NeuroBank-FastAPI-Toolkit-1 b/NeuroBank-FastAPI-Toolkit-1 new file mode 160000 index 0000000..3eca2ea --- /dev/null +++ b/NeuroBank-FastAPI-Toolkit-1 @@ -0,0 +1 @@ +Subproject commit 3eca2ea47bd3f2fc11bf5cb1f97ce36a8b636d06 diff --git a/PIPELINE_FIX_SUMMARY.md b/PIPELINE_FIX_SUMMARY.md index b10b957..c5bc52a 100644 --- a/PIPELINE_FIX_SUMMARY.md +++ b/PIPELINE_FIX_SUMMARY.md @@ -78,7 +78,7 @@ Process completed with exit code 1. ``` 🔍 Code Quality & Security Analysis ✅ -🧪 Comprehensive Testing Suite ✅ +🧪 Comprehensive Testing Suite ✅ 🐳 Docker Security & Build Validation ✅ [FIXED] 🎨 Frontend Assets & Performance ✅ 🚨 Pre-Deployment Validation ✅ @@ -146,7 +146,7 @@ Process completed with exit code 1. 🎉 **NeuroBank FastAPI Banking System** is now enterprise-ready with: - ✅ Railway crash issue completely resolved -- ✅ Admin dashboard 100% functional with real-time features +- ✅ Admin dashboard 100% functional with real-time features - ✅ CI/CD pipeline fixed and operational - ✅ Security scanning and vulnerability assessment - ✅ Professional deployment automation diff --git a/PRODUCTION_README.md b/PRODUCTION_README.md index addbdaf..92042f4 100644 --- a/PRODUCTION_README.md +++ b/PRODUCTION_README.md @@ -54,14 +54,14 @@ git checkout release/v1.0.0-backoffice ### **What This Demonstrates** -✅ **Enterprise Architecture**: Scalable FastAPI backend with production patterns -✅ **Modern UI/UX**: Professional banking dashboard with responsive design -✅ **Real-time Systems**: Live data updates and monitoring capabilities -✅ **API Design**: RESTful endpoints with proper documentation -✅ **Security**: Authentication, CORS, and security headers -✅ **DevOps**: Docker, CI/CD, and deployment automation -✅ **Data Management**: Complex filtering, pagination, and export features -✅ **Code Quality**: Clean architecture, error handling, and logging +✅ **Enterprise Architecture**: Scalable FastAPI backend with production patterns +✅ **Modern UI/UX**: Professional banking dashboard with responsive design +✅ **Real-time Systems**: Live data updates and monitoring capabilities +✅ **API Design**: RESTful endpoints with proper documentation +✅ **Security**: Authentication, CORS, and security headers +✅ **DevOps**: Docker, CI/CD, and deployment automation +✅ **Data Management**: Complex filtering, pagination, and export features +✅ **Code Quality**: Clean architecture, error handling, and logging ### **Technical Highlights** @@ -119,7 +119,7 @@ sudo systemctl start neurobank-fastapi ## 🚀 **Future Roadmap** - [ ] PostgreSQL integration -- [ ] Redis caching layer +- [ ] Redis caching layer - [ ] JWT authentication - [ ] Kubernetes deployment - [ ] Prometheus metrics @@ -130,14 +130,14 @@ sudo systemctl start neurobank-fastapi ## 🏆 **Production Quality Checklist** -✅ **Code Quality**: Clean, documented, and maintainable -✅ **Performance**: Optimized for production workloads -✅ **Security**: Industry-standard security practices -✅ **Scalability**: Ready for horizontal scaling -✅ **Monitoring**: Comprehensive health and metrics -✅ **Documentation**: Complete API and deployment docs -✅ **Testing**: Validated and production-tested -✅ **DevOps**: Automated deployment pipeline +✅ **Code Quality**: Clean, documented, and maintainable +✅ **Performance**: Optimized for production workloads +✅ **Security**: Industry-standard security practices +✅ **Scalability**: Ready for horizontal scaling +✅ **Monitoring**: Comprehensive health and metrics +✅ **Documentation**: Complete API and deployment docs +✅ **Testing**: Validated and production-tested +✅ **DevOps**: Automated deployment pipeline --- diff --git a/PR_DESCRIPTION.md b/PR_DESCRIPTION.md index 756f13e..cfbab43 100644 --- a/PR_DESCRIPTION.md +++ b/PR_DESCRIPTION.md @@ -71,11 +71,11 @@ async def verify_api_key( token = authorization.split(" ")[1] if token == VALID_API_KEY: return token - + # X-API-Key Header Authentication if x_api_key == VALID_API_KEY: return x_api_key - + raise HTTPException( status_code=401, detail="Authentication required. Provide valid Bearer token or X-API-Key header" @@ -96,7 +96,7 @@ class OrderStatusResponse(BaseModel): } } ) - + order_id: str = Field(..., description="Unique order identifier") status: str = Field(..., description="Current order status") amount: float = Field(..., description="Order amount in USD") @@ -107,7 +107,7 @@ class OrderStatusResponse(BaseModel): ```python # Modern HTTPx Testing with ASGITransport client = AsyncClient( - transport=ASGITransport(app=app), + transport=ASGITransport(app=app), base_url="http://test" ) @@ -146,7 +146,7 @@ pytest -v # ===================================== test session starts ====================================== # platform darwin -- Python 3.12.3, pytest-8.2.0, pluggy-1.6.0 # collected 7 items -# +# # app/tests/test_main.py::test_health_check PASSED [ 14%] # app/tests/test_main.py::test_root_endpoint PASSED [ 28%] # app/tests/test_operator.py::test_order_status PASSED [ 42%] @@ -154,7 +154,7 @@ pytest -v # app/tests/test_operator.py::test_order_status_with_bearer_token PASSED [ 71%] # app/tests/test_operator.py::test_order_status_unauthorized PASSED [ 85%] # app/tests/test_operator.py::test_order_status_forbidden PASSED [100%] -# +# # ====================================== 7 passed in 0.50s ====================================== ``` diff --git a/PR_MAIN_EPIC_DESCRIPTION.md b/PR_MAIN_EPIC_DESCRIPTION.md index 576d3ed..142c042 100644 --- a/PR_MAIN_EPIC_DESCRIPTION.md +++ b/PR_MAIN_EPIC_DESCRIPTION.md @@ -44,7 +44,7 @@ ├── app/routers/ ✅ API endpoints for banking operations └── app/backoffice/ ✅ Complete admin dashboard system -📁 Admin Dashboard Templates +📁 Admin Dashboard Templates ├── basic_dashboard.html ✅ Main dashboard with real-time metrics ├── admin_transactions.html ✅ Complete transaction management ├── admin_users.html ✅ User administration with CRUD @@ -55,7 +55,7 @@ ``` 📁 Railway Optimization ├── railway.json ✅ Complete Railway configuration -├── Dockerfile ✅ Optimized for Railway deployment +├── Dockerfile ✅ Optimized for Railway deployment ├── start.sh ✅ Intelligent startup script └── Procfile ✅ Railway process configuration @@ -68,7 +68,7 @@ ### **📚 Documentation & Workflows** ``` 📁 Professional Documentation -├── README.md ✅ Enterprise-grade presentation +├── README.md ✅ Enterprise-grade presentation ├── RAILWAY_DEPLOYMENT.md ✅ Complete deployment guide ├── SECURITY.md ✅ Security implementation details └── API Documentation ✅ Interactive Swagger UI @@ -86,7 +86,7 @@ ### **💳 Transaction Management System** - **Real-time Search**: Instantaneous transaction filtering -- **Advanced Filters**: Status, type, date range, amount filtering +- **Advanced Filters**: Status, type, date range, amount filtering - **Pagination**: Smooth navigation through large datasets - **Export Functions**: CSV/Excel export with real data - **Detail Views**: Modal windows with complete transaction information @@ -121,7 +121,7 @@ ### **⚡ Performance Optimizations** - **uvloop Integration**: 40% performance boost for async operations -- **Single Worker Config**: Optimized for Railway resource constraints +- **Single Worker Config**: Optimized for Railway resource constraints - **Memory Management**: Efficient resource utilization - **Caching Strategy**: Optimized data retrieval and storage - **Connection Pooling**: Database connection optimization diff --git a/PR_MAIN_FINAL_EPIC.md b/PR_MAIN_FINAL_EPIC.md index ea01e2a..a1ba69d 100644 --- a/PR_MAIN_FINAL_EPIC.md +++ b/PR_MAIN_FINAL_EPIC.md @@ -16,7 +16,7 @@ ├── Professional admin backoffice dashboard └── Railway-optimized deployment configuration -✅ FRONTEND (100%) +✅ FRONTEND (100%) ├── Bootstrap 5 responsive banking interface ├── Interactive Chart.js financial dashboards ├── Real-time transaction management system @@ -34,37 +34,37 @@ ## 🎯 **FUNCTIONALITY VERIFICATION - TODAS OPERATIVAS** ### **💳 Transaction Management** (`/backoffice/admin/transactions`) -✅ **Search System**: Real-time transaction search by any field -✅ **Advanced Filtering**: Status, type, amount, date range filters -✅ **Smart Pagination**: Navigate through thousands of records -✅ **Export Functions**: CSV/Excel export with filtered data -✅ **Detail Modals**: Complete transaction information popups -✅ **Bulk Actions**: Process multiple transactions simultaneously +✅ **Search System**: Real-time transaction search by any field +✅ **Advanced Filtering**: Status, type, amount, date range filters +✅ **Smart Pagination**: Navigate through thousands of records +✅ **Export Functions**: CSV/Excel export with filtered data +✅ **Detail Modals**: Complete transaction information popups +✅ **Bulk Actions**: Process multiple transactions simultaneously ✅ **Real-time Updates**: Live data refresh without page reload ### **👥 User Administration** (`/backoffice/admin/users`) -✅ **User Search**: Instant search by name, email, ID, phone -✅ **Account Management**: View, edit, activate, block operations -✅ **Profile Cards**: Professional user cards with avatars -✅ **Status Filtering**: Filter by active, inactive, pending, blocked -✅ **Bulk Operations**: Mass user updates and exports -✅ **Activity Tracking**: User login and transaction history +✅ **User Search**: Instant search by name, email, ID, phone +✅ **Account Management**: View, edit, activate, block operations +✅ **Profile Cards**: Professional user cards with avatars +✅ **Status Filtering**: Filter by active, inactive, pending, blocked +✅ **Bulk Operations**: Mass user updates and exports +✅ **Activity Tracking**: User login and transaction history ✅ **Security Controls**: Account verification and fraud flags ### **📈 Financial Reports** (`/backoffice/admin/reports`) -✅ **Interactive Charts**: 4 chart types (Line, Bar, Pie, Area) -✅ **Animated Metrics**: Real-time counters with smooth animations -✅ **Period Selection**: Day, week, month, quarter, year, custom -✅ **Risk Analysis**: Fraud detection with alert counters -✅ **Top Performers**: User ranking by transaction volume -✅ **Export Suite**: PDF, Excel, CSV report generation +✅ **Interactive Charts**: 4 chart types (Line, Bar, Pie, Area) +✅ **Animated Metrics**: Real-time counters with smooth animations +✅ **Period Selection**: Day, week, month, quarter, year, custom +✅ **Risk Analysis**: Fraud detection with alert counters +✅ **Top Performers**: User ranking by transaction volume +✅ **Export Suite**: PDF, Excel, CSV report generation ✅ **Scheduled Reports**: Automated report delivery system ### **🏥 System Health** (`/health`, `/backoffice/api/system-health`) -✅ **Comprehensive Monitoring**: Database, API, cache status -✅ **Railway Integration**: Cloud-specific metrics and variables -✅ **Performance Metrics**: Response time, uptime, memory usage -✅ **Auto-restart**: Intelligent failure detection and recovery +✅ **Comprehensive Monitoring**: Database, API, cache status +✅ **Railway Integration**: Cloud-specific metrics and variables +✅ **Performance Metrics**: Response time, uptime, memory usage +✅ **Auto-restart**: Intelligent failure detection and recovery ✅ **Health Dashboards**: Visual system health indicators --- @@ -74,17 +74,17 @@ ### **Configuration Files Complete:** ``` ✅ railway.json → Health checks + restart policies + timeout optimization -✅ Dockerfile → Single worker + uvloop + production optimizations +✅ Dockerfile → Single worker + uvloop + production optimizations ✅ start.sh → Smart startup with Railway environment detection ✅ Procfile → Optimized process configuration ✅ requirements.txt → Performance libraries (uvloop, requests) ``` ### **Deployment Guarantees:** -✅ **NO crashes** after 2 minutes (PROBLEMA RESUELTO) -✅ **Stable 24/7** operation without memory issues -✅ **Auto-restart** on any failure with 5-retry policy -✅ **Health monitoring** every 30 seconds +✅ **NO crashes** after 2 minutes (PROBLEMA RESUELTO) +✅ **Stable 24/7** operation without memory issues +✅ **Auto-restart** on any failure with 5-retry policy +✅ **Health monitoring** every 30 seconds ✅ **Performance optimization** with uvloop (40% faster) --- @@ -92,25 +92,25 @@ ## 📊 **QUALITY METRICS - ENTERPRISE LEVEL** ### **🔒 Security Implementation** -✅ **API Authentication**: Secure key-based access control -✅ **Input Validation**: Complete Pydantic model validation -✅ **SQL Injection Prevention**: Parameterized query protection -✅ **XSS Protection**: Template escaping and sanitization -✅ **CORS Security**: Proper cross-origin configuration +✅ **API Authentication**: Secure key-based access control +✅ **Input Validation**: Complete Pydantic model validation +✅ **SQL Injection Prevention**: Parameterized query protection +✅ **XSS Protection**: Template escaping and sanitization +✅ **CORS Security**: Proper cross-origin configuration ✅ **Vulnerability Scanning**: Bandit + Safety automated checks ### **⚡ Performance Benchmarks** -✅ **Response Time**: < 2 seconds average (tested) -✅ **Memory Usage**: < 512MB stable (Railway optimized) -✅ **Uptime Target**: 99.9% availability -✅ **Concurrent Users**: 100+ simultaneous users supported +✅ **Response Time**: < 2 seconds average (tested) +✅ **Memory Usage**: < 512MB stable (Railway optimized) +✅ **Uptime Target**: 99.9% availability +✅ **Concurrent Users**: 100+ simultaneous users supported ✅ **Error Rate**: < 0.1% error rate achieved ### **🧪 Testing Coverage** -✅ **Unit Tests**: Core business logic validation -✅ **Integration Tests**: API endpoint comprehensive testing -✅ **Frontend Tests**: JavaScript functionality validation -✅ **Load Testing**: Performance under stress validated +✅ **Unit Tests**: Core business logic validation +✅ **Integration Tests**: API endpoint comprehensive testing +✅ **Frontend Tests**: JavaScript functionality validation +✅ **Load Testing**: Performance under stress validated ✅ **Security Testing**: Penetration testing completed --- @@ -119,7 +119,7 @@ ### **💼 For Recruiters & Banking Professionals** - **Professional Grade**: Enterprise-level banking application ready for demos -- **Complete Functionality**: Every button, form, and feature 100% operational +- **Complete Functionality**: Every button, form, and feature 100% operational - **Industry Standards**: Banking UI/UX patterns and workflows implemented - **Scalable Architecture**: Ready for real-world banking operations - **Security Compliant**: Meets banking security requirements @@ -145,7 +145,7 @@ ### **Live Demo URLs** (Post-Railway Deploy): ``` 🏠 Main Dashboard: https://your-app.railway.app/backoffice/ -💳 Transactions: https://your-app.railway.app/backoffice/admin/transactions +💳 Transactions: https://your-app.railway.app/backoffice/admin/transactions 👥 Users: https://your-app.railway.app/backoffice/admin/users 📈 Reports: https://your-app.railway.app/backoffice/admin/reports 📚 API Docs: https://your-app.railway.app/docs @@ -170,7 +170,7 @@ git commit -m "🏆 FINAL EPIC: Complete Banking Solution Production Ready ✅ 100% Functional Banking Application: - Complete transaction management with search/filter/export -- Full user administration with CRUD operations +- Full user administration with CRUD operations - Interactive financial reports with Chart.js integration - Real-time dashboards with animated metrics @@ -203,7 +203,7 @@ git push origin main ### **🏆 What We Achieved:** - **Transformed** basic FastAPI app → Complete banking solution -- **Eliminated** Railway crashes → Stable 24/7 operation +- **Eliminated** Railway crashes → Stable 24/7 operation - **Implemented** all functionality → 100% operational buttons/features - **Delivered** enterprise quality → Production-ready application - **Created** recruiter-ready demo → Professional banking showcase @@ -224,7 +224,7 @@ git push origin main **¡Epic completamente finalizado y listo para deployment inmediato!** - ✅ **Functionality**: 100% operativa -- ✅ **Stability**: Zero crashes guaranteed +- ✅ **Stability**: Zero crashes guaranteed - ✅ **Performance**: Railway-optimized - ✅ **Security**: Enterprise-level - ✅ **Documentation**: Complete diff --git a/PR_MAIN_MERGE.md b/PR_MAIN_MERGE.md index 460f7d1..d82b403 100644 --- a/PR_MAIN_MERGE.md +++ b/PR_MAIN_MERGE.md @@ -163,7 +163,7 @@ This pull request merges the `feat/railway-deployment-optimization` branch into --- -**Merge Confidence: HIGH** ✅ -**Breaking Changes: NONE** ✅ -**Security Impact: POSITIVE** ✅ +**Merge Confidence: HIGH** ✅ +**Breaking Changes: NONE** ✅ +**Security Impact: POSITIVE** ✅ **Production Ready: YES** ✅ diff --git a/PR_README_SPECTACULAR.md b/PR_README_SPECTACULAR.md index 3b8af75..5696c3d 100644 --- a/PR_README_SPECTACULAR.md +++ b/PR_README_SPECTACULAR.md @@ -3,7 +3,7 @@ ## 🏦 **README EVOLUTION: Basic → Enterprise Banking Presentation** ### **🎯 TRANSFORMATION OVERVIEW** -**ANTES:** README básico con información técnica mínima +**ANTES:** README básico con información técnica mínima **DESPUÉS:** Presentación empresarial completa para recruiters bancarios --- @@ -94,7 +94,7 @@ Basic FastAPI application ``` ### **📊 Feature Matrix Enhancement** -**BEFORE:** Simple list of endpoints +**BEFORE:** Simple list of endpoints **AFTER:** Comprehensive feature matrix with business impact ```markdown @@ -107,7 +107,7 @@ Basic FastAPI application ``` ### **🎨 Visual Architecture Diagrams** -**BEFORE:** No visual representation +**BEFORE:** No visual representation **AFTER:** Complete system architecture with Mermaid diagrams ```mermaid @@ -118,13 +118,13 @@ graph TB B --> D[💳 Transaction Engine] B --> E[👥 User Management] B --> F[📈 Reporting System] - + C --> G[📱 Responsive UI] D --> H[💾 Database Layer] E --> I[🔐 Authentication] F --> J[📊 Chart.js Analytics] end - + subgraph "☁️ Railway Deployment" K[🚂 Railway Platform] L[📦 Docker Container] @@ -272,7 +272,7 @@ graph TB ### **🏆 Transformation Results:** - **BEFORE**: Generic technical README → **AFTER**: Professional banking solution presentation -- **BEFORE**: No visual appeal → **AFTER**: Rich diagrams, charts, interactive elements +- **BEFORE**: No visual appeal → **AFTER**: Rich diagrams, charts, interactive elements - **BEFORE**: Developer-only focus → **AFTER**: Recruiter and business stakeholder ready - **BEFORE**: Basic feature list → **AFTER**: Complete business value proposition - **BEFORE**: No demo access → **AFTER**: Immediate hands-on evaluation ready diff --git a/RAILWAY_COMPLETE_SOLUTION.md b/RAILWAY_COMPLETE_SOLUTION.md index 7ca9be6..7052413 100644 --- a/RAILWAY_COMPLETE_SOLUTION.md +++ b/RAILWAY_COMPLETE_SOLUTION.md @@ -4,7 +4,7 @@ **Situación Inicial:** - ❌ railway.json VACÍO -- ❌ start.sh VACÍO +- ❌ start.sh VACÍO - ❌ Templates NO conectados con router - ❌ Configuración Railway subóptima - ❌ Botones y funcionalidades NO funcionaban @@ -14,7 +14,7 @@ - ✅ start.sh OPTIMIZADO para Railway - ✅ Templates CONECTADOS correctamente: - `/admin/transactions` → `admin_transactions.html` ✅ - - `/admin/users` → `admin_users.html` ✅ + - `/admin/users` → `admin_users.html` ✅ - `/admin/reports` → `admin_reports.html` ✅ - ✅ Dockerfile OPTIMIZADO con uvloop y single worker - ✅ requirements.txt MEJORADO con uvloop y requests @@ -68,7 +68,7 @@ - ✅ Modal de detalles - ✅ JavaScript totalmente operativo -#### **admin_users.html** +#### **admin_users.html** - ✅ Gestión completa de usuarios - ✅ Filtros por estado y tipo de cuenta - ✅ Búsqueda por nombre/email/ID diff --git a/RAILWAY_CONFIG.md b/RAILWAY_CONFIG.md index 4ceb58c..0fd0469 100644 --- a/RAILWAY_CONFIG.md +++ b/RAILWAY_CONFIG.md @@ -1,18 +1,18 @@ # Railway Deployment Status -**Status**: Active deployment configuration -**Branch**: main -**Last Updated**: 2025-07-21 05:05:00 +**Status**: Active deployment configuration +**Branch**: main +**Last Updated**: 2025-07-21 05:05:00 ## Configuration Summary - ✅ Branch: `main` -- ✅ Port: `8000` +- ✅ Port: `8000` - ✅ Health Check: `/health` - ✅ Start Command: `uvicorn app.main:app --host 0.0.0.0 --port $PORT --workers 1 --timeout-keep-alive 120` ## Required Environment Variables - `API_KEY`: Required for production -- `SECRET_KEY`: Required for production +- `SECRET_KEY`: Required for production - `ENVIRONMENT`: Set to `production` - `PORT`: Auto-provided by Railway diff --git a/RAILWAY_CONFIG_STATUS.md b/RAILWAY_CONFIG_STATUS.md index 7ee869b..0407699 100644 --- a/RAILWAY_CONFIG_STATUS.md +++ b/RAILWAY_CONFIG_STATUS.md @@ -44,7 +44,7 @@ uvicorn app.main:app --host 0.0.0.0 --port $PORT --workers 1 --timeout-keep-aliv ### 6. Resources ``` 💻 CPU: 2 vCPU -🧠 Memory: 1 GB +🧠 Memory: 1 GB 🌍 Region: EU West (Amsterdam) - 1 replica ``` @@ -57,7 +57,7 @@ uvicorn app.main:app --host 0.0.0.0 --port $PORT --workers 1 --timeout-keep-aliv ### 8. Variables de Entorno (¡IMPORTANTE!) ```bash API_KEY=tu_valor_aqui -SECRET_KEY=tu_valor_aqui +SECRET_KEY=tu_valor_aqui DATABASE_URL=postgresql://... (si aplica) ENVIRONMENT=production ``` diff --git a/RAILWAY_DEPLOYMENT.md b/RAILWAY_DEPLOYMENT.md index 1742555..2182209 100644 --- a/RAILWAY_DEPLOYMENT.md +++ b/RAILWAY_DEPLOYMENT.md @@ -126,7 +126,7 @@ Railway asigna automáticamente: ### Endpoints Importantes: - Health: `/health` -- Docs: `/docs` +- Docs: `/docs` - Admin: `/backoffice/` ### Variables Railway Disponibles: diff --git a/RAILWAY_STATUS.md b/RAILWAY_STATUS.md index 7952cc2..bb0bad4 100644 --- a/RAILWAY_STATUS.md +++ b/RAILWAY_STATUS.md @@ -4,7 +4,7 @@ ### **🔧 Variables Automáticas de Railway (Ya configuradas):** - `RAILWAY_PRIVATE_DOMAIN` - Dominio privado del servicio -- `RAILWAY_PROJECT_NAME` - Nombre del proyecto +- `RAILWAY_PROJECT_NAME` - Nombre del proyecto - `RAILWAY_ENVIRONMENT_NAME` - Nombre del entorno - `RAILWAY_SERVICE_NAME` - Nombre del servicio - `RAILWAY_PROJECT_ID` - ID del proyecto @@ -34,7 +34,7 @@ Ahora incluye toda la info de Railway: "environment": "production", "railway": { "project_name": "tu-proyecto", - "service_name": "tu-servicio", + "service_name": "tu-servicio", "environment_name": "production", "private_domain": "tu-dominio.railway.app" } diff --git a/README.md b/README.md index ac600be..03a8675 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ chmod +x deploy_production.sh && ./deploy_production.sh |---|---|---| | **Lines of Code** | 2,000+ | Professional codebase | | **API Endpoints** | 15+ | Comprehensive backend | -| **UI Components** | 20+ | Modern dashboard | +| **UI Components** | 20+ | Modern dashboard | | **Docker Ready** | ✅ | Production deployment | | **Security Layer** | ✅ | Banking-grade auth | | **Real-time Features** | ✅ | Live data updates | @@ -143,7 +143,7 @@ chmod +x deploy_production.sh && ./deploy_production.sh ### 🎯 **Core Sections** [🎯 Project Overview](#project-overview) • [✨ Key Features](#key-features) • [🏗️ Architecture](#architecture) • [🚀 Quick Start](#quick-start) -### 📊 **Technical Details** +### 📊 **Technical Details** [🔗 Live Access Points](#live-access-points) • [📱 Dashboard Preview](#dashboard-preview) • [🔧 Technical Stack](#technical-stack) • [📂 Project Structure](#project-structure) ### 🚀 **Deployment & Operations** @@ -167,11 +167,11 @@ chmod +x deploy_production.sh && ./deploy_production.sh -**NeuroBank FastAPI Toolkit** es una aplicación bancaria de **nivel empresarial** diseñada específicamente para **impresionar a reclutadores técnicos de la industria bancaria**. +**NeuroBank FastAPI Toolkit** es una aplicación bancaria de **nivel empresarial** diseñada específicamente para **impresionar a reclutadores técnicos de la industria bancaria**. 🎪 **Este proyecto demuestra:** - ✅ **Habilidades Python/FastAPI avanzadas** con patrones async/await -- ✅ **Arquitectura de microservicios** production-ready +- ✅ **Arquitectura de microservicios** production-ready - ✅ **Dashboard administrativo completo** con UI moderna - ✅ **Mejores prácticas de seguridad** para fintech - ✅ **DevOps y deployment** automatizado @@ -198,12 +198,12 @@ graph TD B --> C[Demostrar Habilidades Enterprise] B --> D[Showcase Técnico Completo] B --> E[Aplicación Production-Ready] - + C --> C1[🔧 Backend APIs] - C --> C2[🎨 Frontend Moderno] + C --> C2[🎨 Frontend Moderno] C --> C3[🚀 DevOps & Deploy] C --> C4[🔒 Security Best Practices] - + D --> D1[📊 Real-time Dashboard] D --> D2[💳 Transaction Management] D --> D3[👥 User Administration] @@ -220,7 +220,7 @@ graph TD ### 🏦 **Banking Dashboard** - ✅ Professional banking UI/UX -- ✅ Real-time metrics & analytics +- ✅ Real-time metrics & analytics - ✅ Interactive data visualization - ✅ Mobile-responsive design - ✅ Modern Bootstrap 5 theme @@ -246,7 +246,7 @@ graph TD - ✅ Multi-environment deployment - ✅ Health checks & monitoring - ✅ Nginx reverse proxy -- ✅ Systemd service integration +- ✅ Systemd service integration - ✅ CI/CD pipeline ready @@ -263,27 +263,27 @@ graph TB UI[🎨 Modern Web UI
Bootstrap 5 + Chart.js] Mobile[📱 Responsive Design
Mobile-First] end - + subgraph "🔀 Load Balancer" Nginx[🌐 Nginx Reverse Proxy
SSL + Security Headers] end - + subgraph "🚀 Application Layer" FastAPI[⚡ FastAPI Backend
Async/Await + Pydantic] Jinja[🎭 Jinja2 Templates
Server-Side Rendering] end - + subgraph "💾 Data Layer" SQLite[(🗄️ SQLite Database
Transaction Data)] Mock[🎲 Mock Data Generator
Demo Purposes] end - + subgraph "📊 Monitoring" Health[🏥 Health Checks] Metrics[📈 Metrics API] Logs[📋 Structured Logging] end - + UI --> Nginx Mobile --> Nginx Nginx --> FastAPI @@ -293,7 +293,7 @@ graph TB FastAPI --> Health FastAPI --> Metrics FastAPI --> Logs - + style FastAPI fill:#1e3a8a,stroke:#fff,color:#fff style UI fill:#3b82f6,stroke:#fff,color:#fff style Nginx fill:#10b981,stroke:#fff,color:#fff @@ -378,17 +378,17 @@ graph LR B[📈 Interactive Charts
- Transaction Trends
- Volume Analysis
- Status Distribution] C[🔔 System Health
- API Status
- Response Time
- Uptime Monitor] end - + subgraph "💳 Transaction Panel" D[🔍 Advanced Filters
- Status Filter
- Date Range
- Amount Range
- User Search] E[📋 Data Table
- Sortable Columns
- Pagination
- Bulk Actions
- Export Options] F[🎯 Quick Actions
- View Details
- Edit Transaction
- Status Update
- Generate Report] end - + A --> D - B --> E + B --> E C --> F - + style A fill:#1e3a8a,stroke:#fff,color:#fff style D fill:#10b981,stroke:#fff,color:#fff style B fill:#3b82f6,stroke:#fff,color:#fff @@ -437,7 +437,7 @@ graph LR # Core Dependencies - requirements.txt fastapi==0.104.1 # ⚡ Modern web framework uvicorn[standard]==0.24.0 # 🚀 ASGI server -jinja2==3.1.3 # 🎭 Template engine +jinja2==3.1.3 # 🎭 Template engine python-multipart==0.0.9 # 📤 File upload support pydantic==2.5.0 # ✅ Data validation ``` @@ -478,7 +478,7 @@ pydantic==2.5.0 # ✅ Data validation ├── ⚙️ neurobank-fastapi.service # Systemd service ├── 🌐 nginx/nginx.conf # Reverse proxy config │ -├── 📋 requirements.txt # Python dependencies +├── 📋 requirements.txt # Python dependencies ├── 📖 README.md # This amazing documentation ├── 📄 PRODUCTION_README.md # Production deployment guide ├── 🔢 VERSION # Semantic versioning @@ -510,14 +510,14 @@ graph TD C[👥 GET /backoffice/admin/users] --> C1[👤 User Administration] D[📈 GET /backoffice/admin/reports] --> D1[📋 Financial Reports] end - + subgraph "🔧 Data APIs" E[📊 GET /backoffice/api/metrics] --> E1[📈 Real-time Metrics] F[🔍 GET /backoffice/api/transactions/search] --> F1[🔎 Transaction Search] G[🏥 GET /backoffice/api/system-health] --> G1[❤️ System Health] H[ℹ️ GET /backoffice/info] --> H1[📋 System Information] end - + style A fill:#1e3a8a,stroke:#fff,color:#fff style E fill:#10b981,stroke:#fff,color:#fff ``` @@ -535,7 +535,7 @@ GET /backoffice/ - **Template**: [`basic_dashboard.html`](./app/backoffice/templates/basic_dashboard.html) - **Features**: Real-time metrics, animated counters, system health -#### **Transaction Management** +#### **Transaction Management** ```http GET /backoffice/admin/transactions ``` @@ -551,7 +551,7 @@ GET /backoffice/admin/transactions ```http GET /backoffice/api/metrics ``` -- **Response**: +- **Response**: ```json { "total_transactions": 156, @@ -582,27 +582,27 @@ GET /backoffice/api/transactions/search?page=1&page_size=20&status=completed graph TD subgraph "☁️ Production Environment" LB[🌐 Load Balancer
Nginx + SSL] - + subgraph "🚀 Application Servers" APP1[⚡ FastAPI Instance 1
Gunicorn + Uvicorn] - APP2[⚡ FastAPI Instance 2
Gunicorn + Uvicorn] + APP2[⚡ FastAPI Instance 2
Gunicorn + Uvicorn] APP3[⚡ FastAPI Instance 3
Gunicorn + Uvicorn] end - + subgraph "💾 Data Layer" DB[(🗄️ SQLite Database)] CACHE[(🔄 Redis Cache)] end - + subgraph "📊 Monitoring" HEALTH[🏥 Health Checks] METRICS[📈 Metrics Collection] LOGS[📋 Centralized Logging] end end - + LB --> APP1 - LB --> APP2 + LB --> APP2 LB --> APP3 APP1 --> DB APP2 --> DB @@ -610,14 +610,14 @@ graph TD APP1 --> CACHE APP2 --> CACHE APP3 --> CACHE - + APP1 --> HEALTH APP2 --> METRICS APP3 --> LOGS - + style LB fill:#10b981,stroke:#fff,color:#fff style APP1 fill:#1e3a8a,stroke:#fff,color:#fff - style APP2 fill:#1e3a8a,stroke:#fff,color:#fff + style APP2 fill:#1e3a8a,stroke:#fff,color:#fff style APP3 fill:#1e3a8a,stroke:#fff,color:#fff ``` @@ -649,7 +649,7 @@ services: - APP_ENV=production - LOG_LEVEL=info restart: unless-stopped - + nginx: image: nginx:alpine ports: @@ -730,7 +730,7 @@ graph LR D --> E[🔍 Pull Request Review] E --> F[✅ Merge to Develop] F --> G[🚀 Deploy to Production] - + style A fill:#3b82f6,stroke:#fff,color:#fff style G fill:#10b981,stroke:#fff,color:#fff ``` @@ -753,25 +753,25 @@ graph LR graph TB subgraph "📊 Metrics Collection" A[⚡ API Response Times] - B[💳 Transaction Volumes] + B[💳 Transaction Volumes] C[👥 Active Users] D[💾 Database Health] E[🔄 Cache Performance] end - + subgraph "🎯 Monitoring Tools" F[📈 Grafana Dashboards] G[🚨 Alerting System] - H[📋 Log Aggregation] + H[📋 Log Aggregation] I[🔍 Performance Profiling] end - + A --> F B --> F C --> G D --> H E --> I - + style F fill:#1e3a8a,stroke:#fff,color:#fff style G fill:#ef4444,stroke:#fff,color:#fff ``` @@ -798,7 +798,7 @@ sequenceDiagram participant A as 🔐 Auth Middleware participant B as ⚡ Backend API participant D as 💾 Database - + C->>A: Request with API Key A->>A: Validate API Key alt ✅ Valid Key @@ -834,26 +834,26 @@ graph LR B[📊 Data Validation
Pydantic Models] C[💾 Connection Pooling
Database Optimization] end - - subgraph "🎨 Frontend Optimizations" + + subgraph "🎨 Frontend Optimizations" D[📦 CDN Assets
Bootstrap + Chart.js] E[🗜️ Minified Code
CSS + JavaScript] F[🖼️ Lazy Loading
Images + Components] end - + subgraph "🌐 Infrastructure" G[🔄 Load Balancing
Nginx Proxy] H[💨 Gzip Compression
Static Assets] I[⚡ HTTP/2 Support
Modern Protocol] end - + A --> D - B --> E + B --> E C --> F D --> G E --> H F --> I - + style A fill:#10b981,stroke:#fff,color:#fff style D fill:#3b82f6,stroke:#fff,color:#fff style G fill:#1e3a8a,stroke:#fff,color:#fff @@ -899,23 +899,23 @@ graph TD B[☰ Hamburger Menu
Collapsible Navigation] C[📊 Simplified Charts
Touch-Friendly] end - + subgraph "💻 Tablet (768px - 1024px)" D[📦 Grid Layout
2-Column Design] E[📋 Side Navigation
Expanded Menu] F[📈 Full Charts
Interactive Elements] end - + subgraph "🖥️ Desktop (> 1024px)" G[🎯 Full Layout
Multi-Column Grid] H[🎪 Rich Navigation
All Features Visible] I[📊 Advanced Charts
All Interactions] end - + A --> D --> G B --> E --> H C --> F --> I - + style A fill:#ef4444,stroke:#fff,color:#fff style D fill:#f59e0b,stroke:#fff,color:#fff style G fill:#10b981,stroke:#fff,color:#fff diff --git a/README_NEW.md b/README_NEW.md index 0898498..ad69076 100644 --- a/README_NEW.md +++ b/README_NEW.md @@ -213,7 +213,7 @@ curl -X POST \ # Response { "invoice_id": "INV-2025-789012", - "order_id": "ORD-2025-001234", + "order_id": "ORD-2025-001234", "amount": 1250.75, "currency": "EUR", "issued_at": "2025-07-20T15:45:30Z" @@ -248,7 +248,7 @@ API_KEY=your-production-key # Opcional (se genera automáticamente) # Tests unitarios pytest -# Con coverage detallado +# Con coverage detallado pytest --cov=app --cov-report=html --cov-report=term-missing # Tests de endpoints específicos @@ -269,7 +269,7 @@ safety check --json --output safety-report.json ### **CloudWatch Dashboard** - **Lambda Metrics**: Duration, Errors, Invocations, Throttles -- **API Gateway**: Request count, Latency, 4xx/5xx errors +- **API Gateway**: Request count, Latency, 4xx/5xx errors - **Custom Metrics**: Business KPIs y performance indicators ### **Logging estructurado** diff --git a/SECURITY.md b/SECURITY.md index 60aa054..9c9d443 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,7 +8,7 @@ ## Reporting a Vulnerability -If you discover a security vulnerability, please send an email to security@neurobank.com. +If you discover a security vulnerability, please send an email to security@neurobank.com. Do not report security vulnerabilities through public GitHub issues. ## Security Measures Implemented @@ -54,7 +54,7 @@ Do not report security vulnerabilities through public GitHub issues. ## Security Checklist for Deployment - [ ] API_KEY configured and strong -- [ ] SECRET_KEY configured and strong +- [ ] SECRET_KEY configured and strong - [ ] CORS_ORIGINS properly configured - [ ] No wildcard CORS origins - [ ] No hardcoded secrets in code diff --git a/SOLUTION_STATUS_FINAL.md b/SOLUTION_STATUS_FINAL.md index 599f34a..d843d37 100644 --- a/SOLUTION_STATUS_FINAL.md +++ b/SOLUTION_STATUS_FINAL.md @@ -25,7 +25,7 @@ jobs: test: runs-on: ubuntu-latest - + # ✅ Variables de entorno para tests env: API_KEY: "NeuroBankDemo2025-SecureKey-ForTestingOnly" @@ -37,7 +37,7 @@ jobs: ```yaml security: runs-on: ubuntu-latest - + # ✅ Variables de entorno para security checks env: API_KEY: "NeuroBankDemo2025-SecureKey-ForTestingOnly" @@ -85,7 +85,7 @@ El workflow debería mostrar: ## 🎉 **ESTADO FINAL** - **🔧 CI/CD**: Completamente solucionado con doble protección -- **🚂 Railway**: Listo para deployment automático +- **🚂 Railway**: Listo para deployment automático - **🔒 Security**: Validación robusta mantenida - **📚 Documentation**: Completa y actualizada - **✅ Production Ready**: 100% verificado diff --git a/WORKFLOW.md b/WORKFLOW.md index 93becba..d410688 100644 --- a/WORKFLOW.md +++ b/WORKFLOW.md @@ -248,7 +248,7 @@ production: API_KEY: ${{ secrets.API_KEY_PROD }} staging: - branch: develop + branch: develop domain: neurobank-staging.railway.app variables: ENVIRONMENT: staging @@ -264,18 +264,18 @@ name: Deploy to Railway on: push: branches: [main, develop] - + jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - + - name: Run Tests run: | pytest --cov=app tests/ bandit -r app/ - + - name: Deploy to Railway uses: railway/railway@v1 with: @@ -321,7 +321,7 @@ GET /backoffice/api/system-health # Detailed monitoring # Metrics collection - Response times -- Memory usage +- Memory usage - Active connections - Error rates - Transaction volumes @@ -334,11 +334,11 @@ alerts: - name: "High Response Time" condition: avg_response_time > 5s notification: email, slack - + - name: "Memory Usage High" condition: memory_usage > 80% notification: email - + - name: "Health Check Failed" condition: health_check_fails >= 3 notification: email, slack, sms diff --git a/WORKFLOW_FIX.md b/WORKFLOW_FIX.md index 9d50f24..cdb086a 100644 --- a/WORKFLOW_FIX.md +++ b/WORKFLOW_FIX.md @@ -17,7 +17,7 @@ PydanticImportError: `BaseSettings` has been moved to the `pydantic-settings` pa # ❌ Antes from pydantic import BaseSettings -# ✅ Después +# ✅ Después from pydantic_settings import BaseSettings ``` @@ -47,7 +47,7 @@ def __init__(self, **kwargs): ============= 7 passed in 1.80s ============== ✅ test_health_check PASSED -✅ test_root_endpoint PASSED +✅ test_root_endpoint PASSED ✅ test_order_status PASSED ✅ test_generate_invoice PASSED ✅ test_order_status_with_bearer_token PASSED @@ -84,7 +84,7 @@ feat/railway-deployment-optimization: ## 🔄 **Próximos Pasos** 1. **✅ GitHub Actions** - El workflow debería pasar ahora -2. **✅ Railway Deploy** - Compatible con la nueva configuración +2. **✅ Railway Deploy** - Compatible con la nueva configuración 3. **✅ Pull Request** - Listo para merge a main ## 🎯 **Resultado** diff --git a/app/auth/dependencies.py b/app/auth/dependencies.py index 6633d11..5b0b94b 100644 --- a/app/auth/dependencies.py +++ b/app/auth/dependencies.py @@ -1,4 +1,3 @@ -import os from typing import Optional from fastapi import Depends, HTTPException, Request diff --git a/app/backoffice/router.py b/app/backoffice/router.py index 6ef4b5f..0e1a845 100644 --- a/app/backoffice/router.py +++ b/app/backoffice/router.py @@ -8,11 +8,9 @@ from datetime import datetime, timedelta from decimal import Decimal from enum import Enum -from typing import Any, Dict, List -from fastapi import APIRouter, HTTPException, Request -from fastapi.responses import HTMLResponse, JSONResponse -from fastapi.staticfiles import StaticFiles +from fastapi import APIRouter, Request +from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from pydantic import BaseModel, Field diff --git a/app/backoffice/router_clean.py b/app/backoffice/router_clean.py index 0f22a96..6040539 100644 --- a/app/backoffice/router_clean.py +++ b/app/backoffice/router_clean.py @@ -8,11 +8,9 @@ from datetime import datetime, timedelta from decimal import Decimal from enum import Enum -from typing import Any, Dict, List -from fastapi import APIRouter, HTTPException, Request -from fastapi.responses import HTMLResponse, JSONResponse -from fastapi.staticfiles import StaticFiles +from fastapi import APIRouter, Request +from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from pydantic import BaseModel, Field @@ -107,11 +105,11 @@ async def search_transactions( Endpoint para filtrar transacciones con múltiples criterios. """ - # Generar transacciones mock transactions = [] total = random.randint(100, 200) - for i in range(min(page_size, total)): + # ⚙️ corrección B007: variable no usada reemplazada por "_" + for _ in range(min(page_size, total)): tx_id = str(uuid.uuid4())[:8] transactions.append( { @@ -257,3 +255,4 @@ async def backoffice_info(): "Real-time data updates", ], } + diff --git a/app/backoffice/templates/admin_reports.html b/app/backoffice/templates/admin_reports.html index 99fa299..d9d1292 100644 --- a/app/backoffice/templates/admin_reports.html +++ b/app/backoffice/templates/admin_reports.html @@ -613,4 +613,4 @@
- \ No newline at end of file + diff --git a/app/backoffice/templates/admin_transactions.html b/app/backoffice/templates/admin_transactions.html index 895a20c..ef097f3 100644 --- a/app/backoffice/templates/admin_transactions.html +++ b/app/backoffice/templates/admin_transactions.html @@ -4,14 +4,14 @@ {{ title }} - + - +