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

# Use Case Documentation

## Overview

The member management module implements various use cases for managing team members within the Bee O'clock system. The module follows Clean Architecture principles and CQRS pattern to separate business logic concerns.

## Core Use Cases

### 1. Get Paged Members Use Case

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

**Location**: `GetPagedMembersUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `pageSize?: number` - Number of items per page
* `page?: number` - Page number to retrieve
* `searchTerm?: string` - Optional search term for filtering
* `assignmentFilter?: string` - Optional assignment filter

**Business Logic**:

1. Validates actor permissions (`VIEW_MEMBER`)
2. Applies search filters if provided
3. Executes paginated query through repository
4. Returns paginated result with members and metadata

**Output**: `PaginatedResponse<MemberDto>`

### 2. Get Member By ID Use Case

**Purpose**: Retrieves a specific member by their unique identifier.

**Location**: `GetMemberByIdUseCase`

**Input Parameters**:

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

**Business Logic**:

1. Validates actor permissions (`VIEW_MEMBER`)
2. Retrieves member from repository
3. Throws exception if member not found
4. Maps persistence model to DTO

**Output**: `MemberDto`

### 3. Add New Member Use Case

**Purpose**: Creates a new member within a tenant, handling invitation codes and account linking.

**Location**: `AddNewMemberUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `accountId: string` - Associated account identifier
* `member: MemberDto` - Member data to create

**Business Logic**:

1. Validates actor permissions (`CREATE_MEMBER`)
2. Checks tenant tariff plan limits
3. Validates against maximum specialist limit
4. Initializes member with default values (role, assignments, referral code)
5. Creates member through command
6. Links existing account if found by email
7. Creates member context for account linkage
8. Emits member added event for notifications
9. Handles transaction rollback on errors

**Special Considerations**:

* Checks tariff plan specialist limits
* Generates unique invitation codes
* Links to existing accounts automatically
* Emits events for downstream processing

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

### 4. Update Member Use Case

**Purpose**: Updates an existing member's information with role change validation.

**Location**: `UpdateMemberUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `member: MemberDto` - Updated member data

**Business Logic**:

1. Validates actor permissions (`EDIT_MEMBER`)
2. Retrieves existing member for comparison
3. Validates role changes:
   * Prevents self-removal of owner role
   * Ensures proper role change permissions
4. Executes update command
5. Handles transaction rollback on errors

**Special Role Validation**:

* Owners cannot remove their own owner role
* Role changes require specific validations
* Compares current vs new roles for changes

**Output**: `void`

### 5. Delete Member Use Case

**Purpose**: Safely deletes a member with comprehensive validation checks.

**Location**: `DeleteMemberUseCase`

**Input Parameters**:

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

**Business Logic**:

1. Validates actor permissions (`DELETE_MEMBER`)
2. Checks member exists
3. Validates actor is owner
4. Prevents self-deletion
5. Checks for active events/orders
6. Marks member as deleted (soft delete)
7. Publishes deletion notification
8. Emits member deleted event
9. Clears related caches

**Safety Validations**:

* Only owners can delete members
* Cannot delete self
* Cannot delete members with active events
* Checks for active orders before deletion

**Output**: `void`

### 6. Update Member Assignment Use Case

**Purpose**: Updates member service assignments and permissions.

**Location**: `UpdateMemberAssignmentUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `memberId: string` - ID of member to update
* `assignments: AssignmentsDto` - New assignment configuration

**Business Logic**:

1. Validates actor permissions (`EDIT_MEMBER`)
2. Retrieves existing member
3. Updates assignment configuration
4. Handles full access vs specific service assignments
5. Saves updated assignments

**Output**: `void`

### 7. Avatar Management Use Cases

#### Upsert Member Avatar

**Purpose**: Uploads or updates a member's avatar image.

**Location**: `UpsertMemberAvatarUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `memberId: string` - ID of member
* `file: Express.Multer.File` - Avatar image file

**Business Logic**:

1. Validates actor permissions (`EDIT_MEMBER`)
2. Validates file format and size
3. Uploads to storage service
4. Updates member avatar URL
5. Handles storage errors

#### Delete Member Avatar

**Purpose**: Removes a member's avatar image.

**Location**: `DeleteMemberAvatarUseCase`

**Input Parameters**:

* `ctx: TenantActorContext` - Context with tenant and actor information
* `memberId: string` - ID of member

**Business Logic**:

1. Validates actor permissions (`EDIT_MEMBER`)
2. Removes avatar from storage
3. Clears avatar URL from member record

## Permission Requirements

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

* **VIEW\_MEMBER**: Required for read operations
* **CREATE\_MEMBER**: Required for creating new members
* **EDIT\_MEMBER**: Required for updates and avatar management
* **DELETE\_MEMBER**: Required for deletion operations

## Error Handling

### Common Exceptions

* `MemberNotFoundException`: When member ID doesn't exist
* `MemberUpdationException`: When update validation fails
* `MemberCannotDeleteItselfException`: Self-deletion prevention
* `MemberNotAuthorizedToDeleteException`: Insufficient permissions for deletion
* `MemberHasActiveEventsException`: Cannot delete member with active events
* `TenantTariffPlanMaxMembersReachedException`: Specialist limit exceeded
* `TenantHasNoActiveTariffPlanException`: No active plan for member creation

### Error Response Pattern

All use cases follow consistent error handling:

1. Log errors with context
2. Preserve original error for debugging
3. Throw domain-specific exceptions
4. Handle transaction rollback automatically

## Integration Points

### Event Publishing

* **MemberAddedMessage**: Published when member is created
* **MemberDeletedMessage**: Published when member is deleted
* **MemberDeletedNotification**: Internal notification for cleanup

### Cache Management

* Automatic cache invalidation on mutations
* Cache keys: `GET_MEMBER`, `GET_PAGED_MEMBERS`
* Uses `@DeleteCache` decorator for automatic cleanup

### Transaction Management

* Uses `@InitializeSharedDbConnection` for transaction support
* Automatic rollback on failures
* Shared unit of work pattern for consistency

## Business Rules

### Member Creation Rules

1. **Tariff Plan Validation**: Must have active tariff plan
2. **Specialist Limits**: Cannot exceed plan's specialist limit
3. **Default Role Assignment**: New members get SPECIALIST role by default
4. **Invitation Codes**: Automatically generated for each member
5. **Account Linking**: Automatically links to existing accounts by email

### Member Update Rules

1. **Role Change Validation**: Complex validation for role modifications
2. **Owner Protection**: Owners cannot remove their own owner role
3. **Permission Inheritance**: Role changes affect permission inheritance

### Member Deletion Rules

1. **Owner Only**: Only owners can delete members
2. **Self-Protection**: Cannot delete own account
3. **Active Events Check**: Cannot delete members with active events
4. **Soft Delete**: Members are marked as deleted, not physically removed

### Assignment Rules

1. **Service Assignments**: Can be full access or specific services
2. **Permission Inheritance**: Assignments affect service access
3. **Validation**: Assignments must reference valid services

## Performance Considerations

### Caching Strategy

* Paginated results are cached
* Individual member lookups are cached
* Cache invalidation on mutations
* Distributed cache support

### Query Optimization

* Indexed queries for pagination
* Optimized search operations
* Population of related data in single queries
* Efficient filtering and sorting

### Async Processing

* Event publishing for notifications
* Background processing for file uploads
* Deferred cleanup operations
* Message queue integration

## Testing Strategy

### Unit Tests

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

### Integration Tests

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

### End-to-End Tests

* Full workflow testing
* API endpoint validation
* File upload testing
* Permission integration testing
