Skip to content

yasmim-passos/java-payment-processor

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

💳 Payment Processor - Event Sourcing & CQRS

Sistema enterprise de processamento de pagamentos implementando Event Sourcing, CQRS e Saga Pattern com Spring Boot.

Java Spring Boot Maven Docker


🎯 Arquitetura e Patterns

Event Sourcing

  • Todos os eventos de domínio são armazenados no Event Store
  • Estado do agregado é reconstruído a partir do histórico de eventos
  • Auditoria completa e time-travel debugging

CQRS (Command Query Responsibility Segregation)

  • Commands: PaymentCommandService - Operações de escrita
  • Queries: PaymentQueryService - Operações de leitura
  • Separação clara entre modelos de escrita e leitura

Saga Pattern

  • Orquestração de transações distribuídas
  • Fluxo de pagamento: Create → Validate → Authorize → Capture → Complete
  • Compensating transactions em caso de falha

DDD (Domain-Driven Design)

  • Aggregate Root: Payment
  • Domain Events: PaymentCreatedEvent, PaymentAuthorizedEvent, etc.
  • Value Objects e Entities bem definidos

🏗️ Estrutura do Projeto

payment-processor/
├── src/main/java/com/portfolio/payment/
│   ├── domain/                    # Domain Layer (DDD)
│   │   ├── Payment.java           # Aggregate Root
│   │   ├── PaymentStatus.java     # Value Object
│   │   └── events/                # Domain Events
│   │       ├── DomainEvent.java
│   │       └── PaymentEvents.java
│   │
│   ├── application/               # Application Layer (Use Cases)
│   │   ├── commands/              # CQRS Commands
│   │   ├── dto/                   # Data Transfer Objects
│   │   └── services/
│   │       ├── PaymentCommandService.java
│   │       └── PaymentQueryService.java
│   │
│   ├── infrastructure/            # Infrastructure Layer
│   │   ├── eventstore/
│   │   │   └── EventStore.java    # Event Store Implementation
│   │   └── persistence/
│   │       ├── EventStoreEntity.java
│   │       └── EventStoreRepository.java
│   │
│   ├── api/                       # Presentation Layer
│   │   ├── PaymentController.java # REST API
│   │   └── GlobalExceptionHandler.java
│   │
│   └── PaymentProcessorApplication.java
│
├── src/test/java/                # Tests
│   ├── domain/
│   │   └── PaymentTest.java      # Unit Tests
│   └── api/
│       └── PaymentControllerIntegrationTest.java
│
├── pom.xml                        # Maven Dependencies
├── Dockerfile                     # Docker Image
├── docker-compose.yml             # Orchestration
└── README.md

🚀 Tecnologias

Categoria Tecnologia
Framework Spring Boot 3.2
Language Java 17
Build Tool Maven
ORM Spring Data JPA / Hibernate
Database H2 (in-memory)
Validation Jakarta Validation
Documentation SpringDoc OpenAPI (Swagger)
Utilities Lombok, Apache Commons
Testing JUnit 5, Mockito, AssertJ
Containerization Docker

📋 Pré-requisitos

  • Java 17+
  • Maven 3.9+
  • Docker (opcional)

🔧 Como Executar

Opção 1: Maven (Local)

# Compilar o projeto
mvn clean install

# Executar a aplicação
mvn spring-boot:run

# Executar testes
mvn test

Opção 2: Docker

# Build e executar
docker-compose up --build

# Parar
docker-compose down

Opção 3: JAR

# Build
mvn clean package

# Executar
java -jar target/payment-processor-1.0.0.jar

📚 Endpoints da API

Base URL: http://localhost:8080/api/v1

Criar Pagamento (Command)

POST /payments
Content-Type: application/json

{
  "customerId": "CUST-123",
  "amount": 100.00,
  "currency": "USD",
  "description": "Payment for order #456"
}

Resposta:

{
  "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "customerId": "CUST-123",
  "amount": 100.00,
  "currency": "USD",
  "description": "Payment for order #456",
  "status": "PENDING",
  "version": 0
}

Processar Pagamento (Saga)

POST /payments/{paymentId}/process

Executa o fluxo completo:

  1. Valida
  2. Autoriza
  3. Captura
  4. Completa

Consultar Pagamento (Query)

GET /payments/{paymentId}

Histórico de Eventos (Event Sourcing)

GET /payments/{paymentId}/history

Resposta:

{
  "paymentId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "currentStatus": "COMPLETED",
  "events": [
    {
      "eventId": "evt-001",
      "eventType": "PaymentCreated",
      "version": 0,
      "occurredAt": "2024-01-20T10:00:00Z",
      "payload": "{...}"
    },
    {
      "eventType": "PaymentValidated",
      "version": 1
    },
    ...
  ]
}

Estornar Pagamento

POST /payments/{paymentId}/refund

{
  "refundAmount": 50.00,
  "reason": "Customer request"
}

Todos os Eventos (Event Store)

GET /payments/events

📖 Documentação Swagger

Acesse após iniciar a aplicação:


🧪 Testes

Executar todos os testes

mvn test

Testes com cobertura

mvn test jacoco:report

Testes incluídos:

  • Unit Tests: Testes de domínio (Aggregate)
  • Integration Tests: Testes de API (Controllers)
  • Event Sourcing Tests: Reconstrução de estado

🎨 Fluxo de Pagamento

PENDING → VALIDATED → AUTHORIZED → CAPTURED → COMPLETED
                                                    ↓
                                                REFUNDED

         (qualquer etapa pode ir para) → FAILED

💡 Conceitos Demonstrados

Design Patterns

Event Sourcing - Histórico completo de eventos
CQRS - Separação de Commands e Queries
Saga Pattern - Orquestração de transações
Domain-Driven Design - Aggregates, Entities, Value Objects
Repository Pattern - Abstração de persistência

Princípios SOLID

✅ Single Responsibility
✅ Open/Closed
✅ Liskov Substitution
✅ Interface Segregation
✅ Dependency Inversion

Enterprise Patterns

✅ Layered Architecture
✅ Aggregate Root
✅ Domain Events
✅ Event Store
✅ Eventual Consistency


🔍 Event Sourcing em Detalhes

Como funciona?

  1. Commands alteram o estado criando Domain Events
  2. Events são persistidos no Event Store
  3. Estado atual é reconstruído a partir dos eventos
  4. Time-travel: Podemos ver o estado em qualquer ponto no tempo

Vantagens

  • ✅ Auditoria completa
  • ✅ Debug temporal
  • ✅ Replay de eventos
  • ✅ Análise de comportamento
  • ✅ Event-driven architecture ready

🎯 Próximos Passos

  • Implementar projections (read models)
  • Adicionar snapshots para performance
  • Integração com Kafka/RabbitMQ
  • Implementar idempotência
  • Circuit Breaker para external services
  • API de compensação (undo)
  • Métricas e monitoring (Micrometer)

📊 Comparação: Biblioteca vs Payment Processor

Aspecto Biblioteca (Antigo) Payment Processor (Novo)
Arquitetura Simples 3-layer Event Sourcing + CQRS + DDD
Patterns Básicos Enterprise (10+ patterns)
Persistência Arquivo TXT Event Store (JPA)
Histórico Não tem Completo (Event Sourcing)
Testes Não tem Unit + Integration (JUnit 5)
API CLI REST (Spring Boot)
Docs Básico Swagger/OpenAPI
Docker Não Sim
Complexidade Júnior Pleno/Sênior

🤝 Para Recrutadores

Este projeto demonstra:

  1. Arquitetura Enterprise - Event Sourcing, CQRS, Saga
  2. Domain-Driven Design - Aggregates, Events, Bounded Contexts
  3. Spring Ecosystem - Boot, Data JPA, Web, Validation
  4. Testes Automatizados - TDD, Integration Tests
  5. Clean Code - SOLID, Design Patterns
  6. DevOps Ready - Docker, CI/CD ready

Nível: Pleno/Sênior
Tempo de desenvolvimento: 8-12 horas
Impacto no portfólio: ⭐⭐⭐⭐⭐


📝 Licença

MIT License


👤 Autor

Desenvolvido como projeto de portfólio demonstrando expertise em:

  • Java Enterprise
  • Spring Framework
  • Event-Driven Architecture
  • Domain-Driven Design
  • Microservices Patterns

About

Payment Processor com Event Sourcing, Spring Boot, Kafka/RabbitMQ e Docker

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors