Saltearse al contenido

Microservicio de proveedores

Arquitectura del microservicio de proveedores

1. Descripción general del servicio

El microservicio de proveedores es un servicio sofisticado responsable de la gestión de proveedores, validación de documentos y el complejo sistema de subastas para la adquisición de servicios.

Service Details:

  • Repositorio: algesta-ms-provider-nestjs
  • Port: 3000 (configurable via PORT environment variable)
  • Database: MongoDB (providers Base de datos)
  • Estado: ✅ Activo

Key Responsibilities:

  • Provider registration and profile management
  • Document validation and expiration tracking
  • Auction system for service procurement
  • Dynamic quotation management with flexible item structures
  • Auction inflation system (admin-controlled price adjustments)
  • User management (providers, clients, agents)
  • Service catalog and provider-service associations
  • Provider performance tracking
  • Order workflow for providers (inspection, work start, completion, delivery)

Reference Files:

  • Module configuration: algesta-ms-provider-nestjs/src/app.module.ts
  • Provider entity: algesta-ms-provider-nestjs/src/domain/entities/provider.entity.ts
  • Auction entity: algesta-ms-provider-nestjs/src/domain/entities/auction.entity.ts
  • Controller: algesta-ms-provider-nestjs/src/infrastructure/controllers/provider.controller.ts
  • Documentoation: algesta-ms-provider-nestjs/README.md

2. Module Structure

The Provider Microservicio follows NestJS modular Arquitectura with Clean Architecture principles.

Core Business Modules

ModuleLocationPurposeKey Componentes
ProviderModulesrc/infrastructure/modules/provider.module.tsProvider management and workflowsProviderController, Provider handlers, Provider Repositorio
AuctionsModulesrc/infrastructure/modules/auctions.module.tsAuction system and biddingAuctionsController, Auction handlers, Auction Repositorio
DocumentosModulesrc/infrastructure/modules/Documentos.module.tsDocument validationDocumentosController, Documento handlers
ServicesModulesrc/infrastructure/modules/services.module.tsService catalogServicesController, Service handlers

Shared Infrastructure Modules

ModulePurpose
Base de datosModuleMongoDB connection and configuration
MessagingModuleRedis/Kafka messaging configuration
HealthModuleHealth check Endpoints
WinstonModuleStructured logging
ScheduleModuleCron job scheduling

Note: CQRS is wired within feature modules such as ProviderModule, AuctionsModule, DocumentosModule, and ServicesModule, not at the root AppModule level. Each feature module imports CqrsModule internally to provide command/query bus functionality for its specific domain Operaciones.

Reference: algesta-ms-provider-nestjs/src/app.module.ts

3. CQRS Implementación

The Provider Microservicio implements CQRS pattern using @nestjs/cqrs for complex business logic.

Commands (Write Operaciones)

Commands represent state-changing Operaciones on providers, auctions, Documentos, and users.

Provider Management Commands

CommandHandlerPurposeFile Path
CreateProviderCommandCreateProviderHandlerRegister new providersrc/application/commands/create-provider.command.ts
UpdateProviderCommandUpdateProviderHandlerUpdate provider informationsrc/application/commands/update-provider.command.ts
ProcessRegistrationCommandProcessRegistrationHandlerProcess provider registration workflowsrc/application/commands/process-registration.command.ts
MarkDocumentoRequiredCommandMarkDocumentoRequiredHandlerMark Documento as requiredsrc/application/commands/mark-Documento-required.command.ts
ValidateDiscountCommandValidateDiscountHandlerValidate discount eligibilitysrc/application/commands/validate-discount.command.ts

Provider Workflow Commands

CommandHandlerPurposeFile Path
InitialInspectionCommandInitialInspectionHandlerSubmit initial inspectionsrc/application/commands/initial-inspection.command.ts
ConfirmWorkStartCommandConfirmWorkStartHandlerConfirm work startsrc/application/commands/confirm-work-start.command.ts
WorkCompletionReportCommandWorkCompletionReportHandlerSubmit work completion reportsrc/application/commands/work-completion-report.command.ts
FinalDeliveryCommandFinalDeliveryHandlerSubmit final deliverysrc/application/commands/final-delivery.command.ts
SendReportCommandSendReportHandlerSend report to clientsrc/application/commands/send-report.command.ts
SaveFinalDeliveryReportUrlCommandSaveFinalDeliveryReportUrlHandlerSave report URLsrc/application/commands/save-final-delivery-report-url.command.ts

Auction Management Commands

CommandHandlerPurposeFile Path
PublishOrderForAuctionCommandPublishOrderForAuctionHandlerPublish order to auctionsrc/application/commands/publish-order-for-auction.command.ts
ProviderAuctionResponseCommandProviderAuctionResponseHandlerProvider accepts/rejects auctionsrc/application/commands/provider-auction-response.command.ts
CreateAuctionOfferCommandCreateAuctionOfferHandlerCreate auction bidsrc/application/commands/create-auction-offer.command.ts
EditAuctionOfferCommandEditAuctionOfferHandlerEdit existing bidsrc/application/commands/edit-auction-offer.command.ts
CreateOfferInflationCommandCreateOfferInflationHandlerCreate price inflationsrc/application/commands/create-offer-inflation.command.ts
UploadInflationPdfCommandUploadInflationPdfHandlerUpload inflation PDFsrc/application/commands/upload-inflation-pdf.command.ts
GenerateInflationQuotePdfCommandGenerateInflationQuotePdfHandlerGenerate quotation PDFsrc/application/commands/generate-inflation-quote-pdf.command.ts
AssignProviderCommandAssignProviderHandlerAssign provider to ordersrc/application/commands/assign-provider.command.ts
CreateDynamicItemsCommandCreateDynamicItemsHandlerCreate dynamic quotation itemssrc/application/commands/create-dynamic-items.command.ts
UploadAuctionDocumentoCommandUploadAuctionDocumentoHandlerUpload auction Documentossrc/application/commands/upload-auction-Documento.command.ts

Documento Management Commands

CommandHandlerPurposeFile Path
CreateDocumentoCommandCreateDocumentoHandlerCreate Documento recordsrc/application/commands/create-Documento.command.ts
UpdateDocumentoEstadoCommandUpdateDocumentoEstadoHandlerUpdate Documento Estadosrc/application/commands/update-Documento-Estado.command.ts
DeleteDocumentoCommandDeleteDocumentoHandlerDelete Documentosrc/application/commands/delete-Documento.command.ts

User Management Commands

CommandHandlerPurposeFile Path
CreateUserCommandCreateUserHandlerCreate user accountsrc/application/commands/create-user.command.ts
UpdateUserCommandUpdateUserHandlerUpdate user informationsrc/application/commands/update-user.command.ts
DeleteUserCommandDeleteUserHandlerDelete user accountsrc/application/commands/delete-user.command.ts

Service Management Commands

CommandHandlerPurposeFile Path
AssociateServiceCommandAssociateServiceHandlerAssociate service with providersrc/application/commands/associate-service.command.ts

Order Processing Commands

CommandHandlerPurposeFile Path
SendOrderReminderCommandSendOrderReminderHandlerSend order remindersrc/application/commands/send-order-reminder.command.ts
ProcessQuoteApprovalCommandProcessQuoteApprovalHandlerProcess quote approvalsrc/application/commands/process-quote-approval.command.ts

Reference: algesta-ms-provider-nestjs/src/application/commands/ and algesta-ms-provider-nestjs/src/application/handlers/

Queries (Read Operaciones)

Queries represent read-only Operaciones for retrieving provider, auction, and related data.

Provider Queries

QueryHandlerPurposeFile Path
GetProviderByIdentificationQueryGetProviderByIdentificationHandlerGet provider by IDsrc/application/queries/get-provider-by-identification.query.ts
ListProvidersQueryListProvidersHandlerList all providers with paginationsrc/application/queries/list-providers.query.ts
ValidateProviderEligibilityQueryValidateProviderEligibilityHandlerValidate provider eligibilitysrc/application/queries/validate-provider-eligibility.query.ts
GetProviderPerformanceQueryGetProviderPerformanceHandlerGet provider performance Métricassrc/application/queries/get-provider-performance.query.ts
GetOrderDetailsForProviderQueryGetOrderDetailsForProviderHandlerGet order details for providersrc/application/queries/get-order-details-for-provider.query.ts
ValidateStartWorkQueryValidateStartWorkHandlerValidate work start conditionssrc/application/queries/validate-start-work.query.ts
GetInitialInspectionQueryGetInitialInspectionHandlerGet initial inspection datasrc/application/queries/get-initial-inspection.query.ts
ListAuctionsForProviderQueryListAuctionsForProviderHandlerList auctions for providersrc/application/queries/list-auctions-for-provider.query.ts
ListAuctionOffersForProviderQueryListAuctionOffersForProviderHandlerList provider’s auction offerssrc/application/queries/list-auction-offers-for-provider.query.ts

Auction Queries

QueryHandlerPurposeFile Path
GetAuctionOrdersQueryGetAuctionOrdersHandlerGet orders in auctionsrc/application/queries/get-auction-orders.query.ts
ListAuctionsQueryListAuctionsHandlerList all auctionssrc/application/queries/list-auctions.query.ts
GetAuctionByOrderIdQueryGetAuctionByOrderIdHandlerGet auction by order IDsrc/application/queries/get-auction-by-order-id.query.ts
GetAuctionDetailQueryGetAuctionDetailHandlerGet detailed auction informationsrc/application/queries/get-auction-detail.query.ts
ListAuctionOffersQueryListAuctionOffersHandlerList all offers for auctionsrc/application/queries/list-auction-offers.query.ts
ListFinishedAuctionsQueryListFinishedAuctionsHandlerList Completod auctionssrc/application/queries/list-finished-auctions.query.ts
GetProviderLastOfferQueryGetProviderLastOfferHandlerGet provider’s last offersrc/application/queries/get-provider-last-offer.query.ts

Documento Queries

QueryHandlerPurposeFile Path
GetDocumentosQueryGetDocumentosHandlerGet Documentos with filterssrc/application/queries/get-Documentos.query.ts
GetDocumentosResumenQueryGetDocumentosResumenHandlerGet Documentos Resumensrc/application/queries/get-Documentos-Resumen.query.ts

User Queries

QueryHandlerPurposeFile Path
ListAllUsersQueryListAllUsersHandlerList all users with filterssrc/application/queries/list-all-users.query.ts
ListClientsQueryListClientsHandlerList client userssrc/application/queries/list-clients.query.ts

Service Queries

QueryHandlerPurposeFile Path
GetServicesQueryGetServicesHandlerGet available servicessrc/application/queries/get-services.query.ts

Reference: algesta-ms-provider-nestjs/src/application/queries/ and algesta-ms-provider-nestjs/src/application/handlers/

4. Domain Models

The Provider Microservicio implements rich domain models for provider and auction management.

Provider Entity

The Provider entity represents a service provider registered on the platform.

File: algesta-ms-provider-nestjs/src/domain/entities/provider.entity.ts

Basic Information:

  • name (string): Provider first name
  • lastName (string): Provider last name
  • email (string, unique): Provider email address
  • identification (string): Tax ID or identification number
  • phone (string): Contact phone number

Location:

  • city (string): Provider city
  • country (string): Provider country
  • address (string): Physical address
  • location (object): Geolocation coordinates
    • latitude (number)
    • longitude (number)

Banking Information:

  • bank (string): Bank name
  • typeAccount (enum: SAVINGS, CHECKING): Account type
  • numberAccount (string): Account number

Account Information:

  • password (string): Hashed password
  • role (enum: PROVIDER): User role
  • isActivo (boolean): Account Activo Estado

Metadata:

  • createdAt (Date): Registration timestamp
  • updatedAt (Date): Last update timestamp

Collection: providers

Auction Entity

The Auction entity is the most complex entity, managing the entire auction lifecycle including bids, dynamic quotations, and inflations.

File: algesta-ms-provider-nestjs/src/domain/entities/auction.entity.ts

Auction Identification:

  • auctionId (string, unique): Unique auction identifier
  • orderId (string): Associated order ID
  • assetId (string): Associated asset ID

Auction Duration:

  • duration (object): Auction duration configuration
    • days (number): Duration in days
    • hours (number): Duration in hours
    • minutes (number): Duration in minutes
  • expiredAuction (Date): Auction expiration timestamp
  • durationInHours (number): Total duration in hours (calculated)

Auction Questions:

  • questions (array): Custom questions for providers
    • question (string): Question text
    • order (number): Display order
    • responseType (enum: TEXT, NUMBER, BOOLEAN, FILE): Expected response type

Auction Bids (auctionBids): Array of provider bids with the following structure:

Bid Identification:

  • bidId (string): Unique bid identifier
  • providerId (string): Provider who submitted bid
  • providerEmail (string): Provider email
  • providerName (string): Provider name

Offer Data (offerData):

  • totalOfferValor (number): Total bid amount
  • laborCost (number): Labor cost Componente
  • materials (array): Materials needed
    • item (string): Material Descripción
    • quantity (number): Quantity needed
    • unitPrice (number): Price per unit
    • totalPrice (number): Total for this material
  • spareParts (array): Spare parts needed
    • part (string): Part Descripción
    • quantity (number)
    • unitPrice (number)
    • totalPrice (number)
  • equipment (array): Equipment rental
    • equipment (string): Equipment Descripción
    • quantity (number)
    • dailyRate (number)
    • days (number)
    • totalPrice (number)
  • transport (object): Transportation costs
    • origin (string): Starting location
    • destination (string): Delivery location
    • distance (number): Distance in km
    • cost (number): Transportation cost
  • items (array): Flexible item structure for complex quotes

Bid Estado:

  • isAssigned (boolean): Is this bid selected
  • assignedAt (Date): Assignment timestamp
  • isCurrent (boolean): Is this the Activo bid
  • isRejected (boolean): Is this bid rejected
  • rejectedAt (Date): Rejection timestamp

Metadata:

  • metadata (object): Bid submission metadata
    • ipAddress (string): IP address of submission
    • userAgent (string): Browser/client user agent

Dynamic Quotations (dynamicQuotations): Array of dynamic quotation structures for flexible pricing:

  • quotationId (string): Unique quotation ID
  • providerId (string): Provider who created quotation
  • items (array): Flexible item array
    • itemId (string): Item identifier
    • name (string): Item name
    • Descripción (string): Item Descripción
    • quantity (number): Quantity
    • unitPrice (number): Price per unit
    • totalPrice (number): Total for this item
    • category (enum: LABOR, MATERIAL, EQUIPMENT, TRANSPORT, OTHER): Item category
    • enabled (boolean): Is this item included in quote
    • Custom fields as needed
  • transport (object): Transportation quotation
    • origin (string)
    • destination (string)
    • type (enum: LOCAL, NATIONAL, INTERNATIONAL)
    • cost (number)
  • totalEstimatedCost (number): Total quotation amount
  • notes (string): Additional notes

Auction Inflations (auctionInflations): Array of admin-created price inflations:

  • inflationId (string): Unique inflation ID
  • messageId (string): Associated message ID
  • bidId (string): Original bid being inflated
  • providerId (string): Provider whose bid is inflated
  • inflationData (object): Inflation details
    • items (array): Inflated items
      • Original item data plus:
      • inflationPercentage (number): Inflation percentage
      • originalPrice (number): Original price
      • inflatedPrice (number): Inflated price
    • additionalAnswers (array): Additional information
    • transport (object): Inflated transport costs
    • totalInflatedValor (number): Total after inflation
  • createdBy (object): Admin who created inflation
    • userId (string)
    • userName (string)
    • userEmail (string)
  • metadata (object): Inflation creation metadata
    • createdAt (Date)
    • ipAddress (string)

Price Documentoation (price):

  • DocumentoUrl (string): URL to generated price quote PDF
  • auctionInflationId (string): Associated inflation ID
  • uploadedAt (Date): Upload timestamp
  • Estado (enum: Pendiente, APPROVED, REJECTED): Quote Estado
  • totalInflatedValor (number): Final inflated Valor

Timestamps:

  • createdAt (Date): Auction creation timestamp
  • updatedAt (Date): Last update timestamp

Collection: auction

Indexes:

  • auctionId (unique)
  • orderId
  • assetId
  • createdAt
  • auctionBids.providerId
  • auctionBids.isCurrent
  • orderId + auctionBids.providerId (compound)
  • orderId + auctionBids.providerId + auctionBids.isCurrent (compound)
  • dynamicQuotations.providerId
  • orderId + dynamicQuotations.providerId (compound)
  • auctionInflations.bidId
  • auctionInflations.providerId
  • orderId + auctionInflations.bidId (compound)
  • auctionInflations.createdAt

Other Entities

Order Entity (denormalized):

  • Order information shared with Orders MS
  • Used for provider order queries

Documento Entity:

  • Documento metadata and validation Estado
  • Provider Documento tracking

Service Entity:

  • Available services on the platform
  • Service categories and Descripcións

ServiceProvider Entity (junction table):

  • Provider-service associations
  • Mapping providers to services they can perform

User Entity:

  • User accounts (providers, clients, agents, admins)
  • Authentication and authorization

Asset Entity (denormalized):

  • Asset information shared with Orders MS
  • Used for auction context

Reference: algesta-ms-provider-nestjs/src/domain/entities/

5. Auction System Arquitectura

The Provider Microservicio implements a sophisticated auction system for service procurement.

Auction Lifecycle

stateDiagram-v2
    [*] --> Created: Order published to auction
    Created --> Open: Auction opens
    Open --> Bidding: Providers submit bids
    Bidding --> Evaluation: Auction closes
    Evaluation --> Inflation: Admin inflates prices (optional)
    Inflation --> Selection: Best offer selected
    Selection --> Assigned: Provider assigned
    Assigned --> [*]: Auction completed

    Open --> Cancelled: No bids received
    Evaluation --> Cancelled: No suitable bids
    Cancelled --> [*]

1. Creation:

  • Order published from Orders MS
  • Auction created with duration and questions
  • Eligible providers notified

2. Bidding:

  • Providers submit detailed offers
  • Bids include labor, materials, spare parts, equipment, transport
  • Dynamic quotations support flexible item structures
  • Providers can edit bids before auction closes

3. Inflation (Admin Feature):

  • Admin can inflate provider offers
  • Percentage-based increases per item
  • Maintains original and inflated Valors
  • PDF generation for inflated quotations
  • Audit trail with admin information

4. Selection:

  • Best offer selected (manual or automatic)
  • Provider assigned to order
  • Losing providers notified

5. Completion:

  • Auction closed
  • Assignment confirmed
  • Order moves to execution phase

Bid Structure

Provider bids are structured to capture comprehensive pricing information:

Labor Cost:

  • Provider’s labor charges
  • Hourly rate or fixed price
  • Estimated hours

Materials:

{
item: string; // Material description
quantity: number; // Quantity needed
unitPrice: number; // Price per unit
totalPrice: number; // Calculated total
}

Spare Parts:

{
part: string; // Part description
quantity: number; // Quantity needed
unitPrice: number; // Price per part
totalPrice: number; // Calculated total
}

Equipment:

{
equipment: string; // Equipment description
quantity: number; // Quantity needed
dailyRate: number; // Daily rental rate
days: number; // Rental duration
totalPrice: number; // Calculated total
}

Transport:

{
origin: string; // Starting location
destination: string; // Delivery location
distance: number; // Distance in km
cost: number; // Transportation cost
}

Dynamic Quotation System

The dynamic quotation system provides flexibility for complex service quotes:

Funcionalidades:

  • Flexible item structure with configurable fields
  • Support for different item types (materials, labor, equipment)
  • Enabled fields configuration per item
  • Custom fields for specialized services
  • Transport quotation with origin, destination, type

Item Structure:

{
itemId: string;
name: string;
description: string;
quantity: number;
unitPrice: number;
totalPrice: number;
category: 'LABOR' | 'MATERIAL' | 'EQUIPMENT' | 'TRANSPORT' | 'OTHER';
enabled: boolean;
// Custom fields as needed for specific services
}

Use Cases:

  • Complex repairs with multiple Componentes
  • Installation projects with varied materials
  • Maintenance contracts with recurring items
  • Specialized services with unique pricing

Inflation System

The inflation system allows administrators to adjust provider offers:

Propósito:

  • Adjust provider bids based on market conditions
  • Apply percentage-based increases to specific items
  • Maintain transparency with original and inflated Valors
  • Generate professional quotations with inflated prices

Inflation Process:

  1. Admin selects bid to inflate
  2. Specifies inflation percentage per item
  3. System calculates inflated Valors
  4. Generates PDF quotation with new prices
  5. Saves audit trail with admin information
  6. Notifies provider of inflated quote

Inflation Data Structure:

{
inflationId: string;
bidId: string;
providerId: string;
inflationData: {
items: [
{
...originalItemData,
inflationPercentage: number;
originalPrice: number;
inflatedPrice: number;
}
],
totalInflatedValue: number;
},
createdBy: {
userId: string;
userName: string;
userEmail: string;
},
metadata: {
createdAt: Date;
ipAddress: string;
}
}

PDF Generation:

  • Puppeteer-based PDF generation
  • Professional quotation template
  • Original and inflated prices shown
  • Item-by-item breakdown
  • Total calculation
  • Provider and client information

6. API Endpoints (MessagePatterns)

The Provider Microservicio exposes extensive functionality via MessagePattern decorators.

Controllers: algesta-ms-provider-nestjs/src/infrastructure/controllers/

Provider Management Patterns

PatternInput DTOOutput DTODescription
provider.create-providerCreateProviderDtoUserCreate provider account
provider.get-by-identificationGetProviderByIdentificationDtoUserGet provider by ID
provider.update-providerUpdateProviderDtoUserUpdate provider information
provider.validate-eligibility{providerId}ValidateProviderEligibilityResponseDtoValidate provider eligibility
provider.get-order-details-by-id{orderId, providerId}GetOrderByIdResponseDtoGet order details for provider
provider.get-performance{email}PerformanceDtoGet provider performance Métricas
provider.mark-Documento-requiredMarkDocumentoRequiredDtoMarkDocumentoRequiredResponseDtoMark Documento as required

Provider Workflow Patterns

PatternInput DTOOutput DTODescription
provider.initial-inspectionInitialInspectionDtoInitialInspectionResponseDtoSubmit initial inspection
provider.get-initial-inspection{orderId, providerId}InitialInspectionGet inspection data
provider.process-registration{orderId, processes}ResponseRegister work processes
provider.final-deliveryFinalDeliveryDtoResponseSubmit final delivery
provider.send-report{orderId, providerId}ResponseSend report to client
provider.quote.approval{orderId, action}ResponseProcess quote approval

Auction Patterns

PatternInput DTOOutput DTODescription
auction.publishPublishAuctionDtoResponsePublish order to auction
auction.provider-responseProviderAuctionResponseDtoResponseProvider accepts/rejects
auction.create-offerCreateAuctionOfferDtoResponseCreate auction bid
auction.edit-offerEditAuctionOfferDtoResponseEdit existing bid
auction.create-inflationCreateOfferInflationDtoResponseCreate price inflation
auction.upload-inflation-pdfUploadInflationPdfDtoResponseUpload inflation PDF
auction.generate-quote-pdfGenerateInflationQuotePdfDtoResponseGenerate quotation PDF
auction.assign-providerAssignProviderDtoResponseAssign provider to order
auction.listListAuctionsDtoResponseList all auctions
auction.get-by-orderGetAuctionByOrderIdDtoResponseGet auction by order ID
auction.get-detailGetAuctionDetailDtoResponseGet auction details
auction.list-offersListAuctionOffersDtoResponseList all offers
auction.list-finishedListFinishedAuctionsDtoResponseList Completod auctions
auction.create-dynamic-itemsCreateDynamicItemsDtoResponseCreate dynamic items
auction.upload-DocumentoUploadAuctionDocumentoDtoResponseUpload auction Documento

User Management Patterns

PatternInput DTOOutput DTODescription
users.list-providers{search, page, limit}ListProvidersResponseDtoList all providers
users.list-clients{search, page, limit}ListClientsResponseDtoList all clients
users.list-all{role, search, page, limit}ListAllUsersResponseDtoList all users
users.create{name, email, role}UserCreate user account
users.update{userId, updateData}UserUpdate user
users.delete{userId}{success, message}Delete user

Documento Management Patterns

PatternInput DTOOutput DTODescription
Documentos.createCreateDocumentoDtoDocumentCreate Documento record
Documentos.update-EstadoUpdateDocumentoEstadoDtoResponseUpdate Documento Estado
Documentos.delete{DocumentoId}ResponseDelete Documento
Documentos.get-ResumenGetDocumentosResumenDtoResponseGet Documentos Resumen

Service Management Patterns

PatternInput DTOOutput DTODescription
services.getGetServicesDtoServices[]Get available services
services.associateAssociateServiceDtoResponseAssociate service to provider

Reference: algesta-ms-provider-nestjs/src/infrastructure/controllers/

7. Base de datos Schema

The Provider Microservicio uses MongoDB with the following collections:

Collections Descripción General

CollectionPurposeEstimated SizeKey Indexes
providersProvider profiles1-2 KB/docemail (unique), identification, isActivo
auctionAuction records with bids10-100 KB/docauctionId (unique), orderId, multiple compound indexes
DocumentosDocumento records0.5-1 KB/docproviderId, DocumentoType, Estado, expirationDate
servicesAvailable services0.5-1 KB/docname, category, isActivo
service_providersProvider-service mapping0.2 KB/docproviderId + serviceId (compound unique)
usersUser accounts1-2 KB/docemail (unique), role, identification
ordersDenormalized order dataVariableorderId, Estado, assignedProvider

Auction Collection Indexes (Critical for Performance):

  • auctionId (unique): Fast auction lookup
  • orderId: Find auction by order
  • assetId: Find auction by asset
  • createdAt: Chronological sorting
  • auctionBids.providerId: Find bids by provider
  • auctionBids.isCurrent: Find current/Activo bids
  • orderId + auctionBids.providerId (compound): Provider-specific auction queries
  • orderId + auctionBids.providerId + auctionBids.isCurrent (compound): Current bid queries
  • dynamicQuotations.providerId: Find quotations by provider
  • orderId + dynamicQuotations.providerId (compound): Provider quotation queries
  • auctionInflations.bidId: Find inflations by bid
  • auctionInflations.providerId: Find inflations by provider
  • orderId + auctionInflations.bidId (compound): Bid inflation queries
  • auctionInflations.createdAt: Chronological inflation sorting

Reference: algesta-ms-provider-nestjs/src/shared/infrastructure/Base de datos/

8. Documento Validation System

The Provider Microservicio implements a comprehensive Document validation workflow.

Documento Types:

  • RUT (Tax Registration)
  • Cámara de Comercio (Chamber of Commerce)
  • Cédula (ID Card)
  • Certificación Bancaria (Bank Certification)
  • Póliza de Responsabilidad Civil (Liability Insurance)
  • ARL (Occupational Risks Insurance)

Documento Lifecycle:

  1. Provider uploads Documento
  2. Documento saved to Azure Blob Storage
  3. Documento record created in MongoDB
  4. Admin reviews Documento
  5. Documento approved or rejected
  6. Expiration date tracking
  7. Renewal notifications

Validation Estado:

  • Pendiente: Awaiting review
  • APPROVED: Validated and Activo
  • REJECTED: Did not pass validation
  • EXPIRED: Expiration date passed

9. Provider Performance Tracking

The Provider Microservicio tracks provider performance Métricas.

Performance Métricas:

  • Services Completod: Count of successfully Completod orders
  • Services Rejected: Count of rejected or failed orders
  • Auctions Won: Count of auctions won
  • Average Rating: Average client rating (1-5 stars)
  • Response Time: Average time to respond to auctions
  • Completion Rate: Percentage of orders Completod vs assigned

PerformanceDto:

{
providerId: string;
providerName: string;
servicesCompleted: number;
servicesRejected: number;
auctionsWon: number;
averageRating: number;
responseTimeAvgHours: number;
completionRate: number; // Percentage
}

10. Integration Points

The Provider Microservicio integrates with other services and external systems.

Internal Service Integration

Orders Microservicio:

  • Events Subscribed:
    • order.published: Order published to auction
    • order.updated: Order Estado updates
  • Patterns Called:
    • orders.update-info: Update order with provider assignment
    • orders.get-by-id: Get order details
  • Propósito: Synchronize order and provider data

Notifications Microservicio:

  • Patterns Called:
    • notification.send-order-reminder: Send reminders
    • notification.create-notification: Create notifications
  • Propósito: Notify providers and clients of auction events

External Services

Azure Blob Storage:

  • Propósito: Documento and PDF storage
  • SDK: @azure/storage-blob
  • Funcionalidades: Upload Documentos, store PDFs, generate SAS tokens

Puppeteer:

  • Propósito: PDF generation for quotations
  • Version: 24.x
  • Funcionalidades: Headless Chrome, HTML to PDF, template rendering

PDFKit:

  • Propósito: PDF creation and manipulation
  • Funcionalidades: Generate quotations, invoices, reports

11. Provider Workflow Diagram

sequenceDiagram
    participant Provider
    participant ProviderMS as Provider MS
    participant OrdersMS as Orders MS
    participant MongoDB
    participant Notifications as Notifications MS

    Note over Provider,Notifications: Phase 1: Auction & Assignment
    OrdersMS->>ProviderMS: auction.publish
    ProviderMS->>MongoDB: Create auction
    ProviderMS->>Notifications: Notify providers
    Provider->>ProviderMS: auction.create-offer
    ProviderMS->>MongoDB: Save bid
    ProviderMS->>ProviderMS: Evaluate bids
    ProviderMS->>ProviderMS: Assign provider
    ProviderMS->>OrdersMS: orders.update-info (assigned)
    ProviderMS->>Notifications: Notify provider assigned

    Note over Provider,Notifications: Phase 2: Initial Inspection
    Provider->>ProviderMS: provider.initial-inspection
    ProviderMS->>MongoDB: Save inspection
    ProviderMS->>OrdersMS: Update order
    ProviderMS->>Notifications: Notify client

    Note over Provider,Notifications: Phase 3: Work Execution
    Provider->>ProviderMS: confirm-work-start
    ProviderMS->>MongoDB: Update status
    Provider->>ProviderMS: process-registration
    ProviderMS->>MongoDB: Save processes
    Provider->>ProviderMS: work-completion-report
    ProviderMS->>MongoDB: Save report

    Note over Provider,Notifications: Phase 4: Final Delivery
    Provider->>ProviderMS: provider.final-delivery
    ProviderMS->>MongoDB: Save delivery
    ProviderMS->>OrdersMS: Update order (completed)
    ProviderMS->>Notifications: Notify client approval

12. Auction Flow Diagram

sequenceDiagram
    participant Admin
    participant OrdersMS as Orders MS
    participant ProviderMS as Provider MS
    participant Providers
    participant MongoDB
    participant Azure as Azure Blob

    Admin->>OrdersMS: Publish order to auction
    OrdersMS->>ProviderMS: auction.publish
    ProviderMS->>MongoDB: Create auction record
    ProviderMS->>Providers: Notify eligible providers

    loop Bidding Phase
        Providers->>ProviderMS: auction.create-offer
        ProviderMS->>MongoDB: Save bid
        Providers->>ProviderMS: auction.edit-offer
        ProviderMS->>MongoDB: Update bid
    end

    Note over Admin,Azure: Optional Inflation
    Admin->>ProviderMS: auction.create-inflation
    ProviderMS->>MongoDB: Save inflation data
    ProviderMS->>ProviderMS: Generate inflation PDF
    ProviderMS->>Azure: Upload PDF
    ProviderMS->>MongoDB: Save PDF URL

    Admin->>ProviderMS: auction.assign-provider
    ProviderMS->>MongoDB: Update bid (isAssigned=true)
    ProviderMS->>OrdersMS: orders.update-info (assigned)
    ProviderMS->>Providers: Notify providers (winners/losers)

13. Configuration and Environment Variables

Required Environment Variables

Ventana de terminal
# Application
NODE_ENV=development|production
PORT=3000
# Database
MONGODB_URI=mongodb://localhost:27017/providers
DB_POOL_MAX=20
DB_POOL_MIN=5
# 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
# Azure Blob Storage
AZURE_STORAGE_CONNECTION_STRING=your_connection_string
AZURE_STORAGE_CONTAINER_NAME=documents
# SendGrid (via Notifications MS)
SENDGRID_API_KEY=your_sendgrid_api_key
# PDF Generation
PDF_GENERATION_TIMEOUT=30000
PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
# Logging
LOG_LEVEL=info|debug|error

14. Pruebas Strategy

Unit Pruebas

Command Handler Pruebas:

describe('CreateAuctionOfferHandler', () => {
it('should create auction offer successfully', async () => {
const command = new CreateAuctionOfferCommand(offerDto);
const result = await handler.execute(command);
expect(result.success).toBe(true);
});
});

Query Handler Pruebas:

describe('GetAuctionDetailHandler', () => {
it('should retrieve auction details', async () => {
const query = new GetAuctionDetailQuery(auctionId);
const result = await handler.execute(query);
expect(result.auctionId).toBe(auctionId);
});
});

Integration Pruebas

Auction Logic Pruebas:

  • Test Completo auction lifecycle
  • Test bid creation and editing
  • Test inflation calculations
  • Test provider assignment

Documento Validation Pruebas:

  • Test Document upload
  • Test validation workflow
  • Test expiration tracking

E2E Pruebas

Provider Workflow Pruebas:

  • Test end-to-end provider workflow
  • Test auction participation
  • Test order completion

PDF Generation Pruebas:

  • Test quotation PDF generation
  • Test inflation PDF generation
  • Test report generation

Test Coverage Targets:

  • Statements: >90%
  • Branches: >85%
  • Functions: >90%
  • Lines: >90%

Reference: algesta-ms-provider-nestjs/README.md and algesta-ms-provider-nestjs/package.json