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
- Descripción General de la Arquitectura
- Diagrama de Contexto del Sistema
- Diagrama de Contenedores
- Diagramas de Componentes
- Arquitectura de Despliegue
- Diagramas de Flujo de Datos
- Registros de Decisiones Arquitectónicas
- Stack Tecnológico
- Patrones Arquitectónicos
- Aspectos Transversales
Descripción General de la Arquitectura
Principios Arquitectónicos Clave
La Plataforma Algesta está construida sobre los siguientes principios:
- Arquitectura de Microservicios: Servicios independientes y desplegables con límites claros
- Clean Architecture con CQRS: Separación de responsabilidades con segregación de comandos/consultas
- Comunicación Basada en Eventos: Mensajería asíncrona entre servicios vía Redis/Kafka
- Diseño Dirigido por Dominio: Lógica de negocio organizada alrededor de contextos delimitados
- Patrón API Gateway: Punto de entrada único para todas las solicitudes del cliente
- Bulletproof React: Organización frontend basada en características con caché de estado del servidor
Resumen del Stack Tecnológico
| Layer | Technologies |
|---|---|
| Frontend | React 19, Vite, TypeScript, TanStack Query, Zustand, shadcn/ui |
| API Gateway | NestJS 11, TypeScript, JWT, Redis/Kafka |
| Microservicios | NestJS 11, TypeScript, MongoDB, Mongoose, CQRS |
| Messaging | Redis or Kafka |
| Data Storage | MongoDB Atlas, Azure Blob Storage |
| External Integrations | SendGrid, Jelou, Asana, DocuSign, Qsystems |
| CI/CD | Azure Pipelines, Docker, Azure Container Registry |
| Hosting | Azure (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
-
Order Creation via WhatsApp → dataflow-order-creation.md
- Client sends WhatsApp message → Jelou bot → GPT-4 classification → OCR for serial → Order created → Notifications sent
-
Provider Onboarding → dataflow-all-processes.md
- Provider registers → Uploads Documentos → Agent validates → Provider activated
-
Auction/Marketplace → dataflow-all-processes.md
- Agent publishes order → Providers notified → Submit offers → Agent selects winner
-
Quotation Approval → dataflow-all-processes.md
- Agent breaks down order → Provider quotes items → Agent adjusts → Client approves
-
Order Execution and Closure → dataflow-all-processes.md
- Provider confirms date → Executes work → Submits report → Client final approval
-
Asset Management → dataflow-all-processes.md
- Photo OCR → Query/create asset → Link to order → Update history
-
Documento Expiry Management → dataflow-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 # | Decision | Rationale |
|---|---|---|
| ADR-001 | NestJS over Azure Functions | Better TypeScript support, CQRS built-in, easier Pruebas |
| ADR-002 | MongoDB over CosmosDB | Lower cost, better Mongoose integration, flexible schema |
| ADR-003 | Redis/Kafka over Azure Event Grid | Better NestJS integration, flexible messaging patterns |
| ADR-004 | React 19 over Flutter Web | Larger ecosystem, better web performance, team expertise |
| ADR-005 | Photo + OCR over QR Codes | No operational cost, works with existing assets |
| ADR-006 | Item-Based Quotation over Global | Client transparency, accounting accuracy, traceability |
| ADR-007 | New Asset History over Legacy Integration | Faster development, simpler data model, focused scope |
| ADR-008 | WhatsApp over Native Mobile App | High adoption, no installation, lower development cost |
| ADR-009 | CQRS Pattern | Clear separation, better scalability, audit trail |
| ADR-010 | Clean Architecture | Testability, maintainability, Tecnología independence |
Full details: Arquitectura-decision-records.md
Stack Tecnológico
Frontend Stack
| Technology | Version | Purpose |
|---|---|---|
| React | 19.x | UI framework |
| Vite | 6.x | Build tool and dev server |
| TypeScript | 5.x | Type safety |
| TanStack Query | 5.x | Server state caching |
| Zustand | 5.x | Client state management |
| shadcn/ui | Latest | Componente library |
| React Router | 7.x | Routing |
| Axios | 1.x | HTTP client |
Backend Stack
| Technology | Version | Purpose |
|---|---|---|
| NestJS | 11.x | Framework |
| TypeScript | 5.x | Language |
| Mongoose | 8.x | MongoDB ODM |
| @nestjs/cqrs | 11.x | CQRS Implementación |
| @nestjs/Microservicios | 11.x | Messaging |
| class-validator | 0.14.x | Validation |
| Puppeteer | 23.x | PDF generation |
| @azure/storage-blob | 12.x | Blob storage |
| @sendgrid/mail | 8.x | Email delivery |
| Handlebars | 4.x | Template rendering |
Infrastructure Stack
| Technology | Purpose |
|---|---|
| MongoDB | Documento Base de datos |
| Redis/Kafka | Message broker |
| Azure Blob Storage | File storage |
| Docker | Containerization |
| Azure Pipelines | CI/CD |
| Azure Container Registry | Image storage |
| Azure Container Instances/AKS | Hosting |
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 DatabaseBenefits:
- 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 BBenefits:
- 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:
/healthon 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:
- API Versioning:
/v1/,/v2/for backward compatibility - GraphQL API: Alternative to REST for complex queries
- Caching Layer: Redis caching for read-heavy Operaciones
- Distributed Tracing: OpenTelemetry or Jaeger for request tracing
- Métricas Collection: Prometheus for detailed Métricas
- Native Mobile App: If WhatsApp limitations become problematic
- Full Event Sourcing: Completo event history for audit
References
Arquitectura Documentoation
- C4 Diagrams source (see project Repositorio Structurizr workspace)
- Backend Microservicios Descripción General
- API Gateway
- Frontend Dashboard
Componente Diagrams
Despliegue and Operaciones
Data Flow Diagrams
Sprint Documentoation
- Sprint 1-8 - see
docs/Sprint_[1-8].mdin project Repositorio - Completo Backlog Analysis - see
docs/Completo_backlog_analysis.mdin 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)