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

# Interface Documentation

## Overview

This document provides comprehensive documentation of all TypeScript interfaces, DTOs, enums, and type definitions used in the Customer Management module. These interfaces ensure type safety, establish clear contracts between layers, and facilitate integration with other modules in the Bee O'clock ecosystem.

## Core Interfaces

### Customer Entity Interface

```typescript
interface ICustomer extends IBase {
  firstName?: string;           // Customer first name
  lastName?: string;            // Customer last name  
  phone?: string;              // Normalized phone number (numbers only)
  email?: string;              // Validated email address
  note?: string;               // Internal business notes
  customerType?: CustomerTypeEnum; // Customer classification type
  createdAt?: string;          // Creation timestamp (ISO string)
  updatedAt?: string;          // Last update timestamp (ISO string)
}
```

### Base Entity Interface

```typescript
interface IBase {
  _id?: string;                // MongoDB ObjectId as string
  state?: string;              // Entity state (active, inactive, deleted)
  stateHistory?: IStateHistoryEntry[]; // State change audit trail
  _version?: string;           // Optimistic locking version
}
```

## Data Transfer Objects (DTOs)

### CustomerDto

Primary DTO for customer data transfer across API boundaries.

```typescript
@Exclude()
export class CustomerDto extends BaseEntityDto {
  
  @ApiProperty({ example: 'CustomerDto' })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'CustomerDto';

  @ApiProperty({ example: 'John' })
  @IsString()
  @IsOptional()
  @Expose()
  firstName?: string;

  @ApiProperty({ example: 'Smith' })
  @IsString()
  @IsOptional()
  @Expose()
  lastName?: string;

  @ApiProperty({ example: '+0000000000000' })
  @IsString()
  @IsOptional()
  @Expose()
  phone?: string;

  @ApiProperty({ example: 'john.smith@example.com' })
  @IsString()
  @IsOptional()
  @Expose()
  email?: string;

  @ApiProperty()
  @IsString()
  @IsOptional()
  @Expose()
  note?: string;

  @ApiProperty({
    enum: CustomerTypeEnum,
    default: CustomerTypeEnum.regular
  })
  @IsEnum(CustomerTypeEnum)
  @IsOptional()
  @Expose()
  customerType?: CustomerTypeEnum;
}
```

### CustomerPaginationDto

DTO for customer pagination parameters.

```typescript
@Exclude()
export class CustomerPaginationDto extends PaginationDto {
  
  @ApiPropertyOptional({ example: 'john' })
  @IsString()
  @IsOptional()
  @Expose()
  search?: string;

  @ApiPropertyOptional({ 
    enum: CustomerTypeEnum,
    description: 'Filter customers by type'
  })
  @IsEnum(CustomerTypeEnum)
  @IsOptional()
  @Expose()
  customerType?: CustomerTypeEnum;

  @ApiPropertyOptional({ 
    example: 'firstName',
    description: 'Field to sort by'
  })
  @IsString()
  @IsOptional()
  @Expose()
  sortBy?: string;

  @ApiPropertyOptional({ 
    enum: ['asc', 'desc'],
    example: 'asc',
    description: 'Sort direction'
  })
  @IsEnum(['asc', 'desc'])
  @IsOptional()
  @Expose()
  sortDirection?: 'asc' | 'desc';
}
```

### CustomerFilterDto

DTO for advanced customer filtering options.

```typescript
@Exclude()
export class CustomerFilterDto {
  
  @ApiPropertyOptional()
  @IsString()
  @IsOptional()
  @Expose()
  search?: string;

  @ApiPropertyOptional({ enum: CustomerTypeEnum })
  @IsEnum(CustomerTypeEnum)
  @IsOptional()
  @Expose()
  customerType?: CustomerTypeEnum;

  @ApiPropertyOptional()
  @IsDateString()
  @IsOptional()
  @Expose()
  createdAfter?: string;

  @ApiPropertyOptional()
  @IsDateString()
  @IsOptional()
  @Expose()
  createdBefore?: string;

  @ApiPropertyOptional()
  @IsBoolean()
  @IsOptional()
  @Expose()
  hasEmail?: boolean;

  @ApiPropertyOptional()
  @IsBoolean()
  @IsOptional()
  @Expose()
  hasPhone?: boolean;
}
```

## Order Integration DTOs

### AttendantDto

DTO representing a customer as an attendee in order services.

```typescript
@Exclude()
export class AttendantDto {

  @ApiProperty({ example: 'AttendantDto' })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'AttendantDto';

  @ApiProperty({ type: () => CustomerDto })
  @Type(() => CustomerDto)
  @IsOptional()
  @Expose()
  customer?: CustomerDto;

  @ApiProperty({ 
    description: 'Indicates if this is the first time the attendant is visiting the business' 
  })
  @IsOptional()
  @IsBoolean()
  @Expose()
  firstTime?: boolean;
}
```

### PublicAttendantDto

DTO for customer information in public order creation (client-facing).

```typescript
@Exclude()
export class PublicAttendantDto {

  @ApiPropertyOptional()
  @IsString()
  @IsOptional()
  @Expose()
  @Transform(from_object_id)
  _id?: string;

  @ApiPropertyOptional({ example: 'John' })
  @IsString()
  @IsOptional()
  @Expose()
  firstName?: string;

  @ApiPropertyOptional({ example: 'Smith' })
  @IsString()
  @IsOptional()
  @Expose()
  lastName?: string;

  @ApiPropertyOptional({ example: '+1234567890' })
  @IsString()
  @IsOptional()
  @Expose()
  @IsPhone({
    message: 'Invalid phone number format'
  })
  phone?: string;

  @ApiPropertyOptional({ example: 'john.smith@example.com' })
  @IsString()
  @IsOptional()
  @Expose()
  @IsEmail({
    message: 'Invalid email format'
  })
  email?: string;
}
```

## Enumerations

### CustomerTypeEnum

Defines different types of customers in the system.

```typescript
export enum CustomerTypeEnum {
  regular = 'regular',           // Regular registered customer with full profile
  unregistered = 'unregistered', // Customer without full registration
  new = 'new',                   // First-time customer
  anonymous = 'anonymous'        // Anonymous customer (public orders)
}
```

### CustomerStateEnum

Defines possible states for customer entities.

```typescript
export enum CustomerStateEnum {
  active = 'active',           // Customer is active and can book services
  inactive = 'inactive',       // Customer is temporarily inactive
  suspended = 'suspended',     // Customer is suspended due to policy violation
  deleted = 'deleted'          // Customer is soft-deleted
}
```

## Use Case Interfaces

### Customer Use Case Parameters

```typescript
// Create Customer
export interface CreateCustomerUseCaseParams {
  ctx: TenantActorContext;
  customer: CustomerDto;
}

// Get Customer
export interface GetCustomerUseCaseParams {
  ctx: TenantActorContext;
  customerId: string;
}

// Update Customer
export interface UpdateCustomerUseCaseParams {
  ctx: TenantActorContext;
  customerId: string;
  update: CustomerDto;
}

// Delete Customer
export interface DeleteCustomerUseCaseParams {
  ctx: TenantActorContext;
  customerId: string;
}

// Get Paged Customers
export interface GetPagedCustomersUseCaseParams {
  ctx: TenantActorContext;
  pagination: CustomerPaginationDto;
}
```

### Customer Validation Parameters

```typescript
export interface CustomerValidationParams {
  tenantId: string;
  customer: CustomerDto;
  validationFunction: (dto: CustomerDto) => boolean;
  errorMessage: string;
}
```

## Domain Value Objects

### Customer Contact Information

```typescript
interface ICustomerContact {
  email?: string;              // Validated email address
  phone?: string;              // Normalized phone number
  preferredContactMethod?: ContactMethodEnum; // Preferred communication method
  allowMarketing?: boolean;    // Marketing communication consent
}
```

### Customer Preferences

```typescript
interface ICustomerPreferences {
  language?: LanguageCodeEnum;     // Preferred language
  timezone?: string;               // Preferred timezone
  communicationPreferences?: {
    email?: boolean;              // Email notifications enabled
    sms?: boolean;               // SMS notifications enabled
    push?: boolean;              // Push notifications enabled
  };
  appointmentPreferences?: {
    preferredTimeSlots?: string[]; // Preferred appointment times
    reminderPreference?: number;   // Reminder time in minutes
  };
}
```

## Command and Query Interfaces

### Command Interfaces

```typescript
// Add Regular Customer Command
export interface IAddRegularCustomerCommand extends ITenantAware {
  tenantId: string;
  customer: CustomerDto;
}

// Update Customer Command
export interface IUpdateCustomerCommand extends ITenantAware {
  tenantId: string;
  customerId: string;
  customer: CustomerDto;
}

// Delete Customer Command
export interface IDeleteCustomerCommand extends ITenantAware {
  tenantId: string;
  customerId: string;
}

// Add Attendees Command
export interface IAddAttendeesCommand extends ITenantAware {
  tenantId: string;
  attendees: AttendantDto[];
}

// Add Public Attendees Command
export interface IAddPublicAttendeesCommand extends ITenantAware {
  tenantId: string;
  attendees: PublicAttendantDto[];
}
```

### Query Interfaces

```typescript
// Get Customer By ID Query
export interface IGetCustomerByIdQuery extends ITenantAware {
  tenantId: string;
  customerId: string;
}

// Get Paged Customers Query
export interface IGetPagedCustomersQuery extends ITenantAware {
  tenantId: string;
  pagination: CustomerPaginationDto;
}

// Is Customer Exist Query
export interface IIsCustomerExistQuery extends ITenantAware {
  tenantId: string;
  email?: string;
  phone?: string;
}
```

## Message Interfaces

### Customer Event Messages

```typescript
// Customer Added Message
export interface CustomerAddedMessagePayload {
  tenantId: string;
  customer: CustomerDto;
  createdBy: ActorDto;
  timestamp: string;
}

export class CustomerAddedMessage extends BaseMessage<CustomerAddedMessagePayload> {
  constructor(params: CustomerAddedMessagePayload) {
    super(Queue.customerQueue, 'customer-added', params);
  }
}

// Customer Updated Message
export interface CustomerUpdatedMessagePayload {
  tenantId: string;
  customerId: string;
  customer: CustomerDto;
  updatedBy: ActorDto;
  changedFields: string[];
  timestamp: string;
}

export class CustomerUpdatedMessage extends BaseMessage<CustomerUpdatedMessagePayload> {
  constructor(params: CustomerUpdatedMessagePayload) {
    super(Queue.customerQueue, 'customer-updated', params);
  }
}

// Customer Deleted Message
export interface CustomerDeletedMessagePayload {
  tenantId: string;
  customerId: string;
  deletedBy: ActorDto;
  timestamp: string;
}

export class CustomerDeletedMessage extends BaseMessage<CustomerDeletedMessagePayload> {
  constructor(params: CustomerDeletedMessagePayload) {
    super(Queue.customerQueue, 'customer-deleted', params);
  }
}
```

## Cache Interfaces

### Cache Key Definitions

```typescript
export enum CustomerCacheKeys {
  GET_CUSTOMER = 'customer:get',
  GET_PAGED_CUSTOMERS = 'customer:paged',
  CUSTOMER_SEARCH = 'customer:search',
  CUSTOMER_VALIDATION = 'customer:validation'
}
```

### Cache Strategy Interfaces

```typescript
export interface ICustomerCacheStrategy {
  getCustomerCacheKey(tenantId: string, customerId: string): string;
  getPagedCustomersCacheKey(tenantId: string, params: CustomerPaginationDto): string;
  getSearchCacheKey(tenantId: string, searchTerm: string): string;
  invalidateCustomerCache(tenantId: string, customerId: string): Promise<void>;
  invalidatePagedCache(tenantId: string): Promise<void>;
}
```

## Repository Filter Interfaces

### Customer Repository Filters

```typescript
export interface ICustomerRepositoryFilter {
  tenantId: string;
  search?: string;
  customerType?: CustomerTypeEnum;
  state?: CustomerStateEnum;
  hasEmail?: boolean;
  hasPhone?: boolean;
  createdAfter?: Date;
  createdBefore?: Date;
  sortBy?: string;
  sortDirection?: 'asc' | 'desc';
  limit?: number;
  offset?: number;
}
```

### Customer Search Criteria

```typescript
export interface ICustomerSearchCriteria {
  tenantId: string;
  query: string;
  fields: CustomerSearchField[];
  fuzzyMatch?: boolean;
  limit?: number;
}

export enum CustomerSearchField {
  FIRST_NAME = 'firstName',
  LAST_NAME = 'lastName',
  EMAIL = 'email',
  PHONE = 'phone',
  FULL_NAME = 'fullName'
}
```

## Context Interfaces

### Tenant Actor Context

```typescript
export interface TenantActorContext {
  tenantId: string;
  actor: ActorDto;
}

export interface ActorDto {
  issuerId: string;
  issuerType: IssuerTypeEnum;
  roles: string[];
  permissions?: string[];
}
```

### Customer Operation Context

```typescript
export interface CustomerOperationContext extends TenantActorContext {
  operationType: CustomerOperationType;
  requestId: string;
  timestamp: string;
  metadata?: Record<string, any>;
}

export enum CustomerOperationType {
  CREATE = 'create',
  READ = 'read',
  UPDATE = 'update',
  DELETE = 'delete',
  SEARCH = 'search'
}
```

## Validation and Error Interfaces

### Customer Validation Result

```typescript
export interface ICustomerValidationResult {
  isValid: boolean;
  errors: CustomerValidationError[];
  warnings?: CustomerValidationWarning[];
}

export interface CustomerValidationError {
  field: string;
  message: string;
  code: CustomerValidationErrorCode;
  value?: any;
}

export interface CustomerValidationWarning {
  field: string;
  message: string;
  suggestion?: string;
}

export enum CustomerValidationErrorCode {
  REQUIRED_FIELD_MISSING = 'REQUIRED_FIELD_MISSING',
  INVALID_EMAIL_FORMAT = 'INVALID_EMAIL_FORMAT',
  INVALID_PHONE_FORMAT = 'INVALID_PHONE_FORMAT',
  DUPLICATE_CUSTOMER = 'DUPLICATE_CUSTOMER',
  FIELD_TOO_LONG = 'FIELD_TOO_LONG',
  INVALID_CUSTOMER_TYPE = 'INVALID_CUSTOMER_TYPE'
}
```

### Exception Interfaces

```typescript
export interface ICustomerException {
  name: string;
  message: string;
  code: string;
  details?: Record<string, any>;
  timestamp: string;
}

// Customer Not Found Exception
export interface ICustomerNotFoundException extends ICustomerException {
  customerId: string;
  tenantId: string;
}

// Customer Creation Exception
export interface ICustomerCreationException extends ICustomerException {
  validationErrors: CustomerValidationError[];
  customerData: Partial<CustomerDto>;
}

// Customer Already Exists Exception
export interface ICustomerAlreadyExistsException extends ICustomerException {
  existingCustomerId: string;
  conflictingField: string;
  conflictingValue: string;
}
```

## Integration Interfaces

### Order Integration

```typescript
export interface IOrderCustomerInfo {
  customer: CustomerDto;       // Primary customer (payer)
  attendees: AttendantDto[];   // Service attendees
  isFirstTimeCustomer: boolean;
  orderHistory?: {
    totalOrders: number;
    lastOrderDate?: string;
    averageOrderValue?: number;
  };
}
```

### Payment Integration

```typescript
export interface IPaymentCustomerInfo {
  payer: CustomerDto;          // Customer making payment
  billingInfo?: {
    address?: AddressDto;
    paymentMethodPreference?: PaymentMethodEnum;
  };
  paymentHistory?: {
    totalPayments: number;
    lastPaymentDate?: string;
    preferredMethod?: PaymentMethodEnum;
  };
}
```

### Notification Integration

```typescript
export interface ICustomerNotificationProfile {
  customer: CustomerDto;
  preferences: {
    email: boolean;
    sms: boolean;
    push: boolean;
  };
  contactMethods: {
    email?: string;
    phone?: string;
    deviceTokens?: string[];
  };
  language: LanguageCodeEnum;
  timezone: string;
}
```

## Mapper Interfaces

### Customer Mapping Contracts

```typescript
export interface ICustomerMapper {
  toDto(entity: ICustomer): CustomerDto;
  toDtoArray(entities: ICustomer[]): CustomerDto[];
  toPersistence(dto: CustomerDto): ICustomer;
  toPersistenceFromDto(dto: CustomerDto): ICustomer;
  toDomain(persistence: ICustomer): Customer;
  fromDomain(domain: Customer): ICustomer;
}

export interface IAttendantMapper {
  toDto(entity: IAttendant): AttendantDto;
  toDtoArray(entities: IAttendant[]): AttendantDto[];
  toPersistence(dto: AttendantDto): IAttendant;
  fromCustomerDto(customer: CustomerDto, firstTime: boolean): AttendantDto;
}
```

## Type Utilities

### Customer Type Guards

```typescript
export const isCustomerDto = (obj: any): obj is CustomerDto => {
  return obj && typeof obj === 'object' && obj.object === 'CustomerDto';
};

export const isAttendantDto = (obj: any): obj is AttendantDto => {
  return obj && typeof obj === 'object' && obj.object === 'AttendantDto';
};

export const isPublicAttendantDto = (obj: any): obj is PublicAttendantDto => {
  return obj && typeof obj === 'object' && 
         (obj.firstName || obj.lastName || obj.email || obj.phone);
};
```

### Customer Utility Types

```typescript
// Partial customer for updates
export type CustomerUpdate = Partial<Omit<CustomerDto, '_id' | 'object' | 'createdAt' | '_version'>>;

// Customer creation payload
export type CustomerCreation = Omit<CustomerDto, '_id' | 'createdAt' | 'updatedAt' | '_version' | 'stateHistory'>;

// Customer summary for lists
export type CustomerSummary = Pick<CustomerDto, '_id' | 'firstName' | 'lastName' | 'email' | 'customerType'>;

// Customer search result
export type CustomerSearchResult = CustomerSummary & {
  relevanceScore: number;
  matchedFields: string[];
};
```

## Configuration Interfaces

### Customer Module Configuration

```typescript
export interface ICustomerModuleConfig {
  validation: {
    emailValidation: boolean;
    phoneValidation: boolean;
    duplicateCheck: boolean;
    mandatoryFields: (keyof CustomerDto)[];
  };
  pagination: {
    defaultLimit: number;
    maxLimit: number;
  };
  cache: {
    enabled: boolean;
    ttl: {
      customer: number;
      pagedResults: number;
      searchResults: number;
    };
  };
  security: {
    auditLogging: boolean;
    dataEncryption: boolean;
    accessLogging: boolean;
  };
}
```

## Usage Guidelines

### DTO Validation

1. **Always use class-validator decorators** for automatic validation
2. **Apply @Expose() decorators** for proper serialization control
3. **Use @Type() decorators** for nested object transformation
4. **Implement proper error handling** for validation failures

### Type Safety

1. **Use TypeScript interfaces** for compile-time type checking
2. **Implement type guards** for runtime type validation
3. **Apply generic constraints** for reusable type definitions
4. **Use discriminated unions** for type-safe polymorphism

### Error Handling

1. **Implement domain-specific exceptions** with clear error codes
2. **Provide detailed validation results** with field-level errors
3. **Use Result types** for operation outcomes
4. **Maintain error message consistency** across the module

### Message Contracts

1. **Define clear event payloads** for inter-service communication
2. **Version message interfaces** for backward compatibility
3. **Include correlation IDs** for request tracing
4. **Implement idempotent message processing**

### Cache Keys

1. **Use enum-defined cache keys** for consistency
2. **Include tenant context** in cache key generation
3. **Implement cache invalidation strategies** for data consistency
4. **Consider cache TTL values** based on data volatility

### Context Propagation

1. **Always pass TenantActorContext** for proper authorization
2. **Include operation metadata** for auditing and debugging
3. **Maintain request correlation** across service boundaries
4. **Implement proper context validation**

## Interface Evolution

When modifying interfaces:

1. **Consider backward compatibility** for existing consumers
2. **Use optional properties** for new fields to maintain compatibility
3. **Increment version numbers** for breaking changes
4. **Update validation rules** consistently across DTOs
5. **Document migration paths** for interface changes
6. **Test interface changes** thoroughly across all integration points

## Performance Considerations

1. **Use selective field projection** in repository interfaces
2. **Implement efficient search interfaces** with proper indexing
3. **Consider pagination interfaces** for large result sets
4. **Design cache-friendly interfaces** with appropriate granularity
5. **Optimize serialization** through proper DTO design

## Security Considerations

1. **Never expose sensitive data** in public interfaces
2. **Implement proper input validation** in all DTOs
3. **Use secure context propagation** for authorization
4. **Audit interface access** for compliance requirements
5. **Encrypt sensitive fields** in persistence interfaces

***

## Summary

The Customer Management module interfaces provide a comprehensive type-safe foundation for customer operations within the Bee O'clock ecosystem. Key aspects include:

* **Strongly Typed DTOs**: Comprehensive data transfer objects with validation
* **Domain Interfaces**: Clear contracts for business logic and data persistence
* **Integration Support**: Well-defined interfaces for order and payment integration
* **Event-Driven Architecture**: Message interfaces for asynchronous communication
* **Error Handling**: Structured exception and validation interfaces
* **Performance Optimization**: Cache and search interfaces for efficient operations
* **Security Compliance**: Secure context and validation interfaces

These interfaces ensure consistency, maintainability, and reliability across the customer management domain while supporting complex business scenarios and integration requirements.
