# Implementation Plan: Motor de Detecção de Fraudes Bancárias **Branch**: `001-fraud-detection-engine` | **Date**: 2026-05-11 | **Spec**: [spec.md](./spec.md) **Input**: Feature specification from `/specs/001-fraud-detection-engine/spec.md` ## Summary Sistema web para detecção de fraudes bancárias com motor de regras pontuável, explicações auditáveis em linguagem natural, fila de investigação para analistas, gestão de regras por administradores, e dashboard de métricas em tempo real. Backend Python/FastAPI com pipeline de ingestão assíncrono via Redis Streams, frontend React/TypeScript com dashboard interativo, PostgreSQL para dados transacionais e audit log imutável. ## Technical Context **Language/Version**: Python 3.12 (backend), TypeScript 5.x (frontend) **Primary Dependencies**: FastAPI, SQLAlchemy 2.0, Pydantic v2, Alembic, React 19, Tailwind CSS, Recharts **Storage**: PostgreSQL 16 (transacional + audit log), Redis 7 (cache + filas + real-time) **Testing**: pytest + pytest-asyncio (backend), Vitest + React Testing Library (frontend), Playwright (E2E) **Target Platform**: Web browser (frontend) + REST API (backend), Docker Compose (dev/local) **Project Type**: Web service (backend API + SPA frontend) **Performance Goals**: 500 transações/minuto com p95 < 2s de latência de processamento **Constraints**: p95 < 2s (processamento), p95 < 60s (atraso dashboard), audit log imutável, LGPD compliance **Scale/Scope**: 10.000 transações/dia inicial, picos de 5x, 3 perfis de usuário, ~5-20 regras ativas ## Constitution Check *GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.* | Principle | Status | Notes | |-----------|--------|-------| | I. Security-First | ✅ PASS | JWT + OAuth2 via IdP externo, API keys para ingestão, TLS 1.3, secrets via env vars, PII tokenizado antes da ingestão | | II. Explainability | ✅ PASS | Cada regra gera explicação em linguagem natural. Explicação composta agregada no alerta. Formato JSON + texto | | III. Test-First | ✅ PASS | TDD planejado: testes de regra, contrato, integração, E2E. Métricas de FP/FN como gate de deploy | | IV. Observability | ✅ PASS | Audit log imutável com trace ID. Structured logging (JSON). Métricas exportáveis para dashboard | | V. Data Privacy | ✅ PASS | Dados chegam tokenizados. Sem PII armazenado. LGPD: direito à explicação, exclusão, DPIA. Mascaramento em logs/UI | | VI. Simplicity (YAGNI) | ✅ PASS | Rules-based v1 (sem ML). Monolith FastAPI (sem microservices). PostgreSQL sem TimescaleDB até necessidade comprovada. Redis Streams em vez de Kafka | **Gate Result**: ALL PASS — proceeding to implementation. ## Project Structure ### Documentation (this feature) ```text specs/001-fraud-detection-engine/ ├── plan.md # This file ├── research.md # Technology research & decisions ├── data-model.md # Entity definitions, relationships, state machines ├── quickstart.md # Setup, test credentials, smoke test flow ├── contracts/ │ └── api.yaml # OpenAPI 3.0 specification └── tasks.md # Phase 2 output (NOT created by /speckit.plan) ``` ### Source Code (repository root) ```text backend/ ├── fraudshield/ │ ├── __init__.py │ ├── main.py # FastAPI application factory │ ├── config.py # pydantic-settings configuration │ ├── auth.py # JWT validation, OAuth2 middleware, role checks │ ├── db.py # SQLAlchemy engine, session, base │ ├── models/ │ │ ├── __init__.py │ │ ├── transaction.py # Transaction ORM model │ │ ├── rule.py # DetectionRule ORM model │ │ ├── alert.py # FraudAlert ORM model │ │ └── audit.py # AuditLog ORM model (immutable) │ ├── schemas/ │ │ ├── __init__.py │ │ ├── transaction.py # Pydantic request/response schemas │ │ ├── rule.py │ │ ├── alert.py │ │ └── dashboard.py │ ├── engine/ │ │ ├── __init__.py │ │ ├── evaluator.py # Core: iterate rules, compute composite score │ │ ├── explainer.py # Generate natural language explanations │ │ ├── loader.py # Load active rules from DB, cache in memory │ │ └── rules/ # Individual rule implementations │ │ ├── __init__.py │ │ ├── base.py # Abstract Rule base class │ │ ├── amount.py # Amount anomaly rules │ │ ├── location.py # Geolocation rules │ │ ├── time.py # Time-based rules │ │ └── pattern.py # Customer pattern rules │ ├── api/ │ │ ├── __init__.py │ │ ├── deps.py # Dependency injection (DB session, current user) │ │ ├── transactions.py # POST /transactions/ingest, GET /transactions/{id} │ │ ├── alerts.py # GET /alerts, GET /alerts/{id}, POST /alerts/{id}/decide │ │ ├── rules.py # CRUD + activate/deactivate + test │ │ ├── dashboard.py # GET /dashboard/metrics, GET /dashboard/report │ │ └── health.py # GET /health │ ├── services/ │ │ ├── __init__.py │ │ ├── ingestion.py # Transaction ingestion + queue dispatch │ │ ├── detection.py # Orchestrate rule evaluation pipeline │ │ ├── alerts.py # Alert creation, assignment, decision │ │ ├── rules.py # Rule CRUD, activation, snapshot │ │ └── dashboard.py # Metrics aggregation from DB + Redis │ └── seed.py # Development data seeder ├── alembic/ │ ├── env.py │ └── versions/ ├── tests/ │ ├── conftest.py # Fixtures: test DB, test client, auth tokens │ ├── unit/ │ │ ├── test_evaluator.py │ │ ├── test_explainer.py │ │ └── test_rules/ │ │ ├── test_amount.py │ │ ├── test_location.py │ │ └── test_time.py │ ├── integration/ │ │ ├── test_ingestion_pipeline.py │ │ ├── test_alert_workflow.py │ │ └── test_rule_lifecycle.py │ └── contract/ │ ├── test_transactions_api.py │ ├── test_alerts_api.py │ └── test_rules_api.py ├── pyproject.toml └── Dockerfile frontend/ ├── src/ │ ├── api/ │ │ └── client.ts # Generated OpenAPI client │ ├── components/ │ │ ├── layout/ │ │ │ ├── Shell.tsx │ │ │ └── Navbar.tsx │ │ ├── alerts/ │ │ │ ├── AlertQueue.tsx │ │ │ ├── AlertCard.tsx │ │ │ └── AlertDetail.tsx │ │ ├── rules/ │ │ │ ├── RuleList.tsx │ │ │ ├── RuleForm.tsx │ │ │ └── RuleTestResults.tsx │ │ └── dashboard/ │ │ ├── MetricCard.tsx │ │ ├── AlertsByHour.tsx │ │ ├── TopRules.tsx │ │ └── ScoreDistribution.tsx │ ├── pages/ │ │ ├── LoginPage.tsx │ │ ├── AlertsPage.tsx │ │ ├── RulesPage.tsx │ │ └── DashboardPage.tsx │ ├── hooks/ │ │ ├── useAuth.ts │ │ ├── useAlerts.ts │ │ └── useDashboard.ts │ ├── contexts/ │ │ └── AuthContext.tsx │ ├── lib/ │ │ └── utils.ts │ ├── App.tsx │ └── main.tsx ├── tests/ │ ├── components/ │ └── pages/ ├── package.json ├── tsconfig.json ├── tailwind.config.ts └── vite.config.ts docker-compose.yml AGENTS.md ``` **Structure Decision**: Web application with separate `backend/` and `frontend/` directories. Backend is a single FastAPI service (monolith per YAGNI principle). Frontend is a Vite + React SPA. ## Complexity Tracking > No constitutional violations to justify. All gates passed.