Saltearse al contenido

C4 Arquitectura Descripción General

Introducción

Este documento proporciona una descripción general completa de la arquitectura de la Plataforma Algesta utilizando el modelo C4 (Context, Containers, Components, Code). El modelo C4 proporciona un conjunto jerárquico de diagramas de arquitectura para diferentes audiencias:

  • Nivel 1 - Contexto del Sistema: Vista de alto nivel para stakeholders no técnicos
  • Nivel 2 - Contenedores: Descripción general técnica para arquitectos y líderes técnicos
  • Nivel 3 - Componentes: Desglose detallado de componentes para desarrolladores
  • Nivel 4 - Código: Detalles de implementación (no incluidos en esta documentación)

La Plataforma Algesta es una arquitectura de microservicios basada en NestJS diseñada para gestionar órdenes de mantenimiento, marketplace de proveedores y notificaciones multicanal para servicios de mantenimiento de edificios.


Tabla de Contenidos

  1. Descripción General de la Arquitectura
  2. Diagrama de Contexto del Sistema
  3. Diagrama de Contenedores
  4. Diagramas de Componentes
  5. Arquitectura de Despliegue
  6. Diagramas de Flujo de Datos
  7. Registros de Decisiones Arquitectónicas
  8. Stack Tecnológico
  9. Patrones Arquitectónicos
  10. Aspectos Transversales

Descripción General de la Arquitectura

Principios Arquitectónicos Clave

La Plataforma Algesta está construida sobre los siguientes principios:

  1. Arquitectura de Microservicios: Servicios independientes y desplegables con límites claros
  2. Clean Architecture con CQRS: Separación de responsabilidades con segregación de comandos/consultas
  3. Comunicación Basada en Eventos: Mensajería asíncrona entre servicios vía Redis/Kafka
  4. Diseño Dirigido por Dominio: Lógica de negocio organizada alrededor de contextos delimitados
  5. Patrón API Gateway: Punto de entrada único para todas las solicitudes del cliente
  6. Bulletproof React: Organización frontend basada en características con caché de estado del servidor

Resumen del Stack Tecnológico

LayerTechnologies
FrontendReact 19, Vite, TypeScript, TanStack Query, Zustand, shadcn/ui
API GatewayNestJS 11, TypeScript, JWT, Redis/Kafka
MicroserviciosNestJS 11, TypeScript, MongoDB, Mongoose, CQRS
MessagingRedis or Kafka
Data StorageMongoDB Atlas, Azure Blob Storage
External IntegrationsSendGrid, Jelou, Asana, DocuSign, Qsystems
CI/CDAzure Pipelines, Docker, Azure Container Registry
HostingAzure (Container Instances or AKS)

Diagrama de Contexto del Sistema

El diagrama de contexto del sistema muestra cómo la Plataforma Algesta encaja en su entorno, incluyendo usuarios y sistemas externos.

graph TB
Cliente["Cliente de Algesta<br/>[Persona]<br/>Usuario final que solicita servicios de mantenimiento"]
AlgestaTeam["Equipo Algesta<br/>[Persona]<br/>Equipo interno que gestiona órdenes y proveedores"]
Tecnico["Técnico Externo<br/>[Persona]<br/>Proveedor externo que participa en órdenes"]

Plataforma["Plataforma Algesta<br/>[Sistema de Software]<br/>Plataforma de gestión de mantenimiento y marketplace"]

Jelou["Jelou WhatsApp<br/>[Sistema Externo]<br/>Bot de WhatsApp para captura de órdenes"]
SendGrid["SendGrid<br/>[Sistema Externo]<br/>Servicio de entrega de correos electrónicos"]
Asana["Asana<br/>[Sistema Externo]<br/>Gestión interna de tareas"]
DocuSign["DocuSign<br/>[Sistema Externo]<br/>Servicio de firma digital"]
Qsystems["Qsystems<br/>[Sistema Externo]<br/>Sistema de cliente empresarial"]
SistemaActivos["Sistema de Activos<br/>[Sistema Externo]<br/>Gestión de activos legado"]

Cliente -->|"Envía solicitudes de servicio vía WhatsApp"| Jelou
Jelou -->|"Reenvía solicitudes estructuradas"| Plataforma
Cliente -->|"Visualiza estado de órdenes"| Plataforma
Tecnico -->|"Gestiona ofertas y asignaciones"| Plataforma
AlgestaTeam -->|"Gestiona órdenes y curación"| Plataforma

Plataforma -->|"Crea/actualiza tareas"| Asana
Plataforma -->|"Solicita firmas digitales"| DocuSign
Plataforma -->|"Sincroniza datos empresariales"| Qsystems
Plataforma -->|"Consulta detalles de activos"| SistemaActivos
Plataforma -->|"Envía notificaciones por email"| SendGrid
Plataforma -->|"Envía mensajes de WhatsApp"| Jelou

style Cliente fill:#08427b,stroke:#052e56,color:#ffffff
style AlgestaTeam fill:#08427b,stroke:#052e56,color:#ffffff
style Tecnico fill:#08427b,stroke:#052e56,color:#ffffff
style Plataforma fill:#1168bd,stroke:#0b4884,color:#ffffff
style Jelou fill:#999999,stroke:#6b6b6b,color:#ffffff
style SendGrid fill:#999999,stroke:#6b6b6b,color:#ffffff
style Asana fill:#999999,stroke:#6b6b6b,color:#ffffff
style DocuSign fill:#999999,stroke:#6b6b6b,color:#ffffff
style Qsystems fill:#999999,stroke:#6b6b6b,color:#ffffff
style SistemaActivos fill:#999999,stroke:#6b6b6b,color:#ffffff

Figura: C4 Nivel 1: Diagrama de Contexto del Sistema - Vista de alto nivel de la Plataforma Algesta mostrando actores externos (clientes, equipo, proveedores) y sistemas externos (Jelou, SendGrid, Asana, etc.)

Actores

  • Cliente de Algesta: Usuarios finales (gerentes de edificios, administradores de instalaciones) que solicitan servicios de mantenimiento vía WhatsApp
  • Equipo Algesta: Equipo interno (agentes, administradores) que gestiona órdenes, curan proveedores y supervisan operaciones
  • Técnico Externo: Proveedores externos que participan en órdenes en el marketplace y realizan trabajos de mantenimiento

Sistemas Externos

  • Jelou WhatsApp: Plataforma de bot de WhatsApp para captura conversacional de órdenes y notificaciones
  • SendGrid: Servicio de entrega de correos electrónicos para emails transaccionales (confirmaciones, cotizaciones, informes)
  • Asana: Sistema interno de gestión de tareas para coordinación operativa
  • DocuSign: Servicio de firma digital para contratos y documentos legales (integración futura)
  • Qsystems: Sistema de gestión de clientes empresariales para clientes grandes (integración futura)
  • Sistema de Activos: Sistema legado de gestión de activos con datos históricos

Container Diagram

The Container diagram shows the high-level technical building blocks of the Algesta Platform.

For the full Container diagram, see: Full Container diagram (see project Repositorio Structurizr workspace)

Containers

Frontend:

  • React Dashboard (React 19, Vite, TypeScript): Web application for all user types with Bulletproof React Arquitectura

Backend:

  • API Gateway (NestJS 11): Single entry point with JWT authentication, routing, and circuit breaker
  • Orders Microservicio (NestJS 11, CQRS): Order lifecycle management, asset history, quotations
  • Provider Microservicio (NestJS 11, CQRS): Provider management, auctions, Document validation
  • Notifications Microservicio (NestJS 11): Multi-channel notification orchestration (email, WhatsApp)

Data:

  • Orders Base de datos (MongoDB): Orders, clients, assets, quotations
  • Provider Base de datos (MongoDB): Providers, auctions, Documentos, offers
  • Notifications Base de datos (MongoDB): Notification history and templates
  • Blob Storage (Azure): Documentos, photos, PDF reports

Messaging:

  • Message Broker (Redis/Kafka): Event-driven inter-service communication

Communication Patterns

  • Frontend ↔ API Gateway: HTTP/REST over HTTPS
  • API Gateway ↔ Microservicios: Redis/Kafka MessagePattern (request/response + pub/sub)
  • Microservicios ↔ databases: Mongoose ODM
  • Microservicios ↔ Message Broker: Pub/Sub events
  • Microservicios ↔ Blob Storage: Azure SDK
  • Notifications MS ↔ External Services: HTTP REST APIs

Componente Diagrams

Componente diagrams show the internal structure of each Microservicio.

Orders Microservicio Componentes

Layers:

  • Application Layer: Controllers, Command Handlers (Create, Update, Publish, etc.), Query Handlers, Event Handlers
  • Domain Layer: Order Entity, Asset Entity, OrderItem VO, Quotation VO, Repositorio Interfaces
  • Infrastructure Layer: Repositorio Implementacións (Mongoose), External Services (Asana, DocuSign, Qsystems, Assets), Message Broker, PDF Generation

Key Componentes:

  • CreateOrderHandler, UpdateOrderHandler, PublishOrderHandler
  • GetOrderByIdHandler, GetAllOrdersHandler
  • OrderCreatedEventHandler, ProviderSelectedEventHandler
  • AsanaIntegrationService, DocuSignIntegrationService

Full details: Componente-orders-Microservicio.md

Provider Microservicio Componentes

Layers:

  • Application Layer: ProviderController, AuctionController, Command Handlers, Query Handlers, Event Handlers, Scheduled Tasks
  • Domain Layer: Provider Entity, Auction Entity, AuctionOffer VO, ProviderDocumento VO, Repositorio Interfaces
  • Infrastructure Layer: Repositorio Implementacións, Azure Blob Storage Service, Documento Validation, PDF Generation

Key Componentes:

  • CreateProviderHandler, UploadDocumentoHandler, UpdateDocumentoEstadoHandler
  • PublishAuctionHandler, SubmitOfferHandler, SelectWinnerHandler
  • DocumentoExpiryCheckTask (scheduled daily)

Full details: Componente-provider-Microservicio.md

Notifications Microservicio Componentes

Layers:

  • Application Layer: NotificationController, Command Handlers (SendEmail, SendWhatsApp, SendPush), Query Handlers, Event Handlers, Scheduled Tasks
  • Domain Layer: Notification Entity, NotificationTemplate VO, Repositorio Interfaces
  • Infrastructure Layer: Repositorio Implementación, SendGrid Service, WhatsApp Service, Template Rendering

Key Componentes:

  • SendEmailHandler, SendWhatsAppHandler
  • OrderCreatedEventHandler, AuctionClosedEventHandler, QuotationSentEventHandler
  • NotificationRetryTask (scheduled hourly)

Full details: Componente-notifications-Microservicio.md


Despliegue Arquitectura

The platform is deployed using Docker containers on Azure infrastructure.

Despliegue Strategy

  • Containerization: All services packaged as Docker containers
  • CI/CD: Azure Pipelines for automated build, test, and Despliegue
  • Container Registry: Azure Container Registry for image storage
  • Hosting: Azure Container Instances or Azure Kubernetes Service (AKS)
  • Database: MongoDB Atlas (managed) or self-hosted MongoDB
  • Message Broker: Azure Redis Cache or Kafka cluster

Environments

Development: Local Docker Compose with MongoDB, Redis, and all Microservicios

Staging: Azure test environment with shared MongoDB Atlas, Azure Redis Cache

Production: Azure production with dedicated MongoDB cluster, Redis/Kafka cluster, multiple replicas for HA

Full details: Despliegue-Arquitectura.md


Data Flow Diagrams

Data flow diagrams illustrate the end-to-end flow for critical business processes.

Critical Business Processes

  1. Order Creation via WhatsAppdataflow-order-creation.md

    • Client sends WhatsApp message → Jelou bot → GPT-4 classification → OCR for serial → Order created → Notifications sent
  2. Provider Onboardingdataflow-all-processes.md

    • Provider registers → Uploads Documentos → Agent validates → Provider activated
  3. Auction/Marketplacedataflow-all-processes.md

    • Agent publishes order → Providers notified → Submit offers → Agent selects winner
  4. Quotation Approvaldataflow-all-processes.md

    • Agent breaks down order → Provider quotes items → Agent adjusts → Client approves
  5. Order Execution and Closuredataflow-all-processes.md

    • Provider confirms date → Executes work → Submits report → Client final approval
  6. Asset Managementdataflow-all-processes.md

    • Photo OCR → Query/create asset → Link to order → Update history
  7. Documento Expiry Managementdataflow-all-processes.md

    • Upload Documento → Schedule expiry checks → Send reminders → Suspend if expired

Arquitectura Decision Records

ADRs Documento key architectural decisions and their rationale.

Key Decisions

ADR #DecisionRationale
ADR-001NestJS over Azure FunctionsBetter TypeScript support, CQRS built-in, easier Pruebas
ADR-002MongoDB over CosmosDBLower cost, better Mongoose integration, flexible schema
ADR-003Redis/Kafka over Azure Event GridBetter NestJS integration, flexible messaging patterns
ADR-004React 19 over Flutter WebLarger ecosystem, better web performance, team expertise
ADR-005Photo + OCR over QR CodesNo operational cost, works with existing assets
ADR-006Item-Based Quotation over GlobalClient transparency, accounting accuracy, traceability
ADR-007New Asset History over Legacy IntegrationFaster development, simpler data model, focused scope
ADR-008WhatsApp over Native Mobile AppHigh adoption, no installation, lower development cost
ADR-009CQRS PatternClear separation, better scalability, audit trail
ADR-010Clean ArchitectureTestability, maintainability, Tecnología independence

Full details: Arquitectura-decision-records.md


Stack Tecnológico

Frontend Stack

TechnologyVersionPurpose
React19.xUI framework
Vite6.xBuild tool and dev server
TypeScript5.xType safety
TanStack Query5.xServer state caching
Zustand5.xClient state management
shadcn/uiLatestComponente library
React Router7.xRouting
Axios1.xHTTP client

Backend Stack

TechnologyVersionPurpose
NestJS11.xFramework
TypeScript5.xLanguage
Mongoose8.xMongoDB ODM
@nestjs/cqrs11.xCQRS Implementación
@nestjs/Microservicios11.xMessaging
class-validator0.14.xValidation
Puppeteer23.xPDF generation
@azure/storage-blob12.xBlob storage
@sendgrid/mail8.xEmail delivery
Handlebars4.xTemplate rendering

Infrastructure Stack

TechnologyPurpose
MongoDBDocumento Base de datos
Redis/KafkaMessage broker
Azure Blob StorageFile storage
DockerContainerization
Azure PipelinesCI/CD
Azure Container RegistryImage storage
Azure Container Instances/AKSHosting

Architectural Patterns

Clean Architecture

┌─────────────────────────────────────┐
│ Infrastructure Layer │ ← Frameworks, Databases, External APIs
├─────────────────────────────────────┤
│ Application Layer │ ← Use Cases (Command/Query Handlers)
├─────────────────────────────────────┤
│ Domain Layer │ ← Business Logic, Entities, Value Objects
└─────────────────────────────────────┘

Benefits:

  • Business logic independent of frameworks
  • Easy to test (unit Pruebas for domain)
  • Tecnología can be swapped without changing domain

CQRS Pattern

Command (Write) Query (Read)
↓ ↓
Command Handler Query Handler
↓ ↓
Domain Read Model
↓ ↓
Repository Repository
↓ ↓
Database Database

Benefits:

  • Separate optimization for reads and writes
  • Clear separation of concerns
  • Better scalability
  • Natural audit trail through events

Event-Driven Arquitectura

Microservice A → Event Published → Message Broker → Event Consumed → Microservice B

Benefits:

  • Loose coupling between services
  • Asynchronous processing
  • Scalability
  • Eventual consistency

Cross-Cutting Concerns

Authentication and Authorization

  • JWT Tokens: API Gateway validates JWT tokens for all requests
  • RBAC: Role-based access control (CLIENT, PROVIDER, AGENT, ADMIN)
  • Token Refresh: Refresh tokens for long sessions
  • Password Hashing: bcrypt for secure password storage

Logging and Monitoring

  • Winston Logger: Structured JSON logs
  • Azure Log Analytics: Centralized log aggregation
  • Application Insights: Performance monitoring
  • Correlation IDs: Request tracing across services

Error Handling

  • Global Exception Filters: Catch all exceptions in NestJS
  • Custom Exception Classes: BusinessException, ValidationException, etc.
  • Error Codes: Standardized error codes for client handling
  • Retry Policies: Exponential backoff for transient failures

Validation

  • class-validator: DTO validation with decorators
  • Custom Validators: Domain-specific validation rules
  • Schema Validation: MongoDB schema validation

Health Checks

  • Endpoints: /health on all Microservicios
  • Liveness Probes: Container orchestration health checks
  • Readiness Probes: Check Base de datos and message broker connectivity

Correlation and Tracing

  • Request IDs: UUID for each request
  • Propagation: Pass request ID through all service calls
  • Logging: Include request ID in all log entries

Scalability and Performance

Horizontal Scaling

  • Stateless Services: All Microservicios are stateless, can be scaled horizontally
  • Load Balancing: Azure Load Balancer distributes traffic
  • Auto-Scaling: Based on CPU/memory Métricas

Base de datos Performance

  • Indexing: Indexes on frequently queried fields
  • Read Replicas: MongoDB replica sets for read scaling
  • Caching: Redis cache for frequently accessed data (future)

Asynchronous Processing

  • Message Broker: Offload heavy processing to background tasks
  • Event-Driven: Non-blocking event publishing
  • Scheduled Tasks: Background jobs for cleanup, reminders, retries

Security Considerations

  • HTTPS/TLS: All traffic encrypted
  • JWT Validation: Every request validated at gateway
  • Input Validation: All DTOs validated
  • SQL Injection Prevention: Mongoose prevents NoSQL injection
  • File Upload Validation: File type, size, virus scanning
  • Secrets Management: Azure Key Vault or Kubernetes Secrets
  • CORS: Configured allowed origins
  • Rate Limiting: Prevent abuse (future Implementación)

Future Enhancements

Based on backlog analysis and ADRs:

  1. API Versioning: /v1/, /v2/ for backward compatibility
  2. GraphQL API: Alternative to REST for complex queries
  3. Caching Layer: Redis caching for read-heavy Operaciones
  4. Distributed Tracing: OpenTelemetry or Jaeger for request tracing
  5. Métricas Collection: Prometheus for detailed Métricas
  6. Native Mobile App: If WhatsApp limitations become problematic
  7. Full Event Sourcing: Completo event history for audit

References

Arquitectura Documentoation

Componente Diagrams

Despliegue and Operaciones

Data Flow Diagrams

Sprint Documentoation

  • Sprint 1-8 - see docs/Sprint_[1-8].md in project Repositorio
  • Completo Backlog Analysis - see docs/Completo_backlog_analysis.md in project Repositorio

Implementación Files

  • Package.json files in each Repositorio
  • Dockerfile and docker-compose.yml files
  • azure-pipelines.yml files

Appendix: Diagram Legend

Mermaid Color Coding

  • Blue (#438dd5): Frontend containers and Microservicios
  • Dark Blue (#1168bd): API Gateway
  • Red (#ff6b6b): databases
  • Yellow (#feca57): Blob Storage
  • Cyan (#48dbfb): Message Broker
  • Gray (#999999): External Systems
  • Green (#6bcf7f): Domain Entities

Arrow Types

  • Solid Arrow (→): Synchronous communication (HTTP, direct Método call)
  • Dashed Arrow (⇢): Asynchronous communication (events, messages)