> For the complete documentation index, see [llms.txt](https://docs.beeoclock.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.beeoclock.com/services/service-management.md).

# Service Management

## Overview

This directory contains comprehensive documentation for the Service Management module of the Bee O'clock panel service. The service management system handles the complete lifecycle of bookable services, including creation, configuration, pricing, scheduling, and presentation within the multi-tenant SaaS platform.

## Documentation Structure

### [API Documentation](/services/service-management/api.md)

Complete REST API reference including all endpoints, request/response schemas, authentication requirements, and usage examples for service management operations.

**Key Topics Covered:**

* Service CRUD operations
* Pagination and search functionality
* Media and banner management
* Required resource management
* Comprehensive data schemas
* Error handling and status codes

### [Interface Documentation](/services/service-management/interface.md)

Detailed documentation of TypeScript interfaces, DTOs, enums, and contracts used throughout the service management module.

**Key Topics Covered:**

* Data Transfer Objects (DTOs)
* Domain interfaces and entities
* Enum definitions and constants
* Type definitions and contracts
* Validation constraints
* Utility functions and type guards

### [Use Case Documentation](/services/service-management/usecase.md)

Business logic and use case implementations following Clean Architecture principles and CQRS pattern.

**Key Topics Covered:**

* Core business use cases
* Permission validation
* Error handling strategies
* Event publishing
* Performance considerations
* Integration patterns

### [Database Schema Documentation](/services/service-management/db_schema.md)

MongoDB schema definitions, relationships, indexes, and data integrity rules for the service management module.

**Key Topics Covered:**

* Entity schemas and relationships
* Sub-document structures
* Index strategies and optimization
* Multi-tenancy considerations
* Data validation and constraints
* Performance optimization

## Module Architecture

### Technology Stack

* **Framework**: NestJS with TypeScript
* **Database**: MongoDB with Mongoose ODM
* **Architecture**: Clean Architecture + CQRS + DDD
* **Patterns**: Repository Pattern, Event-Driven Architecture
* **Caching**: Redis for performance optimization
* **Storage**: Cloud storage for media files
* **Event System**: AMQP for async processing

### Core Features

#### Service Lifecycle Management

* Service creation with comprehensive validation
* Multi-version service updates with history tracking
* Soft deletion with dependency checking
* State management and audit trails

#### Multilingual Support

* Multiple language versions per service
* Language-specific pricing options
* Localized service descriptions
* International currency support

#### Flexible Pricing Models

* Multiple duration options per service
* Currency-specific pricing
* Language-targeted pricing
* Prepayment policy configuration

#### Rich Presentation

* Banner image management with optimization
* Color theming and branding
* Media upload and processing
* CDN integration for performance

#### Advanced Configuration

* Flexible duration management (fixed/variable)
* Resource requirement specifications
* Schedule and availability management
* Integration with specialist assignments

## Business Rules

### Service Creation

1. **Language Requirements**: At least one language version mandatory
2. **Duration Configuration**: Proper duration and pricing setup required
3. **Presentation**: Valid presentation configuration with optional media
4. **Business Validation**: Compliance with tenant-specific rules
5. **Resource Management**: Optional but validated resource requirements

### Service Updates

1. **Data Integrity**: Cannot remove all language or duration versions
2. **Active Booking Protection**: Restrictions on services with active bookings
3. **Change Tracking**: Complete audit trail of modifications
4. **Media Management**: Proper handling of media updates and deletions
5. **Cache Coordination**: Automatic cache invalidation on changes

### Service Deletion

1. **Dependency Checking**: Cannot delete services with active references
2. **Soft Delete**: Services archived rather than physically removed
3. **Data Preservation**: Historical data maintained for compliance
4. **Cleanup Coordination**: Proper cleanup of related resources

### Media Management

1. **File Validation**: Strict file format and size validation
2. **Image Processing**: Automatic optimization and thumbnail generation
3. **Storage Integration**: Efficient cloud storage utilization
4. **CDN Optimization**: Performance-optimized media delivery

## API Integration Examples

### Creating a Service

```typescript
POST /api/v1/service
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "languageVersions": [
    {
      "language": "en",
      "title": "Premium Massage Therapy",
      "description": "Relaxing therapeutic massage with aromatherapy"
    },
    {
      "language": "es", 
      "title": "Terapia de Masaje Premium",
      "description": "Masaje terapéutico relajante con aromaterapia"
    }
  ],
  "durationVersions": [
    {
      "durationInSeconds": 3600,
      "breakInSeconds": 300,
      "prices": [
        {
          "price": 80.00,
          "currency": "USD",
          "preferredLanguages": ["en"]
        },
        {
          "price": 75.00,
          "currency": "EUR", 
          "preferredLanguages": ["es"]
        }
      ]
    }
  ],
  "presentation": {
    "color": "#4A90E2"
  },
  "configuration": {
    "duration": {
      "durationVersionType": "RANGE"
    }
  },
  "prepaymentPolicy": {
    "isRequired": true,
    "isPercentage": true,
    "value": "25",
    "minimalCancelTime": "86400"
  },
  "schedules": [
    {
      "weekDays": [1, 2, 3, 4, 5],
      "startTime": "09:00",
      "endTime": "18:00"
    }
  ]
}
```

### Updating Service Media

```typescript
POST /api/v1/service/{id}/media
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: multipart/form-data

--boundary
Content-Disposition: form-data; name="file"; filename="service-banner.jpg"
Content-Type: image/jpeg

[binary image data]
--boundary
Content-Disposition: form-data; name="description"

Main promotional banner for massage therapy service
--boundary--
```

### Paginated Service Listing

```typescript
GET /api/v1/service/paged?page=1&size=10&phrase=massage
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Development Guidelines

### Testing Strategy

* **Unit Tests**: Business logic validation and domain rules
* **Integration Tests**: Database operations and external services
* **E2E Tests**: Complete API workflows and user scenarios
* **Performance Tests**: Load testing and scalability validation
* **Media Tests**: File upload and processing validation

### Error Handling

* Domain-specific exceptions with clear error messages
* Consistent error response format across all endpoints
* Proper HTTP status codes for different error types
* Detailed logging for debugging and monitoring
* Graceful degradation for non-critical failures

### Performance Considerations

* Comprehensive database indexing strategy
* Multi-level caching with intelligent invalidation
* Optimized queries with proper data loading
* Asynchronous media processing
* CDN integration for static content delivery

### Security Best Practices

* Input validation and sanitization at all levels
* Role-based access control with granular permissions
* Secure file upload handling with validation
* Audit logging for all sensitive operations
* Rate limiting and abuse prevention

## Related Modules

### Dependencies

* **Permission Module**: Role and permission management
* **Media Module**: File storage and processing
* **Business Client Module**: Tenant management and settings
* **Specialist Module**: Service provider assignments
* **Resource Module**: Resource requirement management
* **Order Module**: Service booking and reservation

### Integration Points

* **Cache Module**: Performance optimization
* **Event Bus**: Async processing and notifications
* **Storage Service**: Media file management
* **Search Service**: Enhanced search capabilities
* **Notification Module**: Service-related notifications

## Performance Metrics

### Key Performance Indicators

* Service creation/update response times
* Search query performance and accuracy
* Media upload and processing speeds
* Cache hit rates and effectiveness
* Database query optimization metrics

### Monitoring and Alerting

* API endpoint response time monitoring
* Database performance and query analysis
* Cache performance and hit rate tracking
* Media processing success rates
* Error rate monitoring and alerting

## Scalability Considerations

### Horizontal Scaling

* Stateless service design for easy scaling
* Database sharding strategies for large datasets
* Distributed caching for multi-instance deployment
* Load balancing for API endpoints
* CDN scaling for media delivery

### Vertical Scaling

* Database optimization and indexing
* Query performance tuning
* Memory usage optimization
* CPU-intensive operation optimization
* Storage efficiency improvements

## Future Enhancements

### Planned Features

* **AI-Powered Recommendations**: Service suggestion algorithms
* **Dynamic Pricing**: Time and demand-based pricing models
* **Service Templates**: Reusable service configuration templates
* **Advanced Analytics**: Service performance and usage insights
* **Bulk Operations**: Mass service management capabilities

### Technical Improvements

* **GraphQL API**: Enhanced query capabilities and flexibility
* **Event Sourcing**: Complete audit trail with event streams
* **Microservice Architecture**: Split into focused microservices
* **Real-time Updates**: WebSocket integration for live updates
* **Advanced Search**: Elasticsearch integration for complex queries

## Troubleshooting Guide

### Common Issues

* **Service Creation Failures**: Validation errors and resolution
* **Media Upload Problems**: File format and size issues
* **Permission Denied Errors**: Access control troubleshooting
* **Performance Issues**: Query optimization and caching
* **Data Consistency**: Multi-tenant isolation problems

### Debugging Tools

* Structured error messages with correlation IDs
* Comprehensive logging with request tracing
* Database query analysis tools
* Cache inspection utilities
* Performance profiling tools

### Support Resources

* API documentation and examples
* Error code reference guide
* Performance optimization guide
* Best practices documentation
* Community forums and support channels

## Contributing Guidelines

### Code Standards

* TypeScript strict mode compliance
* ESLint and Prettier configuration
* Comprehensive test coverage requirements
* Clean Architecture principles adherence
* Domain-Driven Design patterns

### Documentation Requirements

* Update documentation with code changes
* Include comprehensive API examples
* Maintain schema documentation accuracy
* Document business rule changes
* Provide migration guides for breaking changes

### Review Process

* Mandatory code review for all changes
* Testing validation and coverage verification
* Documentation update validation
* Performance impact assessment
* Security review for sensitive changes

## Migration and Deployment

### Database Migrations

* Schema evolution and backwards compatibility
* Data migration scripts and validation
* Index management and optimization
* Performance impact assessment
* Rollback procedures and safety measures

### Deployment Strategies

* Blue-green deployment for zero downtime
* Feature flags for gradual rollouts
* Database migration coordination
* Cache warming strategies
* Health check validation

### Monitoring and Rollback

* Real-time deployment monitoring
* Automated rollback triggers
* Data integrity validation
* Performance regression detection
* User impact assessment
