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

# Member Management

## Overview

This directory contains comprehensive documentation for the Member Management module of the Bee O'clock panel service. The member management system handles team member lifecycle, permissions, service assignments, and user relationships within the multi-tenant SaaS platform.

## Documentation Structure

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

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

**Key Topics Covered:**

* Member CRUD operations
* Pagination and search
* Avatar management
* Assignment management
* Role and permission handling
* Error responses and status codes

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

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

**Key Topics Covered:**

* Data Transfer Objects (DTOs)
* Domain interfaces and entities
* Enum definitions
* Type definitions and contracts
* Request/response models

### [Use Case Documentation](/services/member-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
* Transaction management
* Performance considerations

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

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

**Key Topics Covered:**

* Entity schemas and relationships
* Sub-document structures
* Index strategies
* Multi-tenancy considerations
* Data validation rules
* Migration guidelines

## Module Architecture

### Technology Stack

* **Framework**: NestJS with TypeScript
* **Database**: MongoDB with Mongoose ODM
* **Architecture**: Clean Architecture + CQRS
* **Patterns**: Repository Pattern, Domain-Driven Design
* **Caching**: Redis for performance optimization
* **Event System**: AMQP for async processing

### Core Features

#### Member Lifecycle Management

* Member creation with invitation system
* Profile updates and status management
* Soft deletion with audit trails
* Avatar upload and management

#### Permission System

* Role-based access control (RBAC)
* Service-level assignments
* Owner protection mechanisms
* Permission inheritance

#### Multi-Tenancy

* Tenant-isolated member data
* Tenant-aware operations
* Cross-tenant prevention
* Scalable tenant management

#### Integration Points

* Authentication via member context
* Notification system integration
* Cache management
* Event-driven architecture

## Business Rules

### Member Creation

1. **Tariff Plan Validation**: Active plan required for new members
2. **Specialist Limits**: Enforced based on tenant's plan
3. **Email Uniqueness**: Per tenant constraint
4. **Invitation System**: Automatic code generation and linking
5. **Default Assignments**: Configurable service access

### Member Updates

1. **Role Protection**: Owners cannot remove own owner role
2. **Permission Validation**: Role changes require proper permissions
3. **Assignment Control**: Service access management
4. **Avatar Management**: File upload and storage handling

### Member Deletion

1. **Safety Checks**: Prevent deletion of members with active events
2. **Owner Restrictions**: Only owners can delete members
3. **Self-Protection**: Cannot delete own account
4. **Soft Delete**: Preserve data for compliance and audit

### Permission Model

1. **Hierarchical Roles**: Support for complex role structures
2. **Service Assignments**: Granular service-level permissions
3. **Inheritance**: Permission inheritance from roles
4. **Validation**: Real-time permission checking

## API Integration Examples

### Creating a Member

```typescript
POST /api/member
Authorization: Bearer <token>
Content-Type: application/json

{
  "firstName": "John",
  "lastName": "Doe", 
  "email": "john.doe@example.com",
  "phone": "+1234567890",
  "roles": [{ "name": "SPECIALIST", "isOwner": false }],
  "assignments": {
    "service": {
      "full": false,
      "include": [{ "service": "service-id" }]
    }
  }
}
```

### Updating Member Assignments

```typescript
PUT /api/member/{id}/assignment
Authorization: Bearer <token>
Content-Type: application/json

{
  "service": {
    "full": true,
    "include": []
  }
}
```

### Paginated Member List

```typescript
GET /api/member?page=1&size=10&search=john&profileStatus=active
Authorization: Bearer <token>
```

## Development Guidelines

### Testing Strategy

* **Unit Tests**: Business logic and validation
* **Integration Tests**: Database and external services
* **E2E Tests**: Complete API workflows
* **Performance Tests**: Load and stress testing

### Error Handling

* Domain-specific exceptions
* Consistent error response format
* Proper HTTP status codes
* Detailed error messages for debugging

### Performance Considerations

* Database indexing strategy
* Caching for frequently accessed data
* Optimized queries with population
* Event-driven async processing

### Security Best Practices

* Input validation and sanitization
* Role-based access control
* Audit logging for sensitive operations
* PII data protection

## Related Modules

### Dependencies

* **Identity Module**: Authentication and account management
* **Permission Module**: Role and permission definitions
* **Client Module**: Tenant management
* **Tariff Plan Module**: Subscription and limits
* **Notification Module**: Event notifications
* **Media Module**: Avatar storage

### Integration Points

* **Member Context**: Links members to authentication
* **Cache Module**: Performance optimization
* **Event Bus**: Async processing and notifications
* **File Storage**: Avatar and media management

## Monitoring and Observability

### Logging

* Structured logging with context
* Error tracking and alerting
* Performance metrics
* Business event logging

### Metrics

* Member creation/deletion rates
* Permission validation performance
* Cache hit rates
* Database query performance

### Health Checks

* Database connectivity
* Cache availability
* External service dependencies
* Business rule validation

## Contributing

### Code Standards

* TypeScript strict mode
* ESLint and Prettier configuration
* Comprehensive test coverage
* Clean Architecture principles

### Documentation

* Update documentation with changes
* Include examples in API docs
* Maintain schema documentation
* Document business rule changes

### Review Process

* Code review requirements
* Testing validation
* Documentation updates
* Performance impact assessment

## Support and Troubleshooting

### Common Issues

* Permission validation failures
* Tariff plan limit exceeded
* Email uniqueness violations
* Role change restrictions

### Debugging Tools

* Structured error messages
* Audit trail investigation
* Cache inspection utilities
* Database query analysis

### Performance Optimization

* Index optimization
* Query performance analysis
* Cache strategy tuning
* Event processing optimization
