> 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/usecase.md).

# Use Case Documentation

## Overview

The service management module implements comprehensive business logic for managing bookable services within the Bee O'clock platform. The module follows Clean Architecture principles and CQRS pattern to separate command and query responsibilities while maintaining clear business logic boundaries.

## Core Use Cases

### 1. Get Paged Services Use Case

**Purpose**: Retrieves a paginated list of services for a tenant with optional search and filtering capabilities.

**Location**: `GetPagedServicesUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `pagination: ServicePaginationDto` - Pagination and search parameters

**Business Logic**:

1. Validates actor permissions (`READ_SERVICE`)
2. Applies search phrase filtering if provided
3. Executes paginated query through CQRS query bus
4. Returns paginated result with services and metadata

**Search Functionality**:

* Searches across service titles and descriptions
* Supports multilingual content search
* Case-insensitive phrase matching
* Efficient indexing for performance

**Output**: `PaginationResponseDto<ServiceDto>`

### 2. Get Service by ID Use Case

**Purpose**: Retrieves detailed information about a specific service including all configuration and presentation data.

**Location**: `GetServiceUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `serviceId: string` - Unique identifier of the service

**Business Logic**:

1. Validates actor permissions (`READ_SERVICE`)
2. Retrieves service from repository through query bus
3. Throws `ServiceNotFoundException` if service not found
4. Returns complete service data with all related information

**Data Population**:

* Populates language versions
* Includes duration and pricing options
* Loads presentation media
* Includes scheduling information

**Output**: `ServiceDto`

### 3. Create Service Use Case

**Purpose**: Creates a new service with comprehensive validation and configuration setup.

**Location**: `CreateServiceUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `service: ServiceDto` - Service data to create

**Business Logic**:

1. Validates actor permissions (`CREATE_SERVICE`)
2. Validates service data structure and content
3. Ensures language versions are provided
4. Validates duration versions and pricing
5. Checks business rules compliance
6. Creates service through command bus
7. Publishes service created event
8. Returns created service ID

**Validation Rules**:

* At least one language version required
* Valid duration and pricing configuration
* Proper color format validation
* Media file format validation
* Business-specific constraints

**Event Publishing**:

* Emits `ServiceCreatedEvent` for downstream processing
* Triggers cache invalidation
* Notifies integration systems

**Output**: `string` (Service ID)

### 4. Update Service Use Case

**Purpose**: Updates an existing service with comprehensive validation and change tracking.

**Location**: `UpdateServiceUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `serviceId: string` - ID of service to update
* `update: ServiceDto` - Updated service data

**Business Logic**:

1. Validates actor permissions (`EDIT_SERVICE`)
2. Retrieves existing service for comparison
3. Validates update data and business rules
4. Ensures critical data integrity
5. Executes update through command bus
6. Publishes service updated event
7. Handles cache invalidation

**Update Validation**:

* Cannot remove all language versions
* Cannot remove all duration versions
* Validates pricing changes
* Ensures media consistency
* Checks scheduling conflicts

**Change Tracking**:

* Maintains audit trail
* Tracks field-level changes
* Preserves historical data
* Enables rollback capabilities

**Output**: `void`

### 5. Delete Service Use Case

**Purpose**: Safely deletes a service with comprehensive validation and dependency checking.

**Location**: `DeleteServiceUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `serviceId: string` - ID of service to delete

**Business Logic**:

1. Validates actor permissions (`DELETE_SERVICE`)
2. Checks service exists
3. Validates no active orders reference service
4. Validates no active appointments
5. Performs soft delete (archive)
6. Publishes service deleted event
7. Handles cleanup of related data

**Safety Validations**:

* Cannot delete services with active bookings
* Cannot delete services referenced in orders
* Cannot delete services with pending payments
* Validates business continuity

**Cleanup Process**:

* Archives service data
* Maintains historical references
* Cleans up caches
* Notifies dependent systems

**Output**: `{ deletedCount: number }`

### 6. Update Service Banners Use Case

**Purpose**: Manages service banner images and media presentation.

**Location**: `UpdateServiceBannersUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `serviceId: string` - ID of service to update
* `media: any` - Media metadata
* `file: Express.Multer.File` - Uploaded image file

**Business Logic**:

1. Validates actor permissions (`CREATE_SERVICE`)
2. Validates file format and size
3. Processes image upload
4. Updates service presentation
5. Optimizes images for different sizes
6. Updates service media references

**File Processing**:

* Validates image formats (JPEG, PNG, WebP)
* Enforces file size limits
* Generates thumbnails
* Optimizes for web delivery
* Handles storage integration

**Output**: `MediaDto` (uploaded media information)

### 7. Delete Service Banner Use Case

**Purpose**: Removes specific banner images from service presentation.

**Location**: `DeleteServiceBannerUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `serviceId: string` - ID of service
* `bannerId: string` - ID of banner to delete

**Business Logic**:

1. Validates actor permissions (`CREATE_SERVICE`)
2. Validates banner exists for service
3. Removes banner from service presentation
4. Deletes media files from storage
5. Updates service presentation data

**Storage Cleanup**:

* Removes files from storage
* Cleans up thumbnails
* Updates CDN references
* Maintains data consistency

**Output**: `{ deletedCount: number }`

### 8. Update Service Required Resources Use Case

**Purpose**: Manages resource requirements for service delivery.

**Location**: `UpdateServiceRequiredResourcesUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `serviceId: string` - ID of service
* `requiredResources: RequiredResourceDto[]` - Resource requirements

**Business Logic**:

1. Validates actor permissions (`EDIT_SERVICE`)
2. Validates resource references exist
3. Validates resource quantities
4. Updates service resource requirements
5. Handles resource availability checking

**Resource Validation**:

* Ensures resources exist in system
* Validates quantity requirements
* Checks resource availability
* Validates business constraints

**Output**: `void`

## Permission Requirements

All service management use cases require specific permissions validated through `PermissionValidatorUseCase`:

* **READ\_SERVICE**: Required for viewing services
* **CREATE\_SERVICE**: Required for creating services and managing media
* **EDIT\_SERVICE**: Required for updating services and resources
* **DELETE\_SERVICE**: Required for deleting services

## Error Handling

### Common Exceptions

* `ServiceNotFoundException`: When service ID doesn't exist
* `ServiceCreationException`: When service creation validation fails
* `ServiceUpdationException`: When service update validation fails
* `ServiceDeletionException`: When service cannot be deleted
* `MediaUploadException`: When media upload fails
* `ResourceNotFoundException`: When required resource doesn't exist

### Error Response Pattern

All use cases follow consistent error handling:

1. Log errors with context and stack trace
2. Preserve original error for debugging
3. Throw domain-specific exceptions
4. Handle transaction rollback automatically
5. Provide meaningful error messages

## Business Rules

### Service Creation Rules

1. **Language Requirements**: At least one language version mandatory
2. **Duration Configuration**: Valid duration and pricing required
3. **Presentation**: Color format validation and media constraints
4. **Scheduling**: Schedule validation and conflict checking
5. **Resource Requirements**: Valid resource references

### Service Update Rules

1. **Data Integrity**: Cannot remove all language/duration versions
2. **Active Bookings**: Cannot modify services with active appointments
3. **Pricing Changes**: Proper validation for price updates
4. **Media Management**: File format and size validation
5. **Resource Updates**: Availability and constraint checking

### Service Deletion Rules

1. **Dependency Checking**: Cannot delete services with active references
2. **Soft Delete**: Services are archived, not physically removed
3. **Data Preservation**: Historical data maintained for reporting
4. **Cleanup Process**: Proper cleanup of related data

### Media Management Rules

1. **File Formats**: Only JPEG, PNG, WebP allowed
2. **File Size**: Maximum 10MB per file
3. **Image Processing**: Automatic optimization and thumbnail generation
4. **Storage Management**: Efficient storage and CDN integration

## Integration Points

### Event Publishing

* **ServiceCreatedEvent**: Published when service is created
* **ServiceUpdatedEvent**: Published when service is updated
* **ServiceDeletedEvent**: Published when service is deleted
* **MediaUploadedEvent**: Published when media is uploaded

### Cache Management

* Automatic cache invalidation on mutations
* Cache keys: `GET_SERVICE`, `GET_PAGED_SERVICES`, `GET_PUBLIC_SERVICES`
* Uses distributed caching for performance
* TTL-based cache expiration

### External Services

* **Storage Service**: For media file management
* **Image Processing**: For thumbnail generation
* **CDN Integration**: For media delivery optimization
* **Search Service**: For enhanced search capabilities

## Performance Considerations

### Query Optimization

* Indexed searches for pagination
* Efficient phrase search implementation
* Optimized loading of related data
* Proper query result caching

### Media Processing

* Asynchronous image processing
* Multiple size generation
* Efficient storage utilization
* CDN integration for delivery

### Caching Strategy

* Multi-level caching approach
* Cache warming for popular services
* Intelligent cache invalidation
* Performance monitoring

## Testing Strategy

### Unit Tests

* Mock all external dependencies
* Test business logic in isolation
* Cover all error scenarios
* Validate permission checks
* Test validation rules

### Integration Tests

* Test with real database
* Validate transaction behavior
* Test event publishing
* Cache integration testing
* Media upload testing

### End-to-End Tests

* Full workflow testing
* API endpoint validation
* File upload and processing
* Permission integration testing
* Performance benchmarking

## Monitoring and Observability

### Metrics Collection

* Use case execution times
* Error rates and types
* Cache hit ratios
* Media processing metrics
* Resource utilization

### Logging Strategy

* Structured logging with correlation IDs
* Business event logging
* Error tracking with context
* Performance monitoring
* Security audit logging

### Health Checks

* Database connectivity
* Storage service availability
* Cache system health
* External service dependencies
* Business rule validation

## Future Enhancements

### Planned Features

1. **Advanced Search**: Elasticsearch integration for complex queries
2. **AI Recommendations**: Machine learning for service suggestions
3. **Dynamic Pricing**: Time-based and demand-based pricing
4. **Service Templates**: Reusable service configuration templates
5. **Bulk Operations**: Mass service management capabilities

### Technical Improvements

1. **Event Sourcing**: Complete audit trail with event streams
2. **Microservice Split**: Separate media and core service management
3. **GraphQL API**: Enhanced query capabilities
4. **Real-time Updates**: WebSocket integration for live updates
5. **Advanced Analytics**: Service performance and usage analytics

## Security Considerations

### Data Protection

* PII handling in service descriptions
* Secure media storage and access
* Role-based access control
* Audit logging for compliance

### Input Validation

* Comprehensive validation rules
* SQL injection prevention
* File upload security
* Cross-site scripting protection

### Business Logic Security

* Permission validation at use case level
* Resource access validation
* Multi-tenant data isolation
* Rate limiting and abuse prevention
