Skip to content

andrelima28439/fintech-platform

Repository files navigation

FinTech Platform

Plataforma completa de banco digital com arquitetura moderna, construída para segurança, escalabilidade e conformidade regulatória.

License Node Next.js PostgreSQL Docker TypeScript


Índice


Visão Geral

A FinTech Platform é uma plataforma de banco digital completa que oferece:

Módulo Funcionalidades
Autenticação Login, registro, 2FA (TOTP), biometria, JWT
Contas Conta corrente e poupança, saldo em tempo real
Transferências TED, DOC, transferências internas, PIX com QR Code
Pagamentos Boletos, contas, agendamento, recorrência
Cartões Virtual e físico, bloqueio, limite, criptografia
Investimentos CDB, Tesouro Direto, Ações, carteira
Empréstimos Simulação, solicitação, acompanhamento
Dashboard Gráficos, metas, extrato, export PDF/CSV

Arquitetura

Diagrama de Sistema

graph TB
    subgraph Client["🖥️ Client Layer"]
        FE["Next.js 14 SPA<br/>Port 3000"]
    end

    subgraph API["⚙️ API Layer"]
        GW["Express.js Gateway<br/>Port 3001"]
        
        subgraph Middleware["Middleware Stack"]
            Auth["Auth JWT"]
            Rate["Rate Limiter"]
            Valid["Zod Validator"]
            Audit["Audit Logger"]
            Fraud["Fraud Detection"]
        end
        
        subgraph Services["Business Services"]
            AuthSvc["Auth Service<br/>2FA/TOTP"]
            TxnSvc["Transaction Service"]
            CardSvc["Card Service"]
            InvSvc["Investment Service"]
            LoanSvc["Loan Service"]
            StripeSvc["Stripe Service"]
        end
    end

    subgraph Data["💾 Data Layer"]
        PG[("PostgreSQL 16<br/>Port 5432")]
        Redis[("Redis 7<br/>Port 6379")]
        RMQ[("RabbitMQ 3<br/>Port 5672")]
    end

    subgraph External["🌐 External"]
        Stripe["Stripe API"]
    end

    subgraph Consumers["🔄 Async Consumers"]
        TxnConsumer["Transaction Processor"]
        NotifConsumer["Notification Sender"]
        ReconConsumer["Reconciliation Engine"]
    end

    FE --> GW
    GW --> Auth
    GW --> Rate
    GW --> Valid
    GW --> Audit
    GW --> Fraud
    
    Auth --> AuthSvc
    Rate --> Redis
    Fraud --> Redis
    Audit --> PG
    
    AuthSvc --> PG
    TxnSvc --> PG
    TxnSvc --> Redis
    TxnSvc --> RMQ
    CardSvc --> PG
    InvSvc --> PG
    LoanSvc --> PG
    StripeSvc --> Stripe
    
    RMQ --> TxnConsumer
    RMQ --> NotifConsumer
    RMQ --> ReconConsumer
    
    TxnConsumer --> PG
    NotifConsumer --> PG
    ReconConsumer --> PG

    style Client fill:#1a1a2e,color:#fff
    style API fill:#16213e,color:#fff
    style Data fill:#0f3460,color:#fff
    style External fill:#533483,color:#fff
    style Consumers fill:#1a1a2e,color:#fff
Loading

Diagrama de Componentes

graph LR
    subgraph Frontend["Frontend (Next.js 14)"]
        Pages["App Router Pages<br/>/dashboard<br/>/transfers<br/>/payments<br/>/cards<br/>/investments<br/>/loans<br/>/settings"]
        Components["UI Components<br/>Charts, Forms, Tables<br/>Cards, Modals"]
        Store["Zustand Store<br/>Auth, Transactions"]
        API["Axios Client<br/>Interceptors"]
    end

    subgraph Backend["Backend (Express.js)"]
        Routes["Routes<br/>Auth, Accounts<br/>Transactions, Cards<br/>Investments, Loans"]
        Middleware["Middleware<br/>Auth, Rate Limit<br/>Validation, Audit<br/>Fraud Detection"]
        Services["Services<br/>Business Logic<br/>Encryption, Stripe"]
        Consumers["RabbitMQ Consumers<br/>Transactions<br/>Notifications<br/>Reconciliation"]
    end

    Pages --> Components
    Pages --> Store
    Store --> API
    API --> Routes
    Routes --> Middleware
    Middleware --> Services
    Services --> Consumers

    style Frontend fill:#0ea5e9,color:#fff
    style Backend fill:#0284c7,color:#fff
Loading

Diagrama de Implantação

graph TB
    subgraph Docker["Docker Compose Environment"]
        subgraph Network["fintech-network (bridge)"]
            FE["frontend:3000<br/>Next.js Standalone"]
            BE["backend:3001<br/>Express + Prisma"]
            DB[("postgres:5432<br/>PostgreSQL 16")]
            Cache[("redis:6379<br/>Redis 7")]
            MQ[("rabbitmq:5672<br/>RabbitMQ 3 + UI:15672")]
        end
        
        Volumes["Docker Volumes<br/>postgres_data<br/>redis_data<br/>rabbitmq_data"]
    end

    User["👤 Browser"] -->|HTTP| FE
    FE -->|API Calls| BE
    BE -->|Prisma| DB
    BE -->|ioredis| Cache
    BE -->|amqplib| MQ
    
    DB --> Volumes
    Cache --> Volumes
    MQ --> Volumes

    style Docker fill:#1e293b,color:#fff
    style Network fill:#334155,color:#fff
    style User fill:#0ea5e9,color:#fff
Loading

Fluxos Principais

Fluxo de Autenticação

sequenceDiagram
    participant U as Usuário
    participant F as Frontend
    participant B as Backend
    participant DB as PostgreSQL
    participant R as Redis
    participant OTP as TOTP App

    U->>F: Acessa /register
    F->>U: Formulário multi-step
    U->>F: Preenche dados
    F->>B: POST /api/auth/register
    B->>DB: Verifica email/CPF duplicado
    alt Duplicado
        B-->>F: 409 Conflict
        F-->>U: Mostra erro
    else Novo usuário
        B->>DB: Cria User (senha hash bcrypt)
        B->>DB: Cria conta corrente
        B->>DB: Cria conta poupança
        B-->>F: 201 Created
        F-->>U: Redireciona /login
    end

    U->>F: Acessa /login
    F->>U: Formulário email/senha
    U->>F: Credenciais
    F->>B: POST /api/auth/login
    B->>DB: Busca usuário
    B->>B: Verifica senha (bcrypt.compare)
    alt 2FA habilitado
        B-->>F: requires2FA: true
        F->>U: Input código 6 dígitos
        U->>F: Código TOTP
        F->>B: POST /api/auth/2fa/verify
        B->>OTP: Valida token (window: 1)
        alt Código válido
            B->>DB: Atualiza twoFactorEnabled
        end
    end
    B->>B: Gera JWT (HS256)
    B->>R: Cache sessão
    B-->>F: 200 { token, user }
    F->>F: Salva cookie + Zustand
    F-->>U: Redireciona /dashboard
Loading

Fluxo de Transação

sequenceDiagram
    participant U as Usuário
    participant F as Frontend
    participant Auth as Auth Middleware
    participant Rate as Rate Limiter
    participant Fraud as Fraud Detection
    participant Svc as Transaction Service
    participant DB as PostgreSQL
    participant Cache as Redis
    participant MQ as RabbitMQ
    participant Consumer as Async Consumer

    U->>F: Preenche formulário transferência
    F->>F: Validação client-side
    F->>Auth: POST /api/transactions/transfer + JWT
    Auth->>Auth: Verifica token JWT
    alt Token inválido
        Auth-->>F: 401 Unauthorized
    end
    
    Auth->>Rate: Verifica rate limit
    Rate->>Cache: incr ratelimit:{ip}
    alt Excedido
        Rate-->>F: 429 Too Many Requests
    end
    
    Auth->>Fraud: Fraud check
    Fraud->>Cache: Verifica velocity
    alt Valor > threshold
        Fraud-->>F: 422 Fraud Detected
    end
    
    Fraud->>Svc: Processar transferência
    Svc->>DB: Verifica saldo
    alt Saldo insuficiente
        Svc-->>F: 400 Insufficient funds
    end
    
    Svc->>DB: BEGIN TRANSACTION
    Svc->>DB: UPDATE conta origem (decrement)
    Svc->>DB: UPDATE conta destino (increment)
    Svc->>DB: INSERT transaction (sender)
    Svc->>DB: INSERT transaction (receiver)
    Svc->>DB: COMMIT
    
    Svc->>Cache: Invalidate balance cache
    Svc->>DB: INSERT audit_log
    Svc->>MQ: Publish to transactions queue
    Svc->>MQ: Publish to notifications queue
    
    Svc-->>F: 200 { transaction }
    F-->>U: Confirmação + saldo atualizado
    
    MQ->>Consumer: Process async
    Consumer->>DB: Update status
    Consumer->>DB: Log reconciliation
Loading

Fluxo de Investimento

sequenceDiagram
    participant U as Usuário
    participant F as Frontend
    participant B as Backend
    participant DB as PostgreSQL
    participant Cache as Redis

    U->>F: Acessa /investments
    F->>B: GET /api/investments/products
    B-->>F: Lista produtos (CDB, Tesouro, Ações)
    F->>U: Exibe cards com yield/risco
    
    U->>F: Seleciona produto + valor
    F->>F: Valida valor mínimo
    F->>B: POST /api/investments/apply
    B->>DB: BEGIN TRANSACTION
    B->>DB: Verifica saldo
    B->>DB: UPDATE account (decrement)
    B->>DB: INSERT investment
    B->>DB: INSERT transaction (withdrawal)
    B->>DB: COMMIT
    B->>Cache: Invalidate balance
    B-->>F: 200 { investment }
    
    F->>U: Confirmação de aplicação
    
    Note over U,Cache: Tempo passa...
    
    U->>F: Solicita resgate
    F->>B: POST /api/investments/redeem
    B->>DB: Busca investimento
    B->>B: Calcula yield (dias * taxa)
    B->>DB: BEGIN TRANSACTION
    B->>DB: UPDATE account (increment total)
    B->>DB: UPDATE investment (redeemed)
    B->>DB: INSERT transaction (deposit)
    B->>DB: COMMIT
    B->>Cache: Invalidate balance
    B-->>F: 200 { redemption }
    F->>U: Confirmação + valor recebido
Loading

Modelo de Dados

erDiagram
    USER ||--o{ ACCOUNT : owns
    USER ||--o{ AUDIT_LOG : generates
    ACCOUNT ||--o{ TRANSACTION : has
    ACCOUNT ||--o{ CARD : has
    ACCOUNT ||--o{ INVESTMENT : has
    ACCOUNT ||--o{ LOAN : has
    ACCOUNT ||--o{ PAYMENT_SCHEDULE : has

    USER {
        string id PK
        string email UK
        string password
        string name
        string cpf UK
        string phone
        string twoFactorSecret
        bool twoFactorEnabled
        bool biometricEnabled
        datetime createdAt
        datetime updatedAt
    }

    ACCOUNT {
        string id PK
        string userId FK
        string type "checking|savings"
        decimal balance
        string currency "BRL"
        string status "active|blocked|closed"
        datetime createdAt
        datetime updatedAt
    }

    TRANSACTION {
        string id PK
        string accountId FK
        string type "transfer|pix|payment|deposit|withdrawal"
        decimal amount
        string description
        string status "pending|completed|failed"
        string recipientAccount
        string recipientName
        string pixKey
        string pixKeyType "cpf|email|phone|random"
        datetime scheduledAt
        datetime completedAt
        datetime createdAt
    }

    CARD {
        string id PK
        string accountId FK
        string number "encrypted"
        string holderName
        string expiryMonth
        string expiryYear
        string cvv "encrypted"
        string type "virtual|physical"
        string status "active|blocked|expired"
        decimal limit
        datetime createdAt
        datetime updatedAt
    }

    INVESTMENT {
        string id PK
        string accountId FK
        string type "cdb|treasury|stocks"
        string productName
        decimal amount
        decimal yield
        datetime appliedAt
        datetime redeemedAt
        string status "active|redeemed"
    }

    LOAN {
        string id PK
        string accountId FK
        decimal amount
        decimal interestRate
        int term
        decimal monthlyPayment
        string status "pending|approved|rejected|active|paid"
        datetime requestedAt
        datetime approvedAt
    }

    AUDIT_LOG {
        string id PK
        string userId FK
        string action
        string entityType
        string entityId
        json details
        string ipAddress
        datetime createdAt
    }

    PAYMENT_SCHEDULE {
        string id PK
        string accountId FK
        string payee
        decimal amount
        datetime dueDate
        string status "active|completed|cancelled"
        string recurrence "once|weekly|monthly|quarterly|yearly"
        datetime createdAt
    }
Loading

Segurança e Compliance

Camadas de Segurança

graph TB
    subgraph L1["Camada 1 - Rede"]
        Docker["Docker Network Isolation"]
        Ports["Port Exposure Control"]
    end
    
    subgraph L2["Camada 2 - Aplicação"]
        Helmet["Helmet.js Headers"]
        CORS["CORS Policy"]
        RateL["Rate Limiting (Redis)"]
    end
    
    subgraph L3["Camada 3 - Autenticação"]
        JWT["JWT (HS256)"]
        TOTP["2FA TOTP (RFC 6238)"]
        Bcrypt["bcrypt (12 rounds)"]
    end
    
    subgraph L4["Camada 4 - Dados"]
        AES["AES-256 Encryption"]
        Prisma["Parameterized Queries"]
        Sanitize["Input Sanitization (Zod)"]
    end
    
    subgraph L5["Camada 5 - Monitoramento"]
        Audit["Audit Logging"]
        Fraud["Fraud Detection"]
        Alert["Real-time Alerts"]
    end

    L1 --> L2 --> L3 --> L4 --> L5

    style L1 fill:#dc2626,color:#fff
    style L2 fill:#ea580c,color:#fff
    style L3 fill:#ca8a04,color:#fff
    style L4 fill:#16a34a,color:#fff
    style L5 fill:#2563eb,color:#fff
Loading

Matriz de Segurança

Ameaça Mitigação Camada
SQL Injection Prisma ORM (queries parametrizadas) Dados
XSS Helmet.js + CSP headers Aplicação
CSRF SameSite cookies + JWT Autenticação
Brute Force Rate limiting (Redis) + bcrypt Aplicação
Credential Stuffing 2FA TOTP obrigatório Autenticação
Data Breach AES-256 encryption at rest Dados
Account Takeover Velocity checks + fraud detection Monitoramento
Replay Attack JWT expiry + TOTP time window Autenticação
Man-in-the-Middle HTTPS (production) Rede
Privilege Escalation JWT role validation Autenticação

PCI-DSS Compliance

graph LR
    subgraph InScope["In Scope"]
        CardData["Card Data<br/>(encrypted AES-256)"]
        TransProc["Transaction Processing"]
        Auth["Authentication"]
        Logging["Audit Logging"]
    end
    
    subgraph OutOfScope["Out of Scope"]
        Stripe["Stripe handles<br/>raw card numbers"]
        Network["Network security<br/>handled by Docker"]
    end

    InScope --> OutOfScope

    style InScope fill:#dc2626,color:#fff
    style OutOfScope fill:#16a34a,color:#fff
Loading

LGPD Compliance

Requisito Implementação
Consentimento Checkbox obrigatório no registro
Minimização de dados Schema com apenas campos necessários
Portabilidade Export de extrato (PDF/CSV)
Direito ao esquecimento Endpoint de deleção de conta
Transparência Audit log de todos os acessos
Segurança Criptografia + controle de acesso

API Reference

Base URL

http://localhost:3001/api

Autenticação

Todos os endpoints protegidos requerem header:

Authorization: Bearer <jwt_token>

Endpoints

Auth

Method Endpoint Auth Descrição
POST /auth/register Registrar novo usuário
POST /auth/login Login com email/senha
POST /auth/2fa/setup Configurar 2FA (retorna QR code)
POST /auth/2fa/verify Verificar código 2FA
POST /auth/2fa/disable Desativar 2FA

Exemplo - Register:

POST /api/auth/register
{
  "email": "user@example.com",
  "password": "SecurePass123!",
  "name": "João Silva",
  "cpf": "12345678901",
  "phone": "11999999999"
}

// Response 201
{
  "success": true,
  "data": {
    "user": { "id": "...", "email": "...", "name": "..." },
    "accounts": [
      { "id": "...", "type": "checking" },
      { "id": "...", "type": "savings" }
    ]
  }
}

Exemplo - Login:

POST /api/auth/login
{
  "email": "user@example.com",
  "password": "SecurePass123!"
}

// Response 200
{
  "success": true,
  "data": {
    "token": "eyJhbGci...",
    "user": { "id": "...", "email": "...", "twoFactorEnabled": false }
  }
}

Accounts

Method Endpoint Auth Descrição
GET /accounts Listar contas do usuário
GET /accounts/:id/balance Saldo da conta (cached)
GET /accounts/:id/statement Extrato com paginação

Transactions

Method Endpoint Auth Descrição
POST /transactions/transfer Transferência entre contas
POST /transactions/pix Transferência PIX
POST /transactions/payment Pagamento de boleto/conta
POST /transactions/schedule Agendar pagamento
GET /transactions/:id Detalhes da transação

Cards

Method Endpoint Auth Descrição
POST /cards Criar cartão virtual
GET /cards Listar cartões (números mascarados)
PUT /cards/:id/block Bloquear/desbloquear
PUT /cards/:id/limit Alterar limite

Investments

Method Endpoint Auth Descrição
GET /investments/products Produtos disponíveis
POST /investments/apply Aplicar investimento
POST /investments/redeem Resgatar investimento
GET /investments/portfolio Carteira do usuário

Loans

Method Endpoint Auth Descrição
POST /loans/simulate Simular empréstimo
POST /loans/request Solicitar empréstimo
GET /loans/:id/status Status do empréstimo

Webhooks

Method Endpoint Auth Descrição
POST /webhooks/stripe ✅ (signature) Stripe webhook

Códigos de Erro

Status Código Descrição
400 ValidationError Dados inválidos
401 AuthenticationError Token ausente ou inválido
403 AuthorizationError Permissão insuficiente
404 NotFoundError Recurso não encontrado
409 ConflictError Email/CPF já existe
422 FraudError Transação bloqueada por fraude
429 RateLimitError Limite de requisições excedido
500 InternalError Erro interno do servidor

Getting Started

Pré-requisitos

Software Versão
Docker 24+
Docker Compose 2.20+
Node.js (dev local) 20+

Quick Start

# 1. Clone o repositório
git clone https://github.com/andrelima28439/fintech-platform.git
cd fintech-platform

# 2. Configure variáveis de ambiente
cp .env.example .env

# 3. Inicie todos os serviços
docker compose up -d

# 4. Aplique o schema do banco
docker compose exec backend npx prisma db push --accept-data-loss

# 5. Verifique os serviços
docker compose ps

Acessos

Serviço URL Credenciais
Frontend http://localhost:3000 -
Backend API http://localhost:3001 -
Health Check http://localhost:3001/health -
RabbitMQ UI http://localhost:15672 fintech_rabbit / rabbit_pass_2024
PostgreSQL localhost:5432 fintech_user / fintech_pass_2024
Redis localhost:6379 Senha: redis_pass_2024

Testando a Plataforma

# 1. Registre um usuário
curl -X POST http://localhost:3001/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "Test123456!",
    "name": "Test User",
    "cpf": "12345678901",
    "phone": "11999999999"
  }'

# 2. Faça login
curl -X POST http://localhost:3001/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "Test123456!"
  }'

# 3. Acesse o dashboard
# Abra http://localhost:3000/login no navegador

Desenvolvimento Local

# Terminal 1 - Backend
cd backend
npm install
docker compose up -d postgres redis rabbitmq
npx prisma db push --accept-data-loss
npm run dev

# Terminal 2 - Frontend
cd frontend
npm install
npm run dev

CI/CD

Pipelines GitHub Actions

graph LR
    subgraph PR["Pull Request"]
        Sec["Security Scan<br/>NPM Audit + CodeQL<br/>Trivy + Gitleaks"]
        Comp["Compliance Check<br/>PCI-DSS + LGPD<br/>License Check"]
        Test["TypeScript Check<br/>Build Validation"]
    end
    
    subgraph Main["Push to main"]
        Build["Build Docker Images<br/>Push to GHCR"]
        Stage["Deploy Staging<br/>Health Checks"]
        Prod["Deploy Production<br/>Health Checks"]
    end

    PR --> Sec --> Comp --> Test
    Main --> Build --> Stage --> Prod

    style PR fill:#f59e0b,color:#fff
    style Main fill:#22c55e,color:#fff
Loading

Workflows

Workflow Trigger Jobs
security-scan.yml PR, push main, weekly NPM audit, CodeQL, Trivy, Gitleaks
compliance-check.yml PR, push main PCI-DSS, LGPD, License, TS check
deploy.yml Push main Test, Build, Deploy staging, Deploy prod

Estrutura do Projeto

fintech-platform/
│
├── docker-compose.yml              # Orquestração de containers
├── .env.example                    # Template de variáveis de ambiente
├── README.md                       # Documentação principal
│
├── .github/
│   └── workflows/
│       ├── security-scan.yml       # Scan de vulnerabilidades
│       ├── compliance-check.yml    # Verificação de compliance
│       └── deploy.yml              # Pipeline de deploy
│
├── backend/                        # API Express.js
│   ├── Dockerfile                  # Container backend
│   ├── package.json
│   ├── tsconfig.json
│   ├── prisma/
│   │   └── schema.prisma           # Schema do banco de dados
│   ├── database/
│   │   └── init.sql                # Script de inicialização SQL
│   └── src/
│       ├── index.ts                # Entry point + graceful shutdown
│       ├── config/
│       │   ├── index.ts            # Configurações de todos os serviços
│       │   └── logger.ts           # Winston logger (console + file)
│       ├── database/
│       │   ├── prisma.ts           # Prisma client singleton
│       │   ├── redis.ts            # Redis client + cache helpers
│       │   └── rabbitmq.ts         # RabbitMQ connection + pub/sub
│       ├── middleware/
│       │   ├── auth.ts             # JWT authentication
│       │   ├── rateLimiter.ts      # Redis-based rate limiting
│       │   ├── validator.ts        # Zod validation factory
│       │   ├── audit.ts            # Audit logging middleware
│       │   └── fraud.ts            # Fraud detection (amount + velocity)
│       ├── services/
│       │   ├── authService.ts      # Register, login, 2FA TOTP
│       │   ├── accountService.ts   # Accounts, balance (cached), statement
│       │   ├── transactionService.ts # Transfer, PIX, payment, schedule
│       │   ├── cardService.ts      # Create (encrypted), list (masked), block
│       │   ├── investmentService.ts # Products, apply, redeem, portfolio
│       │   ├── loanService.ts      # Simulate, request, status
│       │   ├── stripeService.ts    # Payment processing, webhooks
│       │   └── encryptionService.ts # AES-256 encrypt/decrypt
│       ├── routes/
│       │   ├── index.ts            # Route aggregator
│       │   ├── auth.routes.ts      # POST /auth/*
│       │   ├── account.routes.ts   # GET /accounts/*
│       │   ├── transaction.routes.ts # POST /transactions/*
│       │   ├── card.routes.ts      # Cards CRUD
│       │   ├── investment.routes.ts # Investments CRUD
│       │   ├── loan.routes.ts      # Loans CRUD
│       │   └── webhook.routes.ts   # POST /webhooks/stripe
│       ├── consumers/
│       │   ├── transactionConsumer.ts  # Processa transações async
│       │   ├── notificationConsumer.ts # Envia notificações
│       │   └── reconciliationConsumer.ts # Conciliação bancária
│       ├── types/
│       │   └── index.ts            # TypeScript interfaces
│       └── utils/
│           ├── response.ts         # API response helpers
│           ├── errors.ts           # Custom error classes
│           └── errorHandler.ts     # Global error middleware
│
└── frontend/                       # Next.js 14 App Router
    ├── Dockerfile                  # Container frontend
    ├── package.json
    ├── tsconfig.json
    ├── next.config.js
    ├── tailwind.config.ts
    ├── postcss.config.js
    └── src/
        ├── app/                    # App Router
        │   ├── globals.css         # Tailwind + custom styles
        │   ├── layout.tsx          # Root layout + providers
        │   ├── page.tsx            # Landing page
        │   ├── (auth)/             # Route group - autenticação
        │   │   ├── layout.tsx      # Auth layout
        │   │   ├── login/page.tsx  # Login + 2FA step
        │   │   └── register/page.tsx # Multi-step registration
        │   └── (dashboard)/        # Route group - protegido
        │       ├── layout.tsx      # Dashboard layout (sidebar + header)
        │       ├── dashboard/page.tsx    # Main dashboard
        │       ├── transfers/page.tsx    # TED/PIX transfers
        │       ├── payments/page.tsx     # Bill payments
        │       ├── cards/page.tsx        # Card management
        │       ├── investments/page.tsx  # Investment portfolio
        │       ├── loans/page.tsx        # Loan simulation
        │       └── settings/page.tsx     # User settings
        ├── components/
        │   ├── ui/                 # UI primitives
        │   │   ├── button.tsx
        │   │   ├── input.tsx
        │   │   ├── card.tsx
        │   │   ├── modal.tsx
        │   │   ├── table.tsx
        │   │   ├── chart.tsx
        │   │   ├── badge.tsx
        │   │   └── tabs.tsx
        │   ├── layout/             # Layout components
        │   │   ├── sidebar.tsx
        │   │   └── header.tsx
        │   ├── dashboard/          # Dashboard widgets
        │   │   ├── balance-card.tsx
        │   │   ├── transaction-list.tsx
        │   │   ├── spending-chart.tsx
        │   │   ├── income-chart.tsx
        │   │   └── savings-goals.tsx
        │   ├── transfers/          # Transfer components
        │   │   ├── transfer-form.tsx
        │   │   └── pix-section.tsx
        │   ├── cards/              # Card components
        │   │   └── card-visual.tsx
        │   ├── investments/        # Investment components
        │   │   ├── product-card.tsx
        │   │   └── portfolio-chart.tsx
        │   ├── loans/              # Loan components
        │   │   └── simulator.tsx
        │   ├── settings/           # Settings components
        │   │   ├── security-panel.tsx
        │   │   └── export-panel.tsx
        │   └── notifications/
        │       └── alert-banner.tsx
        ├── lib/
        │   ├── api.ts              # Axios client + interceptors
        │   └── utils.ts            # Helpers (format, mask, cn)
        ├── store/
        │   ├── authStore.ts        # Zustand auth state
        │   └── transactionStore.ts # Zustand transaction state
        ├── hooks/
        │   ├── useAuth.ts          # Auth hook
        │   └── useTransactions.ts  # Transactions hook
        ├── types/
        │   └── index.ts            # TypeScript types
        └── middleware.ts           # Next.js route protection

Troubleshooting

Problemas Comuns

Problema Solução
MODULE_NOT_FOUND no backend Remova volumes: docker compose down -v e rebuild
Prisma engine error Rebuild com docker compose build --no-cache backend
Rate limit exceeded Redis flush: docker compose exec redis redis-cli -a redis_pass_2024 FLUSHALL
Port already in use Pare serviços locais ou altere portas no docker-compose.yml
Frontend não conecta ao backend Verifique NEXT_PUBLIC_API_URL no .env.local

Logs

# Todos os logs
docker compose logs -f

# Apenas backend
docker compose logs -f backend

# Apenas frontend
docker compose logs -f frontend

# Últimas 50 linhas
docker compose logs --tail=50 backend

Reset Completo

# Para tudo e remove volumes
docker compose down -v

# Rebuild sem cache
docker compose build --no-cache

# Inicia do zero
docker compose up -d

# Aplica schema
docker compose exec backend npx prisma db push --accept-data-loss

License

MIT License - veja o arquivo LICENSE para detalhes.

Support

Para issues e feature requests, utilize GitHub Issues.

About

Complete digital banking platform built with Next.js 14, Express, PostgreSQL, Redis, and RabbitMQ.

Topics

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages