Skip to content

Latest commit

 

History

History
329 lines (264 loc) · 9 KB

PASO_4_COMPLETADO.md

File metadata and controls

329 lines (264 loc) · 9 KB

PASO 4 - COMPLETADO ?

Módulo de Pagos - Implementación Clean Architecture

? Arquitectura Implementada

Modules.Payments/
??? Domain/                                      ? CORE (sin dependencias)
?   ??? Entities/
?   ?   ??? Payment.cs
?   ??? (Events y Exceptions pendientes)
?
??? Application/                                 ? PUERTOS (interfaces)
?   ??? Contracts/
?   ?   ??? Persistence/
?   ?   ?   ??? IPaymentRepository.cs           ? Interface definida aquí
?   ?   ??? Infrastructure/
?   ?       ??? IKafkaMessagePublisher.cs       ? Interface definida aquí
?   ??? CreatePayment/
?   ?   ??? CreatePaymentCommand.cs
?   ?   ??? CreatePaymentCommandValidator.cs
?   ?   ??? CreatePaymentCommandHandler.cs
?   ??? GetPaymentById/
?   ?   ??? GetPaymentByIdQuery.cs
?   ?   ??? GetPaymentByIdQueryHandler.cs
?   ??? UpdatePaymentStatus/
?       ??? UpdatePaymentStatusCommand.cs
?       ??? UpdatePaymentStatusCommandHandler.cs
?
??? Infrastructure/                              ? CONFIGURACIÓN EF
?   ??? Persistence/
?       ??? PaymentEntityConfiguration.cs
?
??? Presentation/                                ? API CONTROLLERS
?   ??? DTOs/
?   ?   ??? CreatePaymentRequest.cs
?   ?   ??? PaymentResponse.cs
?   ?   ??? PaymentStatusResponse.cs
?   ??? PaymentsController.cs
?
??? PaymentsModule.cs                           ? MODULE INITIALIZER

? Implementaciones en Infrastructure (ADAPTADORES)

Infrastructure/
??? Repositories/
?   ??? PaymentRepository.cs                     ? Implementa IPaymentRepository
??? Adapters/
?   ??? KafkaMessagePublisherAdapter.cs         ? Implementa IKafkaMessagePublisher
??? Consumers/
    ??? RiskEvaluationResponseConsumer.cs       ? Consumer de Kafka

Flujo de Dependencias (Clean Architecture)

???????????????????????????????????????????????????
?  Presentation Layer (Controllers)               ?
?  - Depende de: Application                      ?
???????????????????????????????????????????????????
                   ?
???????????????????????????????????????????????????
?  Application Layer (Handlers, Commands)         ?
?  - Define interfaces (IPaymentRepository)       ?
?  - NO depende de Infrastructure                 ?
?  - Depende de: Domain, Shared                   ?
???????????????????????????????????????????????????
                   ?
???????????????????????????????????????????????????
?  Domain Layer (Entities)                        ?
?  - NO tiene dependencias                        ?
?  - Core puro del negocio                        ?
???????????????????????????????????????????????????

???????????????????????????????????????????????????
?  Infrastructure Layer (Repositories, Adapters)  ?
?  - Implementa interfaces de Application         ?
?  - Depende de: Application, Domain              ?
?  - Tiene acceso a EF, Kafka, etc.               ?
???????????????????????????????????????????????????

? Dependency Inversion Principle aplicado correctamente


Archivos Creados por Capa

Domain Layer ?

  • Domain/Entities/Payment.cs - Entidad principal

Application Layer ?

  • Application/Contracts/Persistence/IPaymentRepository.cs - Puerto
  • Application/Contracts/Infrastructure/IKafkaMessagePublisher.cs - Puerto
  • Application/CreatePayment/ - 3 archivos (Command, Validator, Handler)
  • Application/GetPaymentById/ - 2 archivos (Query, Handler)
  • Application/UpdatePaymentStatus/ - 2 archivos (Command, Handler)

Presentation Layer ?

  • Presentation/DTOs/ - 3 archivos (Request, Response, StatusResponse)
  • Presentation/PaymentsController.cs - API Controller

Infrastructure Configuration ?

  • Infrastructure/Persistence/PaymentEntityConfiguration.cs - EF Configuration

Module ?

  • PaymentsModule.cs - IModuleInitializer

Adaptadores en Infrastructure Project ?

Repositories (Persistence)

// Infrastructure/Repositories/PaymentRepository.cs
public class PaymentRepository : IPaymentRepository  // ? Implementa interface del módulo
{
    private readonly ApplicationDbContext _context;
    // Implementación con EF Core
}

Adapters (Infrastructure)

// Infrastructure/Adapters/KafkaMessagePublisherAdapter.cs
public class KafkaMessagePublisherAdapter : IKafkaMessagePublisher  // ? Implementa interface del módulo
{
    private readonly IKafkaProducer _kafkaProducer;
    // Adapta la llamada al KafkaProducer real
}

Consumers (Background Services)

// Infrastructure/Consumers/RiskEvaluationResponseConsumer.cs
public class RiskEvaluationResponseConsumer : KafkaConsumerBase<RiskEvaluationResponseMessage>
{
    // Escucha respuestas de evaluación de riesgo
    // Actualiza Payment.Status en la base de datos
}

Registro de Dependencias (Pendiente en API)

El registro se hará en el Program.cs del proyecto API:

// Registrar Infrastructure (Adaptadores)
services.AddScoped<IPaymentRepository, PaymentRepository>();
services.AddScoped<IKafkaMessagePublisher, KafkaMessagePublisherAdapter>();

// Registrar Consumer
services.AddSingleton<RiskEvaluationResponseConsumer>();

// Registrar Módulos
services.AddScoped<IModuleInitializer, PaymentsModule>();
// Ejecutar ConfigureServices de cada módulo

Paquetes NuGet Instalados ?

Módulo de Payments

<PackageReference Include="FluentValidation" Version="12.1.1" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="12.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="8.0.11" />

Validaciones con FluentValidation ?

public class CreatePaymentCommandValidator : AbstractValidator<CreatePaymentCommand>
{
    public CreatePaymentCommandValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.ServiceProviderId).NotEmpty();
        RuleFor(x => x.PaymentMethodId).GreaterThan(0);
        RuleFor(x => x.Amount)
            .GreaterThan(0)
            .LessThanOrEqualTo(10000);
    }
}

Endpoints del Controller ?

POST /api/payments

  • Request: CreatePaymentRequest
  • Validaciones: FluentValidation
  • Proceso:
    1. Valida request
    2. Genera externalOperationId
    3. Crea Payment con status "Evaluating"
    4. Publica mensaje a Kafka
  • Response: 201 Created con PaymentResponse

GET /api/payments/{externalOperationId}

  • Request: GUID en ruta
  • Proceso:
    1. Busca Payment por externalOperationId
    2. Retorna información completa
  • Response: 200 OK con PaymentStatusResponse

Manejo de Errores ?

Patrón Result

var result = await _handler.HandleAsync(command, cancellationToken);
if (result.IsFailure)
{
    return StatusCode(500, new ProblemDetails { Detail = result.Error });
}

Validaciones

if (!validationResult.IsValid)
{
    return BadRequest(new ProblemDetails 
    { 
        Detail = string.Join("; ", validationResult.Errors) 
    });
}

Consumer de Kafka ?

public class RiskEvaluationResponseConsumer : KafkaConsumerBase<RiskEvaluationResponseMessage>
{
    protected override async Task ProcessMessageAsync(
        RiskEvaluationResponseMessage message,
        CancellationToken cancellationToken)
    {
        // 1. Buscar Payment por ExternalOperationId
        // 2. Actualizar Status (Accepted/Denied)
        // 3. Actualizar UpdatedAt
        // 4. SaveChanges
    }
}

Principios SOLID Aplicados ?

  1. S - Single Responsibility

    • Cada handler tiene una única responsabilidad
    • Controllers solo coordinan
  2. O - Open/Closed

    • Extensible mediante nuevos Commands/Queries
    • Cerrado para modificación
  3. L - Liskov Substitution

    • Interfaces claramente definidas
    • Implementaciones intercambiables
  4. I - Interface Segregation

    • Interfaces pequeñas y específicas
    • IPaymentRepository, IKafkaMessagePublisher
  5. D - Dependency Inversion

    • Application define interfaces (puertos)
    • Infrastructure implementa (adaptadores)
    • NO hay dependencia de Application ? Infrastructure

Patrones Implementados ?

  1. ? Clean Architecture (Capas bien definidas)
  2. ? Ports & Adapters (Hexagonal)
  3. ? CQRS (Commands y Queries separados)
  4. ? Repository Pattern
  5. ? Unit of Work Pattern
  6. ? Result Pattern (Manejo funcional de errores)
  7. ? Validator Pattern (FluentValidation)
  8. ? Module Pattern (IModuleInitializer)
  9. ? Adapter Pattern (KafkaMessagePublisherAdapter)
  10. ? Consumer Pattern (KafkaConsumerBase)

Compilación ?

dotnet build

Resultado: ? Build succeeded in 1.9s

Sin errores ?
Sin warnings ?


Próximos Pasos

  1. Registrar servicios en Program.cs del API
  2. Probar endpoints con Swagger
  3. Implementar módulo de RiskEvaluation (PASO 5)

Fecha de completación: 2025-12-29
Estado: ? COMPLETADO
Clean Architecture: ? 100% Respetada
Líneas de código: ~1,200 líneas
Archivos creados: 17 archivos en el módulo + 2 adaptadores