Microservicio de órdenes
Arquitectura del microservicio de órdenes
1. Descripción general del servicio
El microservicio de órdenes es el servicio de lógica de negocio principal en la plataforma Algesta, gestionando el ciclo de vida completo de las órdenes desde la creación hasta la finalización.
Detalles del Servicio:
- Repositorio:
algesta-ms-orders-nestjs - Puerto: 3000 (configurable mediante variable de entorno
PORT) - Base de datos: MongoDB (base de datos de órdenes)
- Estado: ✅ Activo
Responsabilidades Principales:
- Gestión del ciclo de vida de órdenes (creación, asignación, ejecución, finalización)
- Inventario de activos y seguimiento del ciclo de vida
- Gestión de ubicaciones para entrega de servicios
- Mensajería y comunicación
- Gestión de técnicos y clientes
- Gestión de garantías y contratos
- Seguimiento de pagos (anticipos y pagos finales)
- Historial de órdenes y registro de auditoría
- Plantillas de formularios y formularios dinámicos
Archivos de Referencia:
- Configuración del módulo:
algesta-ms-orders-nestjs/src/app.module.ts - Modelo de dominio:
algesta-ms-orders-nestjs/src/domain/entities/order.entity.ts - Controlador:
algesta-ms-orders-nestjs/src/infrastructure/controllers/order.controller.ts - Documentación:
algesta-ms-orders-nestjs/README.md
2. Estructura del Módulo
El microservicio de órdenes sigue la arquitectura modular de NestJS con principios de Clean Architecture.
Módulos de Negocio Principales
| Módulo | Ubicación | Propósito | Componentes Clave |
|---|---|---|---|
| LocationModule | src/infrastructure/modules/location.module.ts | Gestión de ubicaciones | LocationController, manejadores de ubicación |
| OrderModule | src/infrastructure/modules/order.module.ts | Gestión del ciclo de vida de órdenes | OrderController, manejadores de orden, repositorio de órdenes |
| MessagingModule | src/infrastructure/modules/messaging.module.ts | Mensajería en la aplicación | MessagingController, manejadores de mensajes |
| UserModule | src/infrastructure/modules/user.module.ts | Gestión de usuarios | UserController, manejadores de usuario |
| TechnicianModule | src/infrastructure/modules/technician.module.ts | Gestión de técnicos | TechnicianController, manejadores de técnico |
| AssetsModule | src/infrastructure/modules/assets.module.ts | Inventario y seguimiento de activos | AssetsController, manejadores de activos, repositorio de activos |
Nota: ClientModule está actualmente comentado en AppModule (línea 66). La funcionalidad relacionada con clientes es manejada por ClientController que se registra directamente en AppModule.controllers en lugar de usar un módulo de característica dedicado.
Módulos de Infraestructura Compartidos
| Módulo | Propósito |
|---|---|
| DatabaseModule | Conexión y configuración de MongoDB |
| RedisConfigModule | Configuración de mensajería Redis/Kafka |
| HealthModule | Endpoints de verificación de salud |
| CqrsModule | Bus de comandos/consultas CQRS (importado a nivel raíz) |
| WinstonModule | Registro estructurado |
| ClientsModule | Configuración de cliente de microservicios |
Controladores Registrados Directamente en AppModule
Los siguientes controladores se registran directamente en AppModule.controllers (línea 69) en lugar de estar encapsulados dentro de módulos de característica dedicados:
| Controlador | Propósito | Ruta del Archivo |
|---|---|---|
| AppController | Controlador raíz de la aplicación | src/app.controller.ts |
| ClientController | Operaciones de gestión de clientes | src/infrastructure/controllers/client.controller.ts |
| CounterController | Estadísticas y contadores de órdenes | src/infrastructure/controllers/counter.controller.ts |
| GuaranteeController | Gestión de garantías y contratos | src/infrastructure/controllers/guarantee.controller.ts |
| AdvancePaymentController | Registro de pagos anticipados | src/infrastructure/controllers/advance-payment.controller.ts |
Interceptores Globales
El ConnectivityMonitorInterceptor se registra globalmente mediante APP_INTERCEPTOR en AppModule.providers (líneas 85-88) para monitorear la conectividad del servicio en todos los controladores y manejadores.
Referencia: algesta-ms-orders-nestjs/src/app.module.ts
3. Implementación CQRS
El microservicio de órdenes implementa el patrón CQRS usando @nestjs/cqrs para la separación de operaciones de escritura y lectura.
Comandos (Operaciones de Escritura)
Los comandos representan operaciones que cambian el estado de órdenes, activos y entidades relacionadas.
| Comando | Manejador | Propósito | Ruta del Archivo |
|---|---|---|---|
| CreateOrderFromGatewayCommand | CreateOrderFromGatewayHandler | Crear nueva orden desde API Gateway | src/application/commands/create-order-from-gateway.command.ts |
| UpdateOrderInfoCommand | UpdateOrderInfoHandler | Actualizar información y estado de orden | src/application/commands/update-order-info.command.ts |
| SendQuoteCommand | SendQuoteHandler | Enviar cotización al cliente para aprobación | src/application/commands/send-quote.command.ts |
| PublishOrderCommand | PublishOrderHandler | Publicar orden al sistema de subastas | src/application/commands/publish-order.command.ts |
| CreateAssetCommand | CreateAssetHandler | Crear nuevo registro de activo | src/application/commands/create-asset.command.ts |
| RegisterAdvancePaymentCommand | RegisterAdvancePaymentHandler | Registrar recibo de pago anticipado | src/application/commands/register-advance-payment.command.ts |
| RegisterFinalPaymentCommand | RegisterFinalPaymentHandler | Registrar finalización de pago final | src/application/commands/register-final-payment.command.ts |
| AssignTechnicianToOrderCommand | AssignTechnicianToOrderHandler | Asignar técnico a orden | src/application/commands/assign-technician-to-order.command.ts |
| FinalReportCommand | FinalReportHandler | Generar informe final de completitud del trabajo | src/application/commands/final-report.command.ts |
| AgentFinalReportCommand | AgentFinalReportHandler | Generar informe final del agente | src/application/commands/agent-final-report.command.ts |
| ClientSubmitApprovalCommand | ClientSubmitApprovalHandler | Aprobación del cliente de la entrega final | src/application/commands/client-submit-approval.command.ts |
| RateProviderCommand | RateProviderHandler | Calificar calidad del servicio del proveedor | src/application/commands/rate-provider.command.ts |
| UpdateAdditionalEvaluationCommand | UpdateAdditionalEvaluationHandler | Actualizar notas de evaluación | src/application/commands/update-additional-evaluation.command.ts |
| CreateLocationCommand | CreateLocationHandler | Crear registro de ubicación | src/application/commands/create-location.command.ts |
| CreateMessageCommand | CreateMessageHandler | Crear mensaje de comunicación | src/application/commands/create-message.command.ts |
| CreateTechnicianCommand | CreateTechnicianHandler | Crear perfil de técnico | src/application/commands/create-technician.command.ts |
Referencia: algesta-ms-orders-nestjs/src/application/commands/ y algesta-ms-orders-nestjs/src/application/handlers/commands/
Consultas (Operaciones de Lectura)
Las consultas representan operaciones de solo lectura para recuperar órdenes, activos y datos relacionados.
| Consulta | Manejador | Propósito | Ruta del Archivo |
|---|---|---|---|
| GetOrderByIdQuery | GetOrderByIdHandler | Obtener orden por ID único | src/application/queries/get-order-by-id.query.ts |
| GetAllOrdersQuery | GetAllOrdersHandler | Listar órdenes con paginación y filtros | src/application/queries/get-all-orders.query.ts |
| GetOrderDetailsWithUserQuery | GetOrderDetailsWithUserHandler | Obtener orden detallada con información de usuario | src/application/queries/get-order-details-with-user.query.ts |
| GetOrderHistoryQuery | GetOrderHistoryHandler | Obtener registro de auditoría e historial de orden | src/application/queries/get-order-history.query.ts |
| GetOrdersByClientQuery | GetOrdersByClientHandler | Obtener órdenes para cliente específico | src/application/queries/get-orders-by-client.query.ts |
| GetProviderOrdersQuery | GetProviderOrdersHandler | Obtener órdenes asignadas a proveedor | src/application/queries/get-provider-orders.query.ts |
| GetOrdersCounterQuery | GetOrdersCounterHandler | Obtener estadísticas y contadores de órdenes | src/application/queries/get-orders-counter.query.ts |
| GetAcceptedProvidersForOrderQuery | GetAcceptedProvidersForOrderHandler | Obtener proveedores que aceptaron la subasta | src/application/queries/get-accepted-providers-for-order.query.ts |
| ListAssetsQuery | ListAssetsHandler | Listar activos con filtros y paginación | src/application/queries/list-assets.query.ts |
| GetAssetLifecycleDetailQuery | GetAssetLifecycleDetailHandler | Obtener ciclo de vida del activo e historial de mantenimiento | src/application/queries/get-asset-lifecycle-detail.query.ts |
| GetAssetByIdQuery | GetAssetByIdHandler | Obtener activo por ID | src/application/queries/get-asset-by-id.query.ts |
| GetLocationByIdQuery | GetLocationByIdHandler | Obtener ubicación por ID | src/application/queries/get-location-by-id.query.ts |
| GetMessagesByOrderQuery | GetMessagesByOrderHandler | Obtener mensajes para orden | src/application/queries/get-messages-by-order.query.ts |
| GetTechnicianByIdQuery | GetTechnicianByIdHandler | Obtener perfil de técnico | src/application/queries/get-technician-by-id.query.ts |
Referencia: algesta-ms-orders-nestjs/src/application/queries/ y algesta-ms-orders-nestjs/src/application/handlers/queries/
4. Domain Models
The Orders Microservicio implements rich domain models following Domain-Driven Design principles.
Order Entity
The Order entity is the core aggregate root representing a service request throughout its lifecycle.
File: algesta-ms-orders-nestjs/src/domain/entities/order.entity.ts
Basic Fields:
orderId(string, unique): Unique order identifierchannel(enum: CALL_CENTER, WEB, MOBILE, ADMIN): Order creation channelservice(string): Type of service requestedaddress(string): Service delivery addresscity(string): City for service deliveryDescripción(string): Order Descripción and notesEstado(enum): Current order Estado (see Order Estado enum below)typeOrder(enum: WARRANTY, MAINTENANCE, REPAIR, INSTALLATION): Order type
Contact Information:
phoneNumber(string): Contact phone numbernameContact(string): Contact person nameemailContact(string): Contact emailemailContactClient(string): Client contact emailapproverEmail(string): Approver email for quotes
Assignment Fields:
assignedTo(string): Assigned user/technician IDassignedProvider(object): Assigned provider informationproviderId(string): Provider unique IDproviderName(string): Provider nameproviderEmail(string): Provider emailassignedAt(Date): Assignment timestamp
assignedInternalTechnician(object): Internal technician assignmenttechnicianId(string)technicianName(string)assignedAt(Date)
Workflow Object (workProcess):
Complex nested object tracking the Completo work lifecycle:
startWork(object): Work start confirmationconfirmed(boolean)confirmedAt(Date)confirmedBy(string)
initialInspection(object): Initial inspection dataCompletod(boolean)CompletodAt(Date)findings(string)photos(array of URLs)
workCompletionReport(object): Work completion detailsCompletod(boolean)CompletodAt(Date)notes(string)workPerformed(string)
processRegistration(object): Process trackingregistered(boolean)registeredAt(Date)processes(array of process records)
finalDelivery(object): Final delivery confirmationdelivered(boolean)deliveredAt(Date)clientSignature(string)clientNotes(string)
Financial Fields:
advance(object): Advance payment trackingamount(number)paid(boolean)paidAt(Date)paymentMétodo(string)receiptUrl(string)
quote(object): Quotation managementtotalAmount(number)laborCost(number)materialsCost(number)approved(boolean)approvedAt(Date)approvedBy(string)sentAt(Date)expiresAt(Date)quotePdfUrl(string)
guarantees(object): Contracts and policiescontractId(string)policyId(string)warrantyEndDate(Date)
Auction Fields:
auction(boolean): Is order in auctionuser_rejected(array): Providers who rejecteduser_accepted(array): Providers who accepted
Asset References:
assetIds(array of strings): References to Asset entities
Technical Visit (technicalVisit):
phase1(object): Initial technical visitscheduled(boolean)scheduledDate(Date)Completod(boolean)CompletodAt(Date)findings(string)
phase2(object): Follow-up visitrequired(boolean)scheduled(boolean)scheduledDate(Date)Completod(boolean)
Rating (providerRating):
rating(number, 1-5): Client ratingcomment(string): Client feedbackratedAt(Date): Rating timestamp
Timestamps:
createdAt(Date): Order creation timestampupdatedAt(Date): Last update timestampcallDate(Date): Initial call/request dateexecutionDate(Date): Scheduled execution date
Order Estado Enum:
enum OrderStatus { NEW = 'NEW', QUOTE_SENT = 'QUOTE_SENT', QUOTE_APPROVED = 'QUOTE_APPROVED', QUOTE_REJECTED = 'QUOTE_REJECTED', ASSIGNED = 'ASSIGNED', IN_PROGRESS = 'IN_PROGRESS', WORK_STARTED = 'WORK_STARTED', INSPECTION_COMPLETED = 'INSPECTION_COMPLETED', WORK_COMPLETED = 'WORK_COMPLETED', PENDING_DELIVERY = 'PENDING_DELIVERY', COMPLETED = 'COMPLETED', CANCELLED = 'CANCELLED', ON_HOLD = 'ON_HOLD'}Asset Entity
The Asset entity represents equipment or property being serviced.
File: algesta-ms-orders-nestjs/src/domain/entities/orders/asset.entity.ts
Identification Fields:
serialNumber(string): Manufacturer serial numberserialId(string): Internal asset IDcategory(string): Asset categoryname(string): Asset name/Descripción
Location Fields:
city(string): Asset location cityaddress(string): Asset location addressheadquarters(string): Headquarters/branch nameassetLocation(string): Specific location within facilitylocation(object): Geolocation coordinates
Estado:
assetEstado(enum): Current operational Estadooperational: Fully functionaloperational_with_faults: Working with issuesmaintenance: Under maintenanceout_of_service: Not operationalretired: Decommissioned
Specifications:
brand(string): Manufacturer brandmodel(string): Model numbercapacity(string): Equipment capacityassetType(string): Type of assetDescripción(string): Detailed Descripción
Prioridad Levels:
clientPrioridad(enum: high, medium, low): Client-assigned PrioridadclientImportance(enum: high, medium, low): Business importanceassetValorPrioridad(enum: high, medium, low): Valor-based Prioridad
Purchase Data:
acquisitionDate(Date): Purchase dateOperacionestartDate(Date): Initial operation datepurchasePrice(number): Original purchase pricesupplierCompany(string): Supplier namenit(string): Supplier tax IDsupplierContact(string): Supplier contact namephone(string): Supplier phonewarrantyEndDate(Date): Warranty expiration
Valuation:
valuationPurchasePrice(number): Current valuationpreventiveMaintenanceValor(number): Preventive maintenance costcorrectiveMaintenanceValor(number): Corrective maintenance costtotalMaintenanceValor(number): Total maintenance investmentcurrentAssetValor(number): Current market Valor
Media:
photoSerialUrl(string): Photo of serial number plate
Other Entities
Location Entity:
- Address and location information
- Geolocation coordinates
- Branch/headquarters mapping
Message Entity:
- Communication messages within orders
- Sender and receiver information
- Message content and timestamps
Technician Entity:
- Internal technician profiles
- Specialties and certifications
- Availability and assignments
User Entity:
- User accounts (clients, agents, admins)
- Authentication credentials
- Role and permissions
Company Entity:
- Company information
- Contact details
- Tax identification
Documento Entity:
- Documento metadata
- File URLs
- Documento types and Estadoes
Form Entity:
- Form templates
- Dynamic form configurations
- Usage statistics
Reference: algesta-ms-orders-nestjs/src/domain/entities/
5. API Endpoints (MessagePatterns)
The Orders Microservicio exposes its functionality via MessagePattern decorators for inter-service communication.
Controller: algesta-ms-orders-nestjs/src/infrastructure/controllers/order.controller.ts
Order Management Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
orders.create-order | CreateOrderFromGatewayDto | CreateOrderResponseDto | Create order from API Gateway |
orders.create-location | CreateOrderLocationDto | Order | Create order with location |
orders.get-by-id | {orderId} | Order | Get order by ID |
orders.get-by-phone | {phoneNumber} | Order[] | Get orders by phone number |
orders.service.getAll | filters | PaginatedOrdersResponse | List orders with pagination |
orders.service.getDetails | {orderId} | OrderDetailsDto | Get detailed order information |
orders.update-additional-evaluation | UpdateAdditionalEvaluationDto | Order | Update evaluation notes |
orders.update-info | UpdateOrderInfoDto | Order | Update order information |
orders.get-history | GetOrderHistoryDto | History | Get order audit trail |
Auction Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
orders.publish-order | {orderId, user, metadata} | {success, message} | Publish order to auction |
orders.get-accepted-providers | {orderId} | GetAcceptedProvidersForOrderResponseDto | Get providers who accepted |
Provider Workflow Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
provider.final-report | FinalReportDto | FinalReportResponseDto | Generate final work report |
agent.get-final-report | AgentFinalReportDto | FinalReportResponseDto | Get agent final report |
provider.service.sendQuote | SendQuoteDto | SendQuoteResponseDto | Send quotation to client |
agent.submit-notes | AgentSubmitNotesDto | AgentSubmitNotesResponseDto | Submit agent notes |
Client Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
client.submit-approval-final-delivery | ClientSubmitApprovalDto | ClientSubmitApprovalResponseDto | Client approval of delivery |
Advanced Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
orders.service.raw.query | ExecuteRawMongoQueryDto | any | Execute raw MongoDB query (admin only) |
Reference: algesta-ms-orders-nestjs/src/infrastructure/controllers/
6. Base de datos Schema
The Orders Microservicio uses MongoDB with the following collections:
Collections Descripción General
| Collection | Purpose | Estimated Size | Indexes |
|---|---|---|---|
| orders | Main order Documentos | 5-50 KB/doc | orderId (unique), Estado, channel, phoneNumber, assignedTo, createdAt, assignedProvider.providerId, assetIds |
| assets | Asset inventory | 2-5 KB/doc | serialNumber, serialId (sparse), category, client, assetEstado, location, clientPrioridad |
| locations | Location data | 0.5-1 KB/doc | city, coordinates (2dsphere) |
| messages | Communication messages | 0.5-1 KB/doc | orderId, senderId, receiverId, timestamp |
| technicians | Technician profiles | 1-2 KB/doc | technicianId, nit |
| users | User accounts | 1-2 KB/doc | email (unique), role, identification |
| companies | Company information | 1-3 KB/doc | nit (unique), name |
| order-history | Audit trail | 0.5-2 KB/doc | orderId, timestamp, userId |
| forms | Form templates | Variable | name, usageCount |
| category-assets | Asset categories | 0.2-0.5 KB/doc | name |
Reference: algesta-ms-orders-nestjs/src/shared/infrastructure/Base de datos/Base de datos.config.ts
7. Business Logic Flows
Order Creation Flow
sequenceDiagram
participant Client
participant Gateway as API Gateway
participant Orders as Orders MS
participant MongoDB
participant Kafka
participant Notifications as Notifications MS
Client->>Gateway: POST /orders (REST)
Gateway->>Orders: orders.create-order (MessagePattern)
Orders->>Orders: Validate CreateOrderDto
Orders->>Orders: Execute CreateOrderCommand
Orders->>MongoDB: Save Order document
MongoDB-->>Orders: Order created
Orders->>MongoDB: Save OrderHistory record
Orders->>Kafka: Publish order.created event
Orders-->>Gateway: CreateOrderResponseDto
Gateway-->>Client: Order details (JSON)
Kafka->>Notifications: order.created event
Notifications->>Notifications: Send welcome email
Order Lifecycle Flow
stateDiagram-v2
[*] --> NEW: Order created
NEW --> QUOTE_SENT: Quote generated
QUOTE_SENT --> QUOTE_APPROVED: Client approves
QUOTE_SENT --> QUOTE_REJECTED: Client rejects
QUOTE_REJECTED --> CANCELLED: No rework
QUOTE_REJECTED --> QUOTE_SENT: Revised quote
QUOTE_APPROVED --> ASSIGNED: Provider assigned
ASSIGNED --> WORK_STARTED: Work begins
WORK_STARTED --> INSPECTION_COMPLETED: Initial inspection
INSPECTION_COMPLETED --> IN_PROGRESS: Work proceeds
IN_PROGRESS --> WORK_COMPLETED: Work finished
WORK_COMPLETED --> PENDING_DELIVERY: Awaiting delivery
PENDING_DELIVERY --> COMPLETED: Client accepts
COMPLETED --> [*]
NEW --> CANCELLED: Client cancels
QUOTE_APPROVED --> CANCELLED: Order cancelled
ASSIGNED --> ON_HOLD: Temporary hold
ON_HOLD --> ASSIGNED: Resume
Asset Lifecycle Flow
sequenceDiagram
participant Admin
participant Orders as Orders MS
participant MongoDB
Admin->>Orders: Create Asset
Orders->>MongoDB: Save Asset
MongoDB-->>Orders: Asset created
Note over Orders: Link Asset to Order
Orders->>MongoDB: Update Order.assetIds
Note over Orders: Initial Inspection
Orders->>MongoDB: Update Asset status
Orders->>MongoDB: Add inspection data
Note over Orders: Work Process
Orders->>MongoDB: Update maintenance values
Orders->>MongoDB: Update currentAssetValue
Note over Orders: Final Delivery
Orders->>MongoDB: Update assetStatus
Orders->>MongoDB: Add completion notes
8. Integration Points
The Orders Microservicio integrates with other services and external systems:
Internal Service Integration
Notifications Microservicio:
- Propósito: Send email notifications for order events
- Patterns Used:
notification.send-order-reminder: Send order remindersquotation.approved: Quote approval notifications
- Events Published: order.created, order.updated, quote.sent, quote.approved
Provider Microservicio:
- Propósito: Manage provider assignment and auction
- Patterns Used:
auction.publish: Publish order to auctionprovider.assign: Assign provider to order
- Events Published: order.published, provider.assigned
External Services
SendGrid (via Notifications MS):
- Quote PDFs sent via email
- Order confirmation emails
- Estado update notifications
Puppeteer:
- Generate PDF reports (final delivery, work completion)
- Generate quote PDFs
9. Configuration and Environment Variables
Required Environment Variables
# ApplicationNODE_ENV=development|productionPORT=3000
# DatabaseMONGODB_URI=mongodb://localhost:27017/ordersDB_POOL_MAX=20DB_POOL_MIN=5DB_POOL_IDLE_TIMEOUT=30000
# MessagingMESSAGING_TYPE=REDIS|KAFKAREDIS_HOST=localhostREDIS_PORT=6379KAFKA_BROKERS=localhost:9092
# AuthenticationJWT_SECRET=your_jwt_secret_keyJWT_EXPIRES_IN=1d
# SendGrid (for email notifications)SENDGRID_API_KEY=your_sendgrid_api_key
# LoggingLOG_LEVEL=info|debug|error10. Pruebas Strategy
Unit Pruebas
Command Handlers:
describe('CreateOrderFromGatewayHandler', () => { it('should create order successfully', async () => { const command = new CreateOrderFromGatewayCommand(createOrderDto); const result = await handler.execute(command); expect(result.orderId).toBeDefined(); });});Query Handlers:
describe('GetOrderByIdHandler', () => { it('should retrieve order by ID', async () => { const query = new GetOrderByIdQuery('ORDER-123'); const result = await handler.execute(query); expect(result.orderId).toBe('ORDER-123'); });});Integration Pruebas
Repositorio Pruebas:
- Test MongoDB interactions
- Verify indexes and queries
- Test transaction handling
E2E Pruebas
Message Pattern Pruebas:
- Test Complete order creation flow
- Test order lifecycle transitions
- Test error handling and retries
Test Coverage Targets:
- Statements: >90%
- Branches: >85%
- Functions: >90%
- Lines: >90%
Reference: algesta-ms-orders-nestjs/README.md
11. Related Documentoation
- Backend Microservicios Descripción General
- Provider Microservicio
- Notifications Microservicio
- Inter-Service Communication
- [Base de datos Schemas](/02-architecture/Base de datos-schemas/)