Saltearse al contenido

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óduloUbicaciónPropósitoComponentes Clave
LocationModulesrc/infrastructure/modules/location.module.tsGestión de ubicacionesLocationController, manejadores de ubicación
OrderModulesrc/infrastructure/modules/order.module.tsGestión del ciclo de vida de órdenesOrderController, manejadores de orden, repositorio de órdenes
MessagingModulesrc/infrastructure/modules/messaging.module.tsMensajería en la aplicaciónMessagingController, manejadores de mensajes
UserModulesrc/infrastructure/modules/user.module.tsGestión de usuariosUserController, manejadores de usuario
TechnicianModulesrc/infrastructure/modules/technician.module.tsGestión de técnicosTechnicianController, manejadores de técnico
AssetsModulesrc/infrastructure/modules/assets.module.tsInventario y seguimiento de activosAssetsController, 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óduloPropósito
DatabaseModuleConexión y configuración de MongoDB
RedisConfigModuleConfiguración de mensajería Redis/Kafka
HealthModuleEndpoints de verificación de salud
CqrsModuleBus de comandos/consultas CQRS (importado a nivel raíz)
WinstonModuleRegistro estructurado
ClientsModuleConfiguració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:

ControladorPropósitoRuta del Archivo
AppControllerControlador raíz de la aplicaciónsrc/app.controller.ts
ClientControllerOperaciones de gestión de clientessrc/infrastructure/controllers/client.controller.ts
CounterControllerEstadísticas y contadores de órdenessrc/infrastructure/controllers/counter.controller.ts
GuaranteeControllerGestión de garantías y contratossrc/infrastructure/controllers/guarantee.controller.ts
AdvancePaymentControllerRegistro de pagos anticipadossrc/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.

ComandoManejadorPropósitoRuta del Archivo
CreateOrderFromGatewayCommandCreateOrderFromGatewayHandlerCrear nueva orden desde API Gatewaysrc/application/commands/create-order-from-gateway.command.ts
UpdateOrderInfoCommandUpdateOrderInfoHandlerActualizar información y estado de ordensrc/application/commands/update-order-info.command.ts
SendQuoteCommandSendQuoteHandlerEnviar cotización al cliente para aprobaciónsrc/application/commands/send-quote.command.ts
PublishOrderCommandPublishOrderHandlerPublicar orden al sistema de subastassrc/application/commands/publish-order.command.ts
CreateAssetCommandCreateAssetHandlerCrear nuevo registro de activosrc/application/commands/create-asset.command.ts
RegisterAdvancePaymentCommandRegisterAdvancePaymentHandlerRegistrar recibo de pago anticipadosrc/application/commands/register-advance-payment.command.ts
RegisterFinalPaymentCommandRegisterFinalPaymentHandlerRegistrar finalización de pago finalsrc/application/commands/register-final-payment.command.ts
AssignTechnicianToOrderCommandAssignTechnicianToOrderHandlerAsignar técnico a ordensrc/application/commands/assign-technician-to-order.command.ts
FinalReportCommandFinalReportHandlerGenerar informe final de completitud del trabajosrc/application/commands/final-report.command.ts
AgentFinalReportCommandAgentFinalReportHandlerGenerar informe final del agentesrc/application/commands/agent-final-report.command.ts
ClientSubmitApprovalCommandClientSubmitApprovalHandlerAprobación del cliente de la entrega finalsrc/application/commands/client-submit-approval.command.ts
RateProviderCommandRateProviderHandlerCalificar calidad del servicio del proveedorsrc/application/commands/rate-provider.command.ts
UpdateAdditionalEvaluationCommandUpdateAdditionalEvaluationHandlerActualizar notas de evaluaciónsrc/application/commands/update-additional-evaluation.command.ts
CreateLocationCommandCreateLocationHandlerCrear registro de ubicaciónsrc/application/commands/create-location.command.ts
CreateMessageCommandCreateMessageHandlerCrear mensaje de comunicaciónsrc/application/commands/create-message.command.ts
CreateTechnicianCommandCreateTechnicianHandlerCrear perfil de técnicosrc/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.

ConsultaManejadorPropósitoRuta del Archivo
GetOrderByIdQueryGetOrderByIdHandlerObtener orden por ID únicosrc/application/queries/get-order-by-id.query.ts
GetAllOrdersQueryGetAllOrdersHandlerListar órdenes con paginación y filtrossrc/application/queries/get-all-orders.query.ts
GetOrderDetailsWithUserQueryGetOrderDetailsWithUserHandlerObtener orden detallada con información de usuariosrc/application/queries/get-order-details-with-user.query.ts
GetOrderHistoryQueryGetOrderHistoryHandlerObtener registro de auditoría e historial de ordensrc/application/queries/get-order-history.query.ts
GetOrdersByClientQueryGetOrdersByClientHandlerObtener órdenes para cliente específicosrc/application/queries/get-orders-by-client.query.ts
GetProviderOrdersQueryGetProviderOrdersHandlerObtener órdenes asignadas a proveedorsrc/application/queries/get-provider-orders.query.ts
GetOrdersCounterQueryGetOrdersCounterHandlerObtener estadísticas y contadores de órdenessrc/application/queries/get-orders-counter.query.ts
GetAcceptedProvidersForOrderQueryGetAcceptedProvidersForOrderHandlerObtener proveedores que aceptaron la subastasrc/application/queries/get-accepted-providers-for-order.query.ts
ListAssetsQueryListAssetsHandlerListar activos con filtros y paginaciónsrc/application/queries/list-assets.query.ts
GetAssetLifecycleDetailQueryGetAssetLifecycleDetailHandlerObtener ciclo de vida del activo e historial de mantenimientosrc/application/queries/get-asset-lifecycle-detail.query.ts
GetAssetByIdQueryGetAssetByIdHandlerObtener activo por IDsrc/application/queries/get-asset-by-id.query.ts
GetLocationByIdQueryGetLocationByIdHandlerObtener ubicación por IDsrc/application/queries/get-location-by-id.query.ts
GetMessagesByOrderQueryGetMessagesByOrderHandlerObtener mensajes para ordensrc/application/queries/get-messages-by-order.query.ts
GetTechnicianByIdQueryGetTechnicianByIdHandlerObtener perfil de técnicosrc/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 identifier
  • channel (enum: CALL_CENTER, WEB, MOBILE, ADMIN): Order creation channel
  • service (string): Type of service requested
  • address (string): Service delivery address
  • city (string): City for service delivery
  • Descripción (string): Order Descripción and notes
  • Estado (enum): Current order Estado (see Order Estado enum below)
  • typeOrder (enum: WARRANTY, MAINTENANCE, REPAIR, INSTALLATION): Order type

Contact Information:

  • phoneNumber (string): Contact phone number
  • nameContact (string): Contact person name
  • emailContact (string): Contact email
  • emailContactClient (string): Client contact email
  • approverEmail (string): Approver email for quotes

Assignment Fields:

  • assignedTo (string): Assigned user/technician ID
  • assignedProvider (object): Assigned provider information
    • providerId (string): Provider unique ID
    • providerName (string): Provider name
    • providerEmail (string): Provider email
    • assignedAt (Date): Assignment timestamp
  • assignedInternalTechnician (object): Internal technician assignment
    • technicianId (string)
    • technicianName (string)
    • assignedAt (Date)

Workflow Object (workProcess): Complex nested object tracking the Completo work lifecycle:

  • startWork (object): Work start confirmation
    • confirmed (boolean)
    • confirmedAt (Date)
    • confirmedBy (string)
  • initialInspection (object): Initial inspection data
    • Completod (boolean)
    • CompletodAt (Date)
    • findings (string)
    • photos (array of URLs)
  • workCompletionReport (object): Work completion details
    • Completod (boolean)
    • CompletodAt (Date)
    • notes (string)
    • workPerformed (string)
  • processRegistration (object): Process tracking
    • registered (boolean)
    • registeredAt (Date)
    • processes (array of process records)
  • finalDelivery (object): Final delivery confirmation
    • delivered (boolean)
    • deliveredAt (Date)
    • clientSignature (string)
    • clientNotes (string)

Financial Fields:

  • advance (object): Advance payment tracking
    • amount (number)
    • paid (boolean)
    • paidAt (Date)
    • paymentMétodo (string)
    • receiptUrl (string)
  • quote (object): Quotation management
    • totalAmount (number)
    • laborCost (number)
    • materialsCost (number)
    • approved (boolean)
    • approvedAt (Date)
    • approvedBy (string)
    • sentAt (Date)
    • expiresAt (Date)
    • quotePdfUrl (string)
  • guarantees (object): Contracts and policies
    • contractId (string)
    • policyId (string)
    • warrantyEndDate (Date)

Auction Fields:

  • auction (boolean): Is order in auction
  • user_rejected (array): Providers who rejected
  • user_accepted (array): Providers who accepted

Asset References:

  • assetIds (array of strings): References to Asset entities

Technical Visit (technicalVisit):

  • phase1 (object): Initial technical visit
    • scheduled (boolean)
    • scheduledDate (Date)
    • Completod (boolean)
    • CompletodAt (Date)
    • findings (string)
  • phase2 (object): Follow-up visit
    • required (boolean)
    • scheduled (boolean)
    • scheduledDate (Date)
    • Completod (boolean)

Rating (providerRating):

  • rating (number, 1-5): Client rating
  • comment (string): Client feedback
  • ratedAt (Date): Rating timestamp

Timestamps:

  • createdAt (Date): Order creation timestamp
  • updatedAt (Date): Last update timestamp
  • callDate (Date): Initial call/request date
  • executionDate (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 number
  • serialId (string): Internal asset ID
  • category (string): Asset category
  • name (string): Asset name/Descripción

Location Fields:

  • city (string): Asset location city
  • address (string): Asset location address
  • headquarters (string): Headquarters/branch name
  • assetLocation (string): Specific location within facility
  • location (object): Geolocation coordinates

Estado:

  • assetEstado (enum): Current operational Estado
    • operational: Fully functional
    • operational_with_faults: Working with issues
    • maintenance: Under maintenance
    • out_of_service: Not operational
    • retired: Decommissioned

Specifications:

  • brand (string): Manufacturer brand
  • model (string): Model number
  • capacity (string): Equipment capacity
  • assetType (string): Type of asset
  • Descripción (string): Detailed Descripción

Prioridad Levels:

  • clientPrioridad (enum: high, medium, low): Client-assigned Prioridad
  • clientImportance (enum: high, medium, low): Business importance
  • assetValorPrioridad (enum: high, medium, low): Valor-based Prioridad

Purchase Data:

  • acquisitionDate (Date): Purchase date
  • OperacionestartDate (Date): Initial operation date
  • purchasePrice (number): Original purchase price
  • supplierCompany (string): Supplier name
  • nit (string): Supplier tax ID
  • supplierContact (string): Supplier contact name
  • phone (string): Supplier phone
  • warrantyEndDate (Date): Warranty expiration

Valuation:

  • valuationPurchasePrice (number): Current valuation
  • preventiveMaintenanceValor (number): Preventive maintenance cost
  • correctiveMaintenanceValor (number): Corrective maintenance cost
  • totalMaintenanceValor (number): Total maintenance investment
  • currentAssetValor (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

PatternInput DTOOutput DTODescription
orders.create-orderCreateOrderFromGatewayDtoCreateOrderResponseDtoCreate order from API Gateway
orders.create-locationCreateOrderLocationDtoOrderCreate order with location
orders.get-by-id{orderId}OrderGet order by ID
orders.get-by-phone{phoneNumber}Order[]Get orders by phone number
orders.service.getAllfiltersPaginatedOrdersResponseList orders with pagination
orders.service.getDetails{orderId}OrderDetailsDtoGet detailed order information
orders.update-additional-evaluationUpdateAdditionalEvaluationDtoOrderUpdate evaluation notes
orders.update-infoUpdateOrderInfoDtoOrderUpdate order information
orders.get-historyGetOrderHistoryDtoHistoryGet order audit trail

Auction Patterns

PatternInput DTOOutput DTODescription
orders.publish-order{orderId, user, metadata}{success, message}Publish order to auction
orders.get-accepted-providers{orderId}GetAcceptedProvidersForOrderResponseDtoGet providers who accepted

Provider Workflow Patterns

PatternInput DTOOutput DTODescription
provider.final-reportFinalReportDtoFinalReportResponseDtoGenerate final work report
agent.get-final-reportAgentFinalReportDtoFinalReportResponseDtoGet agent final report
provider.service.sendQuoteSendQuoteDtoSendQuoteResponseDtoSend quotation to client
agent.submit-notesAgentSubmitNotesDtoAgentSubmitNotesResponseDtoSubmit agent notes

Client Patterns

PatternInput DTOOutput DTODescription
client.submit-approval-final-deliveryClientSubmitApprovalDtoClientSubmitApprovalResponseDtoClient approval of delivery

Advanced Patterns

PatternInput DTOOutput DTODescription
orders.service.raw.queryExecuteRawMongoQueryDtoanyExecute 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

CollectionPurposeEstimated SizeIndexes
ordersMain order Documentos5-50 KB/docorderId (unique), Estado, channel, phoneNumber, assignedTo, createdAt, assignedProvider.providerId, assetIds
assetsAsset inventory2-5 KB/docserialNumber, serialId (sparse), category, client, assetEstado, location, clientPrioridad
locationsLocation data0.5-1 KB/doccity, coordinates (2dsphere)
messagesCommunication messages0.5-1 KB/docorderId, senderId, receiverId, timestamp
techniciansTechnician profiles1-2 KB/doctechnicianId, nit
usersUser accounts1-2 KB/docemail (unique), role, identification
companiesCompany information1-3 KB/docnit (unique), name
order-historyAudit trail0.5-2 KB/docorderId, timestamp, userId
formsForm templatesVariablename, usageCount
category-assetsAsset categories0.2-0.5 KB/docname

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 reminders
    • quotation.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 auction
    • provider.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

Ventana de terminal
# Application
NODE_ENV=development|production
PORT=3000
# Database
MONGODB_URI=mongodb://localhost:27017/orders
DB_POOL_MAX=20
DB_POOL_MIN=5
DB_POOL_IDLE_TIMEOUT=30000
# Messaging
MESSAGING_TYPE=REDIS|KAFKA
REDIS_HOST=localhost
REDIS_PORT=6379
KAFKA_BROKERS=localhost:9092
# Authentication
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRES_IN=1d
# SendGrid (for email notifications)
SENDGRID_API_KEY=your_sendgrid_api_key
# Logging
LOG_LEVEL=info|debug|error

10. 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