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

# Customer Management

## Overview

The Customer Management module provides comprehensive customer relationship management capabilities for the Bee O'clock platform. This module handles customer data, relationship tracking, and integration with orders and payments systems.

## Module Structure

```
customer-management/
├── api.md                 # REST API endpoints and operations
├── interface.md           # TypeScript interfaces and contracts
├── usecase.md            # Business use cases and application logic
├── db_schema.md          # Database schema and persistence layer
└── README.md             # This overview document
```

## Key Features

### Customer Lifecycle Management

* **Customer Creation**: Create customer records with validation
* **Profile Management**: Update customer information and preferences
* **Relationship Tracking**: Track customer interactions and history
* **State Management**: Soft delete with complete audit trail

### Order Integration

* **Attendee Processing**: Convert order attendees to customer records
* **Customer Matching**: Smart matching by email and phone
* **First-Time Detection**: Identify new customer visits
* **History Tracking**: Maintain comprehensive order history

### Payment Integration

* **Payer Management**: Link customers to payment records
* **Billing Information**: Manage customer billing preferences
* **Payment History**: Track customer payment patterns
* **Invoice Generation**: Customer billing and invoicing

### Search and Discovery

* **Advanced Search**: Multi-field customer search capabilities
* **Filtering**: Filter by customer type, status, and attributes
* **Pagination**: Efficient handling of large customer datasets
* **Sorting**: Flexible sorting by various criteria

## Technical Architecture

### Design Patterns

* **CQRS**: Command Query Responsibility Segregation
* **Domain-Driven Design**: Rich domain models with business logic
* **Repository Pattern**: Data access abstraction
* **Event-Driven**: Asynchronous event publishing
* **Multi-Tenant**: Business-level data isolation

### Technology Stack

* **Framework**: NestJS with TypeScript
* **Database**: MongoDB with Mongoose ODM
* **Caching**: Redis for performance optimization
* **Messaging**: RabbitMQ for event processing
* **Validation**: Domain-level and schema validation

## API Overview

The Customer Management API provides the following main endpoints:

* **GET /customers**: List and search customers with pagination
* **GET /customers/:id**: Retrieve specific customer details
* **POST /customers**: Create new customer records
* **PUT /customers/:id**: Update existing customer information
* **DELETE /customers/:id**: Soft delete customer records

All endpoints support:

* **Permission Validation**: Role-based access control
* **Tenant Isolation**: Multi-tenant data separation
* **Input Validation**: Comprehensive data validation
* **Error Handling**: Consistent error responses

## Data Model

### Customer Entity

```typescript
interface ICustomer {
  _id?: string;
  firstName?: string;
  lastName?: string;
  phone?: string;
  email?: string;
  note?: string;
  customerType?: CustomerTypeEnum;
  stateHistory?: StateHistory[];
  createdAt?: string;
  updatedAt?: string;
}
```

### Customer Types

* **Regular**: Fully registered customers with complete information
* **Unregistered**: Customers with basic contact information
* **New**: First-time customers being onboarded
* **Anonymous**: Minimal information customers for privacy

### Validation Rules

* **Mandatory Fields**: At least one of firstName, lastName, email, or phone required
* **Email Format**: Valid email format when provided
* **Phone Format**: Valid phone number with automatic normalization
* **Business Rules**: Custom validation based on customer type

## Business Rules

### Customer Creation

1. **Identity Validation**: Ensure unique customer identification
2. **Contact Information**: Validate email and phone formats
3. **Business Context**: Associate with appropriate business tenant
4. **Default Values**: Apply default customer type and state

### Customer Updates

1. **Partial Updates**: Support updating individual fields
2. **Validation**: Maintain data integrity on updates
3. **History Tracking**: Record all changes for audit trail
4. **Cache Invalidation**: Update cached customer data

### Customer Deletion

1. **Soft Delete**: Preserve data for historical purposes
2. **Dependency Validation**: Check for active orders or payments
3. **State Management**: Update customer state history
4. **Related Data**: Handle references in orders and payments

## Integration Points

### Order Management

* **Attendee Processing**: Convert order participants to customers
* **Customer Snapshots**: Preserve customer data in order records
* **First-Time Tracking**: Mark new customer interactions
* **Service History**: Track customer service participation

### Payment Processing

* **Payer Information**: Link payments to customer records
* **Billing History**: Maintain customer payment records
* **Payment Methods**: Store customer payment preferences
* **Invoice Management**: Generate customer invoices

### Notification System

* **Email Communications**: Send order confirmations and updates
* **SMS Notifications**: Send appointment reminders via phone
* **Push Notifications**: Mobile app notifications
* **Marketing Campaigns**: Customer segmentation for targeted messaging

## Security and Compliance

### Data Protection

* **PII Handling**: Secure processing of personal information
* **Encryption**: Protect sensitive customer data at rest and in transit
* **Access Control**: Role-based permissions for customer operations
* **Audit Logging**: Complete audit trail of data access and changes

### Privacy Compliance

* **GDPR Support**: Data portability and right to erasure
* **Consent Management**: Track customer consent preferences
* **Data Retention**: Automated data lifecycle management
* **Anonymization**: Remove personal data while preserving analytics

### Security Measures

* **Input Validation**: Sanitize all customer inputs
* **Rate Limiting**: Prevent abuse of customer APIs
* **Authentication**: Secure access to customer operations
* **Monitoring**: Real-time security threat detection

## Performance Considerations

### Database Optimization

* **Indexing Strategy**: Optimized indexes for common query patterns
* **Query Performance**: Efficient customer search and retrieval
* **Connection Pooling**: Optimal database connection management
* **Caching**: Redis caching for frequently accessed data

### Scalability

* **Pagination**: Handle large customer datasets efficiently
* **Search Optimization**: Fast text search across customer fields
* **Load Balancing**: Distribute customer operations across instances
* **Monitoring**: Performance metrics and alerting

## Development Guidelines

### Code Organization

* **Use Cases**: Business logic in application layer
* **Domain Models**: Rich entities with validation
* **DTOs**: Data transfer objects for API contracts
* **Repositories**: Data access abstraction layer

### Testing Strategy

* **Unit Tests**: Test individual components and business logic
* **Integration Tests**: Test complete customer workflows
* **API Tests**: Validate REST endpoint behavior
* **Performance Tests**: Ensure scalability requirements

### Error Handling

* **Validation Errors**: Clear error messages for validation failures
* **Business Logic Errors**: Meaningful business rule violation messages
* **System Errors**: Graceful handling of infrastructure failures
* **Logging**: Comprehensive error logging and monitoring

## Future Enhancements

### Planned Features

* **Customer Segmentation**: Advanced customer categorization
* **Preference Management**: Detailed customer preferences and settings
* **Communication History**: Complete interaction timeline
* **Loyalty Programs**: Customer rewards and loyalty tracking
* **Analytics**: Customer behavior analysis and insights

### Technical Improvements

* **Event Sourcing**: Complete audit trail with event streams
* **Read Replicas**: Optimize read performance for customer queries
* **Microservice Architecture**: Split into focused microservices
* **Machine Learning**: Customer behavior prediction and insights

## Related Documentation

* [**API Documentation**](/services/customer-management/api.md): Detailed REST API reference
* [**Interface Documentation**](/services/customer-management/interface.md): TypeScript contracts and types
* [**Use Case Documentation**](/services/customer-management/usecase.md): Business logic and workflows
* [**Database Schema**](/services/customer-management/db_schema.md): Data persistence and schema design

## Getting Started

### Prerequisites

* Node.js 18+ and npm/yarn
* MongoDB 5.0+
* Redis 6.0+
* Valid environment configuration

### Development Setup

1. **Install Dependencies**: `npm install`
2. **Database Setup**: Configure MongoDB connection
3. **Environment**: Set up development environment variables
4. **Run Tests**: `npm run test` to verify setup
5. **Start Development**: `npm run start:dev`

### API Testing

Use the provided Postman collection or Swagger UI to test customer management endpoints:

* **Swagger UI**: `/api/docs` when running locally
* **Health Check**: `/health` endpoint for service status

***

For detailed implementation information, refer to the specific documentation files for each component of the Customer Management module.
