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
PORTenvironment 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
| Module | Location | Purpose | Key Componentes |
|---|---|---|---|
| ProviderModule | src/infrastructure/modules/provider.module.ts | Provider management and workflows | ProviderController, Provider handlers, Provider Repositorio |
| AuctionsModule | src/infrastructure/modules/auctions.module.ts | Auction system and bidding | AuctionsController, Auction handlers, Auction Repositorio |
| DocumentosModule | src/infrastructure/modules/Documentos.module.ts | Document validation | DocumentosController, Documento handlers |
| ServicesModule | src/infrastructure/modules/services.module.ts | Service catalog | ServicesController, Service handlers |
Shared Infrastructure Modules
| Module | Purpose |
|---|---|
| Base de datosModule | MongoDB connection and configuration |
| MessagingModule | Redis/Kafka messaging configuration |
| HealthModule | Health check Endpoints |
| WinstonModule | Structured logging |
| ScheduleModule | Cron 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
| Command | Handler | Purpose | File Path |
|---|---|---|---|
| CreateProviderCommand | CreateProviderHandler | Register new provider | src/application/commands/create-provider.command.ts |
| UpdateProviderCommand | UpdateProviderHandler | Update provider information | src/application/commands/update-provider.command.ts |
| ProcessRegistrationCommand | ProcessRegistrationHandler | Process provider registration workflow | src/application/commands/process-registration.command.ts |
| MarkDocumentoRequiredCommand | MarkDocumentoRequiredHandler | Mark Documento as required | src/application/commands/mark-Documento-required.command.ts |
| ValidateDiscountCommand | ValidateDiscountHandler | Validate discount eligibility | src/application/commands/validate-discount.command.ts |
Provider Workflow Commands
| Command | Handler | Purpose | File Path |
|---|---|---|---|
| InitialInspectionCommand | InitialInspectionHandler | Submit initial inspection | src/application/commands/initial-inspection.command.ts |
| ConfirmWorkStartCommand | ConfirmWorkStartHandler | Confirm work start | src/application/commands/confirm-work-start.command.ts |
| WorkCompletionReportCommand | WorkCompletionReportHandler | Submit work completion report | src/application/commands/work-completion-report.command.ts |
| FinalDeliveryCommand | FinalDeliveryHandler | Submit final delivery | src/application/commands/final-delivery.command.ts |
| SendReportCommand | SendReportHandler | Send report to client | src/application/commands/send-report.command.ts |
| SaveFinalDeliveryReportUrlCommand | SaveFinalDeliveryReportUrlHandler | Save report URL | src/application/commands/save-final-delivery-report-url.command.ts |
Auction Management Commands
| Command | Handler | Purpose | File Path |
|---|---|---|---|
| PublishOrderForAuctionCommand | PublishOrderForAuctionHandler | Publish order to auction | src/application/commands/publish-order-for-auction.command.ts |
| ProviderAuctionResponseCommand | ProviderAuctionResponseHandler | Provider accepts/rejects auction | src/application/commands/provider-auction-response.command.ts |
| CreateAuctionOfferCommand | CreateAuctionOfferHandler | Create auction bid | src/application/commands/create-auction-offer.command.ts |
| EditAuctionOfferCommand | EditAuctionOfferHandler | Edit existing bid | src/application/commands/edit-auction-offer.command.ts |
| CreateOfferInflationCommand | CreateOfferInflationHandler | Create price inflation | src/application/commands/create-offer-inflation.command.ts |
| UploadInflationPdfCommand | UploadInflationPdfHandler | Upload inflation PDF | src/application/commands/upload-inflation-pdf.command.ts |
| GenerateInflationQuotePdfCommand | GenerateInflationQuotePdfHandler | Generate quotation PDF | src/application/commands/generate-inflation-quote-pdf.command.ts |
| AssignProviderCommand | AssignProviderHandler | Assign provider to order | src/application/commands/assign-provider.command.ts |
| CreateDynamicItemsCommand | CreateDynamicItemsHandler | Create dynamic quotation items | src/application/commands/create-dynamic-items.command.ts |
| UploadAuctionDocumentoCommand | UploadAuctionDocumentoHandler | Upload auction Documentos | src/application/commands/upload-auction-Documento.command.ts |
Documento Management Commands
| Command | Handler | Purpose | File Path |
|---|---|---|---|
| CreateDocumentoCommand | CreateDocumentoHandler | Create Documento record | src/application/commands/create-Documento.command.ts |
| UpdateDocumentoEstadoCommand | UpdateDocumentoEstadoHandler | Update Documento Estado | src/application/commands/update-Documento-Estado.command.ts |
| DeleteDocumentoCommand | DeleteDocumentoHandler | Delete Documento | src/application/commands/delete-Documento.command.ts |
User Management Commands
| Command | Handler | Purpose | File Path |
|---|---|---|---|
| CreateUserCommand | CreateUserHandler | Create user account | src/application/commands/create-user.command.ts |
| UpdateUserCommand | UpdateUserHandler | Update user information | src/application/commands/update-user.command.ts |
| DeleteUserCommand | DeleteUserHandler | Delete user account | src/application/commands/delete-user.command.ts |
Service Management Commands
| Command | Handler | Purpose | File Path |
|---|---|---|---|
| AssociateServiceCommand | AssociateServiceHandler | Associate service with provider | src/application/commands/associate-service.command.ts |
Order Processing Commands
| Command | Handler | Purpose | File Path |
|---|---|---|---|
| SendOrderReminderCommand | SendOrderReminderHandler | Send order reminder | src/application/commands/send-order-reminder.command.ts |
| ProcessQuoteApprovalCommand | ProcessQuoteApprovalHandler | Process quote approval | src/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
| Query | Handler | Purpose | File Path |
|---|---|---|---|
| GetProviderByIdentificationQuery | GetProviderByIdentificationHandler | Get provider by ID | src/application/queries/get-provider-by-identification.query.ts |
| ListProvidersQuery | ListProvidersHandler | List all providers with pagination | src/application/queries/list-providers.query.ts |
| ValidateProviderEligibilityQuery | ValidateProviderEligibilityHandler | Validate provider eligibility | src/application/queries/validate-provider-eligibility.query.ts |
| GetProviderPerformanceQuery | GetProviderPerformanceHandler | Get provider performance Métricas | src/application/queries/get-provider-performance.query.ts |
| GetOrderDetailsForProviderQuery | GetOrderDetailsForProviderHandler | Get order details for provider | src/application/queries/get-order-details-for-provider.query.ts |
| ValidateStartWorkQuery | ValidateStartWorkHandler | Validate work start conditions | src/application/queries/validate-start-work.query.ts |
| GetInitialInspectionQuery | GetInitialInspectionHandler | Get initial inspection data | src/application/queries/get-initial-inspection.query.ts |
| ListAuctionsForProviderQuery | ListAuctionsForProviderHandler | List auctions for provider | src/application/queries/list-auctions-for-provider.query.ts |
| ListAuctionOffersForProviderQuery | ListAuctionOffersForProviderHandler | List provider’s auction offers | src/application/queries/list-auction-offers-for-provider.query.ts |
Auction Queries
| Query | Handler | Purpose | File Path |
|---|---|---|---|
| GetAuctionOrdersQuery | GetAuctionOrdersHandler | Get orders in auction | src/application/queries/get-auction-orders.query.ts |
| ListAuctionsQuery | ListAuctionsHandler | List all auctions | src/application/queries/list-auctions.query.ts |
| GetAuctionByOrderIdQuery | GetAuctionByOrderIdHandler | Get auction by order ID | src/application/queries/get-auction-by-order-id.query.ts |
| GetAuctionDetailQuery | GetAuctionDetailHandler | Get detailed auction information | src/application/queries/get-auction-detail.query.ts |
| ListAuctionOffersQuery | ListAuctionOffersHandler | List all offers for auction | src/application/queries/list-auction-offers.query.ts |
| ListFinishedAuctionsQuery | ListFinishedAuctionsHandler | List Completod auctions | src/application/queries/list-finished-auctions.query.ts |
| GetProviderLastOfferQuery | GetProviderLastOfferHandler | Get provider’s last offer | src/application/queries/get-provider-last-offer.query.ts |
Documento Queries
| Query | Handler | Purpose | File Path |
|---|---|---|---|
| GetDocumentosQuery | GetDocumentosHandler | Get Documentos with filters | src/application/queries/get-Documentos.query.ts |
| GetDocumentosResumenQuery | GetDocumentosResumenHandler | Get Documentos Resumen | src/application/queries/get-Documentos-Resumen.query.ts |
User Queries
| Query | Handler | Purpose | File Path |
|---|---|---|---|
| ListAllUsersQuery | ListAllUsersHandler | List all users with filters | src/application/queries/list-all-users.query.ts |
| ListClientsQuery | ListClientsHandler | List client users | src/application/queries/list-clients.query.ts |
Service Queries
| Query | Handler | Purpose | File Path |
|---|---|---|---|
| GetServicesQuery | GetServicesHandler | Get available services | src/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 namelastName(string): Provider last nameemail(string, unique): Provider email addressidentification(string): Tax ID or identification numberphone(string): Contact phone number
Location:
city(string): Provider citycountry(string): Provider countryaddress(string): Physical addresslocation(object): Geolocation coordinateslatitude(number)longitude(number)
Banking Information:
bank(string): Bank nametypeAccount(enum: SAVINGS, CHECKING): Account typenumberAccount(string): Account number
Account Information:
password(string): Hashed passwordrole(enum: PROVIDER): User roleisActivo(boolean): Account Activo Estado
Metadata:
createdAt(Date): Registration timestampupdatedAt(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 identifierorderId(string): Associated order IDassetId(string): Associated asset ID
Auction Duration:
duration(object): Auction duration configurationdays(number): Duration in dayshours(number): Duration in hoursminutes(number): Duration in minutes
expiredAuction(Date): Auction expiration timestampdurationInHours(number): Total duration in hours (calculated)
Auction Questions:
questions(array): Custom questions for providersquestion(string): Question textorder(number): Display orderresponseType(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 identifierproviderId(string): Provider who submitted bidproviderEmail(string): Provider emailproviderName(string): Provider name
Offer Data (offerData):
totalOfferValor(number): Total bid amountlaborCost(number): Labor cost Componentematerials(array): Materials neededitem(string): Material Descripciónquantity(number): Quantity neededunitPrice(number): Price per unittotalPrice(number): Total for this material
spareParts(array): Spare parts neededpart(string): Part Descripciónquantity(number)unitPrice(number)totalPrice(number)
equipment(array): Equipment rentalequipment(string): Equipment Descripciónquantity(number)dailyRate(number)days(number)totalPrice(number)
transport(object): Transportation costsorigin(string): Starting locationdestination(string): Delivery locationdistance(number): Distance in kmcost(number): Transportation cost
items(array): Flexible item structure for complex quotes
Bid Estado:
isAssigned(boolean): Is this bid selectedassignedAt(Date): Assignment timestampisCurrent(boolean): Is this the Activo bidisRejected(boolean): Is this bid rejectedrejectedAt(Date): Rejection timestamp
Metadata:
metadata(object): Bid submission metadataipAddress(string): IP address of submissionuserAgent(string): Browser/client user agent
Dynamic Quotations (dynamicQuotations):
Array of dynamic quotation structures for flexible pricing:
quotationId(string): Unique quotation IDproviderId(string): Provider who created quotationitems(array): Flexible item arrayitemId(string): Item identifiername(string): Item nameDescripción(string): Item Descripciónquantity(number): QuantityunitPrice(number): Price per unittotalPrice(number): Total for this itemcategory(enum: LABOR, MATERIAL, EQUIPMENT, TRANSPORT, OTHER): Item categoryenabled(boolean): Is this item included in quote- Custom fields as needed
transport(object): Transportation quotationorigin(string)destination(string)type(enum: LOCAL, NATIONAL, INTERNATIONAL)cost(number)
totalEstimatedCost(number): Total quotation amountnotes(string): Additional notes
Auction Inflations (auctionInflations):
Array of admin-created price inflations:
inflationId(string): Unique inflation IDmessageId(string): Associated message IDbidId(string): Original bid being inflatedproviderId(string): Provider whose bid is inflatedinflationData(object): Inflation detailsitems(array): Inflated items- Original item data plus:
inflationPercentage(number): Inflation percentageoriginalPrice(number): Original priceinflatedPrice(number): Inflated price
additionalAnswers(array): Additional informationtransport(object): Inflated transport coststotalInflatedValor(number): Total after inflation
createdBy(object): Admin who created inflationuserId(string)userName(string)userEmail(string)
metadata(object): Inflation creation metadatacreatedAt(Date)ipAddress(string)
Price Documentoation (price):
DocumentoUrl(string): URL to generated price quote PDFauctionInflationId(string): Associated inflation IDuploadedAt(Date): Upload timestampEstado(enum: Pendiente, APPROVED, REJECTED): Quote EstadototalInflatedValor(number): Final inflated Valor
Timestamps:
createdAt(Date): Auction creation timestampupdatedAt(Date): Last update timestamp
Collection: auction
Indexes:
auctionId(unique)orderIdassetIdcreatedAtauctionBids.providerIdauctionBids.isCurrentorderId + auctionBids.providerId(compound)orderId + auctionBids.providerId + auctionBids.isCurrent(compound)dynamicQuotations.providerIdorderId + dynamicQuotations.providerId(compound)auctionInflations.bidIdauctionInflations.providerIdorderId + 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:
- Admin selects bid to inflate
- Specifies inflation percentage per item
- System calculates inflated Valors
- Generates PDF quotation with new prices
- Saves audit trail with admin information
- 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
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
provider.create-provider | CreateProviderDto | User | Create provider account |
provider.get-by-identification | GetProviderByIdentificationDto | User | Get provider by ID |
provider.update-provider | UpdateProviderDto | User | Update provider information |
provider.validate-eligibility | {providerId} | ValidateProviderEligibilityResponseDto | Validate provider eligibility |
provider.get-order-details-by-id | {orderId, providerId} | GetOrderByIdResponseDto | Get order details for provider |
provider.get-performance | {email} | PerformanceDto | Get provider performance Métricas |
provider.mark-Documento-required | MarkDocumentoRequiredDto | MarkDocumentoRequiredResponseDto | Mark Documento as required |
Provider Workflow Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
provider.initial-inspection | InitialInspectionDto | InitialInspectionResponseDto | Submit initial inspection |
provider.get-initial-inspection | {orderId, providerId} | InitialInspection | Get inspection data |
provider.process-registration | {orderId, processes} | Response | Register work processes |
provider.final-delivery | FinalDeliveryDto | Response | Submit final delivery |
provider.send-report | {orderId, providerId} | Response | Send report to client |
provider.quote.approval | {orderId, action} | Response | Process quote approval |
Auction Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
auction.publish | PublishAuctionDto | Response | Publish order to auction |
auction.provider-response | ProviderAuctionResponseDto | Response | Provider accepts/rejects |
auction.create-offer | CreateAuctionOfferDto | Response | Create auction bid |
auction.edit-offer | EditAuctionOfferDto | Response | Edit existing bid |
auction.create-inflation | CreateOfferInflationDto | Response | Create price inflation |
auction.upload-inflation-pdf | UploadInflationPdfDto | Response | Upload inflation PDF |
auction.generate-quote-pdf | GenerateInflationQuotePdfDto | Response | Generate quotation PDF |
auction.assign-provider | AssignProviderDto | Response | Assign provider to order |
auction.list | ListAuctionsDto | Response | List all auctions |
auction.get-by-order | GetAuctionByOrderIdDto | Response | Get auction by order ID |
auction.get-detail | GetAuctionDetailDto | Response | Get auction details |
auction.list-offers | ListAuctionOffersDto | Response | List all offers |
auction.list-finished | ListFinishedAuctionsDto | Response | List Completod auctions |
auction.create-dynamic-items | CreateDynamicItemsDto | Response | Create dynamic items |
auction.upload-Documento | UploadAuctionDocumentoDto | Response | Upload auction Documento |
User Management Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
users.list-providers | {search, page, limit} | ListProvidersResponseDto | List all providers |
users.list-clients | {search, page, limit} | ListClientsResponseDto | List all clients |
users.list-all | {role, search, page, limit} | ListAllUsersResponseDto | List all users |
users.create | {name, email, role} | User | Create user account |
users.update | {userId, updateData} | User | Update user |
users.delete | {userId} | {success, message} | Delete user |
Documento Management Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
Documentos.create | CreateDocumentoDto | Document | Create Documento record |
Documentos.update-Estado | UpdateDocumentoEstadoDto | Response | Update Documento Estado |
Documentos.delete | {DocumentoId} | Response | Delete Documento |
Documentos.get-Resumen | GetDocumentosResumenDto | Response | Get Documentos Resumen |
Service Management Patterns
| Pattern | Input DTO | Output DTO | Description |
|---|---|---|---|
services.get | GetServicesDto | Services[] | Get available services |
services.associate | AssociateServiceDto | Response | Associate 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
| Collection | Purpose | Estimated Size | Key Indexes |
|---|---|---|---|
| providers | Provider profiles | 1-2 KB/doc | email (unique), identification, isActivo |
| auction | Auction records with bids | 10-100 KB/doc | auctionId (unique), orderId, multiple compound indexes |
| Documentos | Documento records | 0.5-1 KB/doc | providerId, DocumentoType, Estado, expirationDate |
| services | Available services | 0.5-1 KB/doc | name, category, isActivo |
| service_providers | Provider-service mapping | 0.2 KB/doc | providerId + serviceId (compound unique) |
| users | User accounts | 1-2 KB/doc | email (unique), role, identification |
| orders | Denormalized order data | Variable | orderId, Estado, assignedProvider |
Auction Collection Indexes (Critical for Performance):
auctionId(unique): Fast auction lookuporderId: Find auction by orderassetId: Find auction by assetcreatedAt: Chronological sortingauctionBids.providerId: Find bids by providerauctionBids.isCurrent: Find current/Activo bidsorderId + auctionBids.providerId(compound): Provider-specific auction queriesorderId + auctionBids.providerId + auctionBids.isCurrent(compound): Current bid queriesdynamicQuotations.providerId: Find quotations by providerorderId + dynamicQuotations.providerId(compound): Provider quotation queriesauctionInflations.bidId: Find inflations by bidauctionInflations.providerId: Find inflations by providerorderId + auctionInflations.bidId(compound): Bid inflation queriesauctionInflations.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:
- Provider uploads Documento
- Documento saved to Azure Blob Storage
- Documento record created in MongoDB
- Admin reviews Documento
- Documento approved or rejected
- Expiration date tracking
- Renewal notifications
Validation Estado:
Pendiente: Awaiting reviewAPPROVED: Validated and ActivoREJECTED: Did not pass validationEXPIRED: 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 auctionorder.updated: Order Estado updates
- Patterns Called:
orders.update-info: Update order with provider assignmentorders.get-by-id: Get order details
- Propósito: Synchronize order and provider data
Notifications Microservicio:
- Patterns Called:
notification.send-order-reminder: Send remindersnotification.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
# ApplicationNODE_ENV=development|productionPORT=3000
# DatabaseMONGODB_URI=mongodb://localhost:27017/providersDB_POOL_MAX=20DB_POOL_MIN=5
# MessagingMESSAGING_TYPE=REDIS|KAFKAREDIS_HOST=localhostREDIS_PORT=6379KAFKA_BROKERS=localhost:9092
# AuthenticationJWT_SECRET=your_jwt_secret_keyJWT_EXPIRES_IN=1d
# Azure Blob StorageAZURE_STORAGE_CONNECTION_STRING=your_connection_stringAZURE_STORAGE_CONTAINER_NAME=documents
# SendGrid (via Notifications MS)SENDGRID_API_KEY=your_sendgrid_api_key
# PDF GenerationPDF_GENERATION_TIMEOUT=30000PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
# LoggingLOG_LEVEL=info|debug|error14. 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
15. Related Documentoation
- Backend Microservicios Descripción General
- Orders Microservicio
- Notifications Microservicio
- Inter-Service Communication
- [Base de datos Schemas](/02-architecture/Base de datos-schemas/)