# Terms of use

**1. Acceptance of Terms**

By using Bee O'clock, you agree to these Terms of Use and our Privacy Policy. If you do not agree, do not use our services.

**2. Description of Service**

Bee O'clock is a platform for users to find and book services at various salons and professionals. Businesses can manage their bookings, schedules, and customer information.

**3. User Responsibilities**

* Provide accurate and complete information during registration and booking.
* Maintain the confidentiality of account information.
* Use Bee O'clock for lawful purposes and avoid any harmful activities.

**4. Business Responsibilities**

* Provide accurate information about services, availability, and pricing.
* Manage bookings and respond to customer inquiries promptly.
* Comply with all applicable laws and regulations.

**5. Booking and Cancellation**

* Users can book services by selecting available slots.
* Adhere to the cancellation policies specified by businesses.
* Businesses must honor bookings and cancellations as per the specified terms.

**6. Payment**

* Payments are handled according to the terms agreed upon between users and businesses.
* Bee O'clock may facilitate payment processing but is not responsible for issues arising from transactions.

**7. Intellectual Property**

* All content on Bee O'clock is the property of Bee O'clock or its licensors and is protected by intellectual property laws.
* Users and businesses may not use any content from Bee O'clock without prior written permission.

**8. Limitation of Liability**

* Bee O'clock provides the platform "as is" without guarantees on accuracy, completeness, or reliability.
* Bee O'clock is not liable for any damages arising from the use of the platform.

**9. Termination**

* Bee O'clock can terminate or suspend any account for violations of these terms.
* Users and businesses can terminate their accounts at any time following the provided instructions.

**10. Changes to Terms**

Bee O'clock may update these Terms of Use. Users will be notified of significant changes through our website.

**11. Contact Information**

For questions or concerns, contact us at <ask@beeoclock.com>.


# Privacy policy

**Privacy Policy for Bee O'clock**

**1. Introduction**

Welcome to Bee O'clock. We respect your privacy and are committed to protecting your personal data. This Privacy Policy explains how we collect, use, and safeguard your information when you use our services.

**2. Information We Collect**

* **Personal Information**: Name, email address, phone number, and payment information.
* **Usage Data**: Details of your interactions with our service, including booking history and preferences.
* **Device Information**: IP address, browser type, and operating system.

**3. How We Use Your Information**

* To provide and improve our services.
* To manage your bookings and communicate with you.
* To process payments and prevent fraud.
* To send promotional materials (with your consent).

**4. Sharing Your Information**

We do not sell your personal information. We may share your data with:

* Service providers who assist with our operations.
* Law enforcement if required by law.
* Other users for booking purposes (e.g., businesses receiving your booking details).

**5. Data Security**

We implement appropriate technical and organizational measures to protect your data against unauthorized access, alteration, disclosure, or destruction.

**6. Your Rights**

* Access: You can request a copy of your personal data.
* Correction: You can request correction of inaccurate data.
* Deletion: You can request deletion of your data.
* Objection: You can object to the processing of your data for certain purposes.

**7. Cookies**

We use cookies to enhance your experience on our website. You can control cookie preferences through your browser settings.

**8. Changes to This Policy**

We may update this Privacy Policy from time to time. We will notify you of significant changes by posting the new policy on our website.

**9. Contact Us**

If you have any questions or concerns about this Privacy Policy, please contact us at <ask@beeoclock.com>.


# Notification


# Email

This section outlines the scenarios in which the system will send email notifications to clients and specialists, and when it will not.

**When Emails are Sent**

1. **Order Creation**
   * **Specialist Notification**: When a client creates an order that includes services, the specialist assigned to fulfill the service will receive an email notifying them of a new event added to their calendar.
   * **Client Notification**: The client will receive an email confirming that their order is either under review or already confirmed. Specifically:
     * If the order is initially under review and then changes to confirmed status, the client will receive at least two emails: one indicating the order has been created and another confirming it.
     * If the business strategy confirms the order immediately, the client will receive only one email.
2. **Order Status Changes**
   * **Cancellation**: The client will receive an email if their order status changes to "Cancelled".
3. **Modifications to Order Details**
   * **Service Changes**: If there is any change in the ordered service's duration, date, or time, the client will receive an email.
   * **General Order Changes**: Any modification to the order details, such as price changes, addition or removal of services, or products, will trigger an email notification to the client.
   * **Client-Initiated Changes**: If the client makes changes to the order after it has been placed (e.g., canceling the order), both the client and the specialist will receive email notifications.

**When Emails are Not Sent**

* **Automatic Status Updates**: The system does not automatically update order statuses. All status changes for orders or services must be performed manually.
* **Status: Done**: No email notifications are sent when the status is set to "Done".

This ensures that clients and specialists are kept informed of any significant changes or updates to their orders, while avoiding unnecessary notifications for completed orders.


# Entity


# State and State History


# Absence Management

## Overview

The Absence Management module is a core component of the Bee O'clock panel service that handles staff absences, vacations, holidays, and business closures. It provides a comprehensive system for managing when team members are unavailable and when the entire business is closed.

## Purpose

This module enables businesses to:

* **Track Staff Absences**: Record when individual team members are unavailable
* **Manage Business Closures**: Handle business-wide holidays and closures
* **Prevent Scheduling Conflicts**: Integrate with booking systems to avoid conflicts
* **Maintain Compliance**: Track time off for legal and HR requirements
* **Real-time Updates**: Notify stakeholders of absence changes

## Key Features

### ✅ Comprehensive Absence Types

* **Vacation**: Personal time off requests
* **Holiday**: Business holidays and public holidays
* **Break**: Short-term breaks or temporary unavailability

### ✅ Flexible Assignment Options

* **Individual Absences**: Assign to specific team members
* **Business-wide Closures**: Affect entire business operations
* **Multi-location Support**: Target specific business locations

### ✅ Advanced Permission System

* **Role-based Access**: Different permission levels for different roles
* **Scope Control**: OWN (personal) vs ANY (all absences) access
* **Granular Permissions**: Separate create, read, update, delete permissions

### ✅ Real-time Synchronization

* **WebSocket Updates**: Instant notifications to connected clients
* **Event-driven Architecture**: AMQP messaging for system integration
* **Cache Management**: Automatic cache invalidation for optimal performance

### ✅ Robust Data Management

* **Soft Delete**: Maintain audit trails without data loss
* **State History**: Track all changes with full audit trail
* **Multi-tenant**: Complete tenant isolation and security
* **Timezone Support**: Handle global businesses with proper timezone management

## Architecture

The module follows Clean Architecture principles with clear separation of concerns:

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   API Layer     │    │  Application    │    │   Domain        │
│                 │    │     Layer       │    │    Layer        │
│ • REST API      │───▶│ • Use Cases     │───▶│ • Entities      │
│ • Controllers   │    │ • Commands      │    │ • Value Objects │
│ • DTOs          │    │ • Queries       │    │ • Business Rules│
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         ▼                       ▼                       ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│ Infrastructure  │    │   Messaging     │    │  Persistence    │
│                 │    │                 │    │                 │
│ • Guards        │    │ • AMQP Events   │    │ • MongoDB       │
│ • Decorators    │    │ • WebSocket     │    │ • Repository    │
│ • Middleware    │    │ • Cache Events  │    │ • Schemas       │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

## Technology Stack

* **Framework**: NestJS with TypeScript
* **Database**: MongoDB with Mongoose ODM
* **Caching**: Redis for performance optimization
* **Messaging**: AMQP (RabbitMQ) for event-driven communication
* **Real-time**: WebSocket for instant updates
* **Architecture**: CQRS (Command Query Responsibility Segregation)
* **Patterns**: Repository, Domain-Driven Design, Event Sourcing

## Quick Start

### 1. API Usage

Start with the [API Documentation](/services/absence-management/api) to understand available endpoints and how to interact with the absence management system.

### 2. Integration

Review the [Interface Documentation](/services/absence-management/interface) to understand data structures and integration points.

### 3. Business Logic

Explore the [Use Case Documentation](/services/absence-management/usecase) to understand business rules and workflows.

### 4. Data Layer

Check the [Database Schema](/services/absence-management/db_schema) for persistence implementation details.

## Documentation Structure

| Document                                                          | Purpose                                                         | Audience                              |
| ----------------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------- |
| [API Documentation](/services/absence-management/api)             | REST API reference with endpoints, authentication, and examples | Frontend developers, API consumers    |
| [Interface Documentation](/services/absence-management/interface) | TypeScript interfaces, DTOs, and contracts                      | Backend developers, integration teams |
| [Use Case Documentation](/services/absence-management/usecase)    | Business logic, workflows, and application layer                | Backend developers, business analysts |
| [Database Schema](/services/absence-management/db_schema)         | Data persistence, queries, and optimization                     | Backend developers, DevOps teams      |

## Business Rules Summary

### ⚠️ Critical Constraints

1. **Date Validation**: End date must be after start date
2. **Assignment Rule**: Must specify either `entireBusiness: true` OR at least one member
3. **Permission Enforcement**: Users can only manage absences they have access to
4. **Timezone Required**: All absences must include timezone information

### 🔒 Security Features

* Multi-tenant data isolation
* Role-based permission system
* Access scope validation (OWN vs ANY)
* Audit trail for all changes
* Soft delete for data integrity

### 📊 Performance Features

* Redis caching with intelligent invalidation
* Optimized database indexes
* Paginated query results
* Efficient aggregation pipelines
* Background event processing

## Integration Points

### Upstream Dependencies

* **Identity Service**: User authentication and authorization
* **Member Service**: Staff member information
* **Permission Service**: Role and permission management

### Downstream Consumers

* **Order Service**: Booking conflict prevention
* **Notification Service**: Absence alerts and reminders
* **Analytics Service**: Reporting and insights
* **Calendar Service**: Schedule integration

### External Integrations

* **Frontend Applications**: Real-time absence updates
* **Mobile Apps**: Push notifications for absence changes
* **HR Systems**: Compliance and reporting
* **Calendar Systems**: External calendar synchronization

## Common Use Cases

### 👤 Individual User Scenarios

* Employee requests vacation time
* Manager approves/denies absence requests
* Staff member views their absence history
* Employee cancels upcoming absence

### 🏢 Business Management Scenarios

* HR manager schedules business-wide holiday
* Manager views team absence calendar
* Administrator generates absence reports
* Business owner manages location-specific closures

### 🔄 System Integration Scenarios

* Booking system checks for conflicts
* Payroll system imports absence data
* Calendar system syncs absence events
* Notification system sends absence alerts

## Monitoring and Maintenance

### Key Metrics

* API response times
* Cache hit ratios
* Event processing latency
* Database query performance
* Permission validation overhead

### Health Checks

* Database connectivity
* Cache availability
* Message queue status
* WebSocket connection health
* Index performance

## Future Enhancements

### Planned Features

* **Absence Approval Workflow**: Multi-step approval process
* **Recurring Absences**: Support for repeating patterns
* **Advanced Reporting**: Analytics and insights dashboard
* **Mobile Optimizations**: Enhanced mobile app integration
* **AI Predictions**: Intelligent absence pattern detection

### Scalability Considerations

* Database sharding strategies
* Read replica optimization
* Cache partitioning
* Event stream processing
* Microservice decomposition

***

## Getting Help

For technical questions or issues:

1. Check this documentation first
2. Review the API examples and use cases
3. Consult the interface definitions
4. Examine the database schema for data-related questions

For business rule clarifications:

1. Review the use case documentation
2. Check the business rules summary above
3. Consult with the product team

***

*This documentation is maintained by the Bee O'clock development team and is updated with each release.*


# API Documentation

## Overview

The Absence Management API provides endpoints for managing staff absences within the Bee O'clock platform. This API allows businesses to create, update, retrieve, and delete absence records for their members, with support for both individual member absences and business-wide closures.

## Base URL

```
/api/v1/absence
```

## Authentication

All endpoints require:

* **Bearer Token**: JWT authentication token
* **Business-Tenant-Id**: Header specifying the business tenant ID

## API Endpoints

### 1. Get Paginated Absences

**Endpoint:** `GET /paged`

**Description:** Retrieves a paginated list of absences for the authenticated tenant.

**Query Parameters:**

* `page` (number, optional): Page number (default: 1)
* `pageSize` (number, optional): Number of items per page (default: 10)
* Additional pagination parameters from `AbsencePaginationDto`

**Response:**

```typescript
{
  items: AbsenceDto[],
  totalSize: number,
  page: number,
  pageSize: number
}
```

**Permissions Required:** `READ_ABSENCE`

**Access Control:**

* Users with `OWN` scope can only see their own absences
* Users with `ANY` scope can see all absences
* Business-wide absences are visible to all authorized users

***

### 2. Get Absence by ID

**Endpoint:** `GET /:id`

**Description:** Retrieves a specific absence by its ID.

**Path Parameters:**

* `id` (string): The unique identifier of the absence

**Response:** `AbsenceDto`

**Permissions Required:** `READ_ABSENCE`

**Access Control:**

* Users can only access absences they are assigned to or business-wide absences
* Returns `null` if absence not found or access denied

***

### 3. Create Absence

**Endpoint:** `POST /`

**Description:** Creates a new absence record.

**Request Body:** `AbsenceDto`

**Required Fields:**

* `start`: Start date/time (ISO string)
* `end`: End date/time (ISO string)
* `type`: Absence type (vacation, holiday, break)
* `timeZone`: Timezone identifier

**Optional Fields:**

* `note`: Description or notes about the absence
* `entireBusiness`: Boolean indicating if this affects the entire business
* `members`: Array of member IDs affected (required if not entireBusiness)
* `locations`: Array of affected locations

**Response:** `void` (201 Created)

**Permissions Required:** `CREATE_ABSENCE`

**Validation Rules:**

* End date must be after start date
* Must specify either `entireBusiness: true` or at least one member
* Users with `OWN` scope can only create absences for themselves

***

### 4. Update Absence

**Endpoint:** `PUT /:id`

**Description:** Updates an existing absence record.

**Path Parameters:**

* `id` (string): The unique identifier of the absence

**Request Body:** `AbsenceDto` (complete object with `_id` field)

**Response:** `void` (200 OK)

**Permissions Required:** `EDIT_ABSENCE`

**Access Control:**

* Users can only update absences they have access to
* Business-wide absences require appropriate permissions

***

### 5. Delete Absence

**Endpoint:** `DELETE /:id`

**Description:** Soft deletes an absence record by updating its state history.

**Path Parameters:**

* `id` (string): The unique identifier of the absence

**Response:** `void` (200 OK)

**Permissions Required:** `DELETE_ABSENCE`

**Access Control:**

* Users can only delete absences they have access to
* Performs soft delete by updating state history to 'deleted'

## Data Transfer Objects

### AbsenceDto

```typescript
{
  _id?: string;
  object?: 'AbsenceDto';
  note?: string;
  start: string;           // ISO date string
  end: string;             // ISO date string
  type?: AbsenceTypeEnum;  // 'vacation' | 'holiday' | 'break'
  entireBusiness?: boolean;
  members?: MemberDto[];
  locations?: LocationDto[];
  timeZone?: string;
  meta?: MetaDto;
  createdAt?: string;
  updatedAt?: string;
}
```

### AbsenceTypeEnum

```typescript
enum AbsenceTypeEnum {
  vacation = 'vacation',
  holiday = 'holiday',
  break = 'break'
}
```

## Error Responses

### Common HTTP Status Codes

* **400 Bad Request**: Invalid request data or validation errors
* **401 Unauthorized**: Missing or invalid authentication token
* **403 Forbidden**: Insufficient permissions
* **404 Not Found**: Absence not found or access denied
* **500 Internal Server Error**: Server-side processing error

### Error Response Format

```typescript
{
  statusCode: number;
  message: string | string[];
  error?: string;
}
```

## Permission System

The absence management system uses a role-based permission system with the following permissions:

* **READ\_ABSENCE**: View absence records
* **CREATE\_ABSENCE**: Create new absence records
* **EDIT\_ABSENCE**: Modify existing absence records
* **DELETE\_ABSENCE**: Delete absence records

### Permission Scopes

* **OWN**: User can only manage their own absences
* **ANY**: User can manage any absences within their tenant

## Business Rules

1. **Date Validation**: End date must be greater than start date
2. **Assignment Validation**: Must specify either `entireBusiness: true` or at least one member
3. **Permission Enforcement**: Users can only manage absences they have permission to access
4. **Soft Deletion**: Absences are not physically deleted but marked as deleted in state history
5. **Timezone Support**: All dates are stored with timezone information
6. **Business-wide Impact**: Setting `entireBusiness: true` affects all operations regardless of member assignments

## Integration Points

* **Message Queue**: Publishes events for absence creation, updates, and deletions
* **WebSocket**: Real-time notifications sent to connected clients
* **Cache**: Automatic cache invalidation for affected queries
* **Audit Trail**: State history tracking for all changes

## Rate Limiting

Standard API rate limiting applies to all endpoints. Refer to the main API documentation for specific limits.

## Examples

### Create a Personal Absence

```javascript
POST /api/v1/absence
{
  "start": "2024-12-25T09:00:00.000Z",
  "end": "2024-12-25T17:00:00.000Z",
  "type": "vacation",
  "note": "Christmas vacation",
  "timeZone": "America/New_York",
  "members": [
    { "_id": "member-id-123" }
  ]
}
```

### Create a Business-wide Closure

```javascript
POST /api/v1/absence
{
  "start": "2024-12-25T00:00:00.000Z",
  "end": "2024-12-25T23:59:59.000Z",
  "type": "holiday",
  "note": "Christmas Day - Business Closed",
  "timeZone": "America/New_York",
  "entireBusiness": true
}
```


# Interface Documentation

## Overview

This document describes the interfaces, types, and contracts used in the Absence Management module. These interfaces define the structure of data objects, repository contracts, and service interfaces used throughout the system.

## Core Interfaces

### IAbsence

The main interface for absence entities, extending the base entity interface.

```typescript
interface IAbsence extends IBase {
  note?: string;                    // Optional description or notes
  start: string;                    // Start date/time (ISO string)
  end: string;                      // End date/time (ISO string)
  entireBusiness?: boolean;         // Affects entire business if true
  memberIds?: string[];             // Array of member ID strings
  members?: IMember[];              // Populated member objects
  locations?: ILocation[];          // Affected locations
  type: AbsenceTypeEnum;           // Type of absence
  timeZone: string;                // Timezone identifier
  meta?: IMeta;                    // Metadata information
}
```

### IAbsenceRepository

Repository interface defining data access operations for absences.

```typescript
interface IAbsenceRepository extends IBaseRepository<IAbsence> {
  getAbsencesWithFilter(params: GetBusySlotsWithFilterParams): Promise<ISlot[]>;
}
```

## Data Transfer Objects (DTOs)

### AbsenceDto

Main DTO for absence data transfer between layers.

```typescript
class AbsenceDto extends BaseEntityDto {
  object?: 'AbsenceDto';
  note?: string;
  start: string;
  end: string;
  type?: AbsenceTypeEnum;
  entireBusiness?: boolean;
  members?: MemberDto[];
  locations?: LocationDto[];
  timeZone?: string;
  meta?: MetaDto;
}
```

**Validation Rules:**

* `start`: Required string (ISO date format)
* `end`: Required string (ISO date format)
* `type`: Optional enum value (vacation, holiday, break)
* `entireBusiness`: Optional boolean
* `members`: Optional array of MemberDto objects
* `locations`: Optional array of LocationDto objects
* `timeZone`: Optional string
* `note`: Optional string

### AbsencePaginationDto

DTO for pagination parameters when querying absences.

```typescript
class AbsencePaginationDto extends PaginationRequestDto {
  // Inherits pagination fields from base class
  // Additional absence-specific filtering can be added here
}
```

## Enumerations

### AbsenceTypeEnum

Defines the types of absences supported by the system.

```typescript
enum AbsenceTypeEnum {
  vacation = 'vacation',
  holiday = 'holiday',
  break = 'break'
}
```

**Values:**

* `vacation`: Personal time off
* `holiday`: Business holidays
* `break`: Short breaks or temporary unavailability

## Use Case Interfaces

### CreateAbsenceUseCaseParams

```typescript
interface CreateAbsenceUseCaseParams {
  ctx: TenantActorContext;
  absence: AbsenceDto;
}
```

### GetAbsenceUseCaseParams

```typescript
interface GetAbsenceUseCaseParams {
  ctx: TenantActorContext;
  absenceId: string;
}
```

### GetPagedAbsencesUseCaseParams

```typescript
interface GetPagedAbsencesUseCaseParams {
  ctx: TenantActorContext;
  pagination: AbsencePaginationDto;
}
```

### UpdateAbsenceUseCaseParams

```typescript
interface UpdateAbsenceUseCaseParams {
  ctx: TenantActorContext;
  absenceId: string;
  update: AbsenceDto;
}
```

### DeleteAbsenceUseCaseParams

```typescript
interface DeleteAbsenceUseCaseParams {
  ctx: TenantActorContext;
  absenceId: string;
}
```

## Domain Value Objects

### AbsenceSearchCriteria

```typescript
interface AbsenceSearchCriteria {
  memberIds?: string[];
  startDate?: string;
  endDate?: string;
  types?: AbsenceTypeEnum[];
  entireBusinessOnly?: boolean;
}
```

### ISlot

Interface representing a time slot, used in absence conflict detection.

```typescript
interface ISlot {
  start: string;
  end: string;
  memberId?: string;
  absenceId?: string;
  type?: string;
}
```

## Command and Query Interfaces

### Commands

#### CreateAbsenceCommand

```typescript
class CreateAbsenceCommand implements ITenantAware {
  constructor(
    public readonly tenantId: string,
    public readonly absenceDto: AbsenceDto
  ) {}
}
```

#### UpdateAbsenceCommand

```typescript
class UpdateAbsenceCommand implements ITenantAware {
  constructor(
    public readonly tenantId: string,
    public readonly absence: AbsenceDto
  ) {}
}
```

#### DeleteAbsenceCommand

```typescript
class DeleteAbsenceCommand {
  constructor(
    public readonly tenantId: string,
    public readonly absenceId: string
  ) {}
}
```

### Queries

#### GetAbsenceByIdQuery

```typescript
class GetAbsenceByIdQuery implements ITenantAware {
  constructor(
    public readonly tenantId: string,
    public readonly absenceId: string
  ) {}
}
```

#### GetPagedAbsencesQuery

```typescript
class GetPagedAbsencesQuery implements ITenantAware {
  constructor(
    public readonly tenantId: string,
    public readonly criteria: AbsenceSearchCriteria,
    public readonly pagination: PaginationRequestDto
  ) {}
}
```

## Message Interfaces

### Event Messages

#### AbsenceCreatedMessage

```typescript
interface AbsenceCreatedMessagePayload {
  tenantId: string;
  absence: AbsenceDto;
}

class AbsenceCreatedMessage extends BaseMessage<AbsenceCreatedMessagePayload> {
  constructor(params: AbsenceCreatedMessagePayload) {
    super(Queue.notificationQueue, 'absence-created', params);
  }
}
```

#### AbsenceUpdatedMessage

```typescript
interface AbsenceUpdatedMessagePayload {
  tenantId: string;
  absence: AbsenceDto;
}

class AbsenceUpdatedMessage extends BaseMessage<AbsenceUpdatedMessagePayload> {
  constructor(params: AbsenceUpdatedMessagePayload) {
    super(Queue.notificationQueue, 'absence-updated', params);
  }
}
```

#### AbsenceDeletedMessage

```typescript
interface AbsenceDeletedMessagePayload {
  tenantId: string;
  absence: AbsenceDto;
}

class AbsenceDeletedMessage extends BaseMessage<AbsenceDeletedMessagePayload> {
  constructor(params: AbsenceDeletedMessagePayload) {
    super(Queue.notificationQueue, 'absence-deleted', params);
  }
}
```

### WebSocket Messages

#### AbsenceCreatedWsMessage

```typescript
interface AbsenceCreatedWsMessage {
  type: 'absence-created';
  payload: { absence: AbsenceDto };
}
```

#### AbsenceUpdatedWsMessage

```typescript
interface AbsenceUpdatedWsMessage {
  type: 'absence-updated';
  payload: { absence: AbsenceDto };
}
```

#### AbsenceDeletedWsMessage

```typescript
interface AbsenceDeletedWsMessage {
  type: 'absence-deleted';
  payload: { absence: AbsenceDto };
}
```

## Cache Interfaces

### AbsenceCacheKeys

```typescript
enum AbsenceCacheKeys {
  GET_ABSENCE = 'GET_ABSENCE',
  GET_PAGED_ABSENCES = 'GET_PAGED_ABSENCES'
}
```

## Repository Filter Interfaces

### GetBusySlotsWithFilterParams

```typescript
interface GetBusySlotsWithFilterParams {
  specialistIds?: string[];
  start: string;
  end: string;
  state?: string;
}
```

## Context Interfaces

### TenantActorContext

```typescript
interface TenantActorContext {
  tenantId: string;
  actor: {
    issuerId: string;
    type: ActorTypeEnum;
    // Additional actor properties
  };
}
```

## Validation and Error Interfaces

### AbsenceDomainError

```typescript
class AbsenceDomainError extends Error {
  constructor(
    public readonly code: AbsenceErrorCode,
    message: string,
    public readonly fields: string[]
  ) {
    super(message);
  }
}
```

### AbsenceErrorCode

```typescript
enum AbsenceErrorCode {
  absenceNotFound = 'ABSENCE_NOT_FOUND',
  invalidDateRange = 'INVALID_DATE_RANGE',
  invalidAssignment = 'INVALID_ASSIGNMENT',
  permissionDenied = 'PERMISSION_DENIED'
}
```

## Integration Interfaces

### IMessageQueueService

```typescript
interface IMessageQueueService {
  emitEvent<T>(event: BaseMessage<T>): Promise<void>;
}
```

### IWebSocketGateway

```typescript
interface IWebSocketGateway {
  sendMessage<T>(tenantId: string, message: T): void;
}
```

## Usage Guidelines

1. **DTO Validation**: Always validate DTOs using class-validator decorators
2. **Type Safety**: Use TypeScript interfaces to ensure type safety across layers
3. **Error Handling**: Implement proper error handling using domain-specific exceptions
4. **Message Contracts**: Maintain consistent message interfaces for event-driven communication
5. **Cache Keys**: Use enum-defined cache keys for consistent cache management
6. **Context Propagation**: Always pass TenantActorContext for proper authorization and tenancy

## Interface Evolution

When modifying interfaces:

1. Consider backward compatibility
2. Use optional properties for new fields
3. Update validation rules accordingly
4. Document breaking changes
5. Version the API if necessary


# Use Case Documentation

## Overview

This document describes the business use cases and application layer logic for the Absence Management module. Each use case encapsulates business rules, permissions, and orchestrates the interaction between domain entities, repositories, and external services.

## Architecture Pattern

The module follows the CQRS (Command Query Responsibility Segregation) pattern with the following structure:

* **Use Cases**: Application layer orchestrating business logic
* **Commands**: Write operations (Create, Update, Delete)
* **Queries**: Read operations (Get, List)
* **Domain Entities**: Business logic and validation
* **Events**: Asynchronous notifications

## Use Cases

### 1. CreateAbsenceUseCase

**Purpose:** Creates a new absence record with proper validation and permission checking.

**Input:** `CreateAbsenceUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  absence: AbsenceDto
}
```

**Output:** `void`

**Business Rules:**

1. User must have `CREATE_ABSENCE` permission
2. Users with `OWN` scope can only create absences for themselves
3. Absence must have valid date range (end > start)
4. Must specify either `entireBusiness: true` or at least one member
5. Timezone must be provided

**Process Flow:**

1. Validate user permissions using `PermissionValidatorUseCase`
2. Check scope restrictions for member assignments
3. Execute `CreateAbsenceCommand` via command bus
4. Command handler validates domain rules
5. Persist absence to database
6. Emit `AbsenceCreatedMessage` for notifications
7. Clear relevant cache entries

**Permission Matrix:**

* **OWN scope**: Can only create absences where the actor is in the members list
* **ANY scope**: Can create any absence within the tenant

**Error Scenarios:**

* Insufficient permissions → `AccessPermissionException`
* Invalid domain data → `AbsenceDomainError`
* Database errors → Logged and re-thrown

***

### 2. GetAbsenceUseCase

**Purpose:** Retrieves a specific absence by ID with proper access control.

**Input:** `GetAbsenceUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  absenceId: string
}
```

**Output:** `AbsenceDto | null`

**Business Rules:**

1. User must have `READ_ABSENCE` permission
2. Users with `OWN` scope can only view their own absences or business-wide absences
3. Returns `null` if absence not found or access denied

**Process Flow:**

1. Validate user permissions
2. Execute `GetAbsenceByIdQuery` via query bus
3. Check access rights based on permission scope
4. Return absence data or null if unauthorized

**Access Control Logic:**

```typescript
// Business-wide absences are visible to all authorized users
if (absence.entireBusiness) return absence;

// Check if user has access to non-business-wide absence
const hasAccess = scope === PermissionScopeEnum.ANY || 
                  absence.members.some(member => member._id === ctx.actor.issuerId);

return hasAccess ? absence : null;
```

**Caching:** Results are cached using `AbsenceCacheKeys.GET_ABSENCE`

***

### 3. GetPagedAbsencesUseCase

**Purpose:** Retrieves a paginated list of absences with filtering and access control.

**Input:** `GetPagedAbsencesUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  pagination: AbsencePaginationDto
}
```

**Output:** `PaginationResponseDto<AbsenceDto>`

**Business Rules:**

1. User must have `READ_ABSENCE` permission
2. Users with `OWN` scope only see their own absences and business-wide absences
3. Users with `ANY` scope see all absences within the tenant
4. Returns empty result if no permissions

**Process Flow:**

1. Validate permissions with fallback to empty result
2. Apply scope-based filtering
3. Execute paginated query
4. Return formatted pagination response

**Scope-based Filtering:**

* **OWN scope**: Filter to show only absences where user is a member or business-wide absences
* **ANY scope**: Show all absences within the tenant

**Caching:** Results can be cached using `AbsenceCacheKeys.GET_PAGED_ABSENCES`

***

### 4. UpdateAbsenceUseCase

**Purpose:** Updates an existing absence with validation and access control.

**Input:** `UpdateAbsenceUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  absenceId: string,
  update: AbsenceDto
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_ABSENCE` permission
2. Absence must exist and be accessible
3. Users can only update absences they have access to
4. Domain validation rules apply (dates, assignments, etc.)

**Process Flow:**

1. Validate user permissions
2. Fetch existing absence
3. Check access rights using `assertActorHasAccessToAbsence`
4. Execute `UpdateAbsenceCommand`
5. Domain validation and persistence
6. Emit `AbsenceUpdatedMessage`
7. Clear cache entries

**Access Validation:**

```typescript
function assertActorHasAccessToAbsence(options: {
  actorMemberId: string;
  absence: AbsenceDto;
  scope: PermissionScopeEnum;
  action: string;
  logger: Logger;
}): void {
  const hasAccess = absence.entireBusiness || 
                    scope === PermissionScopeEnum.ANY ||
                    absence.members.some(m => m._id.toString() === actorMemberId);
  
  if (!hasAccess) {
    throw new AccessPermissionException(`You can only ${action} your own absences`);
  }
}
```

***

### 5. DeleteAbsenceUseCase

**Purpose:** Soft deletes an absence record by updating its state history.

**Input:** `DeleteAbsenceUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  absenceId: string
}
```

**Output:** `void`

**Business Rules:**

1. User must have `DELETE_ABSENCE` permission
2. Absence must exist and be accessible
3. Performs soft delete (state history update)
4. Cannot delete already deleted absences

**Process Flow:**

1. Validate user permissions
2. Fetch absence to verify existence and access
3. Check access rights
4. Execute `DeleteAbsenceCommand`
5. Update state history to 'deleted'
6. Emit `AbsenceDeletedMessage`
7. Clear cache entries

**Soft Delete Implementation:**

* Absences are not physically removed from the database
* State history is updated with `EntityStateEnum.deleted`
* Deleted absences are filtered out in queries
* Maintains audit trail and referential integrity

***

## Command Handlers

### CreateAbsenceHandler

**Responsibilities:**

1. Domain entity creation and validation
2. Database persistence
3. Event emission
4. Cache invalidation

**Key Operations:**

```typescript
// Create domain entity with validation
const absence: IAbsence = AbsenceMap.toPersistenceFromDto(command.absenceDto);
const absenceDomain = Absence.create(absence);

// Persist to database
const createdAbsence = await this.sharedUnitOfWork.absences.createItem(
  AbsenceMap.toPersistence(absenceDomain.getValue())
);

// Emit event
await this.messageQueueService.emitEvent(new AbsenceCreatedMessage({
  tenantId: command.tenantId,
  absence: AbsenceMap.toDto(createdAbsence)
}));
```

### UpdateAbsenceHandler

**Responsibilities:**

1. Domain validation of updates
2. Database update operation
3. Event emission
4. Cache invalidation

### DeleteAbsenceHandler

**Responsibilities:**

1. Fetch existing absence
2. Create domain object
3. Update state history
4. Persist changes
5. Event emission

***

## Query Handlers

### GetAbsenceByIdHandler

**Responsibilities:**

1. Database query execution
2. Result transformation
3. Cache management

**Caching Strategy:**

* Uses `@Cached` decorator with `AbsenceCacheKeys.GET_ABSENCE`
* Cache key includes tenant ID for multi-tenancy
* Automatically invalidated on updates/deletes

### GetPagedAbsenceHandler

**Responsibilities:**

1. Build query filters
2. Execute paginated database query
3. Transform results
4. Return pagination metadata

**Query Building:**

```typescript
// Build aggregation pipeline
const pipeline = [
  { $match: matchConditions },
  { $lookup: memberLookup },
  { $skip: (page - 1) * pageSize },
  { $limit: pageSize }
];
```

***

## Domain Validation Rules

### Absence Entity Validation

1. **ID Validation**: Must be valid ObjectId
2. **Date Validation**: Start date must be before end date
3. **Type Validation**: Must be valid AbsenceTypeEnum value
4. **Timezone Validation**: Must be provided
5. **Assignment Validation**: Must have either entireBusiness=true or at least one member

```typescript
// Core validation in Absence.create()
if (new Date(props.start) >= new Date(props.end)) {
  validationErrors.push('End date must be greater than start date');
}

if (!props.entireBusiness && props.members.length === 0) {
  validationErrors.push('Absence must have at least one member assigned or be for the entire business');
}
```

***

## Event-Driven Architecture

### Message Types

1. **AbsenceCreatedMessage**: Published when a new absence is created
2. **AbsenceUpdatedMessage**: Published when an absence is modified
3. **AbsenceDeletedMessage**: Published when an absence is deleted

### Event Consumers

**AbsenceConsumer (Panel Service):**

* Receives AMQP messages
* Transforms to WebSocket messages
* Broadcasts to connected clients

**AbsenceCacheConsumer (Cache Service):**

* Receives cache invalidation events
* Clears relevant cache entries
* Maintains cache consistency

### WebSocket Integration

Real-time notifications are sent to connected clients:

```typescript
// Example WebSocket message
const wsMessage: AbsenceCreatedWsMessage = {
  type: 'absence-created',
  payload: { absence: createdAbsence }
};

this.webSocket.sendMessage(tenantId, wsMessage);
```

***

## Permission Integration

### Permission Validation

All use cases integrate with the `PermissionValidatorUseCase`:

```typescript
const { scope } = await this.permissionValidatorUseCase.execute({
  actor: ctx.actor,
  requiredPermissions: [ModulePermissionEnum.CREATE_ABSENCE],
});
```

### Permission Scopes

* **PermissionScopeEnum.OWN**: Limited to user's own data
* **PermissionScopeEnum.ANY**: Access to all tenant data

### Access Patterns

1. **Create**: Users can only create absences they're assigned to (OWN scope)
2. **Read**: Users can view their absences + business-wide absences
3. **Update/Delete**: Users can only modify absences they have access to

***

## Cache Management

### Cache Keys

* `GET_ABSENCE`: Individual absence cache
* `GET_PAGED_ABSENCES`: Paginated list cache

### Invalidation Strategy

* **Create**: Invalidates `GET_PAGED_ABSENCES`
* **Update**: Invalidates both `GET_ABSENCE` and `GET_PAGED_ABSENCES`
* **Delete**: Invalidates both cache keys

### Cache Decorators

```typescript
@DeleteCache([
  AbsenceCacheKeys.GET_ABSENCE,
  AbsenceCacheKeys.GET_PAGED_ABSENCES
])
```

***

## Error Handling

### Exception Types

1. **AccessPermissionException**: Permission-related errors
2. **AbsenceDomainError**: Domain validation errors
3. **AbsenceCreationException**: Creation-specific errors
4. **AbsenceUpdationException**: Update-specific errors

### Error Logging

All use cases implement comprehensive error logging:

```typescript
catch (error) {
  this.logger.error('Error creating absence', error);
  throw error;
}
```

***

## Testing Considerations

### Unit Testing

* Mock dependencies (CommandBus, QueryBus, PermissionValidator)
* Test permission scenarios
* Validate business rules
* Test error conditions

### Integration Testing

* Test with real database
* Verify event emission
* Test cache behavior
* Validate multi-tenancy

### Example Test Scenarios

1. **Permission Tests**: Verify OWN vs ANY scope behavior
2. **Validation Tests**: Test domain validation rules
3. **Access Control Tests**: Verify users can only access appropriate data
4. **Event Tests**: Verify correct events are emitted
5. **Cache Tests**: Verify cache invalidation works correctly


# Database Schema

## Overview

This document describes the database schema and data persistence layer for the Absence Management module. The system uses MongoDB as the primary database with Mongoose as the ODM layer.

## Database Schema

### Absence Collection

**Collection Name:** `absence`

The absence collection stores all absence records with the following schema structure:

```typescript
{
  _id: ObjectId,                    // Primary key
  note: String,                     // Optional description
  start: String,                    // Start date/time (ISO string) - REQUIRED
  end: String,                      // End date/time (ISO string) - REQUIRED
  entireBusiness: Boolean,          // Affects entire business flag
  members: [ObjectId],              // References to Member collection
  memberIds: [String],              // Array of member ID strings
  locations: [LocationSchema],      // Embedded location documents
  type: String,                     // Absence type (vacation, holiday, break) - REQUIRED
  timeZone: String,                 // Timezone identifier - REQUIRED
  meta: MetaSchema,                 // Metadata information
  stateHistory: [StateHistorySchema], // State tracking for soft deletes
  createdAt: Date,                  // Auto-generated creation timestamp
  updatedAt: Date                   // Auto-generated update timestamp
}
```

### Schema Definition

```typescript
const AbsenceSchema = new Schema<IAbsence>({
  note: { 
    type: String 
  },
  start: {
    type: String,
    required: true,
  },
  end: {
    type: String,
    required: true,
  },
  entireBusiness: { 
    type: Boolean 
  },
  members: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: Member.name 
  }],
  memberIds: [{
    type: String
  }],
  locations: {
    type: [LocationSchema],
  },
  type: {
    type: String,
    required: true,
  },
  timeZone: {
    type: String,
    required: true,
  },
  meta: { 
    type: MetaSchema 
  },
  stateHistory: { 
    type: [StateHistorySchema], 
    default: [] 
  },
}, {
  timestamps: true,
  collection: Absence.name.toLowerCase(),
});
```

## Field Specifications

### Required Fields

| Field      | Type   | Description                   | Validation                                         |
| ---------- | ------ | ----------------------------- | -------------------------------------------------- |
| `start`    | String | Start date/time in ISO format | Must be valid ISO date string                      |
| `end`      | String | End date/time in ISO format   | Must be valid ISO date string, must be after start |
| `type`     | String | Type of absence               | Must be one of: 'vacation', 'holiday', 'break'     |
| `timeZone` | String | IANA timezone identifier      | Must be valid timezone string                      |

### Optional Fields

| Field            | Type              | Description                              | Default |
| ---------------- | ----------------- | ---------------------------------------- | ------- |
| `note`           | String            | Description or notes about the absence   | null    |
| `entireBusiness` | Boolean           | Whether this affects the entire business | false   |
| `members`        | ObjectId\[]       | References to assigned members           | \[]     |
| `memberIds`      | String\[]         | Member IDs as strings                    | \[]     |
| `locations`      | LocationSchema\[] | Affected locations                       | \[]     |

### System Fields

| Field          | Type                  | Description                 | Auto-Generated |
| -------------- | --------------------- | --------------------------- | -------------- |
| `_id`          | ObjectId              | Primary key                 | Yes            |
| `meta`         | MetaSchema            | Metadata information        | Partial        |
| `stateHistory` | StateHistorySchema\[] | State change tracking       | Yes            |
| `createdAt`    | Date                  | Creation timestamp          | Yes            |
| `updatedAt`    | Date                  | Last modification timestamp | Yes            |

## Embedded Schemas

### LocationSchema

```typescript
{
  _id: ObjectId,
  name: String,
  address: String,
  coordinates: {
    latitude: Number,
    longitude: Number
  }
}
```

### MetaSchema

```typescript
{
  createdBy: ObjectId,
  updatedBy: ObjectId,
  version: Number,
  tags: [String],
  customFields: Map
}
```

### StateHistorySchema

```typescript
{
  state: String,           // Current state (active, deleted, etc.)
  timestamp: Date,         // When the state change occurred
  actor: ObjectId,         // Who made the change
  reason: String,          // Optional reason for the change
  metadata: Map            // Additional context
}
```

## Relationships

### Member Relationship

* **Type**: One-to-Many (Absence → Members)
* **Implementation**: Array of ObjectId references
* **Collection**: `member`
* **Lookup**: Populated during queries when member details are needed

```typescript
// Population example
absence.populate('members', 'name email role')
```

### Location Relationship

* **Type**: Embedded Documents
* **Implementation**: Array of LocationSchema subdocuments
* **Storage**: Denormalized within absence document

## Indexing Strategy

### Primary Indexes

```typescript
// Compound index for date range queries
db.absence.createIndex({ 
  "start": 1, 
  "end": 1 
});

// Index for member-based queries
db.absence.createIndex({ 
  "members": 1 
});

// Index for business-wide absences
db.absence.createIndex({ 
  "entireBusiness": 1 
});

// Index for type-based filtering
db.absence.createIndex({ 
  "type": 1 
});

// Soft delete index (state history)
db.absence.createIndex({ 
  "stateHistory.state": 1 
});

// Tenant-based partitioning (via meta.tenantId)
db.absence.createIndex({ 
  "meta.tenantId": 1 
});
```

### Composite Indexes

```typescript
// Optimal index for member-based date range queries
db.absence.createIndex({ 
  "members": 1, 
  "start": 1, 
  "end": 1 
});

// Index for tenant-specific queries
db.absence.createIndex({ 
  "meta.tenantId": 1, 
  "stateHistory.state": 1,
  "start": 1 
});
```

## Query Patterns

### Common Queries

#### Find Absences by Date Range

```typescript
// Find overlapping absences
db.absence.find({
  $or: [
    { start: { $gte: startDate, $lt: endDate } },
    { end: { $gt: startDate, $lte: endDate } },
    { start: { $lte: startDate }, end: { $gte: endDate } }
  ],
  $expr: {
    $ne: [
      { $arrayElemAt: ['$stateHistory.state', -1] },
      'deleted'
    ]
  }
});
```

#### Find Member-Specific Absences

```typescript
// Find absences for specific members or business-wide
db.absence.find({
  $or: [
    { members: { $in: memberIds } },
    { entireBusiness: true }
  ],
  $expr: {
    $ne: [
      { $arrayElemAt: ['$stateHistory.state', -1] },
      'deleted'
    ]
  }
});
```

#### Paginated Query with Population

```typescript
// Aggregation pipeline for paginated results
const pipeline = [
  // Match criteria
  {
    $match: {
      'meta.tenantId': tenantId,
      $expr: {
        $ne: [
          { $arrayElemAt: ['$stateHistory.state', -1] },
          'deleted'
        ]
      }
    }
  },
  // Lookup members
  {
    $lookup: {
      from: 'member',
      localField: 'members',
      foreignField: '_id',
      as: 'members'
    }
  },
  // Sort
  { $sort: { start: -1 } },
  // Pagination
  { $skip: (page - 1) * pageSize },
  { $limit: pageSize }
];
```

## Repository Implementation

### AbsenceRepository

The repository class extends `BaseRepository` and implements `IAbsenceRepository`:

```typescript
export class AbsenceRepository extends BaseRepository<IAbsence> implements IAbsenceRepository {
  constructor(
    public readonly model: Model<AbsenceDocument>,
    public readonly member: Model<MemberDocument>
  ) {
    super(model);
  }

  // Specialized query for busy slots
  public async getAbsencesWithFilter(
    params: GetBusySlotsWithFilterParams
  ): Promise<ISlot[]> {
    // Implementation details for conflict detection
  }
}
```

### Key Repository Methods

#### Standard CRUD Operations

* `createItem(absence: IAbsence): Promise<IAbsence>`
* `updateItem(id: string, absence: IAbsence): Promise<IAbsence>`
* `findById(id: string): Promise<IAbsence | null>`
* `deleteItem(id: string): Promise<void>` (soft delete)

#### Specialized Queries

* `getAbsencesWithFilter(params): Promise<ISlot[]>`
* `findByDateRange(start: string, end: string): Promise<IAbsence[]>`
* `findByMember(memberId: string): Promise<IAbsence[]>`

## Data Consistency

### Soft Delete Pattern

Absences use soft deletion through the state history mechanism:

```typescript
// Soft delete implementation
absence.stateHistory.push({
  state: EntityStateEnum.deleted,
  timestamp: new Date(),
  actor: actorId,
  reason: 'User requested deletion'
});

await absence.save();
```

### State History Tracking

All state changes are tracked in the `stateHistory` array:

* Initial state: 'active'
* Soft delete: 'deleted'
* Future states: 'archived', 'suspended', etc.

### Query Filtering

Non-deleted records are filtered using aggregation expressions:

```typescript
$expr: {
  $ne: [
    { $arrayElemAt: ['$stateHistory.state', -1] },
    'deleted'
  ]
}
```

## Multi-Tenancy

### Tenant Isolation

Data isolation is achieved through the `meta.tenantId` field:

* All queries must include tenant filter
* Indexes include `meta.tenantId` for performance
* Application layer enforces tenant boundary

### Tenant-Aware Queries

```typescript
// All repository methods include tenant context
async findById(id: string, tenantId: string): Promise<IAbsence | null> {
  return this.model.findOne({
    _id: id,
    'meta.tenantId': tenantId,
    $expr: {
      $ne: [
        { $arrayElemAt: ['$stateHistory.state', -1] },
        'deleted'
      ]
    }
  });
}
```

## Performance Considerations

### Query Optimization

1. **Index Usage**: Ensure queries use appropriate indexes
2. **Projection**: Select only needed fields
3. **Population**: Use selective field population
4. **Aggregation**: Use aggregation pipelines for complex queries

### Scaling Strategies

1. **Sharding**: Consider sharding by `meta.tenantId`
2. **Read Replicas**: Use read replicas for query-heavy operations
3. **Caching**: Implement Redis caching for frequently accessed data
4. **Archive Strategy**: Archive old absences to separate collection

## Data Migration

### Schema Evolution

When schema changes are needed:

1. **Backward Compatible**: Add optional fields
2. **Migration Scripts**: Create scripts for data transformation
3. **Versioning**: Use `meta.version` for schema versioning
4. **Rollback**: Maintain rollback procedures

### Example Migration Script

```javascript
// Add new field to existing documents
db.absence.updateMany(
  { newField: { $exists: false } },
  { $set: { newField: defaultValue } }
);
```

## Backup and Recovery

### Backup Strategy

1. **Regular Snapshots**: Daily MongoDB snapshots
2. **Point-in-Time Recovery**: Enable oplog for PITR
3. **Cross-Region Replication**: For disaster recovery
4. **Testing**: Regular backup restoration testing

### Data Retention

1. **Active Data**: Keep in primary collection
2. **Archived Data**: Move to archive collection after retention period
3. **Deleted Data**: Hard delete after legal retention requirements

## Monitoring and Alerts

### Database Metrics

* Query performance
* Index usage statistics
* Document growth rate
* Connection pool utilization

### Alert Conditions

* Slow queries (>100ms)
* Index misses
* High memory usage
* Replication lag

## Security Considerations

### Data Protection

1. **Encryption at Rest**: Enable MongoDB encryption
2. **Encryption in Transit**: Use TLS for connections
3. **Field-Level Encryption**: For sensitive data
4. **Access Control**: Role-based database access

### Audit Trail

State history provides audit trail for:

* Who modified the absence
* When changes occurred
* What the previous state was
* Reason for changes


# Business Profile

## Overview

The Business Profile Management module is a comprehensive component of the Bee O'clock panel service that handles complete business information, settings, and configuration management. It provides a centralized system for businesses to manage their profile information, operational settings, media assets, and customer-facing configurations.

## Purpose

This module enables businesses to:

* **Manage Business Information**: Complete business details, descriptions, and featured content
* **Configure Operational Settings**: Booking, payment, notification, and business settings
* **Handle Media Assets**: Logo, banners, and gallery images with optimization
* **Control Public Presence**: Published profile visibility and public page settings
* **Manage Multiple Locations**: Address management with geospatial support
* **Configure Communication**: Contact information and social media integration
* **Set Operating Hours**: Regular and special schedule management
* **Customize User Experience**: Panel and public page customizations

## Key Features

### ✅ Comprehensive Profile Management

* **Business Information**: Name, description, features, and facilities
* **Contact Management**: Multiple contact types with primary designation
* **Address Management**: Multiple locations with geospatial coordinates
* **Social Integration**: Social media platform links and profiles

### ✅ Advanced Settings Configuration

* **Booking Settings**: Customer booking rules and automation
* **Business Settings**: Timezone, currency, language, and format preferences
* **Payment Settings**: Multiple payment gateway configurations
* **Notification Settings**: Communication preferences and templates
* **Panel Settings**: Administrative interface customization
* **Public Page Settings**: Customer-facing page configuration

### ✅ Professional Media Management

* **Business Logo**: Primary brand identifier with multiple sizes
* **Banner Images**: Promotional content with landscape optimization
* **Gallery Management**: Portfolio showcase with aspect ratio preservation
* **Automatic Optimization**: Image compression and thumbnail generation
* **CDN Integration**: Global delivery and performance optimization

### ✅ Flexible Schedule Management

* **Regular Schedules**: Daily operating hours with break periods
* **Special Schedules**: Holiday hours and special events
* **Timezone Support**: Multi-timezone business operations
* **Break Management**: Detailed break period configuration

### ✅ Multi-Settings Architecture

* **Hierarchical Configuration**: Organized settings by functional area
* **Validation Framework**: Comprehensive validation for all settings
* **Partial Updates**: Update specific settings without affecting others
* **Default Values**: Sensible defaults for new business profiles

### ✅ Advanced Data Management

* **Publication Control**: Manage profile visibility to customers
* **State Tracking**: Complete audit trail of all changes
* **Multi-tenant Security**: Complete tenant isolation and security
* **Reference Integrity**: Maintained relationships between profile and media

## Architecture

The module follows Clean Architecture principles with clear separation of concerns:

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   API Layer     │    │  Application    │    │   Domain        │
│                 │    │     Layer       │    │    Layer        │
│ • REST API      │───▶│ • Use Cases     │───▶│ • Entities      │
│ • Controllers   │    │ • Commands      │    │ • Value Objects │
│ • DTOs          │    │ • Queries       │    │ • Business Rules│
│ • File Upload   │    │ • Validators    │    │ • Settings      │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │
         ▼                       ▼                       ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│ Infrastructure  │    │   Integration   │    │  Persistence    │
│                 │    │                 │    │                 │
│ • Guards        │    │ • Media Service │    │ • MongoDB       │
│ • Decorators    │    │ • File Storage  │    │ • Repository    │
│ • Middleware    │    │ • CDN Service   │    │ • Schemas       │
│ • Validation    │    │ • Cache Service │    │ • Indexing      │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

## Technology Stack

* **Framework**: NestJS with TypeScript
* **Database**: MongoDB with Mongoose ODM
* **File Storage**: Cloud storage with CDN integration
* **Caching**: Redis for performance optimization
* **Image Processing**: Automatic compression and thumbnail generation
* **Architecture**: CQRS (Command Query Responsibility Segregation)
* **Patterns**: Repository, Domain-Driven Design, Value Objects

## Quick Start

### 1. API Usage

Start with the [API Documentation](/services/business-profile/api) to understand available endpoints and how to interact with the business profile management system.

### 2. Integration

Review the [Interface Documentation](/services/business-profile/interface) to understand data structures, DTOs, and integration points.

### 3. Business Logic

Explore the [Use Case Documentation](/services/business-profile/usecase) to understand business rules, settings management, and workflows.

### 4. Data Layer

Check the [Database Schema](/services/business-profile/db_schema) for persistence implementation and query optimization details.

## Documentation Structure

| Document                                                        | Purpose                                              | Audience                              |
| --------------------------------------------------------------- | ---------------------------------------------------- | ------------------------------------- |
| [API Documentation](/services/business-profile/api)             | REST API reference, endpoints, media upload          | Frontend developers, API consumers    |
| [Interface Documentation](/services/business-profile/interface) | TypeScript interfaces, DTOs, settings objects        | Backend developers, integration teams |
| [Use Case Documentation](/services/business-profile/usecase)    | Business logic, settings management, media workflows | Backend developers, business analysts |
| [Database Schema](/services/business-profile/db_schema)         | Data persistence, indexing, query optimization       | Backend developers, DevOps teams      |

## Business Rules Summary

### ⚠️ Critical Constraints

1. **Profile Uniqueness**: Each tenant has exactly one business profile
2. **Username Uniqueness**: Business usernames must be globally unique (when provided)
3. **Settings Validation**: All nested settings objects must pass validation
4. **Media Format Restrictions**: Only supported image formats allowed for media uploads
5. **Publication Control**: Only published profiles are visible to customers

### 🔒 Security Features

* Tenant-based data isolation
* Role-based permission system
* Secure media file handling
* Audit trail for all changes
* State history tracking

### 📊 Performance Features

* Redis caching with intelligent invalidation
* Optimized database indexes
* CDN integration for media delivery
* Image compression and optimization
* Geospatial indexing for location queries

## Settings Architecture

### Core Settings Categories

#### 🏢 **Business Settings**

* Timezone and locale configuration
* Currency and language preferences
* Date/time format settings
* Email communication language

#### 📅 **Booking Settings**

* Customer booking rules and automation
* Advance booking time limits
* Auto-confirmation settings
* Payment requirement configuration
* Mandatory customer information fields

#### 💳 **Payment Settings**

* Multiple payment gateway support (Stripe, PayPal, Square)
* Currency configuration and exchange rates
* Tax calculation settings
* Default and accepted payment methods

#### 🔔 **Notification Settings**

* Email notification preferences
* SMS notification configuration
* Push notification settings
* Reminder and escalation rules

#### 🎨 **Panel Settings**

* Administrative interface customization
* Color schemes and themes
* Language preferences
* Display format preferences

#### 🌐 **Public Page Settings**

* Customer-facing page configuration
* Booking widget settings
* Public information display
* SEO and meta information

## Media Management

### 📸 **Media Types**

#### Logo Management

* **Purpose**: Primary business brand identifier
* **Format**: Square format (200x200px recommended)
* **Limit**: Single logo per business
* **Features**: Automatic thumbnail generation, format optimization

#### Banner Management

* **Purpose**: Promotional and marketing content
* **Format**: Landscape format (1200x400px recommended)
* **Limit**: Multiple banners supported
* **Features**: Display ordering, automatic compression

#### Gallery Management

* **Purpose**: Portfolio and work showcase
* **Format**: Variable dimensions (aspect ratio preserved)
* **Limit**: Multiple images supported
* **Features**: Thumbnail generation, optimization, CDN delivery

### 🔧 **Media Features**

* Automatic image compression and optimization
* Multiple thumbnail size generation
* CDN integration for global delivery
* Format validation and conversion
* Orphaned media cleanup
* Secure URL generation

## Integration Points

### Upstream Dependencies

* **Identity Service**: User authentication and authorization
* **Media Service**: File upload and management
* **Permission Service**: Role and permission management
* **Cache Service**: Performance optimization

### Downstream Consumers

* **Client Applications**: Public profile information
* **Booking Service**: Settings and availability information
* **Payment Service**: Payment configuration
* **Notification Service**: Communication preferences
* **Analytics Service**: Business information and metrics

### External Integrations

* **Payment Gateways**: Stripe, PayPal, Square integration
* **Cloud Storage**: AWS S3, Google Cloud Storage
* **CDN Services**: CloudFront, CloudFlare
* **Geolocation Services**: Address validation and coordinates
* **Social Platforms**: Profile verification and integration

## Common Use Cases

### 👤 **Business Owner Scenarios**

* Set up complete business profile during onboarding
* Update business information and contact details
* Configure booking and payment settings
* Upload and manage media assets (logo, banners, gallery)
* Set operating hours and special schedules
* Configure notification preferences

### 🏢 **Multi-Location Business Scenarios**

* Manage multiple business addresses
* Configure location-specific settings
* Handle timezone differences across locations
* Coordinate schedules across multiple sites

### 🎨 **Branding and Marketing Scenarios**

* Upload professional logo and branding materials
* Create promotional banner campaigns
* Showcase work portfolio in gallery
* Optimize images for web performance
* Maintain consistent brand presentation

### ⚙️ **System Administrator Scenarios**

* Bulk profile management and updates
* Settings template creation and application
* Media storage management and cleanup
* Performance monitoring and optimization
* Backup and recovery operations

## Monitoring and Maintenance

### Key Metrics

* Profile completeness rates
* Media upload success rates
* Settings update frequency
* API response times
* Cache hit ratios
* Database query performance
* Media storage utilization

### Health Checks

* Database connectivity and performance
* Media service availability
* Cache service status
* CDN delivery performance
* Payment gateway connectivity
* File upload functionality

### Maintenance Tasks

* Orphaned media cleanup
* Cache optimization and cleanup
* Database index maintenance
* Media thumbnail regeneration
* Backup verification
* Performance optimization

## Future Enhancements

### Planned Features

* **Advanced SEO Management**: Meta tags, structured data, sitemap generation
* **Multi-Brand Support**: Multiple brand identities per business
* **Template System**: Pre-configured setting templates for different business types
* **Analytics Integration**: Business profile performance metrics
* **A/B Testing**: Profile configuration testing and optimization
* **API Rate Limiting**: Enhanced rate limiting and throttling
* **Automated Backups**: Scheduled profile and media backups

### Scalability Considerations

* Database sharding strategies for large-scale deployments
* Media storage optimization and archiving
* CDN optimization for global performance
* Cache partitioning and distribution
* Microservice decomposition for specific features
* Event sourcing for audit trail optimization

## Security Considerations

### Data Protection

* **Encryption**: All sensitive data encrypted at rest and in transit
* **Access Control**: Role-based access with principle of least privilege
* **Audit Logging**: Complete audit trail of all profile changes
* **Data Validation**: Comprehensive input validation and sanitization
* **File Security**: Secure file upload with content type validation

### Privacy Compliance

* **Data Minimization**: Store only necessary business information
* **Right to Deletion**: Support for complete profile deletion
* **Data Portability**: Export capabilities for business profile data
* **Consent Management**: Privacy preference management
* **GDPR Compliance**: European data protection regulation compliance

### Business Continuity

* **Disaster Recovery**: Automated backup and recovery procedures
* **High Availability**: Redundant systems and failover mechanisms
* **Data Integrity**: Consistency checks and validation
* **Performance Monitoring**: Real-time performance and availability monitoring

***

## Getting Help

For technical questions or issues:

1. Check this documentation first
2. Review the API examples and use cases
3. Consult the interface definitions for data structures
4. Examine the database schema for data-related questions
5. Check the settings validation rules for configuration issues

For business rule clarifications:

1. Review the use case documentation
2. Check the business rules summary above
3. Consult the settings architecture section
4. Contact the product team for policy questions

For media-related issues:

1. Check file format and size requirements
2. Review media management documentation
3. Verify CDN and storage configuration
4. Contact the infrastructure team for storage issues

***

*This documentation is maintained by the Bee O'clock development team and is updated with each release.*


# API Documentation

## Overview

The Business Profile Management API provides endpoints for managing business information, settings, and configuration within the Bee O'clock platform. This API allows businesses to create, update, and retrieve their complete business profile including basic information, media assets, settings configurations, and operational parameters.

## Base URL

```
/api/v1/business-profile
```

## Authentication

All endpoints require:

* **Bearer Token**: JWT authentication token
* **Business-Tenant-Id**: Header specifying the business tenant ID

## API Endpoints

### 1. Get Business Profile

**Endpoint:** `GET /`

**Description:** Retrieves the complete business profile for the authenticated tenant.

**Response:** `BusinessProfileDto`

**Permissions Required:** `READ_BUSINESS_PROFILE`

**Response Structure:**

```typescript
{
  _id: string;
  object: 'BusinessProfileDto';
  published: ActiveEnum;
  name: string;
  username?: string;
  description?: string;
  feature?: string;
  facilities?: FacilityEnum[];
  logo?: MediaDto;
  banners?: MediaDto[];
  gallery?: MediaDto[];
  addresses?: AddressDto[];
  contacts?: ContactDto[];
  schedules?: ScheduleDto[];
  specialSchedules?: SpecialScheduleDto[];
  socialNetworkLinks?: SocialNetworkLinkDto[];
  bookingSettings?: BookingSettingsClientDto;
  businessSettings?: BusinessSettingsDto;
  paymentSettings?: PaymentSettingsDto;
  panelSettings?: PanelSettingsDto;
  publicPageSettings?: PublicPageSettingsDto;
  notificationSettings?: NotificationSettingsDto;
  businessTariffPlanType?: BusinessTariffPlanType;
  createdAt?: string;
  updatedAt?: string;
}
```

***

### 2. Update Business Profile

**Endpoint:** `PUT /`

**Description:** Updates the complete business profile with the provided data.

**Request Body:** `BusinessProfileDto` (complete object)

**Response:** `BusinessProfileDto` (updated profile)

**Permissions Required:** `EDIT_BUSINESS_PROFILE`

**Validation Rules:**

* `name`: Required for business identification
* `published`: Must be ActiveEnum value (YES/NO)
* Nested objects must pass their respective validation rules
* Media references must exist in the system

***

### 3. Update Payment Settings

**Endpoint:** `PATCH /payment-settings`

**Description:** Updates only the payment settings portion of the business profile.

**Request Body:** `PaymentSettingsDto`

**Response:** `PaymentSettingsDto` (updated payment settings)

**Permissions Required:** `EDIT_BUSINESS_PROFILE`

**Payment Settings Structure:**

```typescript
{
  stripeSettings?: StripeSettingsDto;
  paypalSettings?: PaypalSettingsDto;
  squareSettings?: SquareSettingsDto;
  defaultPaymentMethod?: PaymentMethodEnum;
  acceptedPaymentMethods?: PaymentMethodEnum[];
  currencySettings?: CurrencySettingsDto;
  taxSettings?: TaxSettingsDto;
}
```

***

## Business Profile Media API

### Base URL for Media Operations

```
/api/v1/business-profile-media
```

### 4. Update Business Logo

**Endpoint:** `PATCH /logo`

**Description:** Updates the business logo image.

**Request:** Multipart form data with image file

**Response:** `void`

**Permissions Required:** `EDIT_BUSINESS_PROFILE`

**Content Type:** `multipart/form-data`

**File Requirements:**

* Supported formats: JPEG, PNG, WebP
* Maximum file size: 5MB
* Recommended dimensions: 200x200px (square)

***

### 5. Delete Business Logo

**Endpoint:** `DELETE /logo`

**Description:** Removes the current business logo.

**Response:** `void`

**Permissions Required:** `EDIT_BUSINESS_PROFILE`

***

### 6. Update Banner Item

**Endpoint:** `PATCH /banner/:bannerItemId`

**Description:** Updates a specific banner image.

**Path Parameters:**

* `bannerItemId` (string): The ID of the banner item to update

**Request:** Multipart form data with image file

**Response:** `void`

**Permissions Required:** `EDIT_BUSINESS_PROFILE`

**File Requirements:**

* Supported formats: JPEG, PNG, WebP
* Maximum file size: 10MB
* Recommended dimensions: 1200x400px (landscape)

***

### 7. Delete Banner Item

**Endpoint:** `DELETE /banner/:bannerItemId`

**Description:** Removes a specific banner image.

**Path Parameters:**

* `bannerItemId` (string): The ID of the banner item to delete

**Response:** `void`

**Permissions Required:** `EDIT_BUSINESS_PROFILE`

***

### 8. Update Gallery Item

**Endpoint:** `PATCH /gallery/:galleryItemId`

**Description:** Updates a specific gallery image.

**Path Parameters:**

* `galleryItemId` (string): The ID of the gallery item to update

**Request:** Multipart form data with image file

**Response:** `void`

**Permissions Required:** `EDIT_BUSINESS_PROFILE`

**File Requirements:**

* Supported formats: JPEG, PNG, WebP
* Maximum file size: 8MB
* Recommended dimensions: Variable (maintains aspect ratio)

***

### 9. Delete Gallery Item

**Endpoint:** `DELETE /gallery/:galleryItemId`

**Description:** Removes a specific gallery image.

**Path Parameters:**

* `galleryItemId` (string): The ID of the gallery item to delete

**Response:** `void`

**Permissions Required:** `EDIT_BUSINESS_PROFILE`

***

## Data Transfer Objects

### BusinessProfileDto

The main DTO containing all business profile information:

```typescript
{
  _id?: string;
  object?: 'BusinessProfileDto';
  published?: ActiveEnum;           // YES | NO
  name?: string;                   // Business name
  username?: string;               // Unique username/handle
  description?: string;            // Business description
  feature?: string;                // Featured information
  facilities?: FacilityEnum[];     // Business facilities
  logo?: MediaDto;                 // Logo image
  banners?: MediaDto[];           // Banner images
  gallery?: MediaDto[];           // Gallery images
  addresses?: AddressDto[];       // Business addresses
  contacts?: ContactDto[];        // Contact information
  schedules?: ScheduleDto[];      // Operating schedules
  specialSchedules?: SpecialScheduleDto[]; // Special schedules
  socialNetworkLinks?: SocialNetworkLinkDto[]; // Social media links
  bookingSettings?: BookingSettingsClientDto; // Booking configuration
  businessSettings?: BusinessSettingsDto;     // Business configuration
  paymentSettings?: PaymentSettingsDto;       // Payment configuration
  panelSettings?: PanelSettingsDto;          // Panel UI settings
  publicPageSettings?: PublicPageSettingsDto; // Public page settings
  notificationSettings?: NotificationSettingsDto; // Notification settings
  businessTariffPlanType?: BusinessTariffPlanType; // Subscription plan
  createdAt?: string;
  updatedAt?: string;
}
```

### Key Nested DTOs

#### AddressDto

```typescript
{
  _id?: string;
  street: string;
  city: string;
  state?: string;
  zipCode?: string;
  country: string;
  coordinates?: {
    latitude: number;
    longitude: number;
  };
  isPrimary?: boolean;
}
```

#### ContactDto

```typescript
{
  _id?: string;
  type: ContactTypeEnum;    // PHONE | EMAIL | WEBSITE
  value: string;
  label?: string;
  isPrimary?: boolean;
}
```

#### ScheduleDto

```typescript
{
  dayOfWeek: DayOfWeekEnum;
  isOpen: boolean;
  openTime?: string;        // HH:mm format
  closeTime?: string;       // HH:mm format
  breaks?: BreakDto[];
}
```

### ActiveEnum

```typescript
enum ActiveEnum {
  NO = 0,
  YES = 1
}
```

### FacilityEnum

```typescript
enum FacilityEnum {
  PARKING = 'PARKING',
  WIFI = 'WIFI',
  ACCESSIBILITY = 'ACCESSIBILITY',
  CARD_PAYMENT = 'CARD_PAYMENT',
  CASH_PAYMENT = 'CASH_PAYMENT',
  APPOINTMENT_ONLY = 'APPOINTMENT_ONLY',
  WALK_INS_WELCOME = 'WALK_INS_WELCOME'
}
```

## Error Responses

### Common HTTP Status Codes

* **400 Bad Request**: Invalid request data or validation errors
* **401 Unauthorized**: Missing or invalid authentication token
* **403 Forbidden**: Insufficient permissions
* **404 Not Found**: Business profile not found
* **413 Payload Too Large**: File upload exceeds size limits
* **415 Unsupported Media Type**: Invalid file format for media uploads
* **500 Internal Server Error**: Server-side processing error

### Error Response Format

```typescript
{
  statusCode: number;
  message: string | string[];
  error?: string;
}
```

## Permission System

The business profile management system uses a role-based permission system:

* **READ\_BUSINESS\_PROFILE**: View business profile information
* **EDIT\_BUSINESS\_PROFILE**: Modify business profile information

### Permission Enforcement

* All endpoints require appropriate permissions
* Media upload/delete operations require EDIT permissions
* Profile visibility is controlled by the `published` field

## Business Rules

### 📝 **Profile Validation**

1. **Name Requirement**: Business name is required for profile creation
2. **Publication Control**: Only published profiles are visible to clients
3. **Media Limits**: Maximum file sizes enforced for different media types
4. **Format Restrictions**: Only supported image formats allowed for media

### 🖼️ **Media Management**

1. **Logo Requirements**: Square format recommended, single logo per business
2. **Banner Specifications**: Landscape format for promotional banners
3. **Gallery Flexibility**: Multiple images with preserved aspect ratios
4. **Automatic Cleanup**: Orphaned media files are cleaned up periodically

### ⚙️ **Settings Hierarchy**

1. **Business Settings**: Core operational parameters
2. **Booking Settings**: Customer booking configuration
3. **Payment Settings**: Financial transaction setup
4. **Notification Settings**: Communication preferences
5. **Panel Settings**: Administrative interface customization

## Integration Points

* **Media Service**: File upload and management
* **Identity Service**: User authentication and authorization
* **Notification Service**: Settings synchronization
* **Payment Service**: Payment gateway configuration
* **Cache Service**: Performance optimization

## Rate Limiting

Standard API rate limiting applies to all endpoints:

* **GET requests**: 100 requests per minute
* **PUT/PATCH requests**: 20 requests per minute
* **Media uploads**: 10 requests per minute

## Examples

### Get Business Profile

```javascript
GET /api/v1/business-profile
Authorization: Bearer <jwt-token>
Business-Tenant-Id: <tenant-id>

Response:
{
  "_id": "64f7b1234567890abcdef123",
  "object": "BusinessProfileDto",
  "published": 1,
  "name": "Bella Vista Salon",
  "username": "bellavista",
  "description": "Premium hair and beauty services",
  "addresses": [
    {
      "street": "123 Main Street",
      "city": "New York",
      "state": "NY",
      "zipCode": "10001",
      "country": "USA",
      "isPrimary": true
    }
  ],
  "bookingSettings": {
    "autoBookOrder": true,
    "earliestBooking": 24,
    "latestBooking": 4320
  }
}
```

### Update Business Profile

```javascript
PUT /api/v1/business-profile
Authorization: Bearer <jwt-token>
Business-Tenant-Id: <tenant-id>
Content-Type: application/json

{
  "name": "Bella Vista Spa & Salon",
  "description": "Premium hair, beauty, and spa services",
  "facilities": ["PARKING", "WIFI", "CARD_PAYMENT"],
  "addresses": [
    {
      "street": "123 Main Street",
      "city": "New York", 
      "state": "NY",
      "zipCode": "10001",
      "country": "USA",
      "isPrimary": true
    }
  ]
}
```

### Update Payment Settings

```javascript
PATCH /api/v1/business-profile/payment-settings
Authorization: Bearer <jwt-token>
Business-Tenant-Id: <tenant-id>
Content-Type: application/json

{
  "defaultPaymentMethod": "STRIPE",
  "acceptedPaymentMethods": ["STRIPE", "PAYPAL", "CASH"],
  "stripeSettings": {
    "publishableKey": "pk_test_...",
    "webhookSecret": "whsec_..."
  }
}
```

### Upload Business Logo

```javascript
PATCH /api/v1/business-profile-media/logo
Authorization: Bearer <jwt-token>
Business-Tenant-Id: <tenant-id>
Content-Type: multipart/form-data

Form Data:
- file: [image file]
```


# Interface Documentation

## Overview

This document describes the interfaces, types, and contracts used in the Business Profile Management module. These interfaces define the structure of business data objects, repository contracts, service interfaces, and configuration objects used throughout the system.

## Core Interfaces

### IBusinessProfile

The main interface for business profile entities, extending the base entity interface.

```typescript
interface IBusinessProfile extends IBase {
  published: ActiveEnum;                      // Publication status
  name: string;                              // Business name
  username?: string;                         // Unique business username
  facilities?: FacilityEnum[];               // Available facilities
  socialNetworkLinks?: ISocialNetworkLink[]; // Social media links
  bookingSettings: IBookingSettings;         // Booking configuration
  businessSettings: IBusinessSettings;       // Business configuration
  notificationSettings?: INotificationSettings; // Notification preferences
  paymentSettings?: IPaymentSettings;        // Payment configuration
  panelSettings?: IPanelSettings;           // Panel UI settings
  publicPageSettings?: IPublicPageSettings; // Public page settings
  addresses?: IBusinessAddress[];           // Business addresses
  schedules?: ISchedule[];                  // Operating schedules
  specialSchedules?: ISpecialSchedule[];    // Special schedules
  contacts?: IContact[];                    // Contact information
  gallery?: IMedia[];                       // Gallery images
  logo?: IMedia;                           // Business logo
  banners?: IMedia[];                      // Banner images
  description?: string;                     // Business description
  feature?: string;                        // Featured information
}
```

### IBusinessProfileRepository

Repository interface defining data access operations for business profiles.

```typescript
interface IBusinessProfileRepository extends IBaseRepository<IBusinessProfile> {
  findByUsername(username: string): Promise<IBusinessProfile | null>;
  findByIdentifier(identifier: string): Promise<IBusinessProfile | null>;
  updateSettings<T>(tenantId: string, settings: T, settingsType: string): Promise<void>;
}
```

## Data Transfer Objects (DTOs)

### BusinessProfileDto

Main DTO for business profile data transfer between layers.

```typescript
class BusinessProfileDto extends BaseEntityDto {
  object?: 'BusinessProfileDto';
  published?: ActiveEnum;
  name?: string;
  username?: string;
  description?: string;
  feature?: string;
  facilities?: FacilityEnum[];
  logo?: MediaDto;
  banners?: MediaDto[];
  gallery?: MediaDto[];
  addresses?: AddressDto[];
  contacts?: ContactDto[];
  schedules?: ScheduleDto[];
  specialSchedules?: SpecialScheduleDto[];
  socialNetworkLinks?: SocialNetworkLinkDto[];
  bookingSettings?: BookingSettingsClientDto;
  businessSettings?: BusinessSettingsDto;
  paymentSettings?: PaymentSettingsDto;
  panelSettings?: PanelSettingsDto;
  publicPageSettings?: PublicPageSettingsDto;
  notificationSettings?: NotificationSettingsDto;
  businessTariffPlanType?: BusinessTariffPlanType;
}
```

**Validation Rules:**

* `name`: Optional string for business identification
* `published`: Optional ActiveEnum value (YES/NO)
* `username`: Optional unique identifier
* `facilities`: Optional array of FacilityEnum values
* All nested objects have their own validation requirements

### Business Settings DTOs

#### BusinessSettingsDto

```typescript
class BusinessSettingsDto {
  timeZone?: string;                    // IANA timezone identifier
  currencies?: CurrencyEnum[];          // Supported currencies
  baseCurrency?: CurrencyEnum;          // Primary currency
  languages?: LanguageCodeEnum[];       // Supported languages
  baseLanguage?: LanguageCodeEnum;      // Primary language
  emailLanguage?: LanguageCodeEnum;     // Email communication language
  availableLanguages?: LanguageCodeEnum[]; // Available interface languages
  dateFormat?: DateFormatEnum;          // Date display format
  timeFormat?: TimeFormatEnum;          // Time display format
}
```

#### BookingSettingsClientDto

```typescript
class BookingSettingsClientDto {
  autoActionSettings?: AutoActionSettingsDto;
  earliestBooking?: number;             // Hours in advance
  latestBooking?: number;               // Hours in advance (max)
  slotSettings?: SlotSettingsDto;
  autoBookOrder?: boolean;              // Auto-confirm bookings
  paymentRequirement?: PaymentRequirementEnum;
  mandatoryAttendeeProperties?: AttendeePropertyEnum[];
}
```

#### PaymentSettingsDto

```typescript
class PaymentSettingsDto {
  stripeSettings?: StripeSettingsDto;
  paypalSettings?: PaypalSettingsDto;
  squareSettings?: SquareSettingsDto;
  defaultPaymentMethod?: PaymentMethodEnum;
  acceptedPaymentMethods?: PaymentMethodEnum[];
  currencySettings?: CurrencySettingsDto;
  taxSettings?: TaxSettingsDto;
}
```

### Location and Contact DTOs

#### AddressDto

```typescript
class AddressDto {
  _id?: string;
  street: string;
  city: string;
  state?: string;
  zipCode?: string;
  country: string;
  coordinates?: {
    latitude: number;
    longitude: number;
  };
  isPrimary?: boolean;
}
```

#### ContactDto

```typescript
class ContactDto {
  _id?: string;
  type: ContactTypeEnum;        // PHONE | EMAIL | WEBSITE | FAX
  value: string;
  label?: string;
  isPrimary?: boolean;
  isPublic?: boolean;
}
```

#### SocialNetworkLinkDto

```typescript
class SocialNetworkLinkDto {
  _id?: string;
  platform: SocialPlatformEnum; // FACEBOOK | INSTAGRAM | TWITTER | LINKEDIN
  url: string;
  username?: string;
  isActive?: boolean;
}
```

### Schedule DTOs

#### ScheduleDto

```typescript
class ScheduleDto {
  _id?: string;
  dayOfWeek: DayOfWeekEnum;     // MONDAY | TUESDAY | ... | SUNDAY
  isOpen: boolean;
  openTime?: string;            // HH:mm format
  closeTime?: string;           // HH:mm format
  breaks?: BreakDto[];
  timeZone?: string;
}
```

#### SpecialScheduleDto

```typescript
class SpecialScheduleDto {
  _id?: string;
  date: string;                 // YYYY-MM-DD format
  type: SpecialScheduleTypeEnum; // HOLIDAY | CLOSURE | EXTENDED_HOURS
  isOpen: boolean;
  openTime?: string;
  closeTime?: string;
  description?: string;
  isRecurring?: boolean;
  recurrencePattern?: RecurrencePatternDto;
}
```

## Enumerations

### ActiveEnum

```typescript
enum ActiveEnum {
  NO = 0,
  YES = 1
}
```

### FacilityEnum

```typescript
enum FacilityEnum {
  PARKING = 'PARKING',
  WIFI = 'WIFI',
  ACCESSIBILITY = 'ACCESSIBILITY',
  CARD_PAYMENT = 'CARD_PAYMENT',
  CASH_PAYMENT = 'CASH_PAYMENT',
  APPOINTMENT_ONLY = 'APPOINTMENT_ONLY',
  WALK_INS_WELCOME = 'WALK_INS_WELCOME',
  AIR_CONDITIONING = 'AIR_CONDITIONING',
  WAITING_AREA = 'WAITING_AREA',
  ONLINE_BOOKING = 'ONLINE_BOOKING'
}
```

### ContactTypeEnum

```typescript
enum ContactTypeEnum {
  PHONE = 'PHONE',
  EMAIL = 'EMAIL',
  WEBSITE = 'WEBSITE',
  FAX = 'FAX',
  MOBILE = 'MOBILE'
}
```

### SocialPlatformEnum

```typescript
enum SocialPlatformEnum {
  FACEBOOK = 'FACEBOOK',
  INSTAGRAM = 'INSTAGRAM',
  TWITTER = 'TWITTER',
  LINKEDIN = 'LINKEDIN',
  YOUTUBE = 'YOUTUBE',
  TIKTOK = 'TIKTOK'
}
```

## Use Case Interfaces

### GetBusinessProfileParams

```typescript
interface GetBusinessProfileParams {
  ctx: TenantActorContext;
}
```

### UpdateBusinessProfileParams

```typescript
interface UpdateBusinessProfileParams {
  ctx: TenantActorContext;
  profile: BusinessProfileDto;
}
```

### UpdateBusinessPaymentSettingsParams

```typescript
interface UpdateBusinessPaymentSettingsParams {
  ctx: TenantActorContext;
  settings: PaymentSettingsDto;
}
```

### Media Management Use Case Interfaces

#### UpdateClientLogoParams

```typescript
interface UpdateClientLogoParams {
  ctx: TenantActorContext;
  file: Express.Multer.File;
}
```

#### DeleteClientLogoParams

```typescript
interface DeleteClientLogoParams {
  ctx: TenantActorContext;
}
```

#### UpdateClientBannerParams

```typescript
interface UpdateClientBannerParams {
  ctx: TenantActorContext;
  bannerItemId: string;
  file: Express.Multer.File;
}
```

#### UpdateClientGalleryParams

```typescript
interface UpdateClientGalleryParams {
  ctx: TenantActorContext;
  galleryItemId: string;
  file: Express.Multer.File;
}
```

## Value Objects Interfaces

### IBookingSettings

```typescript
interface IBookingSettings {
  autoActionSettings?: IAutoActionSettings;
  earliestBooking?: number;
  latestBooking?: number;
  slotSettings?: ISlotSettings;
  autoBookOrder?: boolean;
  paymentRequirement?: PaymentRequirementEnum;
  mandatoryAttendeeProperties?: AttendeePropertyEnum[];
}
```

### IBusinessSettings

```typescript
interface IBusinessSettings {
  timeZone?: string;
  currencies?: CurrencyEnum[];
  baseCurrency?: CurrencyEnum;
  languages?: LanguageCodeEnum[];
  baseLanguage?: LanguageCodeEnum;
  emailLanguage?: LanguageCodeEnum;
  availableLanguages?: LanguageCodeEnum[];
  dateFormat?: DateFormatEnum;
  timeFormat?: TimeFormatEnum;
}
```

### IPaymentSettings

```typescript
interface IPaymentSettings {
  stripeSettings?: IStripeSettings;
  paypalSettings?: IPaypalSettings;
  squareSettings?: ISquareSettings;
  defaultPaymentMethod?: PaymentMethodEnum;
  acceptedPaymentMethods?: PaymentMethodEnum[];
  currencySettings?: ICurrencySettings;
  taxSettings?: ITaxSettings;
}
```

### IPanelSettings

```typescript
interface IPanelSettings {
  orderServiceColorMode: OrderServiceColorModeEnum;
  theme?: ThemeEnum;
  language?: LanguageCodeEnum;
  timezone?: string;
  dateFormat?: DateFormatEnum;
  timeFormat?: TimeFormatEnum;
}
```

### INotificationSettings

```typescript
interface INotificationSettings {
  reminderSettings?: IReminderSettings;
  smsNotificationSettings?: ISmsNotificationSettings;
  emailNotificationSettings?: IEmailNotificationSettings;
  pushNotificationSettings?: IPushNotificationSettings;
}
```

## Command and Query Interfaces

### Commands

#### CreateBusinessProfileCommand

```typescript
class CreateBusinessProfileCommand implements ITenantAware {
  constructor(
    public readonly tenantId: string,
    public readonly params: IBusinessProfile
  ) {}
}
```

#### UpdateBusinessProfileCommand

```typescript
class UpdateBusinessProfileCommand implements ITenantAware {
  constructor(
    public readonly tenantId: string,
    public readonly profile: BusinessProfileDto
  ) {}
}
```

#### UpdateBusinessPaymentSettingsCommand

```typescript
class UpdateBusinessPaymentSettingsCommand implements ITenantAware {
  constructor(
    public readonly tenantId: string,
    public readonly settings: PaymentSettingsDto
  ) {}
}
```

#### Media Management Commands

**UpsertClientLogoCommand**

```typescript
class UpsertClientLogoCommand implements ITenantAware {
  constructor(
    public readonly tenantId: string,
    public readonly mediaId: string
  ) {}
}
```

**DeleteClientLogoCommand**

```typescript
class DeleteClientLogoCommand implements ITenantAware {
  constructor(
    public readonly tenantId: string
  ) {}
}
```

### Queries

#### GetBusinessProfileQuery

```typescript
class GetBusinessProfileQuery implements ITenantAware {
  constructor(
    public readonly tenantId: string
  ) {}
}
```

#### GetBusinessProfileByIdentifierQuery

```typescript
class GetBusinessProfileByIdentifierQuery implements ITenantAware {
  constructor(
    public readonly tenantId: string
  ) {}
}
```

#### GetBusinessSettingsQuery

```typescript
class GetBusinessSettingsQuery implements ITenantAware {
  constructor(
    public readonly tenantId: string
  ) {}
}
```

#### GetBusinessBookingSettingsQuery

```typescript
class GetBusinessBookingSettingsQuery implements ITenantAware {
  constructor(
    public readonly tenantId: string
  ) {}
}
```

## Cache Interfaces

### BusinessCacheKeys

```typescript
enum BusinessCacheKeys {
  GET_BUSINESS_PROFILE = 'GET_BUSINESS_PROFILE',
  GET_BUSINESS_SETTINGS = 'GET_BUSINESS_SETTINGS',
  GET_BUSINESS_BOOKING_SETTINGS = 'GET_BUSINESS_BOOKING_SETTINGS',
  GET_CLIENT_LOGO = 'GET_CLIENT_LOGO',
  GET_CLIENT_BANNERS = 'GET_CLIENT_BANNERS',
  GET_CLIENT_GALLERY = 'GET_CLIENT_GALLERY'
}
```

## Media Management Interfaces

### IMedia

```typescript
interface IMedia {
  _id: string;
  filename: string;
  originalName: string;
  mimeType: string;
  size: number;
  url: string;
  thumbnailUrl?: string;
  alt?: string;
  title?: string;
  description?: string;
  uploadedAt: Date;
  uploadedBy: string;
}
```

### MediaDto

```typescript
class MediaDto {
  _id?: string;
  filename?: string;
  originalName?: string;
  mimeType?: string;
  size?: number;
  url?: string;
  thumbnailUrl?: string;
  alt?: string;
  title?: string;
  description?: string;
  uploadedAt?: Date;
  uploadedBy?: string;
}
```

## Validation Interfaces

### ValidationResult

```typescript
class ValidationResult {
  private constructor(
    public readonly isSuccess: boolean,
    public readonly error?: string
  ) {}

  static ok(): ValidationResult;
  static fail(error: string): ValidationResult;
  isFailureResult(): boolean;
  errorValue(): string;
}
```

### Business Rule Validation Interfaces

#### IBusinessAddressValidation

```typescript
interface IBusinessAddressValidation {
  validateStreet(street: string): ValidationResult;
  validateCity(city: string): ValidationResult;
  validateCountry(country: string): ValidationResult;
  validateCoordinates(lat: number, lng: number): ValidationResult;
}
```

#### IContactValidation

```typescript
interface IContactValidation {
  validateEmail(email: string): ValidationResult;
  validatePhone(phone: string): ValidationResult;
  validateWebsite(url: string): ValidationResult;
}
```

#### ISocialNetworkLinkValidation

```typescript
interface ISocialNetworkLinkValidation {
  validatePlatform(platform: SocialPlatformEnum): ValidationResult;
  validateUrl(url: string, platform: SocialPlatformEnum): ValidationResult;
  validateUsername(username: string): ValidationResult;
}
```

## Context Interfaces

### TenantActorContext

```typescript
interface TenantActorContext {
  tenantId: string;
  actor: {
    issuerId: string;
    type: ActorTypeEnum;
    permissions: string[];
    scope: PermissionScopeEnum;
  };
  requestId?: string;
  timestamp: Date;
}
```

## Service Integration Interfaces

### IMediaService

```typescript
interface IMediaService {
  uploadImage(file: Express.Multer.File, options: UploadOptions): Promise<IMedia>;
  deleteImage(mediaId: string): Promise<void>;
  generateThumbnail(mediaId: string, dimensions: ThumbnailDimensions): Promise<string>;
}
```

### INotificationService

```typescript
interface INotificationService {
  sendBusinessProfileUpdate(profile: BusinessProfileDto): Promise<void>;
  sendSettingsChange(tenantId: string, settingsType: string): Promise<void>;
}
```

### IPaymentGatewayService

```typescript
interface IPaymentGatewayService {
  validateStripeSettings(settings: IStripeSettings): Promise<ValidationResult>;
  validatePaypalSettings(settings: IPaypalSettings): Promise<ValidationResult>;
  testConnection(settings: any, provider: PaymentMethodEnum): Promise<boolean>;
}
```

## Error Interfaces

### BusinessProfileException

```typescript
class BusinessProfileException extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly details?: any
  ) {
    super(message);
  }
}
```

### BusinessProfileErrorCodes

```typescript
enum BusinessProfileErrorCodes {
  PROFILE_NOT_FOUND = 'PROFILE_NOT_FOUND',
  INVALID_SETTINGS = 'INVALID_SETTINGS',
  USERNAME_TAKEN = 'USERNAME_TAKEN',
  MEDIA_UPLOAD_FAILED = 'MEDIA_UPLOAD_FAILED',
  INVALID_PAYMENT_SETTINGS = 'INVALID_PAYMENT_SETTINGS',
  SETTINGS_VALIDATION_FAILED = 'SETTINGS_VALIDATION_FAILED'
}
```

## Module Configuration Interfaces

### BusinessProfileModuleConfig

```typescript
interface BusinessProfileModuleConfig {
  mediaUploadLimits: {
    logoMaxSize: number;
    bannerMaxSize: number;
    galleryMaxSize: number;
  };
  supportedImageFormats: string[];
  cacheSettings: {
    profileTtl: number;
    settingsTtl: number;
  };
  validationRules: {
    requireName: boolean;
    requireAddress: boolean;
    maxSocialLinks: number;
  };
}
```

## Usage Guidelines

1. **DTO Validation**: Always validate DTOs using class-validator decorators
2. **Type Safety**: Use TypeScript interfaces to ensure type safety across layers
3. **Nested Validation**: Validate nested objects using their respective validation rules
4. **Media Handling**: Use proper interfaces for file upload and management
5. **Settings Management**: Separate concerns for different settings types
6. **Cache Management**: Use enum-defined cache keys for consistency
7. **Error Handling**: Implement domain-specific exceptions for business rules
8. **Context Propagation**: Always pass TenantActorContext for proper authorization

## Interface Evolution

When modifying interfaces:

1. Consider backward compatibility for existing clients
2. Use optional properties for new fields
3. Update validation rules accordingly
4. Document breaking changes
5. Version the API if necessary
6. Update corresponding DTOs and mappers
7. Consider impact on cache invalidation
8. Update media handling if related to file operations


# Use Case Documentation

## Overview

This document describes the business use cases and application layer logic for the Business Profile Management module. Each use case encapsulates business rules, permissions, and orchestrates the interaction between domain entities, repositories, media services, and external integrations.

## Architecture Pattern

The module follows the CQRS (Command Query Responsibility Segregation) pattern with the following structure:

* **Use Cases**: Application layer orchestrating business logic
* **Commands**: Write operations (Create, Update, Media Operations)
* **Queries**: Read operations (Get Profile, Get Settings)
* **Domain Entities**: Business logic and validation
* **Value Objects**: Settings and configuration objects
* **Media Management**: File upload and storage operations

## Core Use Cases

### 1. GetBusinessProfileUseCase

**Purpose:** Retrieves the complete business profile for the authenticated tenant.

**Input:** `GetBusinessProfileParams`

```typescript
{
  ctx: TenantActorContext
}
```

**Output:** `BusinessProfileDto`

**Business Rules:**

1. User must have `READ_BUSINESS_PROFILE` permission
2. Returns null if profile not found or access denied
3. Profile includes all related media assets
4. Populates nested settings objects

**Process Flow:**

1. Validate user permissions using `PermissionValidatorUseCase`
2. Execute `GetBusinessProfileByIdentifierQuery` via query bus
3. Transform persistence model to DTO
4. Return complete profile with all nested objects

**Permission Matrix:**

* **Any scope**: Can read business profile they have access to
* Tenant isolation enforced at query level

**Error Scenarios:**

* Insufficient permissions → Returns `null` with warning log
* Profile not found → Returns `null`
* Database errors → Logged and re-thrown

**Caching:** Results are cached using `BusinessCacheKeys.GET_BUSINESS_PROFILE`

***

### 2. UpdateBusinessProfileUseCase

**Purpose:** Updates the complete business profile with comprehensive validation.

**Input:** `UpdateBusinessProfileParams`

```typescript
{
  ctx: TenantActorContext,
  profile: BusinessProfileDto
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_BUSINESS_PROFILE` permission
2. Validates all nested settings objects
3. Preserves existing media references if not provided
4. Updates only provided fields (partial updates supported)
5. Validates business name if provided
6. Validates addresses, contacts, and schedules

**Process Flow:**

1. Validate user permissions
2. Execute `UpdateBusinessProfileCommand` via command bus
3. Command handler validates domain rules
4. Transform DTO to domain entity
5. Validate nested value objects (BookingSettings, BusinessSettings, etc.)
6. Persist changes to database
7. Clear relevant cache entries

**Domain Validation Rules:**

```typescript
// Core validation in BusinessProfile.create()
if (!props.name) {
  validationErrors.push('Name is required.');
}

BusinessProfile.validateBusinessSettings(props.businessSettings, validationErrors);
BusinessProfile.validateBookingSettings(props.bookingSettings, validationErrors);
BusinessProfile.validateSchedules(props.schedules, validationErrors);
BusinessProfile.validateContacts(props.contacts, validationErrors);
BusinessProfile.validateSocialNetworkLinks(props.socialNetworkLinks, validationErrors);
BusinessProfile.validateAddresses(props.addresses, validationErrors);
```

**Cache Invalidation:** Clears `BusinessCacheKeys.GET_BUSINESS_PROFILE`

***

### 3. UpdateBusinessPaymentSettingsUseCase

**Purpose:** Updates only the payment settings portion of the business profile.

**Input:** `UpdateBusinessPaymentSettingsParams`

```typescript
{
  ctx: TenantActorContext,
  settings: PaymentSettingsDto
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_BUSINESS_PROFILE` permission
2. Validates payment gateway configurations
3. Tests payment gateway connections if credentials provided
4. Supports multiple payment providers (Stripe, PayPal, Square)
5. Validates currency settings and tax configurations

**Process Flow:**

1. Validate user permissions
2. Execute `UpdateBusinessPaymentSettingsCommand`
3. Validate payment provider settings
4. Test gateway connections (optional)
5. Update payment settings in profile
6. Clear relevant caches

**Payment Gateway Validation:**

* **Stripe**: Validates API keys and webhook secrets
* **PayPal**: Validates client ID and secret
* **Square**: Validates application ID and access token

**Error Scenarios:**

* Invalid payment credentials → `PaymentSettingsValidationException`
* Gateway connection test failure → Warning logged, settings saved
* Unsupported currency → `InvalidCurrencyException`

***

## Media Management Use Cases

### 4. UpdateClientLogoUseCase

**Purpose:** Uploads and sets a new business logo image.

**Input:** `UpdateClientLogoParams`

```typescript
{
  ctx: TenantActorContext,
  file: Express.Multer.File
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_BUSINESS_PROFILE` permission
2. File must be valid image format (JPEG, PNG, WebP)
3. File size must not exceed configured limits (5MB)
4. Deletes existing logo if present
5. Generates thumbnails automatically
6. Updates business profile with new media reference

**Process Flow:**

1. Validate user permissions
2. Validate file format and size
3. Upload file to media service
4. Generate thumbnail variants
5. Execute `UpsertClientLogoCommand`
6. Delete previous logo media
7. Update business profile reference
8. Clear media and profile caches

**File Validation:**

```typescript
// Supported formats
const supportedFormats = ['image/jpeg', 'image/png', 'image/webp'];

// Size limits
const maxLogoSize = 5 * 1024 * 1024; // 5MB

// Recommended dimensions
const recommendedDimensions = { width: 200, height: 200 };
```

***

### 5. DeleteClientLogoUseCase

**Purpose:** Removes the current business logo.

**Input:** `DeleteClientLogoParams`

```typescript
{
  ctx: TenantActorContext
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_BUSINESS_PROFILE` permission
2. Removes logo reference from business profile
3. Deletes media files from storage
4. Maintains audit trail of deletion

**Process Flow:**

1. Validate user permissions
2. Get current business profile
3. Execute `DeleteClientLogoCommand`
4. Remove media files from storage
5. Update business profile (remove logo reference)
6. Clear relevant caches

***

### 6. UpdateClientBannerUseCase

**Purpose:** Uploads and updates a specific banner image.

**Input:** `UpdateClientBannerParams`

```typescript
{
  ctx: TenantActorContext,
  bannerItemId: string,
  file: Express.Multer.File
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_BUSINESS_PROFILE` permission
2. File must be valid image format
3. File size must not exceed banner limits (10MB)
4. Supports multiple banners per business
5. Banner dimensions optimized for promotional display

**Process Flow:**

1. Validate user permissions
2. Validate file and banner item ID
3. Upload new banner image
4. Execute `UpsertClientBannerItemCommand`
5. Update banner in business profile
6. Clear relevant caches

**Banner Specifications:**

* **Recommended dimensions**: 1200x400px (landscape)
* **Maximum file size**: 10MB
* **Supported formats**: JPEG, PNG, WebP
* **Use cases**: Promotional content, service showcases

***

### 7. UpdateClientGalleryUseCase

**Purpose:** Uploads and updates a specific gallery image.

**Input:** `UpdateClientGalleryParams`

```typescript
{
  ctx: TenantActorContext,
  galleryItemId: string,
  file: Express.Multer.File
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_BUSINESS_PROFILE` permission
2. Supports various image dimensions
3. File size limit of 8MB
4. Gallery images showcase business work
5. Maintains original aspect ratios

**Process Flow:**

1. Validate user permissions
2. Validate file and gallery item ID
3. Upload new gallery image
4. Generate multiple thumbnail sizes
5. Execute `UpsertClientGalleryItemCommand`
6. Update gallery in business profile
7. Clear relevant caches

***

### 8. DeleteClientBannerItemUseCase

**Purpose:** Removes a specific banner image from the business profile.

**Input:** `DeleteClientBannerItemParams`

```typescript
{
  ctx: TenantActorContext,
  bannerItemId: string
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_BUSINESS_PROFILE` permission
2. Banner item must exist in the business profile
3. Removes both file and reference
4. Maintains banner ordering after deletion

**Process Flow:**

1. Validate user permissions
2. Verify banner item exists
3. Execute `DeleteClientBannerItemCommand`
4. Remove media files from storage
5. Update business profile (remove banner reference)
6. Clear relevant caches

***

### 9. DeleteClientGalleryItemUseCase

**Purpose:** Removes a specific gallery image from the business profile.

**Input:** `DeleteClientGalleryItemParams`

```typescript
{
  ctx: TenantActorContext,
  galleryItemId: string
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_BUSINESS_PROFILE` permission
2. Gallery item must exist in the business profile
3. Removes both file and reference
4. Maintains gallery organization after deletion

**Process Flow:**

1. Validate user permissions
2. Verify gallery item exists
3. Execute `DeleteClientGalleryItemCommand`
4. Remove media files from storage
5. Update business profile (remove gallery reference)
6. Clear relevant caches

***

## Customer-Facing Use Cases

### 10. GetPublicBusinessProfileUseCase

**Purpose:** Retrieves public business profile information for customers browsing or booking services.

**Input:** `GetPublicBusinessProfileParams`

```typescript
{
  businessUsername?: string,
  businessId?: string,
  includeSchedules?: boolean,
  includeGallery?: boolean
}
```

**Output:** `PublicBusinessProfileDto`

**Business Rules:**

1. No authentication required (public endpoint)
2. Only returns published business profiles
3. Filters sensitive internal information
4. Includes customer-relevant information only
5. Respects privacy settings configured by business
6. Returns operating hours and contact information
7. Includes public media assets (logo, banners, gallery)

**Process Flow:**

1. Identify business by username or ID
2. Execute `GetPublicBusinessProfileQuery`
3. Verify profile is published and active
4. Filter sensitive business information
5. Include only customer-facing data
6. Transform to public DTO format
7. Apply privacy settings filter
8. Return sanitized profile data

**Public Data Included:**

* Business name and description
* Public contact information
* Business addresses and locations
* Operating hours and schedules
* Public media assets (logo, banners, gallery)
* Published services and features
* Public social media links
* Customer booking settings

**Excluded Data:**

* Internal business settings
* Payment gateway configurations
* Administrative panel settings
* Internal notification settings
* Private contact information
* Financial information
* Analytics data

**Caching:** Results cached using `PublicBusinessCacheKeys.GET_PUBLIC_PROFILE`

***

### 11. GetBusinessAvailabilityInfoUseCase

**Purpose:** Retrieves business availability information for customer booking interface.

**Input:** `GetBusinessAvailabilityInfoParams`

```typescript
{
  businessId: string,
  timezone?: string,
  dateRange?: {
    startDate: Date,
    endDate: Date
  }
}
```

**Output:** `BusinessAvailabilityDto`

**Business Rules:**

1. No authentication required (public endpoint)
2. Returns current operating status
3. Includes regular and special schedules
4. Considers business timezone settings
5. Shows next available booking times
6. Respects booking advance time limits
7. Considers booking settings and rules

**Process Flow:**

1. Validate business ID and date range
2. Execute `GetBusinessAvailabilityQuery`
3. Calculate current operating status
4. Process regular and special schedules
5. Apply booking time restrictions
6. Calculate next available slots
7. Transform to availability DTO
8. Apply customer timezone conversion

**Availability Information:**

* Current operating status (open/closed)
* Today's operating hours
* Weekly schedule summary
* Special hours and holidays
* Next available booking time
* Booking advance time limits
* Break periods and unavailable times

***

### 12. GetBusinessContactInfoUseCase

**Purpose:** Retrieves public contact information for customer communication.

**Input:** `GetBusinessContactInfoParams`

```typescript
{
  businessId: string
}
```

**Output:** `BusinessContactInfoDto`

**Business Rules:**

1. No authentication required (public endpoint)
2. Returns only public contact information
3. Respects privacy settings
4. Includes preferred contact methods
5. Shows business addresses and locations
6. Includes social media links

**Process Flow:**

1. Validate business ID
2. Execute `GetBusinessContactInfoQuery`
3. Filter for public contact information
4. Apply privacy settings
5. Include location and address data
6. Transform to contact DTO format

**Contact Information Included:**

* Public phone numbers
* Public email addresses
* Business addresses with maps integration
* Website and social media links
* Preferred contact methods
* Business hours for contact

***

### 13. GetBusinessMediaGalleryUseCase

**Purpose:** Retrieves business media gallery for customer viewing.

**Input:** `GetBusinessMediaGalleryParams`

```typescript
{
  businessId: string,
  includeMetadata?: boolean,
  thumbnailSize?: 'small' | 'medium' | 'large'
}
```

**Output:** `BusinessMediaGalleryDto`

**Business Rules:**

1. No authentication required (public endpoint)
2. Returns published media only
3. Includes optimized images for web display
4. Supports multiple thumbnail sizes
5. Maintains image aspect ratios
6. Includes alt text for accessibility

**Process Flow:**

1. Validate business ID and parameters
2. Execute `GetBusinessMediaGalleryQuery`
3. Filter for published media assets
4. Generate appropriate thumbnail URLs
5. Include metadata if requested
6. Transform to media gallery DTO

**Media Assets Included:**

* Business logo with multiple sizes
* Published banner images
* Gallery images with thumbnails
* Optimized URLs for different screen sizes
* Alt text and descriptions
* Image metadata (if requested)

***

### 14. SearchPublicBusinessProfilesUseCase

**Purpose:** Allows customers to search for businesses by various criteria.

**Input:** `SearchPublicBusinessProfilesParams`

```typescript
{
  searchQuery?: string,
  location?: {
    latitude: number,
    longitude: number,
    radiusKm: number
  },
  businessType?: string,
  services?: string[],
  openNow?: boolean,
  sortBy?: 'distance' | 'name' | 'rating',
  pagination?: {
    page: number,
    limit: number
  }
}
```

**Output:** `SearchBusinessProfilesResultDto`

**Business Rules:**

1. No authentication required (public endpoint)
2. Only searches published business profiles
3. Supports location-based search with radius
4. Filters by business type and services
5. Can filter for currently open businesses
6. Supports pagination for large result sets
7. Includes distance calculation for location searches

**Process Flow:**

1. Validate search parameters
2. Execute `SearchPublicBusinessProfilesQuery`
3. Apply published profile filter
4. Process location-based filtering
5. Apply business type and service filters
6. Filter for operating hours if requested
7. Sort results by specified criteria
8. Apply pagination
9. Transform to search results DTO

**Search Capabilities:**

* Text search across business names and descriptions
* Geographic search with radius filtering
* Business type and category filtering
* Service-based filtering
* Operating hours filtering
* Distance-based sorting
* Relevance-based result ranking

***

### 15. GetBusinessBookingSettingsUseCase

**Purpose:** Retrieves customer-relevant booking settings for the booking interface.

**Input:** `GetBusinessBookingSettingsParams`

```typescript
{
  businessId: string
}
```

**Output:** `CustomerBookingSettingsDto`

**Business Rules:**

1. No authentication required (public endpoint)
2. Returns customer-facing booking settings only
3. Excludes internal business configuration
4. Includes booking rules and restrictions
5. Shows payment requirements
6. Includes mandatory customer information fields

**Process Flow:**

1. Validate business ID
2. Execute `GetBusinessBookingSettingsQuery`
3. Filter for customer-relevant settings
4. Exclude internal configuration
5. Transform to customer booking settings DTO

**Customer Booking Settings:**

* Advance booking time limits
* Payment requirements and methods
* Mandatory customer information fields
* Booking confirmation settings
* Cancellation policies
* Special booking rules and restrictions

***

### 16. ValidateBusinessAccessUseCase

**Purpose:** Validates customer access to business profile and services.

**Input:** `ValidateBusinessAccessParams`

```typescript
{
  businessId: string,
  customerContext?: CustomerContext
}
```

**Output:** `BusinessAccessValidationDto`

**Business Rules:**

1. No authentication required (public endpoint)
2. Validates business profile is published and active
3. Checks for any access restrictions
4. Validates business operating status
5. Considers geographic restrictions if applicable

**Process Flow:**

1. Validate business ID
2. Execute `ValidateBusinessAccessQuery`
3. Check business publication status
4. Verify business is active
5. Check for access restrictions
6. Validate geographic limitations
7. Transform to access validation DTO

**Access Validation:**

* Business profile published status
* Business active/inactive status
* Geographic access restrictions
* Operating hours validation
* Service availability status
* Customer eligibility checks

***

## Command Handlers

### CreateBusinessProfileHandler

**Responsibilities:**

1. Domain entity creation and validation
2. Settings object validation (BookingSettings, BusinessSettings)
3. Database persistence with tenant ID
4. Cache invalidation

**Key Operations:**

```typescript
// Create and validate booking settings
const bookingSettingsOrError = BookingSettings.create(bookingSettings);
const businessSettingsOrError = BusinessSettings.create(businessSettings);

// Create domain entity with validation
const businessProfileDomain = BusinessProfile.create({
  ...command.params,
  bookingSettings: BookingSettingsMap.toPersistence(bookingSettingsOrError.getValue()),
  businessSettings: BusinessSettingsMap.toPersistence(businessSettingsOrError.getValue())
});

// Persist to database
await this.sharedUnitOfWork.businessProfile.createItemWithId(
  BusinessProfileMap.toPersistence(businessProfileDomain.getValue())
);
```

### UpdateBusinessProfileHandler

**Responsibilities:**

1. Profile validation and transformation
2. Nested settings validation
3. Partial update handling
4. Cache invalidation

### UpdateBusinessPaymentSettingsHandler

**Responsibilities:**

1. Payment settings validation
2. Gateway configuration testing
3. Selective payment settings update
4. Financial compliance validation

### Media Command Handlers

#### UpsertClientLogoHandler

**Responsibilities:**

1. Media reference management
2. Previous logo cleanup
3. Profile reference update
4. Cache invalidation

#### DeleteClientLogoHandler

**Responsibilities:**

1. Media file deletion
2. Profile reference removal
3. Cleanup operations

***

## Query Handlers

### GetBusinessProfileHandler

**Responsibilities:**

1. Profile retrieval with population
2. Media reference resolution
3. Nested settings population
4. Cache management

**Population Strategy:**

```typescript
// Populate media references
const profile = await this.model
  .findOne({ _id: tenantId })
  .populate('logo')
  .populate('banners')
  .populate('gallery')
  .exec();
```

### GetBusinessProfileByIdentifierHandler

**Responsibilities:**

1. Identifier-based lookup
2. Username or tenant ID resolution
3. Profile transformation
4. Cache optimization

### GetBusinessSettingsHandler

**Responsibilities:**

1. Settings-specific queries
2. Lightweight responses
3. Settings validation
4. Performance optimization

### Customer-Facing Query Handlers

#### GetPublicBusinessProfileHandler

**Responsibilities:**

1. Public profile data filtering
2. Privacy settings application
3. Customer-safe data transformation
4. Public cache management

**Data Filtering Strategy:**

```typescript
// Filter sensitive data for public consumption
const publicProfile = {
  name: profile.name,
  description: profile.description,
  addresses: profile.addresses.filter(addr => addr.isPublic),
  contacts: profile.contacts.filter(contact => contact.isPublic),
  schedules: profile.schedules,
  logo: profile.logo,
  banners: profile.banners.filter(banner => banner.isPublished),
  gallery: profile.gallery.filter(item => item.isPublished),
  socialNetworkLinks: profile.socialNetworkLinks.filter(link => link.isPublic)
};
```

#### SearchPublicBusinessProfilesHandler

**Responsibilities:**

1. Complex search query processing
2. Geospatial distance calculations
3. Multi-criteria filtering
4. Result ranking and pagination

**Search Implementation:**

```typescript
// MongoDB aggregation pipeline for complex search
const pipeline = [
  // Text search stage
  {
    $match: {
      $text: { $search: searchQuery },
      isPublished: true,
      isActive: true
    }
  },
  // Geospatial filtering if location provided
  ...(location ? [{
    $geoNear: {
      near: { type: "Point", coordinates: [location.longitude, location.latitude] },
      distanceField: "distance",
      maxDistance: location.radiusKm * 1000,
      spherical: true
    }
  }] : []),
  // Additional filtering stages
  {
    $match: {
      ...(businessType && { businessType }),
      ...(services && { services: { $in: services } })
    }
  },
  // Sorting and pagination
  { $sort: getSortCriteria(sortBy) },
  { $skip: (pagination.page - 1) * pagination.limit },
  { $limit: pagination.limit }
];
```

#### GetBusinessAvailabilityHandler

**Responsibilities:**

1. Real-time availability calculation
2. Schedule processing and validation
3. Timezone conversion
4. Booking rules application

**Availability Calculation:**

```typescript
// Calculate current availability status
const calculateAvailability = (schedules: ISchedule[], currentTime: Date, timezone: string) => {
  const currentLocal = convertToTimezone(currentTime, timezone);
  const currentDay = currentLocal.getDay();
  const currentTimeOfDay = formatTimeOfDay(currentLocal);

  const todaySchedule = schedules.find(s => s.dayOfWeek === currentDay && s.isActive);
  
  if (!todaySchedule) {
    return { isOpen: false, nextAvailable: calculateNextAvailable(schedules, currentLocal) };
  }

  const isCurrentlyOpen = isTimeInRange(currentTimeOfDay, todaySchedule.openTime, todaySchedule.closeTime);
  
  return {
    isOpen: isCurrentlyOpen,
    todayHours: todaySchedule,
    nextAvailable: isCurrentlyOpen ? null : calculateNextAvailable(schedules, currentLocal)
  };
};
```

***

## Domain Validation Rules

### Business Profile Entity Validation

1. **Name Validation**: Required for profile identification
2. **Settings Validation**: All nested settings must pass validation
3. **Media Validation**: File format and size constraints
4. **Address Validation**: Complete address requirements
5. **Contact Validation**: Email, phone format validation
6. **Schedule Validation**: Time format and logic validation
7. **Social Network Validation**: URL format and platform validation

```typescript
// Core validation methods
static validateBusinessSettings(businessSettings: IBusinessSettings, validationErrors: string[]) {
  const result = BusinessSettings.validate(businessSettings);
  if (result.isFailureResult()) {
    validationErrors.push(`BusinessSettings are invalid: ${result.errorValue()}`);
  }
}

static validateBookingSettings(bookingSettings: IBookingSettings, validationErrors: string[]) {
  const result = BookingSettings.validate(bookingSettings);
  if (result.isFailureResult()) {
    validationErrors.push(`BookingSettings are invalid: ${result.errorValue()}`);
  }
}

static validateContacts(contacts: IContact[], validationErrors: string[]) {
  if (contacts && contacts.length > 0) {
    contacts.forEach((contact, index) => {
      const result = Contact.create(contact);
      if (result.isFailureResult()) {
        validationErrors.push(`Contact at index ${index} is invalid: ${result.errorValue()}`);
      }
    });
  }
}
```

***

## Settings Management

### Business Settings Value Object

**Responsibilities:**

* Timezone and locale configuration
* Currency and language settings
* Date/time format preferences
* Email language configuration

**Validation Rules:**

* Valid IANA timezone identifiers
* Supported currency codes
* Available language codes
* Consistent base language settings

### Booking Settings Value Object

**Responsibilities:**

* Customer booking configuration
* Auto-action settings
* Payment requirements
* Mandatory attendee properties

**Validation Rules:**

* Logical earliest/latest booking times
* Valid payment requirement configurations
* Supported attendee property combinations

### Payment Settings Value Object

**Responsibilities:**

* Payment gateway configurations
* Supported payment methods
* Currency and tax settings
* Provider-specific settings

**Validation Rules:**

* Valid API credentials for each provider
* Supported currency combinations
* Tax rate and calculation validations

***

## Media Management Integration

### Media Service Integration

**File Upload Process:**

1. File validation (format, size, dimensions)
2. Upload to cloud storage
3. Thumbnail generation
4. Database reference creation
5. Cache invalidation

**File Deletion Process:**

1. Database reference removal
2. Storage file deletion
3. Thumbnail cleanup
4. Cache invalidation

**Media Types:**

* **Logo**: Single square image, multiple sizes generated
* **Banners**: Multiple landscape images for promotions
* **Gallery**: Multiple images showcasing business work

***

## Cache Management

### Cache Keys and Strategy

* `GET_BUSINESS_PROFILE`: Complete profile cache
* `GET_BUSINESS_SETTINGS`: Settings-specific cache
* `GET_CLIENT_LOGO`: Logo media cache
* `GET_CLIENT_BANNERS`: Banner collection cache
* `GET_CLIENT_GALLERY`: Gallery collection cache
* `GET_PUBLIC_PROFILE`: Public business profile cache
* `GET_PUBLIC_AVAILABILITY`: Business availability cache
* `GET_PUBLIC_CONTACT_INFO`: Public contact information cache
* `SEARCH_PUBLIC_PROFILES`: Business search results cache

### Invalidation Strategy

* **Profile Updates**: Invalidates `GET_BUSINESS_PROFILE` and `GET_PUBLIC_PROFILE`
* **Settings Updates**: Invalidates specific settings caches and public availability
* **Media Updates**: Invalidates media-specific caches and public profile
* **Publication Changes**: Invalidates all public-facing caches
* **Cascade Invalidation**: Profile changes invalidate related public caches

### Cache Decorators

```typescript
@DeleteCache([
  BusinessCacheKeys.GET_BUSINESS_PROFILE,
  BusinessCacheKeys.GET_BUSINESS_SETTINGS,
  PublicBusinessCacheKeys.GET_PUBLIC_PROFILE,
  PublicBusinessCacheKeys.GET_PUBLIC_AVAILABILITY
])
```

### Public Cache Strategies

**Public Profile Cache:**

* Longer TTL (30 minutes) for stable public data
* Invalidated on profile publication changes
* Separate cache namespace for public data

**Availability Cache:**

* Shorter TTL (5 minutes) for real-time data
* Invalidated on schedule changes
* Time-based cache keys for different time periods

**Search Cache:**

* Medium TTL (15 minutes) for search results
* Location-based cache partitioning
* Invalidated on new business publications

***

## Permission Integration

### Permission Validation

All use cases integrate with the `PermissionValidatorUseCase`:

```typescript
await this.permissionValidator.execute({
  actor: ctx.actor,
  requiredPermissions: [ModulePermissionEnum.EDIT_BUSINESS_PROFILE],
});
```

### Required Permissions

* **READ\_BUSINESS\_PROFILE**: View business profile information
* **EDIT\_BUSINESS\_PROFILE**: Modify any aspect of business profile
* **PUBLIC\_ACCESS**: No authentication required (customer-facing endpoints)

### Access Patterns

1. **Read Operations**: Require READ permission (internal) or PUBLIC\_ACCESS (customer)
2. **Update Operations**: Require EDIT permission
3. **Media Operations**: Require EDIT permission
4. **Settings Updates**: Require EDIT permission
5. **Public Operations**: No authentication required but respect privacy settings

### Customer Access Patterns

**Public Endpoints (No Authentication):**

* Get public business profile
* Search public business profiles
* Get business availability information
* Get public contact information
* Get business media gallery
* Get customer booking settings
* Validate business access

**Privacy Filtering:**

* Public endpoints automatically filter sensitive data
* Respect business privacy settings
* Only show published and active content
* Geographic restrictions applied when configured

***

## Error Handling

### Exception Types

1. **BusinessProfileNotFoundException**: Profile not found
2. **BusinessClientCreationException**: Profile creation errors
3. **PaymentSettingsValidationException**: Payment configuration errors
4. **MediaUploadException**: File upload errors
5. **SettingsValidationException**: Settings validation errors
6. **BusinessNotPublishedException**: Business profile not published for public access
7. **BusinessAccessDeniedException**: Geographic or other access restrictions
8. **InvalidSearchCriteriaException**: Invalid search parameters
9. **PublicDataFilterException**: Error filtering public data

### Error Logging

All use cases implement comprehensive error logging:

```typescript
catch (error) {
  this.logger.error('Error updating business profile', error);
  throw error;
}
```

### Customer-Specific Error Handling

**Public Endpoint Errors:**

* Return sanitized error messages to customers
* Log detailed errors for internal monitoring
* Graceful degradation for partial data availability
* Fallback mechanisms for unavailable services

**Privacy Error Handling:**

* Never expose internal business data in errors
* Return generic "not found" for inaccessible data
* Respect privacy settings in error responses

***

## Testing Considerations

### Unit Testing

* Mock dependencies (CommandBus, QueryBus, MediaService)
* Test permission scenarios
* Validate business rules
* Test file upload/deletion scenarios
* Validate settings objects independently

### Integration Testing

* Test with real database and file storage
* Verify cache behavior
* Test multi-tenant isolation
* Validate media file operations

### Example Test Scenarios

1. **Profile Management**: Create, update, retrieve profiles
2. **Settings Validation**: Test all settings objects validation
3. **Media Operations**: Upload, update, delete media files
4. **Permission Tests**: Verify access control
5. **Cache Tests**: Verify cache invalidation works correctly
6. **Error Handling**: Test exception scenarios
7. **Multi-tenant**: Verify tenant isolation
8. **Public Access**: Test customer-facing endpoints without authentication
9. **Privacy Filtering**: Verify sensitive data is filtered in public responses
10. **Search Functionality**: Test business search with various criteria
11. **Availability Calculation**: Test real-time availability logic
12. **Geographic Search**: Test location-based business discovery

### Customer Use Case Testing

**Public Endpoint Testing:**

```typescript
describe('Public Business Profile Access', () => {
  it('should return public profile without authentication', async () => {
    const result = await getPublicBusinessProfile({ businessId: 'test-business' });
    expect(result).not.toContain('paymentSettings');
    expect(result).not.toContain('internalNotes');
  });

  it('should filter unpublished media from public response', async () => {
    const result = await getBusinessMediaGallery({ businessId: 'test-business' });
    result.gallery.forEach(item => {
      expect(item.isPublished).toBe(true);
    });
  });

  it('should calculate availability correctly across timezones', async () => {
    const result = await getBusinessAvailability({ 
      businessId: 'test-business',
      timezone: 'America/New_York'
    });
    expect(result.isOpen).toBeDefined();
    expect(result.nextAvailable).toBeDefined();
  });
});
```

**Search Testing:**

```typescript
describe('Business Search', () => {
  it('should find businesses within specified radius', async () => {
    const result = await searchPublicBusinessProfiles({
      location: { latitude: 40.7128, longitude: -74.0060, radiusKm: 5 },
      sortBy: 'distance'
    });
    result.businesses.forEach(business => {
      expect(business.distance).toBeLessThanOrEqual(5000); // meters
    });
  });

  it('should filter by business type and services', async () => {
    const result = await searchPublicBusinessProfiles({
      businessType: 'restaurant',
      services: ['delivery', 'takeout']
    });
    result.businesses.forEach(business => {
      expect(business.businessType).toBe('restaurant');
      expect(business.services).toContain('delivery');
    });
  });
});
```

***

## Business Workflow Integration

### Profile Setup Workflow

1. **Initial Creation**: Create basic profile during business registration
2. **Information Completion**: Add addresses, contacts, schedules
3. **Settings Configuration**: Configure booking and business settings
4. **Media Upload**: Add logo, banners, gallery images
5. **Publication**: Set profile as published for client visibility

### Settings Management Workflow

1. **Business Settings**: Core operational parameters
2. **Booking Settings**: Customer interaction configuration
3. **Payment Settings**: Financial transaction setup
4. **Notification Settings**: Communication preferences
5. **Panel Settings**: Administrative interface customization

### Media Management Workflow

1. **Logo Management**: Single primary business identifier
2. **Banner Management**: Multiple promotional images
3. **Gallery Management**: Portfolio of business work
4. **Media Optimization**: Automatic resizing and compression
5. **Storage Management**: Cloud storage with CDN delivery

***

## Performance Considerations

### Query Optimization

* Use selective field projection
* Implement proper indexing
* Optimize media population queries
* Cache frequently accessed data

### Media Optimization

* Automatic image compression
* Multiple thumbnail sizes
* CDN delivery for global performance
* Lazy loading for large galleries

### Cache Strategy

* Profile-level caching for complete data
* Component-level caching for settings
* Media-specific caching for assets
* Intelligent cache invalidation


# Database Schema

## Overview

This document describes the database schema and data persistence layer for the Business Profile Management module. The system uses MongoDB as the primary database with Mongoose as the ODM layer. The schema supports comprehensive business information, settings, media assets, and operational configurations.

## Database Schema

### Business Profile Collection

**Collection Name:** `businessProfile`

The business profile collection stores complete business information with the following schema structure:

```typescript
{
  _id: ObjectId,                    // Primary key (tenant ID)
  published: Number,                // Publication status (ActiveEnum)
  name: String,                     // Business name
  username: String,                 // Unique business username
  description: String,              // Business description
  feature: String,                  // Featured information
  facilities: [String],             // Available facilities (FacilityEnum)
  socialNetworkLinks: [SocialNetworkLinkSchema], // Social media links
  bookingSettings: BookingSettingsSchema,        // Booking configuration
  businessSettings: BusinessSettingsSchema,      // Business configuration
  notificationSettings: NotificationSettingsSchema, // Notification preferences
  paymentSettings: PaymentSettingsSchema,        // Payment configuration
  panelSettings: PanelSettingsSchema,           // Panel UI settings
  publicPageSettings: PublicPageSettingsSchema, // Public page settings
  addresses: [AddressSchema],                   // Business addresses
  schedules: [ScheduleSchema],                  // Operating schedules
  specialSchedules: [SpecialScheduleSchema],    // Special schedules
  contacts: [ContactSchema],                    // Contact information
  gallery: [ObjectId],                          // Gallery image references
  logo: ObjectId,                               // Logo image reference
  banners: [ObjectId],                          // Banner image references
  stateHistory: [StateHistorySchema],           // State tracking
  createdAt: Date,                              // Auto-generated creation timestamp
  updatedAt: Date                               // Auto-generated update timestamp
}
```

### Schema Definition

```typescript
const BusinessProfileSchema = new Schema<IBusinessProfile>({
  published: { 
    type: Number, 
    enum: ActiveEnum,
    default: ActiveEnum.YES
  },
  name: { 
    type: String,
    trim: true,
    maxlength: 255
  },
  username: { 
    type: String,
    unique: true,
    sparse: true,
    trim: true,
    lowercase: true,
    maxlength: 50
  },
  description: {
    type: String,
    maxlength: 2000
  },
  feature: {
    type: String,
    maxlength: 500
  },
  facilities: [{ 
    type: String, 
    enum: FacilityEnum 
  }],
  socialNetworkLinks: { 
    type: [SocialNetworkLinkSchema], 
    default: [] 
  },
  bookingSettings: { 
    type: BookingSettingsSchema, 
    default: {} 
  },
  businessSettings: { 
    type: BusinessSettingsSchema, 
    default: {} 
  },
  notificationSettings: { 
    type: NotificationSettingsSchema, 
    default: {} 
  },
  paymentSettings: { 
    type: PaymentSettingsSchema, 
    default: {} 
  },
  panelSettings: { 
    type: PanelSettingsSchema, 
    default: {} 
  },
  publicPageSettings: { 
    type: PublicPageSettingsSchema, 
    default: {} 
  },
  addresses: { 
    type: [AddressSchema], 
    default: [] 
  },
  schedules: { 
    type: [ScheduleSchema], 
    default: [] 
  },
  specialSchedules: { 
    type: [SpecialScheduleSchema], 
    default: [] 
  },
  contacts: { 
    type: [ContactSchema], 
    default: [] 
  },
  gallery: [{ 
    type: Schema.Types.ObjectId, 
    ref: 'Media' 
  }],
  logo: { 
    type: Schema.Types.ObjectId, 
    ref: 'Media' 
  },
  banners: [{ 
    type: Schema.Types.ObjectId, 
    ref: 'Media' 
  }],
  stateHistory: { 
    type: [StateHistorySchema], 
    default: [] 
  },
}, {
  timestamps: true,
  collection: 'businessProfile',
});
```

## Field Specifications

### Required Fields

| Field              | Type   | Description            | Validation                            |
| ------------------ | ------ | ---------------------- | ------------------------------------- |
| `published`        | Number | Publication status     | Must be ActiveEnum value (0 or 1)     |
| `bookingSettings`  | Object | Booking configuration  | Must pass BookingSettings validation  |
| `businessSettings` | Object | Business configuration | Must pass BusinessSettings validation |

### Optional Fields

| Field                | Type      | Description              | Default |
| -------------------- | --------- | ------------------------ | ------- |
| `name`               | String    | Business name            | null    |
| `username`           | String    | Unique business username | null    |
| `description`        | String    | Business description     | null    |
| `feature`            | String    | Featured information     | null    |
| `facilities`         | String\[] | Available facilities     | \[]     |
| `addresses`          | Object\[] | Business addresses       | \[]     |
| `contacts`           | Object\[] | Contact information      | \[]     |
| `schedules`          | Object\[] | Operating schedules      | \[]     |
| `specialSchedules`   | Object\[] | Special schedules        | \[]     |
| `socialNetworkLinks` | Object\[] | Social media links       | \[]     |

### System Fields

| Field          | Type      | Description                 | Auto-Generated        |
| -------------- | --------- | --------------------------- | --------------------- |
| `_id`          | ObjectId  | Primary key (tenant ID)     | No (set to tenant ID) |
| `stateHistory` | Object\[] | State change tracking       | Yes                   |
| `createdAt`    | Date      | Creation timestamp          | Yes                   |
| `updatedAt`    | Date      | Last modification timestamp | Yes                   |

## Embedded Schemas

### AddressSchema

```typescript
{
  _id: ObjectId,
  street: String,                   // Street address
  city: String,                     // City name
  state: String,                    // State/province
  zipCode: String,                  // Postal code
  country: String,                  // Country name
  coordinates: {                    // GPS coordinates
    latitude: Number,
    longitude: Number
  },
  isPrimary: Boolean,               // Primary address flag
  label: String,                    // Address label
  addressType: String               // Address type (business, mailing, etc.)
}
```

### ContactSchema

```typescript
{
  _id: ObjectId,
  type: String,                     // Contact type (PHONE, EMAIL, WEBSITE)
  value: String,                    // Contact value
  label: String,                    // Contact label
  isPrimary: Boolean,               // Primary contact flag
  isPublic: Boolean,                // Public visibility flag
  countryCode: String,              // For phone numbers
  extension: String                 // Phone extension
}
```

### ScheduleSchema

```typescript
{
  _id: ObjectId,
  dayOfWeek: String,                // Day of week (MONDAY, TUESDAY, etc.)
  isOpen: Boolean,                  // Open status for the day
  openTime: String,                 // Opening time (HH:mm format)
  closeTime: String,                // Closing time (HH:mm format)
  breaks: [{                        // Break periods
    startTime: String,
    endTime: String,
    label: String
  }],
  timeZone: String                  // Timezone for the schedule
}
```

### SocialNetworkLinkSchema

```typescript
{
  _id: ObjectId,
  platform: String,                // Social platform (FACEBOOK, INSTAGRAM, etc.)
  url: String,                      // Profile URL
  username: String,                 // Username on platform
  isActive: Boolean,                // Active status
  displayOrder: Number              // Display ordering
}
```

### BookingSettingsSchema

```typescript
{
  autoActionSettings: {
    autoConfirm: Boolean,
    autoConfirmTimeMinutes: Number,
    autoCancel: Boolean,
    autoCancelTimeMinutes: Number
  },
  earliestBooking: Number,          // Hours in advance (minimum)
  latestBooking: Number,            // Hours in advance (maximum)
  slotSettings: {
    slotDuration: Number,
    bufferTime: Number,
    maxAdvanceBookingDays: Number
  },
  autoBookOrder: Boolean,           // Auto-confirm bookings
  paymentRequirement: String,       // Payment requirement (NONE, DEPOSIT, FULL)
  mandatoryAttendeeProperties: [String] // Required customer fields
}
```

### BusinessSettingsSchema

```typescript
{
  timeZone: String,                 // IANA timezone identifier
  currencies: [String],             // Supported currencies
  baseCurrency: String,             // Primary currency
  languages: [String],              // Supported languages
  baseLanguage: String,             // Primary language
  emailLanguage: String,            // Email communication language
  availableLanguages: [String],     // Available interface languages
  dateFormat: String,               // Date display format
  timeFormat: String                // Time display format (12h/24h)
}
```

### PaymentSettingsSchema

```typescript
{
  stripeSettings: {
    publishableKey: String,
    secretKey: String,
    webhookSecret: String,
    isLive: Boolean
  },
  paypalSettings: {
    clientId: String,
    clientSecret: String,
    isLive: Boolean
  },
  squareSettings: {
    applicationId: String,
    accessToken: String,
    isLive: Boolean
  },
  defaultPaymentMethod: String,     // Default payment provider
  acceptedPaymentMethods: [String], // Accepted payment methods
  currencySettings: {
    supportedCurrencies: [String],
    exchangeRateProvider: String
  },
  taxSettings: {
    taxRate: Number,
    taxCalculationMethod: String,
    includeTaxInPrice: Boolean
  }
}
```

## Relationships

### Media Relationships

* **Type**: One-to-One (Logo), One-to-Many (Banners, Gallery)
* **Implementation**: ObjectId references to Media collection
* **Collection**: `media`
* **Lookup**: Populated during queries when media details needed

```typescript
// Population example
businessProfile
  .populate('logo', 'url filename alt title')
  .populate('banners', 'url filename alt title')
  .populate('gallery', 'url filename alt title')
```

### Reference Integrity

* Media references are managed by the application layer
* Orphaned media cleanup handled by background jobs
* Cascade deletion policies for media references

## Indexing Strategy

### Primary Indexes

```typescript
// Primary key index (automatic)
db.businessProfile.createIndex({ "_id": 1 });

// Username uniqueness index
db.businessProfile.createIndex({ 
  "username": 1 
}, { 
  unique: true, 
  sparse: true 
});

// Publication status index
db.businessProfile.createIndex({ 
  "published": 1 
});

// Name search index
db.businessProfile.createIndex({ 
  "name": 1 
});

// Text search index
db.businessProfile.createIndex({
  "name": "text",
  "description": "text",
  "feature": "text"
});
```

### Composite Indexes

```typescript
// Published profiles with name
db.businessProfile.createIndex({ 
  "published": 1, 
  "name": 1 
});

// Location-based queries
db.businessProfile.createIndex({ 
  "addresses.coordinates": "2dsphere" 
});

// Facilities filtering
db.businessProfile.createIndex({ 
  "facilities": 1,
  "published": 1 
});
```

### Sparse Indexes

```typescript
// Username index (sparse for optional field)
db.businessProfile.createIndex(
  { "username": 1 }, 
  { unique: true, sparse: true }
);

// Social network platforms
db.businessProfile.createIndex({ 
  "socialNetworkLinks.platform": 1 
}, { 
  sparse: true 
});
```

## Query Patterns

### Common Queries

#### Find Business Profile by Tenant ID

```typescript
// Standard profile lookup
db.businessProfile.findOne({
  _id: ObjectId(tenantId)
});
```

#### Find Published Profiles

```typescript
// Public profile queries
db.businessProfile.find({
  published: ActiveEnum.YES
});
```

#### Username Availability Check

```typescript
// Check username uniqueness
db.businessProfile.findOne({
  username: usernameToCheck
});
```

#### Location-Based Search

```typescript
// Geospatial queries
db.businessProfile.find({
  published: ActiveEnum.YES,
  "addresses.coordinates": {
    $near: {
      $geometry: {
        type: "Point",
        coordinates: [longitude, latitude]
      },
      $maxDistance: radiusInMeters
    }
  }
});
```

#### Facility-Based Filtering

```typescript
// Filter by facilities
db.businessProfile.find({
  published: ActiveEnum.YES,
  facilities: { $in: ["PARKING", "WIFI"] }
});
```

#### Text Search

```typescript
// Full-text search
db.businessProfile.find({
  published: ActiveEnum.YES,
  $text: { $search: searchTerm }
}, {
  score: { $meta: "textScore" }
}).sort({
  score: { $meta: "textScore" }
});
```

### Complex Aggregation Queries

#### Profile with Media Population

```typescript
const pipeline = [
  // Match criteria
  {
    $match: {
      published: ActiveEnum.YES
    }
  },
  // Lookup logo
  {
    $lookup: {
      from: 'media',
      localField: 'logo',
      foreignField: '_id',
      as: 'logo'
    }
  },
  // Unwind logo (single document)
  {
    $unwind: {
      path: '$logo',
      preserveNullAndEmptyArrays: true
    }
  },
  // Lookup banners
  {
    $lookup: {
      from: 'media',
      localField: 'banners',
      foreignField: '_id',
      as: 'banners'
    }
  },
  // Lookup gallery
  {
    $lookup: {
      from: 'media',
      localField: 'gallery',
      foreignField: '_id',
      as: 'gallery'
    }
  },
  // Project only needed fields
  {
    $project: {
      name: 1,
      description: 1,
      addresses: 1,
      contacts: 1,
      'logo.url': 1,
      'logo.alt': 1,
      'banners.url': 1,
      'banners.alt': 1,
      'gallery.url': 1,
      'gallery.alt': 1
    }
  }
];
```

#### Business Directory Query

```typescript
const directoryPipeline = [
  {
    $match: {
      published: ActiveEnum.YES
    }
  },
  {
    $addFields: {
      primaryAddress: {
        $arrayElemAt: [
          { $filter: {
            input: '$addresses',
            cond: { $eq: ['$$this.isPrimary', true] }
          }}, 0
        ]
      }
    }
  },
  {
    $project: {
      name: 1,
      description: 1,
      facilities: 1,
      'primaryAddress.city': 1,
      'primaryAddress.state': 1,
      logoUrl: '$logo.url'
    }
  },
  {
    $sort: { name: 1 }
  }
];
```

## Repository Implementation

### BusinessProfileRepository

The repository class extends `BaseRepository` and implements `IBusinessProfileRepository`:

```typescript
export class BusinessProfileRepository extends BaseRepository<IBusinessProfile> 
  implements IBusinessProfileRepository {
  
  constructor(
    public readonly model: Model<BusinessProfileDocument>
  ) {
    super(model);
  }

  async findByUsername(username: string): Promise<IBusinessProfile | null> {
    return this.model.findOne({ 
      username: username.toLowerCase() 
    }).exec();
  }

  async findByIdentifier(identifier: string): Promise<IBusinessProfile | null> {
    // Can search by username or tenant ID
    return this.model.findOne({
      $or: [
        { _id: identifier },
        { username: identifier.toLowerCase() }
      ]
    }).exec();
  }

  async updateSettings<T>(
    tenantId: string, 
    settings: T, 
    settingsType: string
  ): Promise<void> {
    const updateQuery = {};
    updateQuery[settingsType] = settings;
    
    await this.model.updateOne(
      { _id: tenantId },
      { $set: updateQuery }
    ).exec();
  }
}
```

### Key Repository Methods

#### Standard CRUD Operations

* `createItemWithId(profile: IBusinessProfile): Promise<IBusinessProfile>`
* `updateItem(id: string, profile: IBusinessProfile): Promise<IBusinessProfile>`
* `findById(id: string): Promise<IBusinessProfile | null>`
* `deleteItem(id: string): Promise<void>` (soft delete)

#### Specialized Queries

* `findByUsername(username: string): Promise<IBusinessProfile | null>`
* `findByIdentifier(identifier: string): Promise<IBusinessProfile | null>`
* `findPublishedProfiles(): Promise<IBusinessProfile[]>`
* `findByLocation(coordinates: number[], radius: number): Promise<IBusinessProfile[]>`
* `searchByText(query: string): Promise<IBusinessProfile[]>`

#### Settings Management

* `updateBookingSettings(tenantId: string, settings: IBookingSettings): Promise<void>`
* `updateBusinessSettings(tenantId: string, settings: IBusinessSettings): Promise<void>`
* `updatePaymentSettings(tenantId: string, settings: IPaymentSettings): Promise<void>`

## Data Consistency

### State History Tracking

Business profiles use state history for audit trails:

```typescript
// State history entry
{
  state: 'active',
  timestamp: new Date(),
  actor: actorId,
  reason: 'Profile updated',
  metadata: {
    fieldsChanged: ['name', 'description'],
    previousValues: {}
  }
}
```

### Media Reference Integrity

* Application layer manages media references
* Orphaned media cleanup via background jobs
* Reference validation during updates

### Settings Validation

All embedded settings objects are validated:

```typescript
// Validation pipeline
const bookingSettingsValidation = BookingSettings.create(settings);
if (bookingSettingsValidation.isFailureResult()) {
  throw new ValidationException(bookingSettingsValidation.errorValue());
}
```

## Multi-Tenancy

### Tenant Isolation

Data isolation is achieved through:

* Document-level isolation (one profile per tenant)
* Tenant ID as primary key
* Application-level tenant context enforcement

### Tenant-Aware Operations

```typescript
// All operations include tenant context
async findProfile(tenantId: string): Promise<IBusinessProfile | null> {
  return this.model.findOne({ _id: tenantId }).exec();
}
```

## Performance Considerations

### Query Optimization

1. **Index Usage**: Ensure queries use appropriate indexes
2. **Projection**: Select only needed fields in queries
3. **Population**: Use selective population for media references
4. **Aggregation**: Use aggregation pipelines for complex queries

### Media Performance

1. **Lazy Loading**: Load media references on demand
2. **CDN Integration**: Serve media files via CDN
3. **Thumbnail Generation**: Multiple sizes for optimal loading
4. **Compression**: Automatic image optimization

### Caching Strategy

1. **Profile Caching**: Cache complete profiles
2. **Settings Caching**: Cache individual settings objects
3. **Media Caching**: Cache media URLs and metadata
4. **Query Result Caching**: Cache common query results

## Data Migration

### Schema Evolution

When schema changes are needed:

1. **Backward Compatibility**: Add optional fields
2. **Migration Scripts**: Transform existing data
3. **Versioning**: Track schema versions
4. **Rollback Procedures**: Maintain rollback capabilities

### Example Migration Scripts

```javascript
// Add new field to existing documents
db.businessProfile.updateMany(
  { newField: { $exists: false } },
  { $set: { newField: defaultValue } }
);

// Transform nested objects
db.businessProfile.updateMany(
  { 'oldSettings': { $exists: true } },
  [
    {
      $set: {
        'newSettings': {
          $mergeObjects: [
            '$oldSettings',
            { newProperty: 'defaultValue' }
          ]
        }
      }
    },
    {
      $unset: 'oldSettings'
    }
  ]
);
```

## Backup and Recovery

### Backup Strategy

1. **Regular Snapshots**: Daily MongoDB snapshots
2. **Point-in-Time Recovery**: Enable oplog for PITR
3. **Media Backup**: Separate media file backup
4. **Cross-Region Replication**: For disaster recovery

### Data Retention

1. **Active Profiles**: Keep in primary collection
2. **Inactive Profiles**: Move to archive after inactivity period
3. **Media Files**: Retain based on business requirements
4. **Audit Logs**: Retain state history for compliance

## Monitoring and Alerts

### Database Metrics

* Query performance and execution times
* Index usage statistics and efficiency
* Document growth rate and collection size
* Memory usage and cache hit ratios
* Connection pool utilization

### Alert Conditions

* Slow queries (>100ms for simple operations)
* Index misses or inefficient queries
* High memory usage or cache pressure
* Media storage growth rate
* Failed operations or validation errors

## Security Considerations

### Data Protection

1. **Encryption at Rest**: Enable MongoDB encryption
2. **Encryption in Transit**: Use TLS for all connections
3. **Field-Level Encryption**: For sensitive payment data
4. **Access Control**: Role-based database access
5. **Audit Logging**: Track all data access and modifications

### Media Security

1. **Secure URLs**: Time-limited signed URLs for media access
2. **Content Validation**: Validate uploaded file types and content
3. **Storage Encryption**: Encrypt media files at rest
4. **Access Logs**: Track media file access patterns

### Privacy Compliance

1. **Data Minimization**: Store only necessary information
2. **Right to Deletion**: Support for profile deletion
3. **Data Portability**: Export capabilities for profile data
4. **Audit Trails**: Complete change history for compliance


# 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): Detailed REST API reference
* [**Interface Documentation**](/services/customer-management/interface): TypeScript contracts and types
* [**Use Case Documentation**](/services/customer-management/usecase): Business logic and workflows
* [**Database Schema**](/services/customer-management/db_schema): 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.


# API Documentation

## Overview

The Customer Management API provides comprehensive endpoints for managing customer information, relationships, and interactions within the Bee O'clock panel service. This API enables businesses to maintain customer records, handle attendee management, and support order-customer relationships with robust validation and data integrity.

## Base URL

```
{base_url}/v1/customer
```

## Authentication

All endpoints require authentication via Bearer token and business tenant ID header.

```http
Authorization: Bearer {access_token}
x-business-tenant-id: {tenant_id}
```

## Core Endpoints

### 1. Get Paginated Customers

Retrieves a paginated list of customers for the authenticated business.

**Endpoint:** `GET /paged`

**Headers:**

```http
Authorization: Bearer {access_token}
x-business-tenant-id: {tenant_id}
```

**Query Parameters:**

```typescript
{
  page?: number;           // Page number (default: 1)
  limit?: number;          // Items per page (default: 10, max: 100)
  sortBy?: string;         // Sort field (firstName, lastName, email, createdAt)
  sortDirection?: 'asc' | 'desc'; // Sort direction (default: 'desc')
  search?: string;         // Search term for name or email
  customerType?: CustomerTypeEnum; // Filter by customer type
}
```

**Response:**

```typescript
{
  items: CustomerDto[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  meta?: {
    searchTerm?: string;
    filters?: Record<string, any>;
  };
}
```

**Example Request:**

```bash
curl -X GET "https://api.beeoclock.com/v1/customer/paged?page=1&limit=20&search=john&sortBy=firstName" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "x-business-tenant-id: 614d1c4c5f1b2c001f5a7b23"
```

**Example Response:**

```json
{
  "items": [
    {
      "object": "CustomerDto",
      "_id": "67b8ac9d4b39c2fd27431017",
      "firstName": "John",
      "lastName": "Smith",
      "email": "john.smith@example.com",
      "phone": "+1234567890",
      "note": "Regular customer, prefers morning appointments",
      "customerType": "regular",
      "state": "active",
      "createdAt": "2025-02-21T16:40:41.031Z",
      "updatedAt": "2025-02-22T12:13:24.745Z"
    }
  ],
  "totalSize": 20,
}
```

**Error Responses:**

```typescript
// 400 Bad Request
{
  "statusCode": 400,
  "message": "Invalid pagination parameters",
  "error": "Bad Request"
}

// 403 Forbidden
{
  "statusCode": 403,
  "message": "Insufficient permissions to read customers",
  "error": "Forbidden"
}
```

***

### 2. Get Customer by ID

Retrieves detailed information for a specific customer.

**Endpoint:** `GET /{id}`

**Path Parameters:**

* `id` (string, required): Customer ID

**Response:**

```typescript
CustomerDto
```

**Example Request:**

```bash
curl -X GET "https://api.beeoclock.com/v1/customer/67b8ac9d4b39c2fd27431017" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "x-business-tenant-id: 614d1c4c5f1b2c001f5a7b23"
```

**Example Response:**

```json
{
  "object": "CustomerDto",
  "_id": "67b8ac9d4b39c2fd27431017",
  "firstName": "John",
  "lastName": "Smith",
  "email": "john.smith@example.com",
  "phone": "+1234567890",
  "note": "Regular customer, prefers morning appointments",
  "customerType": "regular",
  "state": "active",
  "stateHistory": [
    {
      "state": "active",
      "setAt": "2025-02-21T16:40:41.031Z",
      "reason": "Customer created"
    }
  ],
  "createdAt": "2025-02-21T16:40:41.031Z",
  "updatedAt": "2025-02-22T12:13:24.745Z",
  "_version": "2"
}
```

**Error Responses:**

```typescript
// 404 Not Found
{
  "statusCode": 404,
  "message": "Customer not found",
  "error": "Not Found"
}
```

***

### 3. Create Customer

Creates a new customer record with validation.

**Endpoint:** `POST /`

**Request Body:**

```typescript
CustomerDto {
  firstName?: string;      // Customer first name
  lastName?: string;       // Customer last name
  email?: string;          // Customer email (validated)
  phone?: string;          // Customer phone (validated and normalized)
  note?: string;           // Internal notes about customer
  customerType?: CustomerTypeEnum; // Customer type (default: 'regular')
}
```

**Validation Rules:**

* At least one of: `firstName`, `lastName`, `email`, or `phone` must be provided
* Email must be valid format if provided
* Phone must be valid format if provided (automatically normalized)
* Customer type defaults to 'regular'

**Response:**

```typescript
CustomerDto // Complete customer object with generated ID
```

**Example Request:**

```bash
curl -X POST "https://api.beeoclock.com/v1/customer" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "x-business-tenant-id: 614d1c4c5f1b2c001f5a7b23" \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "Jane",
    "lastName": "Doe",
    "email": "jane.doe@example.com",
    "phone": "+1987654321",
    "note": "Prefers text message reminders"
  }'
```

**Example Response:**

```json
{
  "object": "CustomerDto",
  "_id": "67b8ac9d4b39c2fd27431018",
  "firstName": "Jane",
  "lastName": "Doe",
  "email": "jane.doe@example.com",
  "phone": "1987654321",
  "note": "Prefers text message reminders",
  "customerType": "regular",
  "state": "active",
  "stateHistory": [
    {
      "state": "active",
      "setAt": "2025-02-25T10:30:15.123Z",
      "reason": "Customer created"
    }
  ],
  "createdAt": "2025-02-25T10:30:15.123Z",
  "updatedAt": "2025-02-25T10:30:15.123Z",
  "_version": "1"
}
```

**Error Responses:**

```typescript
// 400 Bad Request - Validation Error
{
  "statusCode": 400,
  "message": "At least one field must be filled: phone, email, first name or last name.",
  "error": "Bad Request"
}

// 400 Bad Request - Email Format Error
{
  "statusCode": 400,
  "message": "Invalid email format: invalid-email",
  "error": "Bad Request"
}

// 409 Conflict - Duplicate Customer
{
  "statusCode": 409,
  "message": "Customer with this email already exists",
  "error": "Conflict"
}
```

***

### 4. Update Customer

Updates an existing customer record with partial updates supported.

**Endpoint:** `PUT /{id}`

**Path Parameters:**

* `id` (string, required): Customer ID to update

**Request Body:**

```typescript
CustomerDto // Partial update object
```

**Response:**

```typescript
CustomerDto // Updated customer object
```

**Example Request:**

```bash
curl -X PUT "https://api.beeoclock.com/v1/customer/67b8ac9d4b39c2fd27431017" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "x-business-tenant-id: 614d1c4c5f1b2c001f5a7b23" \
  -H "Content-Type: application/json" \
  -d '{
    "note": "Updated note: Customer prefers afternoon appointments",
    "phone": "+1234567891"
  }'
```

**Example Response:**

```json
{
  "object": "CustomerDto",
  "_id": "67b8ac9d4b39c2fd27431017",
  "firstName": "John",
  "lastName": "Smith",
  "email": "john.smith@example.com",
  "phone": "1234567891",
  "note": "Updated note: Customer prefers afternoon appointments",
  "customerType": "regular",
  "state": "active",
  "stateHistory": [
    {
      "state": "active",
      "setAt": "2025-02-21T16:40:41.031Z",
      "reason": "Customer created"
    }
  ],
  "createdAt": "2025-02-21T16:40:41.031Z",
  "updatedAt": "2025-02-25T11:45:30.456Z",
  "_version": "3"
}
```

***

### 5. Delete Customer

Soft deletes a customer record (sets state to inactive).

**Endpoint:** `DELETE /{id}`

**Path Parameters:**

* `id` (string, required): Customer ID to delete

**Response:**

```typescript
void // No content returned
```

**Example Request:**

```bash
curl -X DELETE "https://api.beeoclock.com/v1/customer/67b8ac9d4b39c2fd27431017" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -H "x-business-tenant-id: 614d1c4c5f1b2c001f5a7b23"
```

**Success Response:**

```http
HTTP/1.1 200 OK
```

**Error Responses:**

```typescript
// 404 Not Found
{
  "statusCode": 404,
  "message": "Customer not found",
  "error": "Not Found"
}

// 409 Conflict - Customer has active orders
{
  "statusCode": 409,
  "message": "Cannot delete customer with active orders",
  "error": "Conflict"
}
```

***

## Data Transfer Objects

### CustomerDto

```typescript
interface CustomerDto {
  object?: 'CustomerDto';
  _id?: string;              // Auto-generated MongoDB ObjectId
  firstName?: string;        // Customer first name (max 100 chars)
  lastName?: string;         // Customer last name (max 100 chars)
  phone?: string;           // Normalized phone number (numbers only)
  email?: string;           // Validated email address
  note?: string;            // Internal business notes (max 1000 chars)
  customerType?: CustomerTypeEnum; // Customer classification
  state?: string;           // Entity state (active, inactive)
  stateHistory?: StateHistoryEntry[]; // State change audit trail
  createdAt?: string;       // ISO date string
  updatedAt?: string;       // ISO date string
  _version?: string;        // Optimistic locking version
}
```

### CustomerPaginationDto

```typescript
interface CustomerPaginationDto {
  page?: number;            // Page number (min: 1, default: 1)
  limit?: number;           // Items per page (min: 1, max: 100, default: 10)
  sortBy?: string;          // Sort field
  sortDirection?: 'asc' | 'desc'; // Sort direction
  search?: string;          // Search term
  customerType?: CustomerTypeEnum; // Filter by type
}
```

## Enumerations

### CustomerTypeEnum

```typescript
enum CustomerTypeEnum {
  regular = 'regular',        // Regular registered customer
  unregistered = 'unregistered', // Unregistered customer
  new = 'new',               // First-time customer
  anonymous = 'anonymous'     // Anonymous customer (public orders)
}
```

## Customer-Order Relationships

### Order Integration

Customers are integrated with orders through the attendee system:

```typescript
// Customer as order attendee
interface AttendantDto {
  object: 'AttendantDto';
  customer: CustomerDto;     // Customer snapshot
  firstTime: boolean;        // First visit indicator
}

// Order contains customer references
interface OrderDto {
  customer: CustomerDto;     // Primary customer (payer)
  services: OrderServiceDto[]; // Services with attendees
}

// Each service has appointment details with attendees
interface OrderAppointmentDetailsDto {
  attendees: AttendantDto[]; // Multiple attendees per service
  // ... other appointment details
}
```

### Payment Integration

Customers are captured in payment records:

```typescript
interface PaymentDto {
  payer: CustomerDto;        // Customer who made payment
  orderId: string;           // Associated order
  // ... payment details
}
```

## Validation Rules

### Customer Creation Validation

1. **Mandatory Fields**: At least one of `firstName`, `lastName`, `email`, or `phone` required
2. **Email Validation**: Must match regex pattern for valid email format
3. **Phone Validation**: Must match international phone number pattern
4. **Phone Normalization**: Automatically extracts and stores only numbers
5. **Duplicate Prevention**: Prevents duplicate customers based on email/phone combination

### Business Rules

1. **Customer Types**:
   * `regular`: Standard registered customers with full profile
   * `unregistered`: Customers without full registration
   * `new`: First-time customers
   * `anonymous`: Anonymous public order customers
2. **Data Integrity**:
   * Customer data is snapshotted in orders and payments
   * Updates to customer records don't affect historical data
   * Soft deletion preserves data for reporting and history
3. **Multi-tenancy**:
   * All operations are tenant-scoped
   * Customers are isolated per business tenant
   * No cross-tenant data access

## Error Handling

### Common Error Codes

| Status Code | Error Type            | Description                                         |
| ----------- | --------------------- | --------------------------------------------------- |
| 400         | Validation Error      | Invalid request data or missing required fields     |
| 401         | Unauthorized          | Invalid or missing authentication token             |
| 403         | Forbidden             | Insufficient permissions for operation              |
| 404         | Not Found             | Customer not found                                  |
| 409         | Conflict              | Duplicate customer or business rule violation       |
| 422         | Unprocessable Entity  | Valid request but business logic prevents execution |
| 500         | Internal Server Error | Unexpected server error                             |

### Error Response Format

```typescript
interface ErrorResponse {
  statusCode: number;
  message: string;
  error: string;
  details?: string[];     // Additional validation errors
  timestamp?: string;     // Error timestamp
  path?: string;         // Request path
}
```

## Security Considerations

### Authentication & Authorization

* **Bearer Token Required**: All endpoints require valid JWT token
* **Tenant Isolation**: Strict tenant-based data separation
* **Permission Validation**: Role-based access control for operations
* **Audit Logging**: All customer operations are logged for security

### Data Protection

* **PII Handling**: Customer data treated as Personally Identifiable Information
* **GDPR Compliance**: Support for data portability and deletion rights
* **Encryption**: Sensitive data encrypted at rest and in transit
* **Access Logging**: Customer data access is logged and monitored

### Rate Limiting

* **API Rate Limits**: Standard rate limiting applied to all endpoints
* **Bulk Operations**: Special consideration for pagination and bulk retrieval
* **Search Optimization**: Search queries optimized to prevent performance issues

## Performance Considerations

### Database Optimization

* **Indexing**: Optimized indexes on frequently queried fields
* **Pagination**: Efficient cursor-based pagination for large datasets
* **Caching**: Redis caching for frequently accessed customer data
* **Query Optimization**: Selective field projection for list operations

### Caching Strategy

```typescript
// Cache keys
const CACHE_KEYS = {
  CUSTOMER_BY_ID: 'customer:id:{customerId}',
  PAGED_CUSTOMERS: 'customers:paged:{tenantId}:{hash}',
  CUSTOMER_SEARCH: 'customers:search:{tenantId}:{query}'
};

// Cache TTL
const CACHE_TTL = {
  CUSTOMER_DETAILS: 300,    // 5 minutes
  CUSTOMER_LIST: 60,        // 1 minute
  SEARCH_RESULTS: 180       // 3 minutes
};
```

## Integration Examples

### Customer Creation Flow

```typescript
// Step 1: Validate customer data
const customerData = {
  firstName: 'John',
  lastName: 'Doe',
  email: 'john.doe@example.com',
  phone: '+1-555-123-4567'
};

// Step 2: Create customer
const response = await fetch('/v1/customer', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'x-business-tenant-id': tenantId,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(customerData)
});

const customer = await response.json();

// Step 3: Customer ID available for orders
const customerId = customer._id;
```

### Order Attendee Integration

```typescript
// Using customer in order creation
const orderService = {
  serviceSnapshot: { /* service details */ },
  orderAppointmentDetails: {
    start: '2025-03-01T10:00:00Z',
    end: '2025-03-01T11:00:00Z',
    attendees: [{
      customer: customer,      // CustomerDto
      firstTime: false
    }]
  }
};
```

### Customer Search and Selection

```typescript
// Search customers for appointment booking
const searchResponse = await fetch(
  `/v1/customer/paged?search=${encodeURIComponent(searchTerm)}&limit=10`,
  {
    headers: {
      'Authorization': `Bearer ${token}`,
      'x-business-tenant-id': tenantId
    }
  }
);

const { items: customers } = await searchResponse.json();

// Present customer list for selection
customers.forEach(customer => {
  console.log(`${customer.firstName} ${customer.lastName} (${customer.email})`);
});
```

## Testing Examples

### Unit Testing

```typescript
describe('Customer API', () => {
  test('should create customer with valid data', async () => {
    const customerData = {
      firstName: 'Test',
      lastName: 'User',
      email: 'test@example.com'
    };

    const response = await request(app)
      .post('/v1/customer')
      .set('Authorization', `Bearer ${authToken}`)
      .set('x-business-tenant-id', tenantId)
      .send(customerData)
      .expect(200);

    expect(response.body.firstName).toBe('Test');
    expect(response.body.email).toBe('test@example.com');
    expect(response.body._id).toBeDefined();
  });

  test('should validate email format', async () => {
    const invalidData = {
      firstName: 'Test',
      email: 'invalid-email'
    };

    await request(app)
      .post('/v1/customer')
      .set('Authorization', `Bearer ${authToken}`)
      .set('x-business-tenant-id', tenantId)
      .send(invalidData)
      .expect(400);
  });
});
```

***

## Summary

The Customer Management API provides a robust foundation for managing customer relationships within the Bee O'clock ecosystem. Key features include:

* **Comprehensive CRUD Operations** with validation and error handling
* **Advanced Search and Pagination** for efficient customer discovery
* **Strong Data Validation** ensuring data quality and consistency
* **Integration Support** for orders, payments, and appointments
* **Multi-tenant Architecture** with proper data isolation
* **Performance Optimization** through caching and efficient querying
* **Security Compliance** with authentication, authorization, and audit logging

The API supports complex business scenarios including customer-order relationships, payment processing, and historical data preservation while maintaining high performance and data integrity standards.


# 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.


# Use Case Documentation

## Overview

This document describes the business use cases and application layer logic for the Customer Management module. Each use case encapsulates business rules, permissions, and orchestrates the interaction between domain entities, repositories, and external integrations within the order and payment ecosystem.

## Architecture Pattern

The module follows the CQRS (Command Query Responsibility Segregation) pattern with the following structure:

* **Use Cases**: Application layer orchestrating business logic
* **Commands**: Write operations (Create, Update, Delete Customer)
* **Queries**: Read operations (Get Customer, Search Customers)
* **Domain Entities**: Business logic and validation
* **Value Objects**: Customer data and relationship objects
* **Integration Services**: Order and payment system integration

## Core Use Cases

### 1. CreateCustomerUseCase

**Purpose:** Creates a new customer record with comprehensive validation and business rule enforcement.

**Input:** `CreateCustomerUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  customer: CustomerDto
}
```

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

**Business Rules:**

1. User must have `CREATE_CUSTOMER` permission
2. At least one of firstName, lastName, email, or phone must be provided
3. Email must be valid format if provided
4. Phone must be valid format if provided (automatically normalized)
5. Customer type defaults to 'regular' if not specified
6. No duplicate customers based on email/phone combination
7. Customer is created with 'active' state

**Process Flow:**

1. Validate user permissions using `PermissionValidatorUseCase`
2. Validate customer data using `CustomerValidator`
3. Execute `AddRegularCustomerCommand` via command bus
4. Command handler validates domain rules and creates entity
5. Persist customer to database with tenant isolation
6. Clear relevant cache entries
7. Publish `CustomerAddedMessage` event
8. Return generated customer ID

**Validation Rules:**

```typescript
// Mandatory field validation
const hasRequiredField = customer.firstName || customer.lastName || 
                        customer.email || customer.phone;
if (!hasRequiredField) {
  throw new ValidationException('At least one field must be filled: phone, email, first name or last name.');
}

// Email format validation
if (customer.email && !isValidEmail(customer.email)) {
  throw new ValidationException('Invalid email format');
}

// Phone format validation and normalization
if (customer.phone) {
  const normalizedPhone = extractNumbers(customer.phone);
  customer.phone = normalizedPhone;
}
```

**Cache Invalidation:** Clears `CustomerCacheKeys.GET_PAGED_CUSTOMERS`

***

### 2. GetCustomerUseCase

**Purpose:** Retrieves detailed customer information by ID with permission validation.

**Input:** `GetCustomerUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  customerId: string
}
```

**Output:** `CustomerDto`

**Business Rules:**

1. User must have `READ_CUSTOMER` permission
2. Customer must exist and belong to the authenticated tenant
3. Returns complete customer information including state history
4. Respects tenant data isolation

**Process Flow:**

1. Validate user permissions
2. Execute `GetCustomerByIdQuery` via query bus
3. Query handler retrieves customer from repository
4. Transform persistence model to DTO
5. Return customer data or throw exception if not found

**Error Scenarios:**

* Insufficient permissions → `ForbiddenException`
* Customer not found → `CustomerNotFoundException`
* Database errors → Logged and re-thrown

**Caching:** Results are cached using `CustomerCacheKeys.GET_CUSTOMER`

***

### 3. UpdateCustomerUseCase

**Purpose:** Updates existing customer information with partial update support and validation.

**Input:** `UpdateCustomerUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  customerId: string,
  update: CustomerDto
}
```

**Output:** `void`

**Business Rules:**

1. User must have `EDIT_CUSTOMER` permission
2. Customer must exist and belong to the authenticated tenant
3. Supports partial updates (only provided fields are updated)
4. Email and phone validation applied if provided
5. Customer type can be changed with proper validation
6. Updates increment version number for optimistic locking

**Process Flow:**

1. Validate user permissions
2. Verify customer exists using `GetCustomerByIdQuery`
3. Validate update data using `CustomerValidator`
4. Execute `UpdateCustomerCommand` via command bus
5. Command handler applies domain validation and updates entity
6. Persist changes with optimistic locking
7. Clear relevant cache entries
8. Publish `CustomerUpdatedMessage` event

**Domain Validation:**

```typescript
// Validate email if provided
if (update.email && !Customer.validateEmail(update.email).isSuccessResult()) {
  throw new ValidationException('Invalid email format');
}

// Validate and normalize phone if provided
if (update.phone) {
  const phoneValidation = Customer.validatePhone(update.phone);
  if (phoneValidation.isFailureResult()) {
    throw new ValidationException(phoneValidation.errorValue());
  }
  update.phone = extractNumbers(update.phone);
}
```

**Cache Invalidation:** Clears `CustomerCacheKeys.GET_CUSTOMER` and `CustomerCacheKeys.GET_PAGED_CUSTOMERS`

***

### 4. DeleteCustomerUseCase

**Purpose:** Soft deletes a customer record with business rule validation.

**Input:** `DeleteCustomerUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  customerId: string
}
```

**Output:** `void`

**Business Rules:**

1. User must have `DELETE_CUSTOMER` permission
2. Customer must exist and belong to the authenticated tenant
3. Performs soft delete (sets state to 'deleted')
4. Validates no active orders exist for the customer
5. Preserves historical data for reporting and compliance

**Process Flow:**

1. Validate user permissions
2. Verify customer exists
3. Check for active orders or dependencies
4. Execute `DeleteCustomerCommand` via command bus
5. Command handler performs soft delete
6. Update state history with deletion reason
7. Clear relevant cache entries
8. Publish `CustomerDeletedMessage` event

**Dependency Validation:**

```typescript
// Check for active orders
const activeOrders = await this.orderService.getActiveOrdersByCustomer(customerId);
if (activeOrders.length > 0) {
  throw new BusinessRuleViolationException('Cannot delete customer with active orders');
}

// Check for pending payments
const pendingPayments = await this.paymentService.getPendingPaymentsByCustomer(customerId);
if (pendingPayments.length > 0) {
  throw new BusinessRuleViolationException('Cannot delete customer with pending payments');
}
```

***

### 5. GetPagedCustomersUseCase

**Purpose:** Retrieves paginated customer list with search and filtering capabilities.

**Input:** `GetPagedCustomersUseCaseParams`

```typescript
{
  ctx: TenantActorContext,
  pagination: CustomerPaginationDto
}
```

**Output:** `PaginationResponseDto<CustomerDto>`

**Business Rules:**

1. User must have `READ_CUSTOMER` permission
2. Results are filtered by tenant for data isolation
3. Supports text search across name and email fields
4. Supports filtering by customer type and state
5. Implements efficient pagination with cursor support
6. Maximum page size limit enforced

**Process Flow:**

1. Validate user permissions
2. Validate pagination parameters
3. Execute `GetPagedCustomersQuery` via query bus
4. Query handler applies filters and pagination
5. Transform results to DTOs
6. Return paginated response with metadata

**Search Implementation:**

```typescript
// MongoDB aggregation pipeline for customer search
const pipeline = [
  // Text search stage
  {
    $match: {
      $or: [
        { firstName: { $regex: searchTerm, $options: 'i' } },
        { lastName: { $regex: searchTerm, $options: 'i' } },
        { email: { $regex: searchTerm, $options: 'i' } },
        { $text: { $search: searchTerm } }
      ],
      tenantId: ctx.tenantId,
      state: { $ne: 'deleted' }
    }
  },
  // Customer type filtering
  ...(customerType ? [{ $match: { customerType } }] : []),
  // Sorting and pagination
  { $sort: getSortCriteria(sortBy, sortDirection) },
  { $skip: (page - 1) * limit },
  { $limit: limit }
];
```

**Caching:** Results cached using `CustomerCacheKeys.GET_PAGED_CUSTOMERS` with pagination context

***

## Order Integration Use Cases

### 6. AddAttendeesUseCase

**Purpose:** Processes customer attendees for order services, creating or updating customer records as needed.

**Input:** `AddAttendeesCommand`

```typescript
{
  tenantId: string,
  attendees: AttendantDto[]
}
```

**Output:** `AttendantDto[]` (Processed attendees with customer IDs)

**Business Rules:**

1. Creates regular customers for attendees with email/phone
2. Reuses existing customers when found by email/phone match
3. Marks first-time visitors based on order history
4. Validates attendee information against business settings
5. Maintains customer snapshots in order data

**Process Flow:**

1. Iterate through provided attendees
2. For each attendee with contact information:
   * Search for existing customer by email/phone
   * If found, use existing customer and mark `firstTime: false`
   * If not found, create new regular customer
   * Validate customer data meets business requirements
3. Create customer snapshots for order persistence
4. Return processed attendee list with customer references

**Customer Matching Logic:**

```typescript
// Find existing customer by email or phone
const existingCustomer = await this.sharedUnitOfWork.customers.findCustomerByEmailOrPhone(
  attendant.customer?.email,
  attendant.customer?.phone
);

if (existingCustomer) {
  // Use existing customer
  attendantDtoArray.push({
    object: 'AttendantDto',
    customer: CustomerMap.toDto({ ...existingCustomer, customerType: CustomerTypeEnum.regular }),
    firstTime: false
  });
} else {
  // Create new regular customer
  const regularCustomer = Customer.createRegular({
    _id: attendant?.customer?._id,
    customerType: CustomerTypeEnum.regular,
    email: attendant.customer?.email,
    firstName: attendant.customer?.firstName,
    lastName: attendant.customer?.lastName,
    phone: attendant.customer?.phone,
  });

  if (regularCustomer.isSuccessResult()) {
    const persistenceCustomer = CustomerMap.toPersistence(regularCustomer.getValue());
    const createdCustomer = await this.sharedUnitOfWork.customers.createCustomer(persistenceCustomer);
    
    attendantDtoArray.push({
      object: 'AttendantDto',
      customer: CustomerMap.toDto(createdCustomer),
      firstTime: true
    });
  }
}
```

***

### 7. AddPublicAttendeesUseCase

**Purpose:** Processes customer information from public order creation with flexible customer handling.

**Input:** `AddPublicAttendeesCommand`

```typescript
{
  tenantId: string,
  attendees: PublicAttendantDto[]
}
```

**Output:** `AttendantDto[]`

**Business Rules:**

1. Handles anonymous and unregistered customers
2. Creates minimal customer records for public orders
3. Validates mandatory attendee properties per business settings
4. Supports guest checkout scenarios
5. Maintains privacy for public customers

**Process Flow:**

1. Validate attendee information against business booking settings
2. For each public attendee:
   * Check if customer exists by contact information
   * Create unregistered customer if sufficient information provided
   * Create anonymous customer for minimal information
   * Apply business mandatory property requirements
3. Return processed attendee list for order creation

**Mandatory Property Validation:**

```typescript
// Validate mandatory attendee properties
const mandatoryProperties = bookingSettings.mandatoryAttendeeProperties || [AttendeePropertyEnum.email];

attendees.forEach((attendee, index) => {
  const missingProperties = mandatoryProperties.filter(prop =>
    attendee[prop] === undefined || attendee[prop] === null || attendee[prop] === ''
  );

  if (missingProperties.length > 0) {
    throw new ValidationException(
      `Attendee #${index + 1} is missing mandatory properties: ${missingProperties.join(', ')}`
    );
  }
});
```

***

## Payment Integration Use Cases

### 8. ProcessPaymentCustomerUseCase

**Purpose:** Handles customer information during payment processing with customer creation as needed.

**Input:** `ProcessPaymentCustomerParams`

```typescript
{
  tenantId: string,
  payerInfo: CustomerDto,
  actor: ActorDto
}
```

**Output:** `CustomerDto` (Processed payer information)

**Business Rules:**

1. Creates customer record for payment if not exists
2. Validates payer information for payment processing
3. Maintains customer snapshots in payment records
4. Supports guest payment scenarios
5. Links payment history to customer records

**Process Flow:**

1. Validate payer information format
2. Search for existing customer by email/phone
3. If customer exists, update payment-relevant information
4. If customer doesn't exist, create new customer record
5. Return customer information for payment processing

**Payment Customer Creation:**

```typescript
// Check if customer exists for payment
const existingCustomer = await this.sharedUnitOfWork.customers.findCustomerByEmailOrPhone(
  payment.payer.email,
  payment.payer.phone
);

if (!existingCustomer) {
  // Create customer for payment
  const customerDomain = Customer.createRegular(
    CustomerMap.toPersistenceFromDto(payment.payer)
  );

  if (customerDomain.isSuccessResult()) {
    await this.sharedUnitOfWork.customers.createCustomer(payment.payer);
  }
}
```

***

## Query Handlers

### GetCustomerByIdHandler

**Responsibilities:**

1. Customer retrieval with tenant filtering
2. State validation and access control
3. Data transformation to DTO format
4. Cache management and optimization

**Implementation:**

```typescript
async execute(query: GetCustomerByIdQuery): Promise<CustomerDto | null> {
  try {
    const customer = await this.sharedUnitOfWork.customers.findCustomerById(
      query.customerId,
      query.tenantId
    );

    if (!customer) {
      return null;
    }

    // Validate customer state
    if (customer.state === 'deleted') {
      return null;
    }

    return CustomerMap.toDto(customer);
  } catch (error) {
    this.logger.error(`Error getting customer by id: ${query.customerId}`, error);
    throw error;
  }
}
```

### GetPagedCustomersHandler

**Responsibilities:**

1. Advanced filtering and search implementation
2. Efficient pagination with cursor support
3. Sort optimization and index utilization
4. Result transformation and metadata

**Search Strategy:**

```typescript
// MongoDB search implementation
const searchFilter = query.search ? {
  $or: [
    { firstName: { $regex: query.search, $options: 'i' } },
    { lastName: { $regex: query.search, $options: 'i' } },
    { email: { $regex: query.search, $options: 'i' } },
    { 
      $expr: {
        $regexMatch: {
          input: { $concat: ['$firstName', ' ', '$lastName'] },
          regex: query.search,
          options: 'i'
        }
      }
    }
  ]
} : {};

const filter = {
  tenantId: query.tenantId,
  state: { $ne: 'deleted' },
  ...searchFilter,
  ...(query.customerType && { customerType: query.customerType })
};
```

### IsCustomerExistHandler

**Responsibilities:**

1. Duplicate customer detection
2. Email and phone uniqueness validation
3. Performance-optimized existence checks
4. Multi-field search support

**Existence Check:**

```typescript
async execute(query: IsCustomerExistQuery): Promise<boolean> {
  const filter: any = { tenantId: query.tenantId, state: { $ne: 'deleted' } };
  
  const orConditions = [];
  if (query.email) orConditions.push({ email: query.email });
  if (query.phone) orConditions.push({ phone: extractNumbers(query.phone) });
  
  if (orConditions.length > 0) {
    filter.$or = orConditions;
  }
  
  const count = await this.model.countDocuments(filter);
  return count > 0;
}
```

***

## Command Handlers

### AddRegularCustomerHandler

**Responsibilities:**

1. Domain entity creation and validation
2. Business rule enforcement
3. Database persistence with tenant ID
4. Event publishing and cache invalidation

**Customer Creation Process:**

```typescript
async execute(command: AddRegularCustomerCommand): Promise<string> {
  try {
    // Create domain entity with validation
    const customerDomain = Customer.createRegular({
      ...command.customer,
      customerType: CustomerTypeEnum.regular
    });

    if (customerDomain.isFailureResult()) {
      throw new CustomerCreationException(customerDomain.errorValue());
    }

    // Convert to persistence model
    const persistenceModel = CustomerMap.toPersistence(customerDomain.getValue());
    persistenceModel.tenantId = command.tenantId;

    // Persist to database
    const createdCustomer = await this.sharedUnitOfWork.customers.createCustomer(persistenceModel);

    // Publish event
    await this.messageQueueService.sendMessage(
      new CustomerAddedMessage({
        tenantId: command.tenantId,
        customer: CustomerMap.toDto(createdCustomer),
        createdBy: { /* actor info */ },
        timestamp: new Date().toISOString()
      })
    );

    return createdCustomer._id.toString();
  } catch (error) {
    this.logger.error('Error creating customer', error);
    throw new CustomerCreationException(error.message);
  }
}
```

### UpdateCustomerHandler

**Responsibilities:**

1. Customer existence validation
2. Partial update processing
3. Domain validation enforcement
4. Optimistic locking support

### DeleteCustomerHandler

**Responsibilities:**

1. Soft delete implementation
2. Dependency validation
3. State history maintenance
4. Cleanup operations

***

## Domain Validation Rules

### Customer Entity Validation

```typescript
// Customer creation validation
static create(props: ICustomer): Result<Customer> {
  const validationErrors: string[] = [];

  // Validate mandatory fields
  const requiredFields: (keyof ICustomer)[] = ['firstName', 'lastName', 'phone', 'email', 'customerType'];
  const fieldValidation = this.validateMandatoryFields(props, requiredFields);
  if (fieldValidation.isFailureResult()) {
    validationErrors.push(fieldValidation.errorValue());
  }

  // Validate email format
  const emailValidation = this.validateEmail(props.email);
  if (emailValidation.isFailureResult()) {
    validationErrors.push(emailValidation.errorValue());
  }

  // Validate phone format
  const phoneValidation = this.validatePhone(props.phone);
  if (phoneValidation.isFailureResult()) {
    validationErrors.push(phoneValidation.errorValue());
  }

  if (validationErrors.length > 0) {
    return Result.fail<Customer>(validationErrors.join('\n'));
  }

  // Normalize phone number
  if (props.phone) {
    props.phone = extractNumbers(props.phone);
  }

  return Result.ok(new Customer(props));
}

// Regular customer validation (stricter rules)
static createRegular(props: ICustomer): Result<Customer> {
  const validationErrors: string[] = [];

  // Validate mandatory fields for regular customers
  const requiredFields: (keyof ICustomer)[] = ['phone', 'email'];
  const fieldValidation = this.validateMandatoryFields(props, requiredFields);
  if (fieldValidation.isFailureResult()) {
    validationErrors.push(fieldValidation.errorValue());
  }

  const emailValidation = this.validateEmail(props.email);
  if (emailValidation.isFailureResult()) {
    validationErrors.push(emailValidation.errorValue());
  }

  const phoneValidation = this.validatePhone(props.phone);
  if (phoneValidation.isFailureResult()) {
    validationErrors.push(phoneValidation.errorValue());
  }

  if (validationErrors.length > 0) {
    return Result.fail<Customer>(validationErrors.join('\n'));
  }

  // Set customer type and normalize phone
  props.customerType = CustomerTypeEnum.regular;
  if (props.phone) {
    props.phone = extractNumbers(props.phone);
  }

  return Result.ok(new Customer(props));
}
```

### Validation Helper Methods

```typescript
// Email validation
private static validateEmail(email?: string): Result<void> {
  if (email && !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
    return Result.fail<void>('Invalid email format: ' + email);
  }
  return Result.ok();
}

// Phone validation
private static validatePhone(phone?: string): Result<void> {
  if (phone && !/^(\+?\d{1,3}[-.\s]?)?(\(?\d{1,4}\)?[-.\s]?)?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}$/.test(phone)) {
    return Result.fail<void>('Invalid phone number format: ' + phone);
  }
  return Result.ok();
}

// Mandatory fields validation
private static validateMandatoryFields(props: ICustomer, fields: (keyof ICustomer)[]): Result<void> {
  const hasAtLeastOneProperty = fields.some(field => 
    props[field] !== undefined && props[field] !== '' && props[field] !== null
  );
  
  return hasAtLeastOneProperty ? 
    Result.ok() : 
    Result.fail<void>('At least one of the following properties must be provided: ' + fields.join(', '));
}
```

***

## Cache Management

### Cache Keys and Strategy

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

// Cache TTL settings
const CACHE_TTL = {
  CUSTOMER_DETAILS: 300,    // 5 minutes
  CUSTOMER_LIST: 60,        // 1 minute  
  SEARCH_RESULTS: 180,      // 3 minutes
  VALIDATION_RESULTS: 600   // 10 minutes
};
```

### Cache Invalidation Strategy

```typescript
// Customer update invalidates related caches
@DeleteCache([
  CustomerCacheKeys.GET_CUSTOMER,
  CustomerCacheKeys.GET_PAGED_CUSTOMERS,
  CustomerCacheKeys.CUSTOMER_SEARCH
])
async updateCustomer(command: UpdateCustomerCommand): Promise<void> {
  // Update implementation
}

// Smart cache invalidation based on changes
private async invalidateCustomerCaches(tenantId: string, customerId: string, changedFields: string[]) {
  // Always invalidate customer detail cache
  await this.cacheService.delete(`${CustomerCacheKeys.GET_CUSTOMER}:${tenantId}:${customerId}`);
  
  // Invalidate search cache if searchable fields changed
  const searchableFields = ['firstName', 'lastName', 'email'];
  if (changedFields.some(field => searchableFields.includes(field))) {
    await this.cacheService.deletePattern(`${CustomerCacheKeys.CUSTOMER_SEARCH}:${tenantId}:*`);
  }
  
  // Invalidate paged results cache
  await this.cacheService.deletePattern(`${CustomerCacheKeys.GET_PAGED_CUSTOMERS}:${tenantId}:*`);
}
```

***

## Permission Integration

### Permission Validation

All customer use cases integrate with the `PermissionValidatorUseCase`:

```typescript
await this.permissionValidator.execute({
  actor: ctx.actor,
  requiredPermissions: [ModulePermissionEnum.CREATE_CUSTOMER],
});
```

### Required Permissions

* **READ\_CUSTOMER**: View customer information and lists
* **CREATE\_CUSTOMER**: Create new customer records
* **EDIT\_CUSTOMER**: Modify existing customer information
* **DELETE\_CUSTOMER**: Delete customer records

### Permission Matrix

| Operation           | Permission       | Scope  | Notes                        |
| ------------------- | ---------------- | ------ | ---------------------------- |
| Get Customer        | READ\_CUSTOMER   | Tenant | Read access to customer data |
| Get Paged Customers | READ\_CUSTOMER   | Tenant | List and search customers    |
| Create Customer     | CREATE\_CUSTOMER | Tenant | Create new customer records  |
| Update Customer     | EDIT\_CUSTOMER   | Tenant | Modify customer information  |
| Delete Customer     | DELETE\_CUSTOMER | Tenant | Soft delete customer records |
| Add Attendees       | EDIT\_CUSTOMER   | Tenant | Process order attendees      |

***

## Error Handling

### Exception Types

```typescript
// Customer-specific exceptions
export class CustomerNotFoundException extends NotFoundException {
  constructor(customerId: string) {
    super(`Customer not found: ${customerId}`);
  }
}

export class CustomerCreationException extends BadRequestException {
  constructor(message: string) {
    super(`Customer creation failed: ${message}`);
  }
}

export class CustomerAlreadyExistsException extends ConflictException {
  constructor(field: string, value: string) {
    super(`Customer already exists with ${field}: ${value}`);
  }
}

export class CustomerValidationException extends BadRequestException {
  constructor(errors: string[]) {
    super(`Customer validation failed: ${errors.join(', ')}`);
  }
}
```

### Error Logging

All use cases implement comprehensive error logging:

```typescript
catch (error) {
  this.logger.error('Error in customer operation', {
    operation: 'createCustomer',
    tenantId: ctx.tenantId,
    customerId: customer._id,
    error: error.message,
    stack: error.stack
  });
  throw error;
}
```

***

## Testing Considerations

### Unit Testing

```typescript
describe('CreateCustomerUseCase', () => {
  test('should create customer with valid data', async () => {
    const customer = {
      firstName: 'John',
      lastName: 'Doe',
      email: 'john.doe@example.com',
      phone: '+1234567890'
    };

    const customerId = await createCustomerUseCase.execute({
      ctx: mockContext,
      customer
    });

    expect(customerId).toBeDefined();
    expect(mockCommandBus.execute).toHaveBeenCalledWith(
      expect.any(AddRegularCustomerCommand)
    );
  });

  test('should validate mandatory fields', async () => {
    const invalidCustomer = {};

    await expect(
      createCustomerUseCase.execute({
        ctx: mockContext,
        customer: invalidCustomer
      })
    ).rejects.toThrow('At least one field must be filled');
  });

  test('should validate email format', async () => {
    const customer = {
      firstName: 'John',
      email: 'invalid-email'
    };

    await expect(
      createCustomerUseCase.execute({
        ctx: mockContext,
        customer
      })
    ).rejects.toThrow('Invalid email format');
  });
});
```

### Integration Testing

```typescript
describe('Customer Integration Tests', () => {
  test('should create customer and retrieve by ID', async () => {
    // Create customer
    const customerId = await createCustomerUseCase.execute({
      ctx: testContext,
      customer: testCustomerData
    });

    // Retrieve customer
    const retrievedCustomer = await getCustomerUseCase.execute({
      ctx: testContext,
      customerId
    });

    expect(retrievedCustomer._id).toBe(customerId);
    expect(retrievedCustomer.email).toBe(testCustomerData.email);
  });

  test('should handle order attendee creation', async () => {
    const attendees = [{
      customer: {
        firstName: 'Jane',
        lastName: 'Smith',
        email: 'jane.smith@example.com'
      }
    }];

    const processedAttendees = await commandBus.execute(
      new AddAttendeesCommand(tenantId, attendees)
    );

    expect(processedAttendees).toHaveLength(1);
    expect(processedAttendees[0].customer._id).toBeDefined();
    expect(processedAttendees[0].firstTime).toBe(true);
  });
});
```

***

## Business Workflow Integration

### Customer Lifecycle Workflow

1. **Customer Creation**: Initial customer registration or first order
2. **Profile Completion**: Adding additional information and preferences
3. **Order Association**: Linking customers to orders as payers and attendees
4. **Payment Processing**: Customer information in payment records
5. **Relationship Management**: Ongoing customer interaction and updates

### Order Integration Workflow

1. **Attendee Processing**: Convert order attendees to customer records
2. **Customer Matching**: Find existing customers or create new ones
3. **Snapshot Creation**: Preserve customer data in order records
4. **First-Time Detection**: Mark new customers for special handling
5. **History Tracking**: Maintain customer order history

### Payment Integration Workflow

1. **Payer Identification**: Link payment to customer record
2. **Customer Creation**: Create customer if not exists for payment
3. **Payment History**: Track customer payment patterns
4. **Billing Information**: Manage customer billing preferences

***

## Performance Considerations

### Database Optimization

1. **Indexing Strategy**: Optimize for common query patterns
2. **Query Optimization**: Efficient filtering and sorting
3. **Batch Processing**: Handle bulk customer operations
4. **Connection Pooling**: Manage database connections efficiently

### Query Patterns

```typescript
// Optimized customer search with indexes
db.customer.createIndex({ 
  tenantId: 1, 
  email: 1 
}, { 
  sparse: true 
});

db.customer.createIndex({ 
  tenantId: 1, 
  phone: 1 
}, { 
  sparse: true 
});

db.customer.createIndex({
  tenantId: 1,
  firstName: 'text',
  lastName: 'text',
  email: 'text'
});

// Compound index for pagination
db.customer.createIndex({
  tenantId: 1,
  state: 1,
  createdAt: -1
});
```

### Memory Management

1. **Selective Field Projection**: Load only required fields
2. **Streaming Results**: Handle large result sets efficiently
3. **Cache Optimization**: Balance memory usage and performance
4. **Connection Management**: Proper resource cleanup

***

## Security Considerations

### Data Protection

1. **PII Handling**: Secure processing of personal information
2. **Encryption**: Protect sensitive customer data
3. **Access Logging**: Track customer data access
4. **Data Retention**: Comply with retention policies

### Privacy Compliance

1. **GDPR Support**: Data portability and deletion rights
2. **Consent Management**: Track customer consent preferences
3. **Data Minimization**: Store only necessary information
4. **Audit Trail**: Complete change history for compliance

### Access Control

1. **Permission Validation**: Enforce role-based access
2. **Tenant Isolation**: Strict multi-tenant data separation
3. **Rate Limiting**: Prevent abuse and DoS attacks
4. **Input Validation**: Sanitize all customer inputs

***

## Business Rules Summary

### Customer Data Rules

1. **Mandatory Information**: At least one identifying field required
2. **Data Validation**: Email and phone format validation
3. **Normalization**: Phone numbers stored in normalized format
4. **Uniqueness**: Prevent duplicate customers per tenant
5. **State Management**: Soft deletion preserves historical data

### Order Integration Rules

1. **Attendee Matching**: Smart customer matching by email/phone
2. **Customer Creation**: Automatic customer creation for orders
3. **Snapshot Preservation**: Historical customer data in orders
4. **First-Time Tracking**: Identify new customer visits
5. **Multi-Attendee Support**: Multiple customers per order service

### Business Logic Rules

1. **Tenant Isolation**: Complete data separation per business
2. **Permission Enforcement**: Role-based operation access
3. **Cache Consistency**: Proper cache invalidation on updates
4. **Event Publishing**: Async notification of customer changes
5. **Error Recovery**: Graceful handling of validation and system errors

***

## Future Enhancements

### Planned Features

1. **Customer Segmentation**: Advanced customer categorization
2. **Preference Management**: Detailed customer preferences
3. **Communication History**: Track all customer interactions
4. **Analytics Integration**: Customer behavior analysis
5. **Loyalty Programs**: Customer loyalty and rewards
6. **Marketing Automation**: Automated customer communication

### Scalability Improvements

1. **Read Replicas**: Optimize read performance
2. **Sharding Strategy**: Handle large customer datasets
3. **Event Sourcing**: Complete audit trail with events
4. **CQRS Optimization**: Separate read/write models
5. **Microservice Decomposition**: Split by business domains

***

## Summary

The Customer Management use cases provide a comprehensive foundation for handling customer operations within the Bee O'clock ecosystem. Key capabilities include:

* **Complete Customer Lifecycle**: From creation to deletion with validation
* **Order Integration**: Seamless customer handling in order processing
* **Payment Integration**: Customer information in payment workflows
* **Advanced Search**: Efficient customer discovery and management
* **Multi-Tenant Security**: Proper data isolation and access control
* **Performance Optimization**: Caching and efficient query patterns
* **Business Rule Enforcement**: Comprehensive validation and business logic
* **Event-Driven Architecture**: Async communication for scalability

The use cases support complex business scenarios while maintaining high performance, data integrity, and security standards across the customer management domain.


# Database Schema

## Overview

This document describes the database schema and data persistence layer for the Customer Management module. The system uses MongoDB as the primary database with Mongoose as the ODM layer, implementing multi-tenant architecture with proper data isolation and validation.

## Database Architecture

### Technology Stack

* **Database**: MongoDB
* **ODM**: Mongoose
* **Pattern**: Domain-Driven Design (DDD) with CQRS
* **Multi-Tenancy**: Tenant-based data isolation
* **State Management**: Soft delete with state history
* **Validation**: Domain-level validation with schema constraints

## Database Schema

### Customer Collection

**Collection Name:** `customer`

The customer collection stores all customer records with comprehensive customer information for business relationship management.

```typescript
{
  _id: ObjectId,                    // Primary key - auto-generated
  firstName: String,                // Customer first name (optional)
  lastName: String,                 // Customer last name (optional)
  phone: String,                    // Normalized phone number (optional)
  email: String,                    // Email address (optional)
  note: String,                     // Additional customer notes (optional)
  customerType: String,             // Customer type enum - REQUIRED with default
  stateHistory: [StateHistorySchema], // State tracking for soft deletes
  createdAt: Date,                  // Auto-generated creation timestamp
  updatedAt: Date                   // Auto-generated update timestamp
}
```

### Schema Definition

```typescript
export const CustomerSchema = new Schema<ICustomer>({
  firstName: { 
    type: String 
  },
  lastName: { 
    type: String 
  },
  phone: { 
    type: String 
  },
  email: { 
    type: String 
  },
  note: { 
    type: String 
  },
  customerType: { 
    type: String, 
    default: CustomerTypeEnum.regular, 
    enum: CustomerTypeEnum 
  },
  stateHistory: { 
    type: [StateHistorySchema], 
    default: [] 
  },
}, { 
  timestamps: true, 
  collection: Customer.name.toLowerCase() 
});
```

## Field Specifications

### Core Customer Fields

#### firstName (String, Optional)

* **Purpose**: Customer's first name
* **Validation**: No specific format validation
* **Usage**: Display names, personalization, search
* **Notes**: Part of mandatory field validation (at least one of firstName, lastName, email, phone required)

#### lastName (String, Optional)

* **Purpose**: Customer's last name
* **Validation**: No specific format validation
* **Usage**: Display names, formal communication, search
* **Notes**: Part of mandatory field validation

#### phone (String, Optional)

* **Purpose**: Customer contact phone number
* **Validation**:
  * Format validation using regex pattern
  * Automatic normalization (numbers only)
  * International format support
* **Storage**: Normalized format (numbers only)
* **Usage**: Contact, SMS notifications, duplicate detection
* **Notes**: Part of mandatory field validation and uniqueness checks

```typescript
// Phone validation pattern
/^(\+?\d{1,3}[-.\s]?)?(\(?\d{1,4}\)?[-.\s]?)?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}$/

// Normalization example
input: "+1 (555) 123-4567" → stored: "15551234567"
```

#### email (String, Optional)

* **Purpose**: Customer email address
* **Validation**:
  * Email format validation
  * Domain validation
* **Usage**: Communication, login, notifications, duplicate detection
* **Notes**: Part of mandatory field validation and uniqueness checks

```typescript
// Email validation pattern
/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
```

#### note (String, Optional)

* **Purpose**: Additional customer information and notes
* **Validation**: No specific validation
* **Usage**: Customer service notes, preferences, special instructions
* **Notes**: Free-form text field for business use

#### customerType (String, Required with Default)

* **Purpose**: Classification of customer type
* **Default**: `CustomerTypeEnum.regular`
* **Enum Values**:
  * `regular`: Standard registered customers
  * `unregistered`: Customers with basic information
  * `new`: First-time customers
  * `anonymous`: Minimal information customers
* **Usage**: Business logic, filtering, reporting
* **Validation**: Must be one of the enum values

### System Fields

#### \_id (ObjectId, Auto-generated)

* **Purpose**: Primary key identifier
* **Generation**: MongoDB auto-generated
* **Format**: 24-character hexadecimal string
* **Usage**: Unique customer identification, relationships
* **Indexing**: Automatic primary index

#### stateHistory (Array, StateHistorySchema)

* **Purpose**: Track customer state changes for soft delete
* **Default**: Empty array
* **Usage**: Soft delete, audit trail, state management
* **Structure**: Array of state change records
* **Notes**: Enables data retention and recovery

#### createdAt (Date, Auto-generated)

* **Purpose**: Record creation timestamp
* **Generation**: Mongoose automatic timestamp
* **Usage**: Audit trail, reporting, data lifecycle
* **Format**: ISO Date string

#### updatedAt (Date, Auto-generated)

* **Purpose**: Last modification timestamp
* **Generation**: Mongoose automatic timestamp on updates
* **Usage**: Audit trail, cache invalidation, conflict resolution
* **Format**: ISO Date string

## Embedded Schemas

### StateHistorySchema

```typescript
{
  state: String,           // Entity state (active, deleted, etc.)
  setAt: String,          // ISO timestamp of state change
  _id: false              // No auto-generated ID for subdocuments
}
```

**States**: Based on `EntityStateEnum`

* `active`: Normal operational state
* `deleted`: Soft deleted state
* `suspended`: Temporarily inactive
* `archived`: Long-term storage

## Validation Rules

### Domain-Level Validation

#### Mandatory Field Validation

At least one of the following fields must be provided:

* `firstName`
* `lastName`
* `email`
* `phone`

```typescript
private static validateMandatoryFields(props: ICustomer, fields: (keyof ICustomer)[]): Result<void> {
  const hasAtLeastOneProperty = fields.some(field => 
    props[field] !== undefined && props[field] !== '' && props[field] !== null
  );
  return hasAtLeastOneProperty ? 
    Result.ok() : 
    Result.fail<void>('At least one of the following properties must be provided: ' + fields.join(', '));
}
```

#### Email Validation

```typescript
private static validateEmail(email?: string): Result<void> {
  if (email && !/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)) {
    return Result.fail<void>('Invalid email format: ' + email);
  }
  return Result.ok();
}
```

#### Phone Validation

```typescript
private static validatePhone(phone?: string): Result<void> {
  if (phone && !/^(\+?\d{1,3}[-.\s]?)?(\(?\d{1,4}\)?[-.\s]?)?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}$/.test(phone)) {
    return Result.fail<void>('Invalid phone number format: ' + phone);
  }
  return Result.ok();
}
```

### Regular Customer Validation

For `CustomerTypeEnum.regular` customers, stricter validation applies:

Required fields:

* `email`: Must be provided and valid
* `phone`: Must be provided and valid

```typescript
public static createRegular(props: ICustomer): Result<Customer> {
  const requiredFields: (keyof ICustomer)[] = ['phone', 'email'];
  const fieldValidation = this.validateMandatoryFields(props, requiredFields);
  // Additional validation...
}
```

## Indexing Strategy

### Primary Indexes

```typescript
// Primary key index (automatic)
db.customer.createIndex({ "_id": 1 });

// Tenant-based queries (multi-tenancy support via application layer)
// Note: Customer collection uses business-level tenant isolation

// Email-based lookups
db.customer.createIndex({ 
  "email": 1 
}, { 
  sparse: true,
  name: "email_lookup" 
});

// Phone-based lookups
db.customer.createIndex({ 
  "phone": 1 
}, { 
  sparse: true,
  name: "phone_lookup" 
});

// Customer type filtering
db.customer.createIndex({ 
  "customerType": 1,
  "createdAt": -1 
}, {
  name: "type_date_filter"
});

// Soft delete state filtering
db.customer.createIndex({ 
  "stateHistory.state": 1 
}, {
  name: "state_filter"
});
```

### Composite Indexes

```typescript
// Email and phone uniqueness validation
db.customer.createIndex({ 
  "email": 1, 
  "phone": 1 
}, { 
  sparse: true,
  name: "contact_uniqueness"
});

// Customer search optimization
db.customer.createIndex({
  "firstName": "text",
  "lastName": "text",
  "email": "text"
}, {
  name: "customer_text_search"
});

// Customer type with creation date for pagination
db.customer.createIndex({
  "customerType": 1,
  "createdAt": -1,
  "_id": 1
}, {
  name: "type_pagination"
});
```

### Performance Optimization Indexes

```typescript
// Recently created customers
db.customer.createIndex({ 
  "createdAt": -1 
}, {
  name: "recent_customers"
});

// Recently updated customers
db.customer.createIndex({ 
  "updatedAt": -1 
}, {
  name: "recent_updates"
});

// Active customers only (excluding deleted)
db.customer.createIndex({
  "stateHistory.state": 1,
  "customerType": 1,
  "createdAt": -1
}, {
  partialFilterExpression: {
    "stateHistory.state": { $ne: "deleted" }
  },
  name: "active_customers"
});
```

## Query Patterns

### Common Queries

#### Find Customer by ID

```typescript
db.customer.findOne({
  "_id": ObjectId("customerId"),
  $expr: {
    $ne: [
      { $arrayElemAt: ["$stateHistory.state", -1] },
      "deleted"
    ]
  }
});
```

#### Find Customer by Email or Phone

```typescript
db.customer.findOne({
  $or: [
    { "email": "customer@example.com" },
    { "phone": "1234567890" }
  ],
  $expr: {
    $ne: [
      { $arrayElemAt: ["$stateHistory.state", -1] },
      "deleted"
    ]
  }
});
```

#### Customer Search with Pagination

```typescript
// Aggregation pipeline for customer search
const pipeline = [
  // Text search stage
  {
    $match: {
      $or: [
        { firstName: { $regex: searchTerm, $options: 'i' } },
        { lastName: { $regex: searchTerm, $options: 'i' } },
        { email: { $regex: searchTerm, $options: 'i' } },
        { $text: { $search: searchTerm } }
      ],
      $expr: {
        $ne: [
          { $arrayElemAt: ["$stateHistory.state", -1] },
          "deleted"
        ]
      }
    }
  },
  // Customer type filtering
  ...(customerType ? [{ $match: { customerType } }] : []),
  // Full name concatenation for search
  {
    $addFields: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] }
    }
  },
  // Sorting
  { $sort: { createdAt: -1 } },
  // Pagination
  { $skip: (page - 1) * limit },
  { $limit: limit }
];

db.customer.aggregate(pipeline);
```

#### Customer Type Statistics

```typescript
db.customer.aggregate([
  {
    $match: {
      $expr: {
        $ne: [
          { $arrayElemAt: ["$stateHistory.state", -1] },
          "deleted"
        ]
      }
    }
  },
  {
    $group: {
      _id: "$customerType",
      count: { $sum: 1 },
      recentCount: {
        $sum: {
          $cond: [
            { $gte: ["$createdAt", new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)] },
            1,
            0
          ]
        }
      }
    }
  }
]);
```

### Integration Queries

#### Customers for Order Processing

```typescript
// Find customers for attendee matching
db.customer.find({
  $or: [
    { email: { $in: attendeeEmails } },
    { phone: { $in: attendeePhones } }
  ],
  $expr: {
    $ne: [
      { $arrayElemAt: ["$stateHistory.state", -1] },
      "deleted"
    ]
  }
}).hint({ "email": 1, "phone": 1 });
```

#### First-Time Customer Detection

```typescript
// Check if customer is first-time (used in order processing)
function isFirstTimeCustomer(customerId, currentOrderDate) {
  const previousOrders = db.order.countDocuments({
    "attendees.customer._id": customerId,
    "createdAt": { $lt: currentOrderDate }
  });
  return previousOrders === 0;
}
```

## Multi-Tenancy

### Tenant Isolation Strategy

The Customer Management module implements tenant isolation at the **application layer** rather than database schema level. This approach provides:

* **Business-Level Isolation**: Each business (tenant) has isolated customer data
* **Shared Database**: All tenants share the same MongoDB database
* **Application Enforcement**: Tenant filtering applied in all repository queries
* **Performance**: Optimized queries with tenant-aware indexing

### Tenant Context Implementation

```typescript
// All repository methods include tenant context
interface CustomerRepositoryContext {
  tenantId: string;
  actor: Actor;
}

// Repository method example
async findCustomerById(id: string, tenantId: string): Promise<ICustomer | null> {
  return this.model.findOne({
    _id: id,
    // Tenant isolation implemented through business logic
    // Customer data is isolated per business via application layer
    $expr: {
      $ne: [
        { $arrayElemAt: ['$stateHistory.state', -1] },
        'deleted'
      ]
    }
  });
}
```

**Note**: Customer records are associated with businesses through the order and service context, not through a direct `tenantId` field in the customer collection. This design allows customers to potentially interact with multiple businesses while maintaining data integrity.

## Data Consistency

### Referential Integrity

#### Customer References in Orders

* **Orders**: Reference customers through embedded customer snapshots
* **Order Services**: Include customer data in attendee arrays
* **Payment Records**: Link to customer information for payer details

#### Customer Data Snapshots

When customers are referenced in orders or payments, their current data is snapshot:

```typescript
// Customer snapshot in order context
{
  orderId: "order123",
  attendees: [{
    customer: {
      _id: "customer456",
      firstName: "John",
      lastName: "Doe",
      email: "john.doe@example.com",
      phone: "1234567890",
      customerType: "regular"
    },
    firstTime: true
  }]
}
```

### State Management

#### Soft Delete Implementation

```typescript
// Soft delete operation
async deleteCustomer(customerId: string): Promise<void> {
  await this.model.updateOne(
    { _id: customerId },
    {
      $push: {
        stateHistory: {
          state: 'deleted',
          setAt: new Date().toISOString()
        }
      }
    }
  );
}

// Query excluding deleted customers
const activeCustomers = await this.model.find({
  $expr: {
    $ne: [
      { $arrayElemAt: ['$stateHistory.state', -1] },
      'deleted'
    ]
  }
});
```

#### State History Tracking

* **State Changes**: All state transitions are recorded
* **Audit Trail**: Complete history of customer lifecycle
* **Recovery**: Ability to restore soft-deleted customers
* **Compliance**: Data retention for regulatory requirements

## Performance Optimization

### Query Optimization

#### Index Utilization

```typescript
// Optimized customer search query
db.customer.find({
  $or: [
    { firstName: { $regex: searchTerm, $options: 'i' } },
    { lastName: { $regex: searchTerm, $options: 'i' } },
    { email: { $regex: searchTerm, $options: 'i' } }
  ],
  $expr: {
    $ne: [
      { $arrayElemAt: ['$stateHistory.state', -1] },
      'deleted'
    ]
  }
}).hint({ firstName: 'text', lastName: 'text', email: 'text' });
```

#### Pagination Optimization

```typescript
// Cursor-based pagination for large datasets
db.customer.find({
  _id: { $gt: lastCustomerId },
  customerType: 'regular',
  $expr: {
    $ne: [
      { $arrayElemAt: ['$stateHistory.state', -1] },
      'deleted'
    ]
  }
}).sort({ _id: 1 }).limit(pageSize);
```

### Memory Management

#### Field Projection

```typescript
// Load only required fields for list views
db.customer.find(
  { /* query criteria */ },
  { 
    firstName: 1, 
    lastName: 1, 
    email: 1, 
    customerType: 1,
    createdAt: 1 
  }
);
```

#### Aggregation Optimization

```typescript
// Efficient customer statistics
db.customer.aggregate([
  {
    $match: {
      $expr: {
        $ne: [
          { $arrayElemAt: ['$stateHistory.state', -1] },
          'deleted'
        ]
      }
    }
  },
  {
    $group: {
      _id: '$customerType',
      count: { $sum: 1 },
      avgCreationTime: { $avg: '$createdAt' }
    }
  }
], { allowDiskUse: true });
```

## Data Migration

### Schema Evolution

When schema changes are needed:

1. **Backward Compatible**: Add optional fields first
2. **Migration Scripts**: Create scripts for data transformation
3. **Field Addition**: New fields with defaults
4. **Validation Updates**: Enhance validation without breaking existing data

### Example Migration Scripts

#### Add Customer Notes Field

```javascript
// Migration script for adding notes field
db.customer.updateMany(
  { note: { $exists: false } },
  { $set: { note: "" } }
);
```

#### Customer Type Migration

```javascript
// Migration script for customer type normalization
db.customer.updateMany(
  { customerType: { $exists: false } },
  { $set: { customerType: "regular" } }
);

// Update deprecated customer types
db.customer.updateMany(
  { customerType: "legacy" },
  { $set: { customerType: "regular" } }
);
```

#### Phone Number Normalization

```javascript
// Migration script for phone number normalization
db.customer.find({ phone: { $exists: true, $ne: null } }).forEach(function(customer) {
  if (customer.phone) {
    const normalizedPhone = customer.phone.replace(/[^\d]/g, '');
    db.customer.updateOne(
      { _id: customer._id },
      { $set: { phone: normalizedPhone } }
    );
  }
});
```

## Backup and Recovery

### Backup Strategy

1. **Regular Snapshots**: Daily MongoDB snapshots
2. **Point-in-Time Recovery**: Enable oplog for PITR
3. **Cross-Region Replication**: For disaster recovery
4. **Testing**: Regular backup restoration testing

### Data Retention

1. **Active Data**: Keep in primary collection
2. **Soft Deleted**: Retain for compliance period
3. **Hard Delete**: After legal retention requirements
4. **Archival**: Long-term storage for historical analysis

## Security Considerations

### Data Protection

#### PII Handling

* **Encryption**: Sensitive fields encrypted at rest
* **Access Control**: Role-based access to customer data
* **Audit Logging**: All customer data access logged
* **Data Masking**: PII masked in non-production environments

#### Privacy Compliance

**GDPR Support**:

* **Right to Portability**: Export customer data
* **Right to Erasure**: Hard delete on request
* **Consent Tracking**: Customer consent preferences
* **Data Processing**: Lawful basis documentation

**Implementation Example**:

```typescript
// GDPR data export
async exportCustomerData(customerId: string): Promise<CustomerExportDto> {
  const customer = await this.customerRepository.findById(customerId);
  const orders = await this.orderRepository.findByCustomer(customerId);
  const payments = await this.paymentRepository.findByCustomer(customerId);
  
  return {
    personalData: customer,
    orderHistory: orders,
    paymentHistory: payments,
    exportDate: new Date().toISOString()
  };
}

// GDPR data deletion
async deleteCustomerData(customerId: string): Promise<void> {
  // Hard delete customer data
  await this.customerRepository.hardDelete(customerId);
  // Anonymize order history
  await this.orderRepository.anonymizeCustomerData(customerId);
  // Remove payment references
  await this.paymentRepository.anonymizeCustomerData(customerId);
}
```

### Access Control

#### Database Security

* **Authentication**: MongoDB authentication required
* **Authorization**: Database-level permissions
* **Network Security**: VPC and firewall protection
* **Encryption**: TLS for data in transit

#### Application Security

* **Input Validation**: All inputs validated and sanitized
* **SQL Injection Prevention**: Parameterized queries (NoSQL injection)
* **Rate Limiting**: API rate limiting for customer operations
* **Session Management**: Secure session handling

## Monitoring and Diagnostics

### Performance Monitoring

#### Key Metrics

* **Query Performance**: Average query execution time
* **Index Usage**: Index hit ratios and efficiency
* **Collection Growth**: Data volume trends
* **Connection Pool**: Database connection utilization

#### Monitoring Queries

```javascript
// Slow query detection
db.runCommand({
  profile: 2,
  slowms: 100,
  filter: { ns: "database.customer" }
});

// Index usage statistics
db.customer.aggregate([
  { $indexStats: {} }
]);

// Collection statistics
db.customer.stats();
```

### Error Monitoring

#### Common Issues

* **Validation Errors**: Field format validation failures
* **Duplicate Detection**: Email/phone uniqueness violations
* **State Consistency**: State history integrity issues
* **Performance**: Slow query identification

#### Diagnostic Queries

```javascript
// Find customers with validation issues
db.customer.find({
  $or: [
    { email: { $exists: true, $not: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ } },
    { customerType: { $nin: ["regular", "unregistered", "new", "anonymous"] } }
  ]
});

// Find duplicate customers
db.customer.aggregate([
  {
    $match: {
      email: { $exists: true, $ne: null }
    }
  },
  {
    $group: {
      _id: "$email",
      count: { $sum: 1 },
      customers: { $push: "$$ROOT" }
    }
  },
  {
    $match: { count: { $gt: 1 } }
  }
]);
```

## Integration Points

### Order Management Integration

#### Customer-Order Relationships

* **Attendees**: Customers linked as service attendees
* **Payers**: Customers linked as payment payers
* **History**: Customer order history tracking
* **Preferences**: Customer service preferences

#### Data Flow

```typescript
// Order creation with customer integration
async createOrderWithCustomers(orderData: CreateOrderDto): Promise<Order> {
  // Process attendees
  const processedAttendees = await this.processAttendees(orderData.attendees);
  
  // Create or update customers
  const customers = await Promise.all(
    processedAttendees.map(attendee => 
      this.createOrUpdateCustomer(attendee.customer)
    )
  );
  
  // Create order with customer snapshots
  return this.orderService.create({
    ...orderData,
    attendees: processedAttendees.map((attendee, index) => ({
      ...attendee,
      customer: customers[index]
    }))
  });
}
```

### Payment System Integration

#### Customer-Payment Relationships

* **Payer Information**: Customer as payment payer
* **Billing History**: Customer payment history
* **Payment Methods**: Customer preferred payment methods
* **Invoicing**: Customer billing information

### Notification System Integration

#### Customer Communication

* **Email Notifications**: Order confirmations, reminders
* **SMS Notifications**: Appointment reminders via phone
* **Push Notifications**: Mobile app notifications
* **Marketing**: Customer segmentation for campaigns

## Summary

The Customer Management database schema provides a robust foundation for customer relationship management within the Bee O'clock ecosystem. Key features include:

* **Flexible Schema**: Optional fields supporting various customer types
* **Data Validation**: Comprehensive validation at domain and schema levels
* **Multi-Tenant Architecture**: Business-level data isolation
* **Performance Optimization**: Strategic indexing and query optimization
* **State Management**: Soft delete with complete audit trail
* **Integration Ready**: Seamless integration with orders and payments
* **GDPR Compliance**: Privacy and data protection features
* **Scalability**: Designed for high-volume customer data
* **Monitoring**: Comprehensive performance and error tracking

The schema supports complex business scenarios while maintaining data integrity, performance, and compliance with privacy regulations.


# Expense Management

## Overview

The Expense Management module is a comprehensive system for managing business expenses within the Bee O'clock panel service. It provides robust functionality for creating, tracking, categorizing, and reporting on business expenses with support for itemized breakdowns, multi-currency operations, and detailed financial tracking.

This module follows Domain-Driven Design (DDD) principles, implements Clean Architecture patterns, and supports multi-tenancy with comprehensive audit trails and soft delete functionality.

## Key Features

### Core Functionality

* **Expense Creation & Management**: Create, update, and delete expense records with comprehensive validation
* **Itemized Expenses**: Support for detailed line-item breakdowns with individual categorization
* **Multi-Currency Support**: Handle expenses in multiple currencies with automatic validation
* **Expense Categories**: Flexible categorization system for organizing and filtering expenses
* **Advanced Search & Filtering**: Text search, date range filtering, and category-based filtering
* **Pagination**: Efficient pagination for large expense datasets

### Business Capabilities

* **Financial Tracking**: Complete expense lifecycle management with audit trails
* **Reporting & Analytics**: Support for financial reporting and expense analysis
* **Source Tracking**: Track expense sources (members, suppliers, resources, products)
* **Bulk Operations**: Efficient bulk creation of categories and batch expense processing
* **Data Integrity**: Comprehensive validation rules and business logic enforcement

### Technical Features

* **Multi-Tenancy**: Complete tenant isolation and data security
* **Soft Delete**: Preserve historical data while maintaining clean active datasets
* **CQRS Pattern**: Separate command and query operations for optimal performance
* **Rich Domain Models**: Value objects and aggregate roots with business behavior
* **Comprehensive API**: RESTful API with detailed documentation and error handling

## Architecture

### Domain-Driven Design Structure

```
expense-management/
├── domain/                     # Core business logic and rules
│   ├── interfaces/            # Repository and service contracts
│   ├── value-objects/         # Immutable business value objects
│   ├── enums/                 # Domain enumerations
│   └── aggregates/            # Aggregate roots and entities
├── application/               # Use cases and application services
│   ├── use-cases/            # Business use case implementations
│   ├── dtos/                 # Data transfer objects
│   ├── mappers/              # Domain-DTO mapping logic
│   └── interfaces/           # Use case contracts
├── infrastructure/           # External concerns and persistence
│   ├── persistence/          # Database schemas and repositories
│   ├── controllers/          # HTTP endpoints and routing
│   └── config/              # Module configuration
└── test/                    # Comprehensive test suites
```

### Clean Architecture Layers

1. **Domain Layer**: Core business logic, entities, value objects, and business rules
2. **Application Layer**: Use cases, DTOs, and application-specific business logic
3. **Infrastructure Layer**: Database access, external services, and framework concerns
4. **Presentation Layer**: Controllers, API endpoints, and request/response handling

## Core Entities

### Expense Entity

The central aggregate root representing a business expense with the following characteristics:

* **Total Value**: Monetary amount with currency specification
* **Expense Date**: When the expense was incurred
* **Description**: Optional textual description for context
* **Line Items**: Detailed breakdown of expense components
* **Audit Trail**: Creation and modification timestamps

### Expense Category Entity

Categorization tags for organizing and filtering expenses:

* **Name**: Unique identifier within tenant scope
* **Description**: Optional detailed description
* **Tenant Scoping**: Multi-tenant isolation

### Value Objects

* **ExpenseValue**: Immutable monetary amount with currency
* **ExpenseItem**: Line item with categorization and source information
* **ExpenseSource**: Reference to the origin entity (member, supplier, etc.)

## API Endpoints

### Expense Operations

* `GET /api/v1/expense/paged` - Retrieve paginated expenses with filtering
* `GET /api/v1/expense/{id}` - Get specific expense by ID
* `POST /api/v1/expense` - Create new expense
* `PUT /api/v1/expense/{id}` - Update existing expense
* `DELETE /api/v1/expense/{id}` - Delete expense (soft delete)

### Category Management

* `GET /api/v1/expense/category/paged` - List expense categories
* `POST /api/v1/expense/category` - Create single category
* `POST /api/v1/expense/category/bulk` - Create multiple categories

For detailed API documentation, see [API Documentation](/services/expense-management/api).

## Business Rules

### Expense Validation

1. **Amount Constraints**: All amounts must be positive with maximum limits
2. **Currency Consistency**: All line items must use the same currency
3. **Date Validation**: Expense dates within reasonable historical and future ranges
4. **Total Validation**: Sum of line items must match total amount (within tolerance)
5. **Required Fields**: Essential fields must be provided and non-empty

### Category Management

1. **Uniqueness**: Category names must be unique within tenant scope
2. **Naming Rules**: Alphanumeric characters, hyphens, underscores, and spaces only
3. **Length Limits**: Names limited to 50 characters, descriptions to 500
4. **Case Insensitive**: Names stored in lowercase for consistency

### Data Integrity

1. **Soft Delete**: Logical deletion preserves historical references
2. **Audit Trail**: All changes tracked with timestamps and user context
3. **Reference Integrity**: Category and source references validated
4. **Tenant Isolation**: All operations scoped to appropriate tenant

## Database Schema

### Collections

* **expenses**: Main expense records with embedded line items
* **expense-categories**: Categorization tags for expense organization

### Key Indexes

* Tenant + date range queries for performance
* Text search indexes for description fields
* Category filtering with compound indexes
* Archive status for soft delete filtering

For complete schema documentation, see [Database Schema](/services/expense-management/db_schema).

## Use Cases

### Command Operations

* **CreateExpenseUseCase**: Create new expenses with validation
* **UpdateExpenseUseCase**: Modify existing expenses
* **DeleteExpenseUseCase**: Soft delete expense records
* **CreateExpenseCategoryUseCase**: Add new expense categories
* **CreateManyExpenseCategoriesUseCase**: Bulk category creation

### Query Operations

* **GetPagedExpensesUseCase**: Retrieve filtered and paginated expenses
* **GetExpenseByIdUseCase**: Fetch specific expense details
* **GetPagedExpenseCategoriesUseCase**: List available categories

For detailed use case documentation, see [Use Cases](/services/expense-management/usecase).

## Integration

### Dependency Injection

The module integrates with NestJS dependency injection system using tokens:

```typescript
// Repository tokens
EXPENSE_REPOSITORY_TOKEN
EXPENSE_CATEGORY_REPOSITORY_TOKEN

// Use case tokens
CREATE_EXPENSE_USE_CASE_TOKEN
GET_PAGED_EXPENSES_USE_CASE_TOKEN
// ... additional use case tokens
```

### Module Configuration

```typescript
@Module({
  imports: [CommonModule, DatabaseModule],
  controllers: [ExpensesController],
  providers: [
    // Repository implementations
    { provide: EXPENSE_REPOSITORY_TOKEN, useClass: ExpenseRepository },
    { provide: EXPENSE_CATEGORY_REPOSITORY_TOKEN, useClass: ExpenseCategoryRepository },
    
    // Use case implementations
    { provide: CREATE_EXPENSE_USE_CASE_TOKEN, useClass: CreateExpenseUseCase },
    { provide: GET_PAGED_EXPENSES_USE_CASE_TOKEN, useClass: GetPagedExpensesUseCase },
    // ... additional use cases
  ],
  exports: [
    EXPENSE_REPOSITORY_TOKEN,
    EXPENSE_CATEGORY_REPOSITORY_TOKEN
  ]
})
export class ExpenseModule {}
```

## Error Handling

### Error Types

* **Validation Errors**: Invalid input data or business rule violations
* **Not Found Errors**: Requested expenses or categories don't exist
* **Conflict Errors**: Duplicate category names or constraint violations
* **Business Rule Errors**: Domain-specific rule violations

### Error Response Format

```typescript
{
  statusCode: number;
  message: string;
  error: string;
  type?: string;        // Specific error type for client handling
  field?: string;       // Field causing validation error
  timestamp: string;
  path: string;
}
```

## Security

### Access Control

* **Permission-based access**: Role-based permissions for different operations
* **Tenant isolation**: Automatic filtering by tenant context
* **Input validation**: Comprehensive validation of all inputs
* **Rate limiting**: API rate limits to prevent abuse

### Data Protection

* **Encryption**: Sensitive financial data encryption at rest
* **Audit logging**: Complete audit trail for compliance
* **Soft delete**: Preserve data for audit while maintaining clean operations
* **Input sanitization**: Protection against injection attacks

## Performance

### Query Optimization

* **Strategic indexing**: Compound indexes for common query patterns
* **Pagination**: Efficient pagination for large datasets
* **Caching**: Category data caching for frequently accessed information
* **Text search**: Optimized full-text search capabilities

### Bulk Operations

* **Batch processing**: Efficient bulk operations for categories and expenses
* **Transaction management**: Atomic operations for data consistency
* **Chunked processing**: Large datasets processed in manageable chunks

## Testing

### Test Structure

```
test/
├── unit/                      # Unit tests for individual components
│   ├── domain/               # Domain logic and value object tests
│   ├── application/          # Use case and service tests
│   └── infrastructure/       # Repository and controller tests
├── integration/              # Integration tests for module interactions
└── e2e/                      # End-to-end API tests
```

### Test Patterns

* **Mock repositories**: Isolated unit testing of use cases
* **Test builders**: Flexible test data creation
* **Integration tests**: Database and module integration validation
* **API tests**: Complete request/response cycle testing

## Development Guidelines

### Code Standards

* **TypeScript**: Strict type checking and modern ES features
* **Clean Architecture**: Clear separation of concerns and dependencies
* **DDD Principles**: Rich domain models with business behavior
* **SOLID Principles**: Single responsibility and dependency inversion

### Best Practices

* **Immutable Value Objects**: Prevent accidental state mutations
* **Explicit Error Handling**: Clear error types and meaningful messages
* **Comprehensive Validation**: Input validation at multiple layers
* **Documentation**: Comprehensive inline and external documentation

## Monitoring

### Business Metrics

* **Expense creation rate**: Track expense entry patterns
* **Category usage**: Monitor category adoption and usage
* **Error rates**: Track validation and business rule violations
* **Performance metrics**: Query execution times and optimization needs

### Operational Monitoring

* **Database performance**: Index usage and query optimization
* **API response times**: Endpoint performance monitoring
* **Error tracking**: Comprehensive error logging and alerting
* **Resource usage**: Memory and CPU utilization patterns

## Future Enhancements

### Planned Features

* **Expense Approval Workflow**: Multi-level approval processes
* **Automated Categorization**: Machine learning-based category suggestions
* **Receipt Management**: Image upload and OCR processing
* **Advanced Reporting**: Custom reports and dashboard widgets
* **Budget Integration**: Expense budget tracking and alerts

### Technical Improvements

* **Real-time Updates**: WebSocket-based real-time expense updates
* **Advanced Caching**: Redis-based caching for improved performance
* **Event Sourcing**: Complete audit trail with event sourcing patterns
* **Microservice Split**: Potential service decomposition for scale

## Related Documentation

* [API Documentation](/services/expense-management/api) - Comprehensive API endpoint documentation
* [Interface Documentation](/services/expense-management/interface) - Domain interfaces and contracts
* [Use Case Documentation](/services/expense-management/usecase) - Business use case implementations
* [Database Schema](/services/expense-management/db_schema) - Complete database schema and optimization

## Contributing

### Development Setup

1. Clone the repository and install dependencies
2. Configure environment variables for database and services
3. Run database migrations to set up schema
4. Execute tests to validate setup
5. Start development server

### Code Review Process

1. Follow established coding standards and patterns
2. Include comprehensive tests for new functionality
3. Update documentation for API or behavior changes
4. Validate performance impact of changes
5. Ensure security review for sensitive operations

### Deployment

1. Run full test suite including integration tests
2. Validate database migration scripts
3. Review security configurations
4. Monitor performance after deployment
5. Validate business metrics and error rates

For technical questions or contributions, please refer to the main project documentation or contact the development team.


# API Documentation

## Overview

The Expense Management API provides comprehensive functionality for managing business expenses and expense categories within the Bee O'clock panel service. This module handles the complete expense lifecycle, including creation, updates, categorization, deletion, and detailed tracking of expense items with multi-currency support.

## Base Configuration

### Authentication

All endpoints require Bearer token authentication.

### Headers

* `Authorization: Bearer <token>` - Required for all endpoints
* `x-business-tenant-id: <tenant_id>` - Required for multi-tenancy support
* `Content-Type: application/json` - For POST/PUT requests

### Base URL

```
/api/v1/expense
```

## Expense Endpoints

### 1. Get Paginated Expenses

**Endpoint:** `GET /api/v1/expense/paged`

**Description:** Retrieves a paginated list of expenses with advanced filtering capabilities.

**Query Parameters:**

```typescript
{
  page?: number;           // Page number (default: 1)
  size?: number;           // Items per page (default: 10)
  phrase?: string;         // Search phrase for expense description
  start?: string;          // Start date filter (ISO string)
  end?: string;            // End date filter (ISO string)
  expenseCategories?: string[]; // Filter by expense categories
}
```

**Response:**

```typescript
{
  items: ExpenseDto[];
  totalSize: number;
}
```

**Example Request:**

```bash
GET /api/v1/expense/paged?page=1&size=10&phrase=office&start=2024-01-01T00:00:00.000Z&end=2024-12-31T23:59:59.999Z&expenseCategories[]=office-supplies&expenseCategories[]=utilities
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64fa1c71b19d6d001c88a91f",
      "object": "ExpenseDto",
      "totalValue": {
        "object": "ExpenseValueDto",
        "amount": 450.75,
        "currency": "USD"
      },
      "expensedAt": "2024-07-26T10:00:00.000Z",
      "description": "Office supplies and equipment purchase",
      "items": [
        {
          "object": "ExpenseLineItemDto",
          "categories": [
            {
              "_id": "64fa1c71b19d6d001c88a920",
              "object": "ExpenseCategoryDto",
              "name": "office-supplies",
              "description": "General office supplies and materials"
            }
          ],
          "itemValue": {
            "object": "ExpenseValueDto",
            "amount": 275.50,
            "currency": "USD"
          },
          "description": "Desk chairs and office furniture",
          "source": {
            "object": "ExpenseSourceDto",
            "sourceId": "64fa1c71b19d6d001c88a921",
            "sourceType": "supplier",
            "name": "Office Depot",
            "description": "Office furniture supplier"
          }
        },
        {
          "object": "ExpenseLineItemDto",
          "categories": [
            {
              "_id": "64fa1c71b19d6d001c88a922",
              "object": "ExpenseCategoryDto",
              "name": "technology",
              "description": "Technology equipment and software"
            }
          ],
          "itemValue": {
            "object": "ExpenseValueDto",
            "amount": 175.25,
            "currency": "USD"
          },
          "description": "Computer peripherals and accessories",
          "source": {
            "object": "ExpenseSourceDto",
            "sourceId": "64fa1c71b19d6d001c88a923",
            "sourceType": "supplier",
            "name": "Best Buy",
            "description": "Technology equipment supplier"
          }
        }
      ],
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:30:00.000Z"
    }
  ],
  "totalSize": 45
}
```

### 2. Get Expense by ID

**Endpoint:** `GET /api/v1/expense/{id}`

**Description:** Retrieves a specific expense by its ID with permission validation.

**Path Parameters:**

* `id` (string, required) - Expense ID

**Response:** `ExpenseDto`

**Example Request:**

```bash
GET /api/v1/expense/64fa1c71b19d6d001c88a91f
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a91f",
  "object": "ExpenseDto",
  "totalValue": {
    "object": "ExpenseValueDto",
    "amount": 1250.00,
    "currency": "USD"
  },
  "expensedAt": "2024-07-26T10:00:00.000Z",
  "description": "Monthly salary payment for staff",
  "items": [
    {
      "object": "ExpenseLineItemDto",
      "categories": [
        {
          "_id": "64fa1c71b19d6d001c88a924",
          "object": "ExpenseCategoryDto",
          "name": "salary",
          "description": "Employee salary and compensation"
        }
      ],
      "itemValue": {
        "object": "ExpenseValueDto",
        "amount": 800.00,
        "currency": "USD"
      },
      "description": "Base salary for massage therapist",
      "source": {
        "object": "ExpenseSourceDto",
        "sourceId": "64fa1c71b19d6d001c88a925",
        "sourceType": "member",
        "name": "Jane Smith",
        "description": "Senior massage therapist"
      }
    },
    {
      "object": "ExpenseLineItemDto",
      "categories": [
        {
          "_id": "64fa1c71b19d6d001c88a924",
          "object": "ExpenseCategoryDto",
          "name": "salary",
          "description": "Employee salary and compensation"
        }
      ],
      "itemValue": {
        "object": "ExpenseValueDto",
        "amount": 450.00,
        "currency": "USD"
      },
      "description": "Part-time receptionist salary",
      "source": {
        "object": "ExpenseSourceDto",
        "sourceId": "64fa1c71b19d6d001c88a926",
        "sourceType": "member",
        "name": "Mike Johnson",
        "description": "Front desk receptionist"
      }
    }
  ],
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:30:00.000Z"
}
```

### 3. Create Expense

**Endpoint:** `POST /api/v1/expense`

**Description:** Creates a new expense with validation and permission checks.

**Request Body:** `ExpenseDto`

**Response:** `ExpenseDto`

**Example Request:**

```bash
POST /api/v1/expense
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "totalValue": {
    "amount": 320.50,
    "currency": "USD"
  },
  "expensedAt": "2024-07-26T14:00:00.000Z",
  "description": "Monthly utility bills payment",
  "items": [
    {
      "categories": [
        {
          "name": "utilities",
          "description": "Utility bills and services"
        }
      ],
      "itemValue": {
        "amount": 180.00,
        "currency": "USD"
      },
      "description": "Electricity bill for spa facility",
      "source": {
        "sourceId": "64fa1c71b19d6d001c88a927",
        "sourceType": "supplier",
        "name": "Electric Company",
        "description": "Local electricity provider"
      }
    },
    {
      "categories": [
        {
          "name": "utilities",
          "description": "Utility bills and services"
        }
      ],
      "itemValue": {
        "amount": 85.50,
        "currency": "USD"
      },
      "description": "Water and sewer services",
      "source": {
        "sourceId": "64fa1c71b19d6d001c88a928",
        "sourceType": "supplier",
        "name": "Water Department",
        "description": "Municipal water services"
      }
    },
    {
      "categories": [
        {
          "name": "utilities",
          "description": "Utility bills and services"
        }
      ],
      "itemValue": {
        "amount": 55.00,
        "currency": "USD"
      },
      "description": "Internet and phone services",
      "source": {
        "sourceId": "64fa1c71b19d6d001c88a929",
        "sourceType": "supplier",
        "name": "Telecom Provider",
        "description": "Business internet and phone services"
      }
    }
  ]
}
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a930",
  "object": "ExpenseDto",
  "totalValue": {
    "object": "ExpenseValueDto",
    "amount": 320.50,
    "currency": "USD"
  },
  "expensedAt": "2024-07-26T14:00:00.000Z",
  "description": "Monthly utility bills payment",
  "items": [
    {
      "object": "ExpenseLineItemDto",
      "categories": [
        {
          "_id": "64fa1c71b19d6d001c88a931",
          "object": "ExpenseCategoryDto",
          "name": "utilities",
          "description": "Utility bills and services"
        }
      ],
      "itemValue": {
        "object": "ExpenseValueDto",
        "amount": 180.00,
        "currency": "USD"
      },
      "description": "Electricity bill for spa facility",
      "source": {
        "object": "ExpenseSourceDto",
        "sourceId": "64fa1c71b19d6d001c88a927",
        "sourceType": "supplier",
        "name": "Electric Company",
        "description": "Local electricity provider"
      }
    }
  ],
  "createdAt": "2024-07-26T14:00:00.000Z",
  "updatedAt": "2024-07-26T14:00:00.000Z"
}
```

### 4. Update Expense

**Endpoint:** `PUT /api/v1/expense/{id}`

**Description:** Updates an existing expense with validation and permission checks.

**Path Parameters:**

* `id` (string, required) - Expense ID

**Request Body:** `ExpenseDto`

**Response:** `ExpenseDto`

**Example Request:**

```bash
PUT /api/v1/expense/64fa1c71b19d6d001c88a930
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "_id": "64fa1c71b19d6d001c88a930",
  "totalValue": {
    "amount": 340.75,
    "currency": "USD"
  },
  "expensedAt": "2024-07-26T14:00:00.000Z",
  "description": "Monthly utility bills payment - Updated",
  "items": [
    {
      "categories": [
        {
          "name": "utilities",
          "description": "Utility bills and services"
        }
      ],
      "itemValue": {
        "amount": 200.25,
        "currency": "USD"
      },
      "description": "Electricity bill for spa facility - Higher usage",
      "source": {
        "sourceId": "64fa1c71b19d6d001c88a927",
        "sourceType": "supplier",
        "name": "Electric Company",
        "description": "Local electricity provider"
      }
    }
  ]
}
```

### 5. Delete Expense

**Endpoint:** `DELETE /api/v1/expense/{id}`

**Description:** Deletes an expense with permission validation.

**Path Parameters:**

* `id` (string, required) - Expense ID

**Response:** `void` (204 No Content)

**Example Request:**

```bash
DELETE /api/v1/expense/64fa1c71b19d6d001c88a930
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Expense Category Endpoints

### 1. Get Paginated Expense Categories

**Endpoint:** `GET /api/v1/expense/category/paged`

**Description:** Retrieves a paginated list of expense categories.

**Query Parameters:**

```typescript
{
  page?: number;           // Page number (default: 1)
  size?: number;           // Items per page (default: 10)
}
```

**Response:**

```typescript
{
  items: ExpenseCategoryDto[];
  totalSize: number;
}
```

**Example Request:**

```bash
GET /api/v1/expense/category/paged?page=1&size=20
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64fa1c71b19d6d001c88a931",
      "object": "ExpenseCategoryDto",
      "name": "salary",
      "description": "Employee salary and compensation expenses",
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:00:00.000Z"
    },
    {
      "_id": "64fa1c71b19d6d001c88a932",
      "object": "ExpenseCategoryDto",
      "name": "utilities",
      "description": "Utility bills and facility services",
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:00:00.000Z"
    },
    {
      "_id": "64fa1c71b19d6d001c88a933",
      "object": "ExpenseCategoryDto",
      "name": "office-supplies",
      "description": "General office supplies and materials",
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:00:00.000Z"
    }
  ],
  "totalSize": 15
}
```

### 2. Create Expense Category

**Endpoint:** `POST /api/v1/expense/category`

**Description:** Creates a new expense category with validation.

**Request Body:** `ExpenseCategoryDto`

**Response:** `void` (201 Created)

**Example Request:**

```bash
POST /api/v1/expense/category
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "name": "marketing",
  "description": "Marketing and advertising expenses"
}
```

### 3. Create Multiple Expense Categories

**Endpoint:** `POST /api/v1/expense/category/bulk`

**Description:** Creates multiple expense categories in a single request.

**Request Body:** `ExpenseCategoryDto[]`

**Response:** `void` (201 Created)

**Example Request:**

```bash
POST /api/v1/expense/category/bulk
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

[
  {
    "name": "marketing",
    "description": "Marketing and advertising expenses"
  },
  {
    "name": "travel",
    "description": "Business travel and transportation expenses"
  },
  {
    "name": "training",
    "description": "Employee training and professional development"
  }
]
```

## Data Models

### ExpenseDto

```typescript
{
  _id?: string;                              // Expense ID
  object?: 'ExpenseDto';                     // Object type identifier
  totalValue: ExpenseValueDto;               // Total amount of the expense
  expensedAt: string;                        // Date of the expense (ISO string)
  description?: string;                      // Optional description
  items?: ExpenseItemDto[];                  // Array of expense line items
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### ExpenseValueDto

```typescript
{
  object?: 'ExpenseValueDto';                // Object type identifier
  amount: number;                            // Expense amount
  currency: CurrencyCodeEnum;                // Currency code (USD, EUR, etc.)
}
```

### ExpenseItemDto

```typescript
{
  object?: 'ExpenseLineItemDto';             // Object type identifier
  categories: ExpenseCategoryDto[];          // Array of categorizing tags
  itemValue: ExpenseValueDto;                // Total price for this line item
  description: string;                       // Description for this line item
  source: ExpenseSourceDto;                  // Associated product, resource, or member
}
```

### ExpenseSourceDto

```typescript
{
  object?: 'ExpenseSourceDto';               // Object type identifier
  sourceId: string;                          // ID of the source entity
  sourceType: ExpenseSourceTypeEnum;         // Type of the source
  name?: string;                             // Name of the entity
  description?: string;                      // Optional description
}
```

### ExpenseCategoryDto

```typescript
{
  _id?: string;                              // Category ID
  object?: 'ExpenseCategoryDto';             // Object type identifier
  name: string;                              // Category name
  description?: string;                      // Optional description
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### ExpensePaginationDto

```typescript
{
  page?: number;                             // Page number (default: 1)
  size?: number;                             // Items per page (default: 10)
  phrase?: string;                           // Search phrase for description
  start?: string;                            // Start date filter (ISO string)
  end?: string;                              // End date filter (ISO string)
  expenseCategories?: string[];              // Filter by expense categories
}
```

## Enums

### ExpenseSourceTypeEnum

```typescript
enum ExpenseSourceTypeEnum {
  member = 'member',                         // Employee/staff member
  resource = 'resource',                     // Business resource
  product = 'product',                       // Product or inventory item
  supplier = 'supplier'                      // External supplier/vendor
}
```

### CurrencyCodeEnum

```typescript
enum CurrencyCodeEnum {
  USD = 'USD',                               // US Dollar
  EUR = 'EUR',                               // Euro
  GBP = 'GBP',                               // British Pound
  CAD = 'CAD',                               // Canadian Dollar
  AUD = 'AUD',                               // Australian Dollar
  JPY = 'JPY',                               // Japanese Yen
  CHF = 'CHF',                               // Swiss Franc
  CNY = 'CNY',                               // Chinese Yuan
  INR = 'INR',                               // Indian Rupee
  BRL = 'BRL',                               // Brazilian Real
  MXN = 'MXN',                               // Mexican Peso
  ZAR = 'ZAR'                                // South African Rand
}
```

## Error Handling

### Common Error Responses

#### 400 Bad Request

```json
{
  "statusCode": 400,
  "message": "Validation failed",
  "error": "Bad Request",
  "details": [
    {
      "field": "totalValue.amount",
      "message": "Amount must be a positive number"
    },
    {
      "field": "expensedAt",
      "message": "Expense date is required"
    }
  ]
}
```

#### 401 Unauthorized

```json
{
  "statusCode": 401,
  "message": "Unauthorized",
  "error": "Authentication required"
}
```

#### 403 Forbidden

```json
{
  "statusCode": 403,
  "message": "Access denied",
  "error": "Insufficient permissions to access expense management"
}
```

#### 404 Not Found

```json
{
  "statusCode": 404,
  "message": "Expense not found",
  "error": "Expense with ID 64fa1c71b19d6d001c88a91f does not exist"
}
```

#### 409 Conflict

```json
{
  "statusCode": 409,
  "message": "Expense category creation conflict",
  "error": "Expense category with name 'salary' already exists"
}
```

#### 422 Unprocessable Entity

```json
{
  "statusCode": 422,
  "message": "Business validation failed",
  "error": "Cannot delete expense category that is currently used in active expenses"
}
```

## Business Rules

### Expense Creation

1. **Amount Validation**: Total expense amount must be positive and match sum of line items
2. **Date Validation**: Expense date is required and must be a valid ISO date string
3. **Currency Consistency**: All line items must use the same currency as the total
4. **Category Validation**: All categories must exist in the expense category collection
5. **Source Validation**: All sources must reference valid entities (members, products, suppliers)

### Expense Updates

1. **Amount Recalculation**: Total amount is automatically recalculated from line items
2. **Category Integrity**: Categories must remain valid and existing
3. **Source Integrity**: Source references must remain valid
4. **Audit Trail**: All changes are tracked for compliance and auditing
5. **Permission Validation**: User must have appropriate permissions for updates

### Expense Deletion

1. **Soft Delete**: Expenses are marked as deleted rather than physically removed
2. **Audit Preservation**: All historical data is maintained for compliance
3. **Reference Integrity**: Related data references are handled appropriately
4. **Permission Requirements**: User must have delete permissions

### Category Management

1. **Name Uniqueness**: Category names must be unique within the tenant
2. **Usage Tracking**: Cannot delete categories that are currently used in expenses
3. **Bulk Operations**: Support for efficient bulk category creation
4. **Predefined Categories**: System provides predefined categories for common expense types

### Permission Requirements

1. **Expense Operations**:
   * `READ_EXPENSE` - View expenses
   * `CREATE_EXPENSE` - Create new expenses
   * `EDIT_EXPENSE` - Update existing expenses
   * `DELETE_EXPENSE` - Delete expenses
2. **Category Operations**:
   * `READ_EXPENSE_CATEGORY` - View expense categories
   * `CREATE_EXPENSE_CATEGORY` - Create new categories
   * `EDIT_EXPENSE_CATEGORY` - Update existing categories
   * `DELETE_EXPENSE_CATEGORY` - Delete categories

## Performance Considerations

### Pagination

* Default page size: 10 items
* Maximum page size: 100 items
* Use pagination for large expense lists

### Filtering and Search

* Date range filtering optimized with database indexes
* Text search across expense descriptions
* Category-based filtering with array operations
* Multi-currency support for international businesses

### Caching

* Expense category data is heavily cached due to infrequent changes
* Recent expenses cached for dashboard displays
* Search result caching for common queries

### Database Optimization

* Compound indexes on date ranges and categories
* Text indexes for description search
* Optimized aggregation for expense totals and reports

## Rate Limiting

* **Read Operations**: 100 requests per minute per user
* **Write Operations**: 30 requests per minute per user
* **Bulk Operations**: 10 requests per minute per user

## Monitoring and Logging

### Request Logging

All API requests are logged with:

* Request ID for tracing
* User context and permissions
* Performance metrics
* Error details and stack traces

### Business Event Logging

* Expense creation, updates, and deletions
* Category management operations
* Permission validation events
* Financial data access and modifications

### Performance Monitoring

* Response time tracking for all endpoints
* Database query performance analysis
* Cache hit rates and effectiveness
* Error rate monitoring and alerting

## Security Considerations

### Input Validation

* Comprehensive validation of all financial data
* Amount validation to prevent negative or invalid values
* Date validation and format checking
* Source and category reference validation

### Access Control

* Role-based permission system with granular controls
* Tenant-based data isolation for multi-tenant security
* API rate limiting and abuse prevention
* Audit logging for all financial operations

### Financial Data Protection

* Encryption of sensitive financial information
* Secure handling of currency and amount data
* Compliance with financial data protection regulations
* Regular security audits and vulnerability assessments

## Integration Examples

### Creating a Comprehensive Expense

```typescript
const salaryExpense = {
  totalValue: {
    amount: 5500.00,
    currency: "USD"
  },
  expensedAt: "2024-07-26T10:00:00.000Z",
  description: "Monthly staff salary payment",
  items: [
    {
      categories: [
        {
          name: "salary",
          description: "Employee salary and compensation"
        }
      ],
      itemValue: {
        amount: 3000.00,
        currency: "USD"
      },
      description: "Senior massage therapist salary",
      source: {
        sourceId: "64fa1c71b19d6d001c88a925",
        sourceType: "member",
        name: "Jane Smith",
        description: "Senior massage therapist"
      }
    },
    {
      categories: [
        {
          name: "salary",
          description: "Employee salary and compensation"
        }
      ],
      itemValue: {
        amount: 2500.00,
        currency: "USD"
      },
      description: "Receptionist and administrative salary",
      source: {
        sourceId: "64fa1c71b19d6d001c88a926",
        sourceType: "member",
        name: "Mike Johnson",
        description: "Front desk receptionist"
      }
    }
  ]
};
```

### Advanced Expense Search

```typescript
// Search for expenses in a date range with specific categories
GET /api/v1/expense/paged?
  start=2024-07-01T00:00:00.000Z&
  end=2024-07-31T23:59:59.999Z&
  expenseCategories[]=salary&
  expenseCategories[]=utilities&
  phrase=monthly&
  page=1&
  size=25
```

### Bulk Category Creation

```typescript
const businessCategories = [
  {
    name: "rent",
    description: "Office and facility rental expenses"
  },
  {
    name: "insurance",
    description: "Business insurance premiums and coverage"
  },
  {
    name: "supplies",
    description: "General business supplies and materials"
  },
  {
    name: "maintenance",
    description: "Facility maintenance and repairs"
  },
  {
    name: "professional-services",
    description: "Legal, accounting, and consulting services"
  }
];

// Create all categories in one request
POST /api/v1/expense/category/bulk
Content-Type: application/json
Body: businessCategories
```


# Interface Documentation

## Overview

This document outlines the interfaces, value objects, repositories, and domain contracts for the Expense Management module in the Bee O'clock panel service. The module follows Domain-Driven Design principles with clear separation between domain logic and infrastructure concerns.

## Domain Interfaces

### IExpense

**File:** `applications/panel.beeoclock/src/modules/expense/domain/interfaces/i.expense.ts`

The core expense aggregate root interface that defines the structure and behavior of expense entities within the domain.

```typescript
import {IBaseEntityBeeoClockTenantId} from '@beeoclock/common/core/entities/i.base.entity.beeoclock.tenant.id';
import {ExpenseValueRootValueObject} from '../value-objects/expense-value.value-object';
import {ExpenseItemValueObject} from '../value-objects/expense-item.value-object';

export interface IExpense extends IBaseEntityBeeoClockTenantId {
  totalValue: ExpenseValueRootValueObject;    // Total monetary value of the expense
  expensedAt: Date;                          // Date when the expense occurred
  description?: string;                      // Optional description of the expense
  items?: ExpenseItemValueObject[];          // Array of individual expense line items
}
```

**Key Characteristics:**

* Extends base entity with tenant ID for multi-tenancy support
* Uses value objects for monetary amounts and complex structures
* Supports itemized expenses with detailed breakdown
* Immutable expense timestamp for audit purposes

### IExpenseCategory

**File:** `applications/panel.beeoclock/src/modules/expense/domain/interfaces/i.expense-category.ts`

Interface defining expense categorization structure for organizing and filtering expenses.

```typescript
import {IBaseEntityBeeoClockTenantId} from '@beeoclock/common/core/entities/i.base.entity.beeoclock.tenant.id';

export interface IExpenseCategory extends IBaseEntityBeeoClockTenantId {
  name: string;                              // Unique category name within tenant
  description?: string;                      // Optional description of the category
}
```

**Key Characteristics:**

* Extends base entity with tenant ID for multi-tenancy support
* Simple name-based categorization system
* Optional description for detailed category information
* Designed for reusability across multiple expenses

### IExpenseRepository

**File:** `applications/panel.beeoclock/src/modules/expense/domain/interfaces/i.expense.repository.ts`

Repository interface defining data access patterns for expense entities with advanced querying capabilities.

```typescript
import {IBaseRepository} from '@beeoclock/common/core/persistance/interfaces/i.base.repository';
import {IExpense} from './i.expense';
import {PaginationRequestDto} from '@beeoclock/common/application/dto/pagination.request.dto';
import {PaginationResponseDto} from '@beeoclock/common/application/dto/pagination.response.dto';
import {ExpensePaginationDto} from '../../application/dtos/expense.pagination.dto';

export interface IExpenseRepository extends IBaseRepository<IExpense> {
  /**
   * Find expenses with advanced pagination and filtering capabilities
   * @param expensePaginationDto - Pagination parameters with expense-specific filters
   * @returns Promise resolving to paginated expense results
   */
  findManyByPagination(
    expensePaginationDto: ExpensePaginationDto
  ): Promise<PaginationResponseDto<IExpense>>;

  /**
   * Find an expense by ID with tenant and permission validation
   * @param id - Expense identifier
   * @returns Promise resolving to expense entity or null if not found
   */
  findOneById(id: string): Promise<IExpense | null>;

  /**
   * Create a new expense entity with validation
   * @param expense - Expense data to persist
   * @returns Promise resolving to created expense entity
   */
  create(expense: IExpense): Promise<IExpense>;

  /**
   * Update an existing expense entity
   * @param id - Expense identifier
   * @param expense - Updated expense data
   * @returns Promise resolving to updated expense entity
   */
  update(id: string, expense: Partial<IExpense>): Promise<IExpense>;

  /**
   * Delete an expense entity (soft delete)
   * @param id - Expense identifier
   * @returns Promise resolving to deletion result
   */
  deleteOneById(id: string): Promise<void>;
}
```

**Key Features:**

* Extends base repository with common CRUD operations
* Advanced pagination with expense-specific filtering
* Supports date range queries and category filtering
* Built-in tenant isolation for multi-tenant architecture
* Soft delete pattern for data integrity

### IExpenseCategoryRepository

**File:** `applications/panel.beeoclock/src/modules/expense/domain/interfaces/i.expense-category.repository.ts`

Repository interface for managing expense categories with pagination and bulk operations.

```typescript
import {IBaseRepository} from '@beeoclock/common/core/persistance/interfaces/i.base.repository';
import {IExpenseCategory} from './i.expense-category';
import {PaginationRequestDto} from '@beeoclock/common/application/dto/pagination.request.dto';
import {PaginationResponseDto} from '@beeoclock/common/application/dto/pagination.response.dto';

export interface IExpenseCategoryRepository extends IBaseRepository<IExpenseCategory> {
  /**
   * Find expense categories with pagination support
   * @param paginationRequestDto - Standard pagination parameters
   * @returns Promise resolving to paginated category results
   */
  findManyByPagination(
    paginationRequestDto: PaginationRequestDto
  ): Promise<PaginationResponseDto<IExpenseCategory>>;

  /**
   * Create multiple expense categories in bulk
   * @param expenseCategories - Array of expense categories to create
   * @returns Promise resolving to array of created categories
   */
  createMany(expenseCategories: IExpenseCategory[]): Promise<IExpenseCategory[]>;

  /**
   * Find an expense category by name within tenant scope
   * @param name - Category name to search for
   * @returns Promise resolving to category entity or null if not found
   */
  findOneByName(name: string): Promise<IExpenseCategory | null>;

  /**
   * Create a single expense category with validation
   * @param expenseCategory - Category data to persist
   * @returns Promise resolving to created category entity
   */
  create(expenseCategory: IExpenseCategory): Promise<IExpenseCategory>;
}
```

**Key Features:**

* Bulk operations for efficient category management
* Name-based lookup with tenant scoping
* Standard pagination for category listing
* Designed for high-frequency read operations

## Value Objects

### ExpenseValueRootValueObject

**File:** `applications/panel.beeoclock/src/modules/expense/domain/value-objects/expense-value.value-object.ts`

Value object representing monetary amounts with currency support.

```typescript
import {CurrencyCodeEnum} from '@beeoclock/common/core/enum/currency.code.enum';

export class ExpenseValueRootValueObject {
  /**
   * Monetary amount for the expense
   */
  public readonly amount: number;

  /**
   * Currency code for the expense amount
   */
  public readonly currency: CurrencyCodeEnum;

  constructor(amount: number, currency: CurrencyCodeEnum) {
    if (amount < 0) {
      throw new Error('Expense amount cannot be negative');
    }
    this.amount = amount;
    this.currency = currency;
  }

  /**
   * Calculate the sum of multiple expense values
   * @param values - Array of expense values to sum
   * @returns New ExpenseValueRootValueObject with total amount
   */
  static sum(values: ExpenseValueRootValueObject[]): ExpenseValueRootValueObject {
    if (values.length === 0) {
      throw new Error('Cannot sum empty array of expense values');
    }

    const currency = values[0].currency;
    if (!values.every(value => value.currency === currency)) {
      throw new Error('All expense values must have the same currency');
    }

    const totalAmount = values.reduce((sum, value) => sum + value.amount, 0);
    return new ExpenseValueRootValueObject(totalAmount, currency);
  }

  /**
   * Check if this value equals another expense value
   * @param other - Other expense value to compare
   * @returns Boolean indicating equality
   */
  equals(other: ExpenseValueRootValueObject): boolean {
    return this.amount === other.amount && this.currency === other.currency;
  }

  /**
   * Convert to plain object for serialization
   * @returns Plain object representation
   */
  toObject(): { amount: number; currency: CurrencyCodeEnum } {
    return {
      amount: this.amount,
      currency: this.currency
    };
  }
}
```

**Key Features:**

* Immutable value object with validation
* Currency consistency enforcement
* Arithmetic operations with currency validation
* Serialization support for persistence

### ExpenseItemValueObject

**File:** `applications/panel.beeoclock/src/modules/expense/domain/value-objects/expense-item.value-object.ts`

Value object representing individual line items within an expense.

```typescript
import {ExpenseValueRootValueObject} from './expense-value.value-object';
import {ExpenseSourceValueObject} from './expense-source.value-object';
import {IExpenseCategory} from '../interfaces/i.expense-category';

export class ExpenseItemValueObject {
  /**
   * Categories associated with this expense item
   */
  public readonly categories: IExpenseCategory[];

  /**
   * Monetary value of this specific line item
   */
  public readonly itemValue: ExpenseValueRootValueObject;

  /**
   * Description of this expense line item
   */
  public readonly description: string;

  /**
   * Source information for this expense item
   */
  public readonly source: ExpenseSourceValueObject;

  constructor(
    categories: IExpenseCategory[],
    itemValue: ExpenseValueRootValueObject,
    description: string,
    source: ExpenseSourceValueObject
  ) {
    if (!categories || categories.length === 0) {
      throw new Error('Expense item must have at least one category');
    }
    if (!description || description.trim().length === 0) {
      throw new Error('Expense item description cannot be empty');
    }

    this.categories = categories;
    this.itemValue = itemValue;
    this.description = description.trim();
    this.source = source;
  }

  /**
   * Check if this item belongs to a specific category
   * @param categoryName - Name of the category to check
   * @returns Boolean indicating category membership
   */
  hasCategory(categoryName: string): boolean {
    return this.categories.some(category => category.name === categoryName);
  }

  /**
   * Get all category names for this item
   * @returns Array of category names
   */
  getCategoryNames(): string[] {
    return this.categories.map(category => category.name);
  }

  /**
   * Convert to plain object for serialization
   * @returns Plain object representation
   */
  toObject(): any {
    return {
      categories: this.categories,
      itemValue: this.itemValue.toObject(),
      description: this.description,
      source: this.source.toObject()
    };
  }
}
```

**Key Features:**

* Encapsulates line item business logic
* Category validation and querying
* Integration with expense value and source objects
* Immutable design with validation

### ExpenseSourceValueObject

**File:** `applications/panel.beeoclock/src/modules/expense/domain/value-objects/expense-source.value-object.ts`

Value object representing the source or origin of an expense item.

```typescript
import {ExpenseSourceTypeEnum} from '../enums/expense-source-type.enum';

export class ExpenseSourceValueObject {
  /**
   * Identifier of the source entity
   */
  public readonly sourceId: string;

  /**
   * Type of the source entity
   */
  public readonly sourceType: ExpenseSourceTypeEnum;

  /**
   * Display name of the source entity
   */
  public readonly name?: string;

  /**
   * Optional description of the source entity
   */
  public readonly description?: string;

  constructor(
    sourceId: string,
    sourceType: ExpenseSourceTypeEnum,
    name?: string,
    description?: string
  ) {
    if (!sourceId || sourceId.trim().length === 0) {
      throw new Error('Source ID cannot be empty');
    }
    if (!Object.values(ExpenseSourceTypeEnum).includes(sourceType)) {
      throw new Error('Invalid expense source type');
    }

    this.sourceId = sourceId.trim();
    this.sourceType = sourceType;
    this.name = name?.trim();
    this.description = description?.trim();
  }

  /**
   * Check if this source is of a specific type
   * @param type - Source type to check
   * @returns Boolean indicating type match
   */
  isOfType(type: ExpenseSourceTypeEnum): boolean {
    return this.sourceType === type;
  }

  /**
   * Get display name or fallback to source ID
   * @returns Display name for the source
   */
  getDisplayName(): string {
    return this.name || this.sourceId;
  }

  /**
   * Convert to plain object for serialization
   * @returns Plain object representation
   */
  toObject(): any {
    return {
      sourceId: this.sourceId,
      sourceType: this.sourceType,
      name: this.name,
      description: this.description
    };
  }
}
```

**Key Features:**

* Encapsulates source entity information
* Type validation and checking
* Flexible naming with fallbacks
* Immutable design with validation

## Enumerations

### ExpenseSourceTypeEnum

**File:** `applications/panel.beeoclock/src/modules/expense/domain/enums/expense-source-type.enum.ts`

Enumeration defining the types of entities that can be associated with expense items.

```typescript
export enum ExpenseSourceTypeEnum {
  /**
   * Business member or employee
   */
  member = 'member',

  /**
   * Business resource or asset
   */
  resource = 'resource',

  /**
   * Product or inventory item
   */
  product = 'product',

  /**
   * External supplier or vendor
   */
  supplier = 'supplier'
}
```

**Usage Context:**

* **member**: Employee salaries, commissions, benefits
* **resource**: Equipment maintenance, facility costs, resource allocation
* **product**: Inventory costs, product-related expenses, cost of goods sold
* **supplier**: Vendor payments, external services, outsourced operations

## Data Transfer Objects (DTOs)

### ExpenseDto

**File:** `applications/panel.beeoclock/src/modules/expense/application/dtos/expense.dto.ts`

Data transfer object for expense entities with validation decorators.

```typescript
import {IsOptional, IsString, IsArray, ValidateNested, IsISO8601, IsNotEmpty} from 'class-validator';
import {Type} from 'class-transformer';
import {BaseBeeoClockEntityDto} from '@beeoclock/common/application/dto/base.beeoclock.entity.dto';
import {ExpenseValueDto} from './expense-value.dto';
import {ExpenseItemDto} from './expense-item.dto';

export class ExpenseDto extends BaseBeeoClockEntityDto {
  @IsOptional()
  @IsString()
  public readonly object?: 'ExpenseDto' = 'ExpenseDto';

  @ValidateNested()
  @Type(() => ExpenseValueDto)
  public totalValue!: ExpenseValueDto;

  @IsISO8601()
  @IsNotEmpty()
  public expensedAt!: string;

  @IsOptional()
  @IsString()
  public description?: string;

  @IsOptional()
  @IsArray()
  @ValidateNested({each: true})
  @Type(() => ExpenseItemDto)
  public items?: ExpenseItemDto[];
}
```

### ExpenseValueDto

**File:** `applications/panel.beeoclock/src/modules/expense/application/dtos/expense-value.dto.ts`

Data transfer object for monetary values with currency validation.

```typescript
import {IsEnum, IsNumber, IsOptional, IsPositive, IsString} from 'class-validator';
import {CurrencyCodeEnum} from '@beeoclock/common/core/enum/currency.code.enum';

export class ExpenseValueDto {
  @IsOptional()
  @IsString()
  public readonly object?: 'ExpenseValueDto' = 'ExpenseValueDto';

  @IsNumber({maxDecimalPlaces: 2})
  @IsPositive()
  public amount!: number;

  @IsEnum(CurrencyCodeEnum)
  public currency!: CurrencyCodeEnum;
}
```

### ExpenseItemDto

**File:** `applications/panel.beeoclock/src/modules/expense/application/dtos/expense-item.dto.ts`

Data transfer object for expense line items with category and source validation.

```typescript
import {IsArray, IsString, ValidateNested, IsNotEmpty, IsOptional} from 'class-validator';
import {Type} from 'class-transformer';
import {ExpenseCategoryDto} from './expense-category.dto';
import {ExpenseValueDto} from './expense-value.dto';
import {ExpenseSourceDto} from './expense-source.dto';

export class ExpenseItemDto {
  @IsOptional()
  @IsString()
  public readonly object?: 'ExpenseLineItemDto' = 'ExpenseLineItemDto';

  @IsArray()
  @ValidateNested({each: true})
  @Type(() => ExpenseCategoryDto)
  public categories!: ExpenseCategoryDto[];

  @ValidateNested()
  @Type(() => ExpenseValueDto)
  public itemValue!: ExpenseValueDto;

  @IsString()
  @IsNotEmpty()
  public description!: string;

  @ValidateNested()
  @Type(() => ExpenseSourceDto)
  public source!: ExpenseSourceDto;
}
```

### ExpenseSourceDto

**File:** `applications/panel.beeoclock/src/modules/expense/application/dtos/expense-source.dto.ts`

Data transfer object for expense source information with type validation.

```typescript
import {IsEnum, IsOptional, IsString, IsNotEmpty} from 'class-validator';
import {ExpenseSourceTypeEnum} from '../domain/enums/expense-source-type.enum';

export class ExpenseSourceDto {
  @IsOptional()
  @IsString()
  public readonly object?: 'ExpenseSourceDto' = 'ExpenseSourceDto';

  @IsString()
  @IsNotEmpty()
  public sourceId!: string;

  @IsEnum(ExpenseSourceTypeEnum)
  public sourceType!: ExpenseSourceTypeEnum;

  @IsOptional()
  @IsString()
  public name?: string;

  @IsOptional()
  @IsString()
  public description?: string;
}
```

### ExpenseCategoryDto

**File:** `applications/panel.beeoclock/src/modules/expense/application/dtos/expense-category.dto.ts`

Data transfer object for expense categories with validation.

```typescript
import {IsOptional, IsString, IsNotEmpty} from 'class-validator';
import {BaseBeeoClockEntityDto} from '@beeoclock/common/application/dto/base.beeoclock.entity.dto';

export class ExpenseCategoryDto extends BaseBeeoClockEntityDto {
  @IsOptional()
  @IsString()
  public readonly object?: 'ExpenseCategoryDto' = 'ExpenseCategoryDto';

  @IsString()
  @IsNotEmpty()
  public name!: string;

  @IsOptional()
  @IsString()
  public description?: string;
}
```

### ExpensePaginationDto

**File:** `applications/panel.beeoclock/src/modules/expense/application/dtos/expense.pagination.dto.ts`

Data transfer object for expense pagination with advanced filtering.

```typescript
import {IsOptional, IsString, IsArray, IsISO8601} from 'class-validator';
import {Transform} from 'class-transformer';
import {PaginationRequestDto} from '@beeoclock/common/application/dto/pagination.request.dto';

export class ExpensePaginationDto extends PaginationRequestDto {
  @IsOptional()
  @IsString()
  public phrase?: string;

  @IsOptional()
  @IsISO8601()
  public start?: string;

  @IsOptional()
  @IsISO8601()
  public end?: string;

  @IsOptional()
  @IsArray()
  @Transform(({value}) => Array.isArray(value) ? value : [value])
  public expenseCategories?: string[];
}
```

## Mappers

### ExpenseMapperToDto

**File:** `applications/panel.beeoclock/src/modules/expense/application/mappers/expense.mapper-to-dto.ts`

Mapper for converting domain entities to DTOs with proper type transformation.

```typescript
import {IExpense} from '../../domain/interfaces/i.expense';
import {ExpenseDto} from '../dtos/expense.dto';
import {ExpenseValueMapperToDto} from './expense-value.mapper-to-dto';
import {ExpenseItemMapperToDto} from './expense-item.mapper-to-dto';

export class ExpenseMapperToDto {
  /**
   * Convert expense domain entity to DTO
   * @param expense - Domain expense entity
   * @returns Expense DTO
   */
  static map(expense: IExpense): ExpenseDto {
    const dto = new ExpenseDto();
    
    dto._id = expense._id;
    dto.totalValue = ExpenseValueMapperToDto.map(expense.totalValue);
    dto.expensedAt = expense.expensedAt.toISOString();
    dto.description = expense.description;
    dto.items = expense.items?.map(item => ExpenseItemMapperToDto.map(item));
    dto.createdAt = expense.createdAt?.toISOString();
    dto.updatedAt = expense.updatedAt?.toISOString();

    return dto;
  }

  /**
   * Convert array of expense entities to DTOs
   * @param expenses - Array of domain expense entities
   * @returns Array of expense DTOs
   */
  static mapArray(expenses: IExpense[]): ExpenseDto[] {
    return expenses.map(expense => this.map(expense));
  }
}
```

### ExpenseMapperToDomain

**File:** `applications/panel.beeoclock/src/modules/expense/application/mappers/expense.mapper-to-domain.ts`

Mapper for converting DTOs to domain entities with validation.

```typescript
import {IExpense} from '../../domain/interfaces/i.expense';
import {ExpenseDto} from '../dtos/expense.dto';
import {ExpenseValueMapperToDomain} from './expense-value.mapper-to-domain';
import {ExpenseItemMapperToDomain} from './expense-item.mapper-to-domain';

export class ExpenseMapperToDomain {
  /**
   * Convert expense DTO to domain entity
   * @param dto - Expense DTO
   * @returns Domain expense entity
   */
  static map(dto: ExpenseDto): IExpense {
    return {
      _id: dto._id,
      totalValue: ExpenseValueMapperToDomain.map(dto.totalValue),
      expensedAt: new Date(dto.expensedAt),
      description: dto.description,
      items: dto.items?.map(item => ExpenseItemMapperToDomain.map(item)),
      createdAt: dto.createdAt ? new Date(dto.createdAt) : undefined,
      updatedAt: dto.updatedAt ? new Date(dto.updatedAt) : undefined,
      businessEntityId: dto.businessEntityId,
      tenantId: dto.tenantId
    };
  }

  /**
   * Convert array of expense DTOs to domain entities
   * @param dtos - Array of expense DTOs
   * @returns Array of domain expense entities
   */
  static mapArray(dtos: ExpenseDto[]): IExpense[] {
    return dtos.map(dto => this.map(dto));
  }
}
```

## Use Case Interfaces

### ICreateExpenseUseCase

Interface defining the contract for expense creation use cases.

```typescript
import {ExpenseDto} from '../dtos/expense.dto';

export interface ICreateExpenseUseCase {
  /**
   * Execute expense creation with validation and business rules
   * @param expenseDto - Expense data to create
   * @returns Promise resolving to created expense DTO
   */
  execute(expenseDto: ExpenseDto): Promise<ExpenseDto>;
}
```

### IGetPagedExpensesUseCase

Interface defining the contract for paginated expense retrieval.

```typescript
import {ExpensePaginationDto} from '../dtos/expense.pagination.dto';
import {PaginationResponseDto} from '@beeoclock/common/application/dto/pagination.response.dto';
import {ExpenseDto} from '../dtos/expense.dto';

export interface IGetPagedExpensesUseCase {
  /**
   * Execute paginated expense retrieval with filtering
   * @param pagination - Pagination and filter parameters
   * @returns Promise resolving to paginated expense results
   */
  execute(pagination: ExpensePaginationDto): Promise<PaginationResponseDto<ExpenseDto>>;
}
```

## Architecture Integration

### Dependency Injection

The expense management module integrates with the NestJS dependency injection system:

```typescript
// Repository tokens
export const EXPENSE_REPOSITORY_TOKEN = Symbol('IExpenseRepository');
export const EXPENSE_CATEGORY_REPOSITORY_TOKEN = Symbol('IExpenseCategoryRepository');

// Use case tokens
export const CREATE_EXPENSE_USE_CASE_TOKEN = Symbol('ICreateExpenseUseCase');
export const GET_PAGED_EXPENSES_USE_CASE_TOKEN = Symbol('IGetPagedExpensesUseCase');
```

### Module Configuration

Integration with the panel module's dependency injection container:

```typescript
@Module({
  providers: [
    {
      provide: EXPENSE_REPOSITORY_TOKEN,
      useClass: ExpenseRepository
    },
    {
      provide: EXPENSE_CATEGORY_REPOSITORY_TOKEN,
      useClass: ExpenseCategoryRepository
    },
    {
      provide: CREATE_EXPENSE_USE_CASE_TOKEN,
      useClass: CreateExpenseUseCase
    },
    {
      provide: GET_PAGED_EXPENSES_USE_CASE_TOKEN,
      useClass: GetPagedExpensesUseCase
    }
  ]
})
export class ExpenseModule {}
```

## Design Patterns

### Repository Pattern

* Abstract data access through repository interfaces
* Consistent querying and persistence operations
* Support for complex queries with filtering and pagination

### Value Object Pattern

* Immutable objects for monetary values and complex data
* Encapsulation of business rules and validation
* Type safety for financial calculations

### Domain-Driven Design

* Clear separation between domain logic and infrastructure
* Rich domain models with business behavior
* Aggregate roots for consistency boundaries

### Command Query Responsibility Segregation (CQRS)

* Separate interfaces for command and query operations
* Optimized data access patterns for different use cases
* Clear separation of concerns for read and write operations

## Validation Rules

### Domain Validation

* Expense amounts must be positive
* Currency consistency across expense items
* Required fields validation (amount, date, source)
* Category existence validation

### DTO Validation

* JSON schema validation using class-validator decorators
* Type conversion and transformation using class-transformer
* Custom validation rules for business-specific requirements

### Repository Validation

* Data integrity checks during persistence
* Constraint validation at the database level
* Foreign key integrity for related entities

## Error Handling

### Domain Exceptions

```typescript
// Value object validation errors
export class InvalidExpenseAmountError extends Error {
  constructor(amount: number) {
    super(`Invalid expense amount: ${amount}. Amount must be positive.`);
  }
}

// Business rule violations
export class CurrencyMismatchError extends Error {
  constructor(expected: string, actual: string) {
    super(`Currency mismatch: expected ${expected}, got ${actual}`);
  }
}
```

### Repository Exceptions

```typescript
// Data access errors
export class ExpenseNotFoundError extends Error {
  constructor(id: string) {
    super(`Expense with ID ${id} not found`);
  }
}

// Constraint violations
export class DuplicateExpenseCategoryError extends Error {
  constructor(name: string) {
    super(`Expense category with name '${name}' already exists`);
  }
}
```

## Testing Interfaces

### Mock Repositories

```typescript
export const createMockExpenseRepository = (): jest.Mocked<IExpenseRepository> => ({
  findManyByPagination: jest.fn(),
  findOneById: jest.fn(),
  create: jest.fn(),
  update: jest.fn(),
  deleteOneById: jest.fn(),
  // ... other base repository methods
});

export const createMockExpenseCategoryRepository = (): jest.Mocked<IExpenseCategoryRepository> => ({
  findManyByPagination: jest.fn(),
  createMany: jest.fn(),
  findOneByName: jest.fn(),
  create: jest.fn(),
  // ... other base repository methods
});
```

### Test Builders

```typescript
export class ExpenseTestBuilder {
  private expense: Partial<IExpense> = {};

  withTotalValue(amount: number, currency: CurrencyCodeEnum): this {
    this.expense.totalValue = new ExpenseValueRootValueObject(amount, currency);
    return this;
  }

  withExpenseDate(date: Date): this {
    this.expense.expensedAt = date;
    return this;
  }

  withDescription(description: string): this {
    this.expense.description = description;
    return this;
  }

  build(): IExpense {
    return {
      totalValue: this.expense.totalValue || new ExpenseValueRootValueObject(100, CurrencyCodeEnum.USD),
      expensedAt: this.expense.expensedAt || new Date(),
      description: this.expense.description,
      items: this.expense.items,
      ...this.expense
    } as IExpense;
  }
}
```

This interface documentation provides a comprehensive view of the expense management module's contracts, value objects, and domain structure, enabling developers to understand and work with the expense system effectively while maintaining consistency with domain-driven design principles.


# Use Case Documentation

## Overview

This document outlines the use cases for the Expense Management module in the Bee O'clock panel service. Each use case represents a specific business operation that can be performed within the expense management system, following the CQRS pattern and Clean Architecture principles.

## Architecture Overview

The expense management use cases are organized following the Clean Architecture pattern:

* **Application Layer**: Use cases that orchestrate business operations
* **Domain Layer**: Business rules and domain entities
* **Infrastructure Layer**: Data persistence and external service integration

Each use case implements a specific interface and encapsulates the business logic for a particular operation while maintaining separation of concerns.

## Command Use Cases

### 1. Create Expense Use Case

**File:** `applications/panel.beeoclock/src/modules/expense/application/use-cases/create-expense.usecase.ts`

**Purpose:** Creates a new expense record with validation, business rule enforcement, and data persistence.

```typescript
import { Inject, Injectable } from '@nestjs/common';
import { ICreateExpenseUseCase } from '../interfaces/i.create-expense.use-case';
import { ExpenseDto } from '../dtos/expense.dto';
import { IExpenseRepository } from '../../domain/interfaces/i.expense.repository';
import { EXPENSE_REPOSITORY_TOKEN } from '../tokens/expense.repository.token';
import { ExpenseMapperToDomain } from '../mappers/expense.mapper-to-domain';
import { ExpenseMapperToDto } from '../mappers/expense.mapper-to-dto';

@Injectable()
export class CreateExpenseUseCase implements ICreateExpenseUseCase {
  constructor(
    @Inject(EXPENSE_REPOSITORY_TOKEN)
    private readonly expenseRepository: IExpenseRepository
  ) {}

  /**
   * Execute expense creation with comprehensive validation and business rule enforcement
   * @param expenseDto - Expense data to create
   * @returns Promise resolving to created expense DTO
   */
  async execute(expenseDto: ExpenseDto): Promise<ExpenseDto> {
    // Convert DTO to domain entity
    const expenseDomain = ExpenseMapperToDomain.map(expenseDto);

    // Validate business rules
    this.validateExpenseBusinessRules(expenseDomain);

    // Calculate and validate total amount
    this.validateAndCalculateTotalAmount(expenseDomain);

    // Validate expense items
    this.validateExpenseItems(expenseDomain);

    // Persist the expense
    const createdExpense = await this.expenseRepository.create(expenseDomain);

    // Convert back to DTO and return
    return ExpenseMapperToDto.map(createdExpense);
  }

  /**
   * Validate core business rules for expense creation
   * @param expense - Domain expense entity
   */
  private validateExpenseBusinessRules(expense: IExpense): void {
    // Validate expense date is not in the future beyond reasonable limits
    const maxFutureDate = new Date();
    maxFutureDate.setDate(maxFutureDate.getDate() + 30); // Allow 30 days in future
    
    if (expense.expensedAt > maxFutureDate) {
      throw new BadRequestException('Expense date cannot be more than 30 days in the future');
    }

    // Validate minimum expense amount
    if (expense.totalValue.amount <= 0) {
      throw new BadRequestException('Expense amount must be greater than zero');
    }

    // Validate maximum expense amount for fraud prevention
    const maxAllowedAmount = 100000; // $100,000 limit
    if (expense.totalValue.amount > maxAllowedAmount) {
      throw new BadRequestException(`Expense amount exceeds maximum allowed limit of ${maxAllowedAmount}`);
    }
  }

  /**
   * Validate and calculate total amount from expense items
   * @param expense - Domain expense entity
   */
  private validateAndCalculateTotalAmount(expense: IExpense): void {
    if (!expense.items || expense.items.length === 0) {
      return; // Simple expense without line items
    }

    // Calculate total from line items
    const calculatedTotal = expense.items.reduce(
      (sum, item) => sum + item.itemValue.amount,
      0
    );

    // Validate currency consistency across all items
    const baseCurrency = expense.totalValue.currency;
    const invalidCurrencyItems = expense.items.filter(
      item => item.itemValue.currency !== baseCurrency
    );

    if (invalidCurrencyItems.length > 0) {
      throw new BadRequestException(
        `All expense items must use the same currency: ${baseCurrency}`
      );
    }

    // Validate total amount matches sum of line items (with small tolerance for rounding)
    const tolerance = 0.01; // 1 cent tolerance
    const difference = Math.abs(calculatedTotal - expense.totalValue.amount);
    
    if (difference > tolerance) {
      throw new BadRequestException(
        `Total expense amount (${expense.totalValue.amount}) does not match sum of line items (${calculatedTotal})`
      );
    }
  }

  /**
   * Validate individual expense items
   * @param expense - Domain expense entity
   */
  private validateExpenseItems(expense: IExpense): void {
    if (!expense.items) {
      return;
    }

    expense.items.forEach((item, index) => {
      // Validate item amount
      if (item.itemValue.amount <= 0) {
        throw new BadRequestException(`Expense item ${index + 1} amount must be greater than zero`);
      }

      // Validate item description
      if (!item.description || item.description.trim().length === 0) {
        throw new BadRequestException(`Expense item ${index + 1} must have a description`);
      }

      // Validate categories
      if (!item.categories || item.categories.length === 0) {
        throw new BadRequestException(`Expense item ${index + 1} must have at least one category`);
      }

      // Validate source information
      if (!item.source || !item.source.sourceId) {
        throw new BadRequestException(`Expense item ${index + 1} must have a valid source`);
      }
    });
  }
}
```

**Business Rules:**

* Expense amounts must be positive and within reasonable limits
* Future-dated expenses are limited to 30 days ahead
* Currency consistency across all line items is enforced
* Total amount must match the sum of line items (within rounding tolerance)
* Each line item must have description, categories, and valid source
* Maximum expense amount is enforced for fraud prevention

**Error Scenarios:**

* Invalid expense amount (negative, zero, or exceeding limits)
* Future date beyond allowed range
* Currency mismatch between total and line items
* Missing required fields (description, categories, source)
* Total amount mismatch with line item sum

## Query Use Cases

### 1. Get Paged Expenses Use Case

**File:** `applications/panel.beeoclock/src/modules/expense/application/use-cases/get-paged-expenses.usecase.ts`

**Purpose:** Retrieves a paginated list of expenses with advanced filtering capabilities.

```typescript
import { Inject, Injectable } from '@nestjs/common';
import { IGetPagedExpensesUseCase } from '../interfaces/i.get-paged-expenses.use-case';
import { ExpensePaginationDto } from '../dtos/expense.pagination.dto';
import { PaginationResponseDto } from '@beeoclock/common/application/dto/pagination.response.dto';
import { ExpenseDto } from '../dtos/expense.dto';
import { IExpenseRepository } from '../../domain/interfaces/i.expense.repository';
import { EXPENSE_REPOSITORY_TOKEN } from '../tokens/expense.repository.token';
import { ExpenseMapperToDto } from '../mappers/expense.mapper-to-dto';

@Injectable()
export class GetPagedExpensesUseCase implements IGetPagedExpensesUseCase {
  constructor(
    @Inject(EXPENSE_REPOSITORY_TOKEN)
    private readonly expenseRepository: IExpenseRepository
  ) {}

  /**
   * Execute paginated expense retrieval with advanced filtering
   * @param pagination - Pagination and filter parameters
   * @returns Promise resolving to paginated expense results
   */
  async execute(
    pagination: ExpensePaginationDto
  ): Promise<PaginationResponseDto<ExpenseDto>> {
    // Validate pagination parameters
    this.validatePaginationParameters(pagination);

    // Normalize and prepare filter parameters
    const normalizedPagination = this.normalizePaginationParameters(pagination);

    // Retrieve paginated expenses from repository
    const paginatedExpenses = await this.expenseRepository.findManyByPagination(
      normalizedPagination
    );

    // Convert domain entities to DTOs
    const expenseDtos = ExpenseMapperToDto.mapArray(paginatedExpenses.items);

    // Return paginated response
    return {
      items: expenseDtos,
      totalSize: paginatedExpenses.totalSize,
      page: paginatedExpenses.page,
      size: paginatedExpenses.size
    };
  }

  /**
   * Validate pagination parameters for security and performance
   * @param pagination - Pagination parameters to validate
   */
  private validatePaginationParameters(pagination: ExpensePaginationDto): void {
    // Validate page number
    if (pagination.page && pagination.page < 1) {
      throw new BadRequestException('Page number must be 1 or greater');
    }

    // Validate page size limits
    const maxPageSize = 100;
    if (pagination.size && pagination.size > maxPageSize) {
      throw new BadRequestException(`Page size cannot exceed ${maxPageSize} items`);
    }

    if (pagination.size && pagination.size < 1) {
      throw new BadRequestException('Page size must be 1 or greater');
    }

    // Validate date range parameters
    if (pagination.start && pagination.end) {
      const startDate = new Date(pagination.start);
      const endDate = new Date(pagination.end);

      if (startDate > endDate) {
        throw new BadRequestException('Start date must be before or equal to end date');
      }

      // Validate date range is not too large (prevent performance issues)
      const maxRangeDays = 365; // 1 year maximum
      const daysDifference = (endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24);
      
      if (daysDifference > maxRangeDays) {
        throw new BadRequestException(`Date range cannot exceed ${maxRangeDays} days`);
      }
    }

    // Validate search phrase length
    if (pagination.phrase && pagination.phrase.length > 100) {
      throw new BadRequestException('Search phrase cannot exceed 100 characters');
    }

    // Validate expense categories array
    if (pagination.expenseCategories) {
      const maxCategories = 20;
      if (pagination.expenseCategories.length > maxCategories) {
        throw new BadRequestException(`Cannot filter by more than ${maxCategories} categories`);
      }

      // Validate individual category names
      pagination.expenseCategories.forEach(category => {
        if (!category || category.trim().length === 0) {
          throw new BadRequestException('Expense category names cannot be empty');
        }
        if (category.length > 50) {
          throw new BadRequestException('Expense category names cannot exceed 50 characters');
        }
      });
    }
  }

  /**
   * Normalize pagination parameters with defaults and sanitization
   * @param pagination - Raw pagination parameters
   * @returns Normalized pagination parameters
   */
  private normalizePaginationParameters(
    pagination: ExpensePaginationDto
  ): ExpensePaginationDto {
    return {
      ...pagination,
      page: pagination.page || 1,
      size: Math.min(pagination.size || 10, 100), // Default 10, max 100
      phrase: pagination.phrase?.trim(),
      expenseCategories: pagination.expenseCategories?.map(cat => cat.trim()).filter(Boolean)
    };
  }
}
```

**Business Rules:**

* Page size is limited to 100 items for performance
* Date ranges are limited to 1 year to prevent performance issues
* Search phrases are limited to 100 characters
* Maximum of 20 expense categories can be filtered at once
* Start date must be before or equal to end date
* Empty or invalid category names are filtered out

**Query Capabilities:**

* Pagination with configurable page size
* Text search across expense descriptions
* Date range filtering (start and end dates)
* Multiple expense category filtering
* Sorting by expense date and creation time

### 2. Get Expense by ID Use Case

**Purpose:** Retrieves a specific expense by its unique identifier with permission validation.

```typescript
import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { IGetExpenseByIdUseCase } from '../interfaces/i.get-expense-by-id.use-case';
import { ExpenseDto } from '../dtos/expense.dto';
import { IExpenseRepository } from '../../domain/interfaces/i.expense.repository';
import { EXPENSE_REPOSITORY_TOKEN } from '../tokens/expense.repository.token';
import { ExpenseMapperToDto } from '../mappers/expense.mapper-to-dto';

@Injectable()
export class GetExpenseByIdUseCase implements IGetExpenseByIdUseCase {
  constructor(
    @Inject(EXPENSE_REPOSITORY_TOKEN)
    private readonly expenseRepository: IExpenseRepository
  ) {}

  /**
   * Execute expense retrieval by ID with validation
   * @param id - Expense identifier
   * @returns Promise resolving to expense DTO
   */
  async execute(id: string): Promise<ExpenseDto> {
    // Validate expense ID format
    this.validateExpenseId(id);

    // Retrieve expense from repository
    const expense = await this.expenseRepository.findOneById(id);

    // Handle not found case
    if (!expense) {
      throw new NotFoundException(`Expense with ID ${id} not found`);
    }

    // Convert to DTO and return
    return ExpenseMapperToDto.map(expense);
  }

  /**
   * Validate expense ID format and constraints
   * @param id - Expense identifier to validate
   */
  private validateExpenseId(id: string): void {
    if (!id || id.trim().length === 0) {
      throw new BadRequestException('Expense ID cannot be empty');
    }

    // Validate MongoDB ObjectId format (24 hex characters)
    const objectIdRegex = /^[0-9a-fA-F]{24}$/;
    if (!objectIdRegex.test(id)) {
      throw new BadRequestException('Invalid expense ID format');
    }
  }
}
```

**Business Rules:**

* Expense ID must be a valid MongoDB ObjectId format
* Expense must exist in the current tenant's scope
* User must have read permissions for expense data

## Category Management Use Cases

### 1. Create Expense Category Use Case

**Purpose:** Creates a new expense category with validation and uniqueness checks.

```typescript
import { Inject, Injectable, ConflictException } from '@nestjs/common';
import { ICreateExpenseCategoryUseCase } from '../interfaces/i.create-expense-category.use-case';
import { ExpenseCategoryDto } from '../dtos/expense-category.dto';
import { IExpenseCategoryRepository } from '../../domain/interfaces/i.expense-category.repository';
import { EXPENSE_CATEGORY_REPOSITORY_TOKEN } from '../tokens/expense-category.repository.token';
import { ExpenseCategoryMapperToDomain } from '../mappers/expense-category.mapper-to-domain';

@Injectable()
export class CreateExpenseCategoryUseCase implements ICreateExpenseCategoryUseCase {
  constructor(
    @Inject(EXPENSE_CATEGORY_REPOSITORY_TOKEN)
    private readonly expenseCategoryRepository: IExpenseCategoryRepository
  ) {}

  /**
   * Execute expense category creation with validation
   * @param categoryDto - Category data to create
   * @returns Promise resolving when category is created
   */
  async execute(categoryDto: ExpenseCategoryDto): Promise<void> {
    // Validate category data
    this.validateCategoryData(categoryDto);

    // Check for existing category with same name
    await this.validateCategoryUniqueness(categoryDto.name);

    // Convert DTO to domain entity
    const categoryDomain = ExpenseCategoryMapperToDomain.map(categoryDto);

    // Persist the category
    await this.expenseCategoryRepository.create(categoryDomain);
  }

  /**
   * Validate category data constraints
   * @param category - Category data to validate
   */
  private validateCategoryData(category: ExpenseCategoryDto): void {
    // Validate name constraints
    if (!category.name || category.name.trim().length === 0) {
      throw new BadRequestException('Category name cannot be empty');
    }

    if (category.name.length > 50) {
      throw new BadRequestException('Category name cannot exceed 50 characters');
    }

    // Validate name format (alphanumeric, hyphens, underscores)
    const nameRegex = /^[a-zA-Z0-9\-_\s]+$/;
    if (!nameRegex.test(category.name)) {
      throw new BadRequestException(
        'Category name can only contain letters, numbers, hyphens, underscores, and spaces'
      );
    }

    // Validate description if provided
    if (category.description && category.description.length > 500) {
      throw new BadRequestException('Category description cannot exceed 500 characters');
    }
  }

  /**
   * Validate that category name is unique within tenant
   * @param name - Category name to check
   */
  private async validateCategoryUniqueness(name: string): Promise<void> {
    const existingCategory = await this.expenseCategoryRepository.findOneByName(name);
    
    if (existingCategory) {
      throw new ConflictException(`Expense category with name '${name}' already exists`);
    }
  }
}
```

**Business Rules:**

* Category names must be unique within a tenant
* Category names are limited to 50 characters
* Category names can only contain alphanumeric characters, hyphens, underscores, and spaces
* Category descriptions are optional and limited to 500 characters
* Category names cannot be empty or whitespace-only

### 2. Create Multiple Expense Categories Use Case

**Purpose:** Creates multiple expense categories in a single operation with batch validation.

```typescript
import { Inject, Injectable } from '@nestjs/common';
import { ICreateManyExpenseCategoriesUseCase } from '../interfaces/i.create-many-expense-categories.use-case';
import { ExpenseCategoryDto } from '../dtos/expense-category.dto';
import { IExpenseCategoryRepository } from '../../domain/interfaces/i.expense-category.repository';
import { EXPENSE_CATEGORY_REPOSITORY_TOKEN } from '../tokens/expense-category.repository.token';
import { ExpenseCategoryMapperToDomain } from '../mappers/expense-category.mapper-to-domain';

@Injectable()
export class CreateManyExpenseCategoriesUseCase implements ICreateManyExpenseCategoriesUseCase {
  constructor(
    @Inject(EXPENSE_CATEGORY_REPOSITORY_TOKEN)
    private readonly expenseCategoryRepository: IExpenseCategoryRepository
  ) {}

  /**
   * Execute bulk expense category creation with validation
   * @param categoriesDto - Array of category data to create
   * @returns Promise resolving when all categories are created
   */
  async execute(categoriesDto: ExpenseCategoryDto[]): Promise<void> {
    // Validate input array
    this.validateCategoriesArray(categoriesDto);

    // Validate each category individually
    categoriesDto.forEach((category, index) => {
      try {
        this.validateCategoryData(category);
      } catch (error) {
        throw new BadRequestException(`Validation error in category ${index + 1}: ${error.message}`);
      }
    });

    // Check for internal duplicates
    this.validateNoDuplicateNames(categoriesDto);

    // Check for existing categories with same names
    await this.validateBatchUniqueness(categoriesDto);

    // Convert DTOs to domain entities
    const categoriesDomain = categoriesDto.map(dto => 
      ExpenseCategoryMapperToDomain.map(dto)
    );

    // Persist all categories in batch
    await this.expenseCategoryRepository.createMany(categoriesDomain);
  }

  /**
   * Validate the categories array constraints
   * @param categories - Array of categories to validate
   */
  private validateCategoriesArray(categories: ExpenseCategoryDto[]): void {
    if (!categories || !Array.isArray(categories)) {
      throw new BadRequestException('Categories must be provided as an array');
    }

    if (categories.length === 0) {
      throw new BadRequestException('At least one category must be provided');
    }

    const maxBatchSize = 50;
    if (categories.length > maxBatchSize) {
      throw new BadRequestException(`Cannot create more than ${maxBatchSize} categories at once`);
    }
  }

  /**
   * Validate that there are no duplicate names within the batch
   * @param categories - Array of categories to check
   */
  private validateNoDuplicateNames(categories: ExpenseCategoryDto[]): void {
    const names = categories.map(cat => cat.name.toLowerCase().trim());
    const uniqueNames = new Set(names);

    if (names.length !== uniqueNames.size) {
      const duplicates = names.filter((name, index) => names.indexOf(name) !== index);
      throw new BadRequestException(`Duplicate category names found: ${duplicates.join(', ')}`);
    }
  }

  /**
   * Validate that none of the categories already exist
   * @param categories - Array of categories to check
   */
  private async validateBatchUniqueness(categories: ExpenseCategoryDto[]): Promise<void> {
    const existingChecks = categories.map(category =>
      this.expenseCategoryRepository.findOneByName(category.name)
    );

    const existingCategories = await Promise.all(existingChecks);
    const conflictingNames = existingCategories
      .map((existing, index) => existing ? categories[index].name : null)
      .filter(Boolean);

    if (conflictingNames.length > 0) {
      throw new ConflictException(
        `The following category names already exist: ${conflictingNames.join(', ')}`
      );
    }
  }

  /**
   * Validate individual category data (reused from single creation)
   * @param category - Category data to validate
   */
  private validateCategoryData(category: ExpenseCategoryDto): void {
    // Implementation same as CreateExpenseCategoryUseCase.validateCategoryData
    // ... (validation logic)
  }
}
```

**Business Rules:**

* Maximum of 50 categories can be created in a single batch operation
* No duplicate names are allowed within the batch
* All category names must be unique across the tenant (including existing categories)
* Each category must pass individual validation rules
* Batch operations are atomic (all succeed or all fail)

### 3. Get Paged Expense Categories Use Case

**Purpose:** Retrieves a paginated list of expense categories for selection and management.

```typescript
import { Inject, Injectable } from '@nestjs/common';
import { IGetPagedExpenseCategoriesUseCase } from '../interfaces/i.get-paged-expense-categories.use-case';
import { PaginationRequestDto } from '@beeoclock/common/application/dto/pagination.request.dto';
import { PaginationResponseDto } from '@beeoclock/common/application/dto/pagination.response.dto';
import { ExpenseCategoryDto } from '../dtos/expense-category.dto';
import { IExpenseCategoryRepository } from '../../domain/interfaces/i.expense-category.repository';
import { EXPENSE_CATEGORY_REPOSITORY_TOKEN } from '../tokens/expense-category.repository.token';
import { ExpenseCategoryMapperToDto } from '../mappers/expense-category.mapper-to-dto';

@Injectable()
export class GetPagedExpenseCategoriesUseCase implements IGetPagedExpenseCategoriesUseCase {
  constructor(
    @Inject(EXPENSE_CATEGORY_REPOSITORY_TOKEN)
    private readonly expenseCategoryRepository: IExpenseCategoryRepository
  ) {}

  /**
   * Execute paginated expense category retrieval
   * @param pagination - Pagination parameters
   * @returns Promise resolving to paginated category results
   */
  async execute(
    pagination: PaginationRequestDto
  ): Promise<PaginationResponseDto<ExpenseCategoryDto>> {
    // Validate pagination parameters
    this.validatePaginationParameters(pagination);

    // Apply defaults and normalize parameters
    const normalizedPagination = this.normalizePaginationParameters(pagination);

    // Retrieve paginated categories from repository
    const paginatedCategories = await this.expenseCategoryRepository.findManyByPagination(
      normalizedPagination
    );

    // Convert domain entities to DTOs
    const categoryDtos = ExpenseCategoryMapperToDto.mapArray(paginatedCategories.items);

    // Return paginated response
    return {
      items: categoryDtos,
      totalSize: paginatedCategories.totalSize,
      page: paginatedCategories.page,
      size: paginatedCategories.size
    };
  }

  /**
   * Validate pagination parameters
   * @param pagination - Pagination parameters to validate
   */
  private validatePaginationParameters(pagination: PaginationRequestDto): void {
    if (pagination.page && pagination.page < 1) {
      throw new BadRequestException('Page number must be 1 or greater');
    }

    const maxPageSize = 100;
    if (pagination.size && pagination.size > maxPageSize) {
      throw new BadRequestException(`Page size cannot exceed ${maxPageSize} items`);
    }

    if (pagination.size && pagination.size < 1) {
      throw new BadRequestException('Page size must be 1 or greater');
    }
  }

  /**
   * Normalize pagination parameters with defaults
   * @param pagination - Raw pagination parameters
   * @returns Normalized pagination parameters
   */
  private normalizePaginationParameters(
    pagination: PaginationRequestDto
  ): PaginationRequestDto {
    return {
      ...pagination,
      page: pagination.page || 1,
      size: Math.min(pagination.size || 20, 100) // Default 20 for categories, max 100
    };
  }
}
```

**Business Rules:**

* Default page size is 20 categories (higher than expenses since categories are typically fewer)
* Maximum page size is 100 categories
* Categories are sorted alphabetically by name for consistency
* Only active (non-deleted) categories are returned

## Use Case Dependencies and Integration

### Dependency Injection Tokens

```typescript
// Use case tokens for dependency injection
export const CREATE_EXPENSE_USE_CASE_TOKEN = Symbol('ICreateExpenseUseCase');
export const GET_PAGED_EXPENSES_USE_CASE_TOKEN = Symbol('IGetPagedExpensesUseCase');
export const GET_EXPENSE_BY_ID_USE_CASE_TOKEN = Symbol('IGetExpenseByIdUseCase');
export const CREATE_EXPENSE_CATEGORY_USE_CASE_TOKEN = Symbol('ICreateExpenseCategoryUseCase');
export const CREATE_MANY_EXPENSE_CATEGORIES_USE_CASE_TOKEN = Symbol('ICreateManyExpenseCategoriesUseCase');
export const GET_PAGED_EXPENSE_CATEGORIES_USE_CASE_TOKEN = Symbol('IGetPagedExpenseCategoriesUseCase');

// Repository tokens
export const EXPENSE_REPOSITORY_TOKEN = Symbol('IExpenseRepository');
export const EXPENSE_CATEGORY_REPOSITORY_TOKEN = Symbol('IExpenseCategoryRepository');
```

### Module Configuration

```typescript
import { Module } from '@nestjs/common';

@Module({
  providers: [
    // Use case implementations
    {
      provide: CREATE_EXPENSE_USE_CASE_TOKEN,
      useClass: CreateExpenseUseCase
    },
    {
      provide: GET_PAGED_EXPENSES_USE_CASE_TOKEN,
      useClass: GetPagedExpensesUseCase
    },
    {
      provide: GET_EXPENSE_BY_ID_USE_CASE_TOKEN,
      useClass: GetExpenseByIdUseCase
    },
    {
      provide: CREATE_EXPENSE_CATEGORY_USE_CASE_TOKEN,
      useClass: CreateExpenseCategoryUseCase
    },
    {
      provide: CREATE_MANY_EXPENSE_CATEGORIES_USE_CASE_TOKEN,
      useClass: CreateManyExpenseCategoriesUseCase
    },
    {
      provide: GET_PAGED_EXPENSE_CATEGORIES_USE_CASE_TOKEN,
      useClass: GetPagedExpenseCategoriesUseCase
    },
    
    // Repository implementations
    {
      provide: EXPENSE_REPOSITORY_TOKEN,
      useClass: ExpenseRepository
    },
    {
      provide: EXPENSE_CATEGORY_REPOSITORY_TOKEN,
      useClass: ExpenseCategoryRepository
    }
  ]
})
export class ExpenseModule {}
```

### Use Case Interfaces

```typescript
// Use case interfaces for type safety and testing
export interface ICreateExpenseUseCase {
  execute(expenseDto: ExpenseDto): Promise<ExpenseDto>;
}

export interface IGetPagedExpensesUseCase {
  execute(pagination: ExpensePaginationDto): Promise<PaginationResponseDto<ExpenseDto>>;
}

export interface IGetExpenseByIdUseCase {
  execute(id: string): Promise<ExpenseDto>;
}

export interface ICreateExpenseCategoryUseCase {
  execute(categoryDto: ExpenseCategoryDto): Promise<void>;
}

export interface ICreateManyExpenseCategoriesUseCase {
  execute(categoriesDto: ExpenseCategoryDto[]): Promise<void>;
}

export interface IGetPagedExpenseCategoriesUseCase {
  execute(pagination: PaginationRequestDto): Promise<PaginationResponseDto<ExpenseCategoryDto>>;
}
```

## Error Handling Patterns

### Common Error Types

```typescript
// Validation errors
export class ExpenseValidationError extends BadRequestException {
  constructor(message: string, field?: string) {
    super({
      message,
      field,
      type: 'EXPENSE_VALIDATION_ERROR'
    });
  }
}

// Business rule violations
export class ExpenseBusinessRuleError extends UnprocessableEntityException {
  constructor(message: string, rule?: string) {
    super({
      message,
      rule,
      type: 'EXPENSE_BUSINESS_RULE_ERROR'
    });
  }
}

// Resource not found
export class ExpenseNotFoundError extends NotFoundException {
  constructor(id: string) {
    super({
      message: `Expense with ID ${id} not found`,
      expenseId: id,
      type: 'EXPENSE_NOT_FOUND_ERROR'
    });
  }
}

// Conflict errors
export class ExpenseCategoryConflictError extends ConflictException {
  constructor(name: string) {
    super({
      message: `Expense category with name '${name}' already exists`,
      categoryName: name,
      type: 'EXPENSE_CATEGORY_CONFLICT_ERROR'
    });
  }
}
```

### Error Response Format

```typescript
// Standard error response structure
interface ErrorResponse {
  statusCode: number;
  message: string;
  error: string;
  type?: string;
  field?: string;
  rule?: string;
  timestamp: string;
  path: string;
}
```

## Transaction Management

### Database Transactions

```typescript
// Example of transactional use case
@Injectable()
export class CreateExpenseWithCategoriesUseCase {
  constructor(
    @Inject(EXPENSE_REPOSITORY_TOKEN)
    private readonly expenseRepository: IExpenseRepository,
    @Inject(EXPENSE_CATEGORY_REPOSITORY_TOKEN)
    private readonly categoryRepository: IExpenseCategoryRepository,
    private readonly databaseService: DatabaseService
  ) {}

  async execute(request: CreateExpenseWithCategoriesRequest): Promise<ExpenseDto> {
    return await this.databaseService.executeInTransaction(async (session) => {
      // Create categories if they don't exist
      const categories = await this.ensureCategoriesExist(
        request.newCategories,
        session
      );

      // Create expense with existing and new categories
      const expense = await this.createExpense(
        request.expense,
        categories,
        session
      );

      return expense;
    });
  }

  private async ensureCategoriesExist(
    newCategories: ExpenseCategoryDto[],
    session: DatabaseSession
  ): Promise<IExpenseCategory[]> {
    // Implementation with session-aware operations
    // ...
  }

  private async createExpense(
    expenseData: ExpenseDto,
    categories: IExpenseCategory[],
    session: DatabaseSession
  ): Promise<ExpenseDto> {
    // Implementation with session-aware operations
    // ...
  }
}
```

## Performance Considerations

### Caching Strategies

```typescript
// Category caching for frequently accessed data
@Injectable()
export class CachedGetExpenseCategoriesUseCase implements IGetPagedExpenseCategoriesUseCase {
  constructor(
    @Inject(GET_PAGED_EXPENSE_CATEGORIES_USE_CASE_TOKEN)
    private readonly baseUseCase: IGetPagedExpenseCategoriesUseCase,
    private readonly cacheService: CacheService
  ) {}

  async execute(
    pagination: PaginationRequestDto
  ): Promise<PaginationResponseDto<ExpenseCategoryDto>> {
    const cacheKey = `expense-categories:${pagination.page}:${pagination.size}`;
    
    const cached = await this.cacheService.get(cacheKey);
    if (cached) {
      return cached;
    }

    const result = await this.baseUseCase.execute(pagination);
    
    // Cache for 15 minutes (categories change infrequently)
    await this.cacheService.set(cacheKey, result, 900);
    
    return result;
  }
}
```

### Batch Operations

```typescript
// Optimized bulk operations
@Injectable()
export class BulkExpenseOperationsUseCase {
  constructor(
    @Inject(EXPENSE_REPOSITORY_TOKEN)
    private readonly expenseRepository: IExpenseRepository
  ) {}

  async createMultipleExpenses(expenses: ExpenseDto[]): Promise<ExpenseDto[]> {
    // Validate all expenses first
    expenses.forEach(this.validateExpense);

    // Batch create in chunks for better performance
    const chunkSize = 10;
    const chunks = this.chunkArray(expenses, chunkSize);
    
    const results: ExpenseDto[] = [];
    
    for (const chunk of chunks) {
      const chunkResults = await Promise.all(
        chunk.map(expense => this.createExpense(expense))
      );
      results.push(...chunkResults);
    }

    return results;
  }

  private chunkArray<T>(array: T[], chunkSize: number): T[][] {
    const chunks: T[][] = [];
    for (let i = 0; i < array.length; i += chunkSize) {
      chunks.push(array.slice(i, i + chunkSize));
    }
    return chunks;
  }
}
```

## Testing Patterns

### Use Case Testing

```typescript
describe('CreateExpenseUseCase', () => {
  let useCase: CreateExpenseUseCase;
  let mockRepository: jest.Mocked<IExpenseRepository>;

  beforeEach(() => {
    mockRepository = createMockExpenseRepository();
    useCase = new CreateExpenseUseCase(mockRepository);
  });

  describe('execute', () => {
    it('should create expense with valid data', async () => {
      // Arrange
      const expenseDto = ExpenseTestBuilder.createValid();
      const expectedExpense = ExpenseTestBuilder.createDomainFromDto(expenseDto);
      mockRepository.create.mockResolvedValue(expectedExpense);

      // Act
      const result = await useCase.execute(expenseDto);

      // Assert
      expect(mockRepository.create).toHaveBeenCalledWith(
        expect.objectContaining({
          totalValue: expectedExpense.totalValue,
          expensedAt: expectedExpense.expensedAt
        })
      );
      expect(result).toEqual(ExpenseMapperToDto.map(expectedExpense));
    });

    it('should throw error for negative amount', async () => {
      // Arrange
      const expenseDto = ExpenseTestBuilder.createWithAmount(-100);

      // Act & Assert
      await expect(useCase.execute(expenseDto)).rejects.toThrow(
        'Expense amount must be greater than zero'
      );
    });

    it('should validate currency consistency across items', async () => {
      // Arrange
      const expenseDto = ExpenseTestBuilder.createWithMixedCurrencies();

      // Act & Assert
      await expect(useCase.execute(expenseDto)).rejects.toThrow(
        'All expense items must use the same currency'
      );
    });
  });
});
```

### Integration Testing

```typescript
describe('Expense Management Integration', () => {
  let app: TestingModule;
  let useCase: CreateExpenseUseCase;
  let repository: IExpenseRepository;

  beforeAll(async () => {
    app = await Test.createTestingModule({
      imports: [ExpenseModule, DatabaseTestModule],
      providers: [
        // Test-specific providers
      ]
    }).compile();

    useCase = app.get(CREATE_EXPENSE_USE_CASE_TOKEN);
    repository = app.get(EXPENSE_REPOSITORY_TOKEN);
  });

  afterEach(async () => {
    await repository.deleteAll(); // Clean up test data
  });

  it('should create expense end-to-end', async () => {
    // Arrange
    const expenseDto = ExpenseTestBuilder.createValid();

    // Act
    const result = await useCase.execute(expenseDto);

    // Assert
    expect(result._id).toBeDefined();
    
    const savedExpense = await repository.findOneById(result._id!);
    expect(savedExpense).toBeDefined();
    expect(savedExpense!.totalValue.amount).toBe(expenseDto.totalValue.amount);
  });
});
```

## Monitoring and Observability

### Use Case Metrics

```typescript
// Decorator for use case monitoring
export function MonitorUseCase(name: string) {
  return function (target: any, propertyName: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value;

    descriptor.value = async function (...args: any[]) {
      const startTime = Date.now();
      const logger = this.logger || console;

      try {
        logger.log(`Starting use case: ${name}`);
        const result = await method.apply(this, args);
        const duration = Date.now() - startTime;
        
        // Log successful execution
        logger.log(`Use case ${name} completed in ${duration}ms`);
        
        // Send metrics to monitoring system
        this.metricsService?.recordUseCaseExecution(name, duration, 'success');
        
        return result;
      } catch (error) {
        const duration = Date.now() - startTime;
        
        // Log error
        logger.error(`Use case ${name} failed after ${duration}ms:`, error);
        
        // Send error metrics
        this.metricsService?.recordUseCaseExecution(name, duration, 'error');
        
        throw error;
      }
    };
  };
}

// Usage in use case
@Injectable()
export class CreateExpenseUseCase implements ICreateExpenseUseCase {
  @MonitorUseCase('CreateExpense')
  async execute(expenseDto: ExpenseDto): Promise<ExpenseDto> {
    // Implementation
  }
}
```

### Business Event Logging

```typescript
// Event logging for business operations
@Injectable()
export class CreateExpenseUseCase implements ICreateExpenseUseCase {
  constructor(
    @Inject(EXPENSE_REPOSITORY_TOKEN)
    private readonly expenseRepository: IExpenseRepository,
    private readonly eventLogger: BusinessEventLogger
  ) {}

  async execute(expenseDto: ExpenseDto): Promise<ExpenseDto> {
    // Implementation

    // Log business event
    await this.eventLogger.logEvent({
      type: 'EXPENSE_CREATED',
      entityId: result._id,
      entityType: 'Expense',
      amount: result.totalValue.amount,
      currency: result.totalValue.currency,
      categories: result.items?.flatMap(item => item.categories.map(cat => cat.name)) || [],
      timestamp: new Date(),
      userId: this.getCurrentUserId(),
      tenantId: this.getCurrentTenantId()
    });

    return result;
  }
}
```

This comprehensive use case documentation provides detailed insights into the business operations of the expense management system, including validation rules, error handling, performance considerations, and testing patterns. Each use case is designed to be maintainable, testable, and aligned with Clean Architecture principles.


# Database Schema

## Overview

This document describes the database schema for the Expense Management module in the Bee O'clock panel service. The schema is designed using MongoDB with Mongoose ODM, following Domain-Driven Design principles and implementing multi-tenancy, soft delete patterns, and comprehensive audit trails.

## Database Design Principles

### Multi-Tenancy

* All collections include `tenantId` for data isolation
* Business entity scoping with `businessEntityId`
* Automatic tenant filtering in all queries

### Soft Delete Pattern

* Logical deletion using `archivedAt` timestamp
* Preservation of historical data for audit purposes
* Filtered queries exclude archived records by default

### Audit Trail

* Automatic `createdAt` and `updatedAt` timestamps
* User context tracking for all modifications
* Immutable expense history for compliance

### Performance Optimization

* Strategic indexing for common query patterns
* Compound indexes for multi-field filtering
* Text indexes for search functionality

## Collections

### 1. Expenses Collection

**Collection Name:** `expenses`

**Purpose:** Stores comprehensive expense records with itemized breakdown and categorization.

#### Schema Definition

**File:** `applications/panel.beeoclock/src/modules/expense/infrastructure/persistence/schemas/expense.scheme.ts`

```typescript
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, Types } from 'mongoose';
import { BaseBeeoClockTenantIdSchema } from '@beeoclock/common/infrastructure/schemas/base.beeoclock.tenant.id.schema';
import { ExpenseValueSchema } from './expense-value.schema';
import { ExpenseItemSchema } from './expense-item.schema';

@Schema({
  collection: 'expenses',
  timestamps: true,
  versionKey: false,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
})
export class ExpenseSchema extends BaseBeeoClockTenantIdSchema {
  /**
   * Total monetary value of the expense
   * Embedded document containing amount and currency
   */
  @Prop({
    type: ExpenseValueSchema,
    required: true,
    validate: {
      validator: function(value: any) {
        return value && value.amount > 0;
      },
      message: 'Total value amount must be greater than zero'
    }
  })
  totalValue!: ExpenseValueSchema;

  /**
   * Date when the expense was incurred
   * Used for reporting and financial period categorization
   */
  @Prop({
    type: Date,
    required: true,
    index: true,
    validate: {
      validator: function(value: Date) {
        // Prevent expenses more than 5 years in the past or 30 days in the future
        const fiveYearsAgo = new Date();
        fiveYearsAgo.setFullYear(fiveYearsAgo.getFullYear() - 5);
        
        const thirtyDaysFromNow = new Date();
        thirtyDaysFromNow.setDate(thirtyDaysFromNow.getDate() + 30);
        
        return value >= fiveYearsAgo && value <= thirtyDaysFromNow;
      },
      message: 'Expense date must be within 5 years in the past and 30 days in the future'
    }
  })
  expensedAt!: Date;

  /**
   * Optional description of the expense
   * Supports full-text search for expense discovery
   */
  @Prop({
    type: String,
    maxlength: 1000,
    trim: true,
    index: 'text'
  })
  description?: string;

  /**
   * Array of itemized expense line items
   * Provides detailed breakdown of expense components
   */
  @Prop({
    type: [ExpenseItemSchema],
    default: [],
    validate: {
      validator: function(items: any[]) {
        if (!items || items.length === 0) {
          return true; // Simple expenses without items are allowed
        }
        
        // Validate that sum of items matches total value
        const itemsTotal = items.reduce((sum, item) => sum + item.itemValue.amount, 0);
        const tolerance = 0.01; // 1 cent tolerance for rounding
        
        return Math.abs(itemsTotal - this.totalValue.amount) <= tolerance;
      },
      message: 'Sum of expense items must match total expense amount'
    }
  })
  items?: ExpenseItemSchema[];

  /**
   * Archive timestamp for soft delete functionality
   * Null for active expenses, Date for archived expenses
   */
  @Prop({
    type: Date,
    default: null,
    index: true
  })
  archivedAt?: Date;
}

export type ExpenseDocument = ExpenseSchema & Document;
export const ExpenseSchemaDefinition = SchemaFactory.createForClass(ExpenseSchema);

// Pre-save middleware to validate business rules
ExpenseSchemaDefinition.pre('save', function(this: ExpenseDocument) {
  // Ensure currency consistency across items
  if (this.items && this.items.length > 0) {
    const baseCurrency = this.totalValue.currency;
    const invalidItems = this.items.filter(item => item.itemValue.currency !== baseCurrency);
    
    if (invalidItems.length > 0) {
      throw new Error(`All expense items must use the same currency: ${baseCurrency}`);
    }
  }
});

// Index definitions for optimal query performance
ExpenseSchemaDefinition.index({ tenantId: 1, expensedAt: -1 }); // Date range queries
ExpenseSchemaDefinition.index({ tenantId: 1, archivedAt: 1 }); // Active/archived filtering
ExpenseSchemaDefinition.index({ tenantId: 1, 'items.categories._id': 1 }); // Category filtering
ExpenseSchemaDefinition.index({ tenantId: 1, description: 'text' }); // Text search
ExpenseSchemaDefinition.index({ 
  tenantId: 1, 
  expensedAt: -1, 
  'totalValue.amount': -1 
}); // Reporting queries
```

#### Field Specifications

| Field              | Type                 | Required | Description                         | Constraints                           |
| ------------------ | -------------------- | -------- | ----------------------------------- | ------------------------------------- |
| `_id`              | ObjectId             | Yes      | Primary key                         | Auto-generated MongoDB ObjectId       |
| `tenantId`         | String               | Yes      | Tenant identifier for multi-tenancy | Inherited from base schema            |
| `businessEntityId` | String               | Yes      | Business entity identifier          | Inherited from base schema            |
| `totalValue`       | ExpenseValueSchema   | Yes      | Total monetary amount               | Must be positive, embedded document   |
| `expensedAt`       | Date                 | Yes      | Date of expense occurrence          | Within 5 years past to 30 days future |
| `description`      | String               | No       | Expense description                 | Max 1000 characters, trimmed          |
| `items`            | ExpenseItemSchema\[] | No       | Itemized expense breakdown          | Sum must match total value            |
| `archivedAt`       | Date                 | No       | Soft delete timestamp               | Null for active records               |
| `createdAt`        | Date                 | Yes      | Record creation timestamp           | Auto-managed by timestamps            |
| `updatedAt`        | Date                 | Yes      | Last modification timestamp         | Auto-managed by timestamps            |

#### Business Rules and Constraints

1. **Amount Validation**: Total value amount must be positive
2. **Date Validation**: Expense date within reasonable range (5 years past to 30 days future)
3. **Currency Consistency**: All items must use the same currency as total value
4. **Sum Validation**: Sum of item amounts must match total amount (within 1 cent tolerance)
5. **Soft Delete**: Archived expenses are excluded from standard queries
6. **Text Search**: Description field supports full-text search operations

### 2. Expense Categories Collection

**Collection Name:** `expense-categories`

**Purpose:** Stores categorization tags for organizing and filtering expenses.

#### Schema Definition

**File:** `applications/panel.beeoclock/src/modules/expense/infrastructure/persistence/schemas/expense-category.scheme.ts`

```typescript
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import { BaseBeeoClockTenantIdSchema } from '@beeoclock/common/infrastructure/schemas/base.beeoclock.tenant.id.schema';

@Schema({
  collection: 'expense-categories',
  timestamps: true,
  versionKey: false,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
})
export class ExpenseCategorySchema extends BaseBeeoClockTenantIdSchema {
  /**
   * Unique name of the expense category within tenant
   * Used for categorizing and filtering expenses
   */
  @Prop({
    type: String,
    required: true,
    trim: true,
    lowercase: true,
    maxlength: 50,
    validate: {
      validator: function(value: string) {
        // Alphanumeric characters, hyphens, underscores, and spaces only
        return /^[a-zA-Z0-9\-_\s]+$/.test(value);
      },
      message: 'Category name can only contain letters, numbers, hyphens, underscores, and spaces'
    }
  })
  name!: string;

  /**
   * Optional description of the category
   * Provides additional context for category usage
   */
  @Prop({
    type: String,
    maxlength: 500,
    trim: true
  })
  description?: string;

  /**
   * Archive timestamp for soft delete functionality
   * Null for active categories, Date for archived categories
   */
  @Prop({
    type: Date,
    default: null,
    index: true
  })
  archivedAt?: Date;
}

export type ExpenseCategoryDocument = ExpenseCategorySchema & Document;
export const ExpenseCategorySchemaDefinition = SchemaFactory.createForClass(ExpenseCategorySchema);

// Unique constraint for category name within tenant
ExpenseCategorySchemaDefinition.index(
  { tenantId: 1, name: 1 }, 
  { 
    unique: true,
    partialFilterExpression: { archivedAt: null } // Only enforce uniqueness for active categories
  }
);

// Index for efficient category listing
ExpenseCategorySchemaDefinition.index({ tenantId: 1, archivedAt: 1, name: 1 });
```

#### Field Specifications

| Field              | Type     | Required | Description                 | Constraints                                                      |
| ------------------ | -------- | -------- | --------------------------- | ---------------------------------------------------------------- |
| `_id`              | ObjectId | Yes      | Primary key                 | Auto-generated MongoDB ObjectId                                  |
| `tenantId`         | String   | Yes      | Tenant identifier           | Inherited from base schema                                       |
| `businessEntityId` | String   | Yes      | Business entity identifier  | Inherited from base schema                                       |
| `name`             | String   | Yes      | Category name               | Max 50 chars, alphanumeric/hyphens/underscores/spaces, lowercase |
| `description`      | String   | No       | Category description        | Max 500 characters, trimmed                                      |
| `archivedAt`       | Date     | No       | Soft delete timestamp       | Null for active records                                          |
| `createdAt`        | Date     | Yes      | Record creation timestamp   | Auto-managed                                                     |
| `updatedAt`        | Date     | Yes      | Last modification timestamp | Auto-managed                                                     |

#### Business Rules and Constraints

1. **Name Uniqueness**: Category names must be unique within a tenant (excluding archived)
2. **Name Format**: Only alphanumeric characters, hyphens, underscores, and spaces allowed
3. **Case Insensitive**: Names are stored in lowercase for consistency
4. **Length Limits**: Name limited to 50 characters, description to 500 characters
5. **Soft Delete**: Archived categories excluded from standard operations but preserve historical references

## Embedded Schemas

### 1. Expense Value Schema

**Purpose:** Represents monetary amounts with currency information.

**File:** `applications/panel.beeoclock/src/modules/expense/infrastructure/persistence/schemas/expense-value.schema.ts`

```typescript
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { CurrencyCodeEnum } from '@beeoclock/common/core/enum/currency.code.enum';

@Schema({
  _id: false, // Embedded document, no separate _id
  versionKey: false
})
export class ExpenseValueSchema {
  /**
   * Monetary amount in the specified currency
   * Stored as decimal with 2 decimal places precision
   */
  @Prop({
    type: Number,
    required: true,
    min: [0.01, 'Amount must be at least 0.01'],
    validate: {
      validator: function(value: number) {
        // Validate decimal places (max 2)
        return Number.isFinite(value) && Math.round(value * 100) === value * 100;
      },
      message: 'Amount must have at most 2 decimal places'
    }
  })
  amount!: number;

  /**
   * Currency code for the amount
   * Must be a valid ISO 4217 currency code
   */
  @Prop({
    type: String,
    required: true,
    enum: Object.values(CurrencyCodeEnum),
    uppercase: true
  })
  currency!: CurrencyCodeEnum;
}

export const ExpenseValueSchemaDefinition = SchemaFactory.createForClass(ExpenseValueSchema);
```

### 2. Expense Item Schema

**Purpose:** Represents individual line items within an expense.

**File:** `applications/panel.beeoclock/src/modules/expense/infrastructure/persistence/schemas/expense-item.schema.ts`

```typescript
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Types } from 'mongoose';
import { ExpenseValueSchema } from './expense-value.schema';
import { ExpenseSourceSchema } from './expense-source.schema';

@Schema({
  _id: false, // Embedded document, no separate _id
  versionKey: false
})
export class ExpenseItemSchema {
  /**
   * Array of category references for this expense item
   * Links to expense-categories collection
   */
  @Prop({
    type: [Types.ObjectId],
    ref: 'ExpenseCategory',
    required: true,
    validate: {
      validator: function(categories: Types.ObjectId[]) {
        return categories && categories.length > 0;
      },
      message: 'Expense item must have at least one category'
    }
  })
  categories!: Types.ObjectId[];

  /**
   * Monetary value for this specific line item
   * Must be positive and match currency of parent expense
   */
  @Prop({
    type: ExpenseValueSchema,
    required: true,
    validate: {
      validator: function(value: any) {
        return value && value.amount > 0;
      },
      message: 'Item value amount must be greater than zero'
    }
  })
  itemValue!: ExpenseValueSchema;

  /**
   * Description of this specific expense item
   * Required for clarity and audit purposes
   */
  @Prop({
    type: String,
    required: true,
    trim: true,
    maxlength: 500,
    validate: {
      validator: function(value: string) {
        return value && value.trim().length > 0;
      },
      message: 'Item description cannot be empty'
    }
  })
  description!: string;

  /**
   * Source information for this expense item
   * References the entity that generated this expense
   */
  @Prop({
    type: ExpenseSourceSchema,
    required: true
  })
  source!: ExpenseSourceSchema;
}

export const ExpenseItemSchemaDefinition = SchemaFactory.createForClass(ExpenseItemSchema);
```

### 3. Expense Source Schema

**Purpose:** Represents the source or origin of an expense item.

**File:** `applications/panel.beeoclock/src/modules/expense/infrastructure/persistence/schemas/expense-source.schema.ts`

```typescript
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { ExpenseSourceTypeEnum } from '../../../domain/enums/expense-source-type.enum';

@Schema({
  _id: false, // Embedded document, no separate _id
  versionKey: false
})
export class ExpenseSourceSchema {
  /**
   * Identifier of the source entity
   * References different collections based on sourceType
   */
  @Prop({
    type: String,
    required: true,
    trim: true,
    validate: {
      validator: function(value: string) {
        return value && value.trim().length > 0;
      },
      message: 'Source ID cannot be empty'
    }
  })
  sourceId!: string;

  /**
   * Type of the source entity
   * Determines which collection the sourceId references
   */
  @Prop({
    type: String,
    required: true,
    enum: Object.values(ExpenseSourceTypeEnum)
  })
  sourceType!: ExpenseSourceTypeEnum;

  /**
   * Display name of the source entity
   * Cached for performance and display purposes
   */
  @Prop({
    type: String,
    trim: true,
    maxlength: 200
  })
  name?: string;

  /**
   * Optional description of the source entity
   * Additional context for the expense source
   */
  @Prop({
    type: String,
    trim: true,
    maxlength: 500
  })
  description?: string;
}

export const ExpenseSourceSchemaDefinition = SchemaFactory.createForClass(ExpenseSourceSchema);
```

## Database Indexes

### Primary Indexes

#### Expenses Collection

```typescript
// Primary performance indexes for expenses
db.expenses.createIndex({ tenantId: 1, expensedAt: -1 }); // Date range queries
db.expenses.createIndex({ tenantId: 1, archivedAt: 1 }); // Active/archived filtering  
db.expenses.createIndex({ tenantId: 1, "items.categories": 1 }); // Category filtering
db.expenses.createIndex({ tenantId: 1, description: "text" }); // Full-text search
db.expenses.createIndex({ 
  tenantId: 1, 
  expensedAt: -1, 
  "totalValue.amount": -1 
}); // Financial reporting

// Compound index for complex queries
db.expenses.createIndex({
  tenantId: 1,
  archivedAt: 1,
  expensedAt: -1,
  "totalValue.currency": 1
}); // Multi-criteria filtering
```

#### Expense Categories Collection

```typescript
// Unique constraint and performance indexes for categories
db.expenseCategories.createIndex(
  { tenantId: 1, name: 1 }, 
  { 
    unique: true,
    partialFilterExpression: { archivedAt: null }
  }
); // Unique active category names per tenant

db.expenseCategories.createIndex({ tenantId: 1, archivedAt: 1, name: 1 }); // Listing and filtering
```

### Query Performance Optimization

#### Common Query Patterns

```typescript
// 1. Get active expenses for tenant with date range
db.expenses.find({
  tenantId: "tenant123",
  archivedAt: null,
  expensedAt: {
    $gte: ISODate("2024-01-01T00:00:00.000Z"),
    $lte: ISODate("2024-12-31T23:59:59.999Z")
  }
}).sort({ expensedAt: -1 });

// 2. Search expenses by description
db.expenses.find({
  tenantId: "tenant123",
  archivedAt: null,
  $text: { $search: "office supplies" }
}).sort({ score: { $meta: "textScore" } });

// 3. Filter expenses by categories
db.expenses.find({
  tenantId: "tenant123",
  archivedAt: null,
  "items.categories": { $in: [ObjectId("..."), ObjectId("...")] }
});

// 4. Aggregate expense totals by category
db.expenses.aggregate([
  {
    $match: {
      tenantId: "tenant123",
      archivedAt: null,
      expensedAt: {
        $gte: ISODate("2024-01-01T00:00:00.000Z"),
        $lte: ISODate("2024-12-31T23:59:59.999Z")
      }
    }
  },
  { $unwind: "$items" },
  { $unwind: "$items.categories" },
  {
    $group: {
      _id: "$items.categories",
      totalAmount: { $sum: "$items.itemValue.amount" },
      count: { $sum: 1 }
    }
  }
]);
```

## Data Validation and Constraints

### Schema-Level Validation

```typescript
// Custom validation functions
const validatePositiveAmount = {
  validator: function(value: number) {
    return value > 0;
  },
  message: 'Amount must be greater than zero'
};

const validateCurrencyConsistency = {
  validator: function(this: ExpenseDocument) {
    if (!this.items || this.items.length === 0) return true;
    
    const baseCurrency = this.totalValue.currency;
    return this.items.every(item => item.itemValue.currency === baseCurrency);
  },
  message: 'All expense items must use the same currency'
};

const validateTotalAmountMatch = {
  validator: function(this: ExpenseDocument) {
    if (!this.items || this.items.length === 0) return true;
    
    const itemsTotal = this.items.reduce((sum, item) => sum + item.itemValue.amount, 0);
    const tolerance = 0.01;
    
    return Math.abs(itemsTotal - this.totalValue.amount) <= tolerance;
  },
  message: 'Sum of expense items must match total expense amount'
};
```

### Application-Level Constraints

```typescript
// Repository-level validation
export class ExpenseRepository implements IExpenseRepository {
  async create(expense: IExpense): Promise<IExpense> {
    // Validate business rules before persistence
    this.validateExpenseBusinessRules(expense);
    
    // Additional database-specific validations
    await this.validateCategoryReferences(expense);
    await this.validateSourceReferences(expense);
    
    return await this.expenseModel.create(expense);
  }

  private async validateCategoryReferences(expense: IExpense): Promise<void> {
    if (!expense.items) return;
    
    const categoryIds = expense.items.flatMap(item => 
      item.categories.map(cat => cat._id)
    ).filter(Boolean);
    
    const existingCategories = await this.categoryModel.find({
      _id: { $in: categoryIds },
      tenantId: expense.tenantId,
      archivedAt: null
    });
    
    if (existingCategories.length !== categoryIds.length) {
      throw new BadRequestException('One or more expense categories do not exist or are archived');
    }
  }

  private async validateSourceReferences(expense: IExpense): Promise<void> {
    if (!expense.items) return;
    
    // Validate that all referenced sources exist in their respective collections
    for (const item of expense.items) {
      await this.validateSourceExists(item.source, expense.tenantId);
    }
  }
}
```

## Migration Scripts

### Initial Schema Creation

```typescript
// Migration: 001_create_expense_collections.ts
export class CreateExpenseCollections001 {
  async up(db: Db): Promise<void> {
    // Create expenses collection with validation
    await db.createCollection('expenses', {
      validator: {
        $jsonSchema: {
          bsonType: 'object',
          required: ['tenantId', 'businessEntityId', 'totalValue', 'expensedAt'],
          properties: {
            tenantId: { bsonType: 'string' },
            businessEntityId: { bsonType: 'string' },
            totalValue: {
              bsonType: 'object',
              required: ['amount', 'currency'],
              properties: {
                amount: { bsonType: 'number', minimum: 0.01 },
                currency: { bsonType: 'string' }
              }
            },
            expensedAt: { bsonType: 'date' },
            description: { bsonType: 'string', maxLength: 1000 },
            archivedAt: { bsonType: ['date', 'null'] }
          }
        }
      }
    });

    // Create expense-categories collection
    await db.createCollection('expense-categories', {
      validator: {
        $jsonSchema: {
          bsonType: 'object',
          required: ['tenantId', 'businessEntityId', 'name'],
          properties: {
            tenantId: { bsonType: 'string' },
            businessEntityId: { bsonType: 'string' },
            name: { bsonType: 'string', maxLength: 50 },
            description: { bsonType: 'string', maxLength: 500 },
            archivedAt: { bsonType: ['date', 'null'] }
          }
        }
      }
    });

    // Create indexes
    await this.createIndexes(db);
  }

  async down(db: Db): Promise<void> {
    await db.dropCollection('expenses');
    await db.dropCollection('expense-categories');
  }

  private async createIndexes(db: Db): Promise<void> {
    const expensesCollection = db.collection('expenses');
    const categoriesCollection = db.collection('expense-categories');

    // Expenses indexes
    await expensesCollection.createIndex({ tenantId: 1, expensedAt: -1 });
    await expensesCollection.createIndex({ tenantId: 1, archivedAt: 1 });
    await expensesCollection.createIndex({ tenantId: 1, 'items.categories': 1 });
    await expensesCollection.createIndex({ tenantId: 1, description: 'text' });

    // Categories indexes
    await categoriesCollection.createIndex(
      { tenantId: 1, name: 1 }, 
      { 
        unique: true,
        partialFilterExpression: { archivedAt: null }
      }
    );
    await categoriesCollection.createIndex({ tenantId: 1, archivedAt: 1, name: 1 });
  }
}
```

### Sample Data Migration

```typescript
// Migration: 002_seed_default_expense_categories.ts
export class SeedDefaultExpenseCategories002 {
  async up(db: Db): Promise<void> {
    const defaultCategories = [
      {
        name: 'salary',
        description: 'Employee salary and compensation expenses'
      },
      {
        name: 'utilities',
        description: 'Utility bills and facility services'
      },
      {
        name: 'office-supplies',
        description: 'General office supplies and materials'
      },
      {
        name: 'marketing',
        description: 'Marketing and advertising expenses'
      },
      {
        name: 'travel',
        description: 'Business travel and transportation expenses'
      },
      {
        name: 'training',
        description: 'Employee training and professional development'
      },
      {
        name: 'insurance',
        description: 'Business insurance premiums and coverage'
      },
      {
        name: 'maintenance',
        description: 'Facility and equipment maintenance costs'
      },
      {
        name: 'technology',
        description: 'Technology equipment and software expenses'
      },
      {
        name: 'professional-services',
        description: 'Legal, accounting, and consulting services'
      }
    ];

    // Get all active tenants to seed categories for each
    const tenants = await db.collection('tenants').find({ archivedAt: null }).toArray();

    for (const tenant of tenants) {
      const categoriesWithTenantId = defaultCategories.map(category => ({
        ...category,
        tenantId: tenant._id.toString(),
        businessEntityId: tenant.businessEntityId,
        createdAt: new Date(),
        updatedAt: new Date(),
        archivedAt: null
      }));

      await db.collection('expense-categories').insertMany(categoriesWithTenantId);
    }
  }

  async down(db: Db): Promise<void> {
    const defaultCategoryNames = [
      'salary', 'utilities', 'office-supplies', 'marketing', 'travel',
      'training', 'insurance', 'maintenance', 'technology', 'professional-services'
    ];

    await db.collection('expense-categories').deleteMany({
      name: { $in: defaultCategoryNames }
    });
  }
}
```

## Backup and Recovery

### Backup Strategy

```typescript
// Automated backup configuration
export class ExpenseBackupService {
  async createBackup(): Promise<void> {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
    
    // Backup expenses collection
    await this.mongoService.backup({
      collection: 'expenses',
      outputFile: `expenses_backup_${timestamp}.json`,
      query: {} // Full backup
    });

    // Backup expense categories
    await this.mongoService.backup({
      collection: 'expense-categories',
      outputFile: `expense_categories_backup_${timestamp}.json`,
      query: {}
    });

    // Create incremental backup (last 24 hours)
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);

    await this.mongoService.backup({
      collection: 'expenses',
      outputFile: `expenses_incremental_${timestamp}.json`,
      query: {
        $or: [
          { createdAt: { $gte: yesterday } },
          { updatedAt: { $gte: yesterday } }
        ]
      }
    });
  }

  async restoreFromBackup(backupFile: string): Promise<void> {
    // Validate backup file integrity
    await this.validateBackupFile(backupFile);
    
    // Create restore point before restoration
    await this.createRestorePoint();
    
    // Restore data with transaction safety
    await this.mongoService.restore({
      inputFile: backupFile,
      dropCollection: false, // Merge with existing data
      validateReferences: true
    });
  }
}
```

### Data Retention Policy

```typescript
// Data retention configuration
export class ExpenseDataRetentionService {
  async applyRetentionPolicy(): Promise<void> {
    // Archive expenses older than 7 years
    const sevenYearsAgo = new Date();
    sevenYearsAgo.setFullYear(sevenYearsAgo.getFullYear() - 7);

    await this.expenseModel.updateMany(
      {
        expensedAt: { $lt: sevenYearsAgo },
        archivedAt: null
      },
      {
        $set: { 
          archivedAt: new Date(),
          archiveReason: 'DATA_RETENTION_POLICY'
        }
      }
    );

    // Permanently delete archived expenses older than 10 years
    const tenYearsAgo = new Date();
    tenYearsAgo.setFullYear(tenYearsAgo.getFullYear() - 10);

    const expensesToDelete = await this.expenseModel.find({
      archivedAt: { $lt: tenYearsAgo }
    }).select('_id');

    // Create audit log before deletion
    await this.createDeletionAuditLog(expensesToDelete);

    // Permanently delete old archived records
    await this.expenseModel.deleteMany({
      archivedAt: { $lt: tenYearsAgo }
    });
  }

  private async createDeletionAuditLog(expenses: any[]): Promise<void> {
    const deletionRecord = {
      action: 'PERMANENT_DELETION',
      collection: 'expenses',
      deletedCount: expenses.length,
      deletedIds: expenses.map(exp => exp._id),
      deletionDate: new Date(),
      reason: 'DATA_RETENTION_POLICY'
    };

    await this.auditLogModel.create(deletionRecord);
  }
}
```

## Performance Monitoring

### Query Performance Analysis

```typescript
// Performance monitoring for expense queries
export class ExpenseQueryPerformanceMonitor {
  async analyzeQueryPerformance(): Promise<QueryPerformanceReport> {
    const db = this.mongoService.getDatabase();
    
    // Enable profiling for slow queries
    await db.admin().command({
      profile: 2,
      slowms: 100 // Log queries slower than 100ms
    });

    // Analyze common query patterns
    const performanceMetrics = await Promise.all([
      this.analyzeExpenseListingPerformance(),
      this.analyzeExpenseSearchPerformance(),
      this.analyzeCategoryFilteringPerformance(),
      this.analyzeAggregationPerformance()
    ]);

    return {
      timestamp: new Date(),
      metrics: performanceMetrics,
      recommendations: this.generateOptimizationRecommendations(performanceMetrics)
    };
  }

  private async analyzeExpenseListingPerformance(): Promise<QueryMetrics> {
    const startTime = Date.now();
    
    await this.expenseModel.find({
      tenantId: 'sample-tenant',
      archivedAt: null
    })
    .sort({ expensedAt: -1 })
    .limit(20)
    .explain('executionStats');

    return {
      queryType: 'EXPENSE_LISTING',
      executionTime: Date.now() - startTime,
      indexesUsed: ['tenantId_1_expensedAt_-1'],
      documentsExamined: 20,
      documentsReturned: 20
    };
  }

  private generateOptimizationRecommendations(metrics: QueryMetrics[]): string[] {
    const recommendations: string[] = [];

    metrics.forEach(metric => {
      if (metric.executionTime > 100) {
        recommendations.push(`Consider optimizing ${metric.queryType} - execution time: ${metric.executionTime}ms`);
      }

      if (metric.documentsExamined / metric.documentsReturned > 10) {
        recommendations.push(`${metric.queryType} has poor selectivity - consider additional indexes`);
      }
    });

    return recommendations;
  }
}
```

## Security Considerations

### Data Encryption

```typescript
// Field-level encryption for sensitive data
export class ExpenseSecurityService {
  private readonly encryptionKey: string;

  constructor() {
    this.encryptionKey = process.env.EXPENSE_ENCRYPTION_KEY!;
  }

  async encryptSensitiveFields(expense: ExpenseDocument): Promise<void> {
    // Encrypt monetary amounts for additional security
    if (expense.totalValue) {
      expense.totalValue.amount = await this.encrypt(expense.totalValue.amount.toString());
    }

    // Encrypt descriptions that might contain sensitive information
    if (expense.description) {
      expense.description = await this.encrypt(expense.description);
    }

    // Encrypt item details
    if (expense.items) {
      for (const item of expense.items) {
        item.itemValue.amount = await this.encrypt(item.itemValue.amount.toString());
        item.description = await this.encrypt(item.description);
      }
    }
  }

  async decryptSensitiveFields(expense: ExpenseDocument): Promise<void> {
    // Decrypt monetary amounts
    if (expense.totalValue) {
      expense.totalValue.amount = parseFloat(await this.decrypt(expense.totalValue.amount as any));
    }

    // Decrypt descriptions
    if (expense.description) {
      expense.description = await this.decrypt(expense.description);
    }

    // Decrypt item details
    if (expense.items) {
      for (const item of expense.items) {
        item.itemValue.amount = parseFloat(await this.decrypt(item.itemValue.amount as any));
        item.description = await this.decrypt(item.description);
      }
    }
  }

  private async encrypt(data: string): Promise<string> {
    // Implementation using crypto library
    // ... encryption logic
  }

  private async decrypt(data: string): Promise<string> {
    // Implementation using crypto library
    // ... decryption logic
  }
}
```

### Access Control

```typescript
// Database-level access control
export class ExpenseDatabaseSecurity {
  async setupTenantLevelSecurity(): Promise<void> {
    const db = this.mongoService.getDatabase();

    // Create role for expense management with tenant restrictions
    await db.admin().command({
      createRole: 'expenseManager',
      privileges: [
        {
          resource: { db: 'beeoclock', collection: 'expenses' },
          actions: ['find', 'insert', 'update', 'remove']
        },
        {
          resource: { db: 'beeoclock', collection: 'expense-categories' },
          actions: ['find', 'insert', 'update']
        }
      ],
      roles: []
    });

    // Create user with tenant-specific restrictions
    await db.admin().command({
      createUser: 'expense_service',
      pwd: process.env.EXPENSE_DB_PASSWORD,
      roles: ['expenseManager']
    });
  }

  async createTenantSpecificViews(): Promise<void> {
    // Create views that automatically filter by tenant
    const db = this.mongoService.getDatabase();

    await db.createCollection('tenant_expenses', {
      viewOn: 'expenses',
      pipeline: [
        {
          $match: {
            tenantId: '$$tenantId',
            archivedAt: null
          }
        }
      ]
    });
  }
}
```

This comprehensive database schema documentation provides detailed insights into the storage structure, performance optimization, security measures, and operational considerations for the expense management system. The schema is designed to be scalable, secure, and performant while maintaining data integrity and supporting complex business requirements.


# 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)

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)

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)

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)

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


# API Documentation

## Overview

The Member Management API provides comprehensive team member management capabilities for the Bee O'clock platform. This API handles member registration, profile management, role assignments, service assignments, and team administration within business contexts.

## Base URL

```
{baseUrl}/api/v1/member
```

## Authentication

All endpoints require authentication via:

* **Bearer Token**: Firebase JWT token in Authorization header
* **Business Tenant ID**: Required in `x-business-tenant-id` header for tenant isolation

## API Endpoints

### 1. Get Paginated Members

**Endpoint:** `GET /member/paged`

**Description:** Retrieves a paginated list of team members with search and filtering capabilities.

**Request Parameters:**

```typescript
interface MemberPaginationDto {
  page?: number;           // Page number (default: 1)
  pageSize?: number;       // Items per page (default: 10, max: 100)
  search?: string;         // Search term for name/email
  role?: RoleEnum;         // Filter by member role
  profileStatus?: MemberProfileStatusEnum; // Filter by profile status
  sortBy?: string;         // Sort field (default: 'createdAt')
  sortDirection?: 'asc' | 'desc'; // Sort direction (default: 'desc')
}
```

**Query Parameters:**

* `page` (optional): Page number starting from 1
* `pageSize` (optional): Number of items per page (1-100)
* `search` (optional): Search in firstName, lastName, email
* `role` (optional): Filter by role (ADMIN, SPECIALIST, RECEPTION)
* `profileStatus` (optional): Filter by status (active, inactive, pending)
* `sortBy` (optional): Field to sort by
* `sortDirection` (optional): Sort direction

**Response:**

```typescript
{
  items: MemberDto[];
  pagination: {
    page: number;
    pageSize: number;
    total: number;
    totalPages: number;
    hasNextPage: boolean;
    hasPreviousPage: boolean;
  }
}
```

**Example Request:**

```bash
GET /api/v1/member/paged?page=1&pageSize=20&search=john&role=SPECIALIST&profileStatus=active
Authorization: Bearer <firebase-jwt>
x-business-tenant-id: <tenant-id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "648f8f2e1234567890abcdef",
      "object": "MemberDto",
      "firstName": "John",
      "lastName": "Doe",
      "email": "john.doe@example.com",
      "phone": "+1234567890",
      "role": "SPECIALIST",
      "profileStatus": "active",
      "assignments": {
        "service": {
          "full": false,
          "include": [
            {
              "service": "service-id-123",
              "serviceId": "service-123"
            }
          ]
        }
      },
      "createdAt": "2023-06-18T10:30:00.000Z",
      "updatedAt": "2023-06-18T10:30:00.000Z"
    }
  ],
  "pagination": {
    "page": 1,
    "pageSize": 20,
  }
}
```

***

### 2. Get Member by ID

**Endpoint:** `GET /member/:id`

**Description:** Retrieves detailed information for a specific team member.

**Path Parameters:**

* `id` (required): Member ID (ObjectId format)

**Response:**

```typescript
MemberDto
```

**Example Request:**

```bash
GET /api/v1/member/648f8f2e1234567890abcdef
Authorization: Bearer <firebase-jwt>
x-business-tenant-id: <tenant-id>
```

**Example Response:**

```json
{
  "_id": "648f8f2e1234567890abcdef",
  "object": "MemberDto",
  "firstName": "John",
  "lastName": "Doe",
  "email": "john.doe@example.com",
  "phone": "+1234567890",
  "avatar": {
    "_id": "avatar-id-123",
    "uri": "https://storage.example.com/avatar.jpg",
    "mediaType": "IMAGE"
  },
  "role": "SPECIALIST",
  "roles": [
    {
      "_id": "role-id-123",
      "name": "Service Provider",
      "permissions": ["READ_SERVICE", "UPDATE_SERVICE"]
    }
  ],
  "profileStatus": "active",
  "language": "en",
  "assignments": {
    "service": {
      "full": false,
      "include": [
        {
          "service": "service-id-123",
          "serviceId": "service-123"
        }
      ]
    }
  },
  "referal": {
    "code": "REF123",
    "source": "website"
  },
  "createdAt": "2023-06-18T10:30:00.000Z",
  "updatedAt": "2023-06-18T15:45:00.000Z"
}
```

***

### 3. Create New Member

**Endpoint:** `POST /member`

**Description:** Creates a new team member and sends invitation.

**Request Body:**

```typescript
interface MemberDto {
  firstName?: string;
  lastName?: string;
  email: string;          // Required - unique within business
  phone?: string;
  role?: RoleEnum;        // Default: SPECIALIST
  profileStatus?: MemberProfileStatusEnum; // Default: active
  assignments?: AssignmentsDto;
  language?: LanguageCodeEnum; // Default: en
  referal?: ReferalDto;
}
```

**Response:**

```typescript
MemberDto // Created member details
```

**Validation Rules:**

* `email`: Required, valid email format, unique within business
* `firstName` or `lastName`: At least one is recommended
* `role`: Must be valid role enum value
* `phone`: Valid phone format if provided

**Example Request:**

```bash
POST /api/v1/member
Authorization: Bearer <firebase-jwt>
x-business-tenant-id: <tenant-id>
Content-Type: application/json

{
  "firstName": "Jane",
  "lastName": "Smith",
  "email": "jane.smith@example.com",
  "phone": "+1987654321",
  "role": "SPECIALIST",
  "language": "en"
}
```

**Example Response:**

```json
{
  "_id": "648f8f2e1234567890abcdef",
  "object": "MemberDto",
  "firstName": "Jane",
  "lastName": "Smith",
  "email": "jane.smith@example.com",
  "phone": "+1987654321",
  "role": "SPECIALIST",
  "profileStatus": "active",
  "language": "en",
  "assignments": {
    "service": {
      "full": false,
      "include": []
    }
  },
  "createdAt": "2023-06-18T10:30:00.000Z",
  "updatedAt": "2023-06-18T10:30:00.000Z"
}
```

***

### 4. Update Member

**Endpoint:** `PUT /member/:memberId`

**Description:** Updates an existing team member's information.

**Path Parameters:**

* `memberId` (required): Member ID to update

**Request Body:**

```typescript
interface MemberDto {
  firstName?: string;
  lastName?: string;
  email?: string;         // Must be unique if changed
  phone?: string;
  role?: RoleEnum;
  profileStatus?: MemberProfileStatusEnum;
  language?: LanguageCodeEnum;
  referal?: ReferalDto;
}
```

**Response:**

```typescript
MemberDto // Updated member details
```

**Business Rules:**

* Email must remain unique within business if changed
* Role changes require appropriate permissions
* Cannot update email to existing member's email
* Profile status changes affect member access

**Example Request:**

```bash
PUT /api/v1/member/648f8f2e1234567890abcdef
Authorization: Bearer <firebase-jwt>
x-business-tenant-id: <tenant-id>
Content-Type: application/json

{
  "firstName": "Jane",
  "lastName": "Doe-Smith",
  "phone": "+1555123456",
  "profileStatus": "active"
}
```

**Example Response:**

```json
{
  "_id": "648f8f2e1234567890abcdef",
  "object": "MemberDto",
  "firstName": "Jane",
  "lastName": "Doe-Smith",
  "email": "jane.smith@example.com",
  "phone": "+1555123456",
  "role": "SPECIALIST",
  "profileStatus": "active",
  "language": "en",
  "updatedAt": "2023-06-18T16:20:00.000Z"
}
```

***

### 5. Update Member Service Assignments

**Endpoint:** `PATCH /member/:memberId/assignments`

**Description:** Updates service assignments for a team member.

**Path Parameters:**

* `memberId` (required): Member ID to update assignments

**Request Body:**

```typescript
interface AssignmentsDto {
  service: {
    full: boolean;        // If true, member can handle all services
    include?: AssignedServiceDto[]; // Specific services if full=false
  }
}

interface AssignedServiceDto {
  service?: string;       // Service ObjectId reference
  serviceId?: string;     // Service identifier
}
```

**Response:**

```typescript
MemberDto // Updated member with new assignments
```

**Assignment Rules:**

* `full: true`: Member can provide all business services
* `full: false`: Member can only provide services in `include` array
* Empty `include` array with `full: false` means no service assignments
* Service references must exist and belong to the business

**Example Request:**

```bash
PATCH /api/v1/member/648f8f2e1234567890abcdef/assignments
Authorization: Bearer <firebase-jwt>
x-business-tenant-id: <tenant-id>
Content-Type: application/json

{
  "service": {
    "full": false,
    "include": [
      {
        "service": "648f8f2e1234567890service1",
        "serviceId": "haircut-basic"
      },
      {
        "service": "648f8f2e1234567890service2",
        "serviceId": "haircut-premium"
      }
    ]
  }
}
```

**Example Response:**

```json
{
  "_id": "648f8f2e1234567890abcdef",
  "object": "MemberDto",
  "firstName": "Jane",
  "lastName": "Smith",
  "email": "jane.smith@example.com",
  "role": "SPECIALIST",
  "assignments": {
    "service": {
      "full": false,
      "include": [
        {
          "service": "648f8f2e1234567890service1",
          "serviceId": "haircut-basic"
        },
        {
          "service": "648f8f2e1234567890service2",
          "serviceId": "haircut-premium"
        }
      ]
    }
  },
  "updatedAt": "2023-06-18T16:45:00.000Z"
}
```

***

### 6. Delete Member

**Endpoint:** `DELETE /member/:memberId`

**Description:** Soft deletes a team member (marks as deleted while preserving data).

**Path Parameters:**

* `memberId` (required): Member ID to delete

**Response:**

```typescript
void // No content (204 status)
```

**Business Rules:**

* Performs soft delete (preserves historical data)
* Member cannot delete themselves
* Requires DELETE\_MEMBER permission
* Checks for active orders before deletion
* Maintains audit trail of deletion

**Deletion Validations:**

1. **Self-deletion protection**: Members cannot delete themselves
2. **Active orders check**: Cannot delete members with pending/active orders
3. **Permission validation**: Requires appropriate deletion permissions
4. **Role validation**: May have restrictions based on member role

**Example Request:**

```bash
DELETE /api/v1/member/648f8f2e1234567890abcdef
Authorization: Bearer <firebase-jwt>
x-business-tenant-id: <tenant-id>
```

**Example Response:**

```
HTTP 204 No Content
```

***

## Member Media Management

### 7. Upload Member Avatar

**Endpoint:** `POST /member-media/:memberId/avatar`

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

**Path Parameters:**

* `memberId` (required): Member ID for avatar upload

**Request Body:**

```typescript
FormData {
  file: File; // Image file (JPG, PNG, WebP)
}
```

**Response:**

```typescript
{
  avatarId: string;     // Media ID of uploaded avatar
  avatarUrl: string;    // Public URL of avatar image
}
```

**File Requirements:**

* **Formats**: JPG, JPEG, PNG, WebP
* **Size**: Maximum 5MB
* **Dimensions**: Recommended 400x400px (will be auto-resized)

**Example Request:**

```bash
POST /api/v1/member-media/648f8f2e1234567890abcdef/avatar
Authorization: Bearer <firebase-jwt>
x-business-tenant-id: <tenant-id>
Content-Type: multipart/form-data

FormData:
  file: [image file]
```

**Example Response:**

```json
{
  "avatarId": "648f8f2e1234567890media123",
  "avatarUrl": "https://storage.example.com/avatars/member-avatar-123.jpg"
}
```

***

### 8. Delete Member Avatar

**Endpoint:** `DELETE /member-media/:memberId/avatar`

**Description:** Removes a member's profile avatar image.

**Path Parameters:**

* `memberId` (required): Member ID for avatar deletion

**Response:**

```typescript
void // No content (204 status)
```

**Example Request:**

```bash
DELETE /api/v1/member-media/648f8f2e1234567890abcdef/avatar
Authorization: Bearer <firebase-jwt>
x-business-tenant-id: <tenant-id>
```

**Example Response:**

```
HTTP 204 No Content
```

***

## Data Transfer Objects

### MemberDto

```typescript
interface MemberDto {
  _id?: string;
  object?: 'MemberDto';
  firstName?: string;
  lastName?: string;
  email: string;                    // Required, unique within business
  phone?: string;
  avatar?: MediaDto;
  role?: RoleEnum;                  // Default: SPECIALIST
  roles?: RoleDto[];                // Advanced role system
  profileStatus?: MemberProfileStatusEnum; // Default: active
  assignments?: AssignmentsDto;
  language?: LanguageCodeEnum;      // Default: en
  referal?: ReferalDto;
  createdAt?: string;               // ISO date string
  updatedAt?: string;               // ISO date string
}
```

### AssignmentsDto

```typescript
interface AssignmentsDto {
  service: {
    full: boolean;                  // Can handle all services
    include?: AssignedServiceDto[]; // Specific service assignments
  }
}

interface AssignedServiceDto {
  service?: string;                 // Service ObjectId reference
  serviceId?: string;               // Service identifier
}
```

### MemberPaginationDto

```typescript
interface MemberPaginationDto {
  page?: number;                    // Page number (default: 1)
  pageSize?: number;                // Items per page (default: 10)
  search?: string;                  // Search term
  role?: RoleEnum;                  // Role filter
  profileStatus?: MemberProfileStatusEnum; // Status filter
  sortBy?: string;                  // Sort field
  sortDirection?: 'asc' | 'desc';   // Sort direction
}
```

## Enumerations

### RoleEnum

```typescript
enum RoleEnum {
  ADMIN = 'ADMIN',                  // Full business administration
  SPECIALIST = 'SPECIALIST',        // Service provider
  RECEPTION = 'RECEPTION'           // Front desk operations
}
```

### MemberProfileStatusEnum

```typescript
enum MemberProfileStatusEnum {
  active = 'active',                // Active and available
  inactive = 'inactive',            // Temporarily inactive
  pending = 'pending'               // Awaiting activation
}
```

### LanguageCodeEnum

```typescript
enum LanguageCodeEnum {
  en = 'en',                        // English
  es = 'es',                        // Spanish
  fr = 'fr',                        // French
  de = 'de',                        // German
  it = 'it',                        // Italian
  pt = 'pt',                        // Portuguese
  // Additional languages supported
}
```

## Permission Requirements

All member management endpoints require appropriate permissions:

### Required Permissions

| Operation          | Permission        | Description                |
| ------------------ | ----------------- | -------------------------- |
| Get Members        | `READ_MEMBER`     | View member information    |
| Create Member      | `CREATE_MEMBER`   | Add new team members       |
| Update Member      | `EDIT_MEMBER`     | Modify member details      |
| Delete Member      | `DELETE_MEMBER`   | Remove team members        |
| Manage Assignments | `ASSIGN_SERVICES` | Update service assignments |
| Upload Avatar      | `EDIT_MEMBER`     | Manage member media        |

### Permission Scopes

* **OWN**: Can only access own member data
* **ANY**: Can access all members within the business
* **ADMIN**: Full administrative access

## Error Responses

### Standard Error Format

```typescript
interface ApiError {
  statusCode: number;
  message: string;
  error: string;
  timestamp: string;
  path: string;
}
```

### Common Error Responses

#### 400 Bad Request

```json
{
  "statusCode": 400,
  "message": "Validation failed: Email is required",
  "error": "Bad Request",
  "timestamp": "2023-06-18T10:30:00.000Z",
  "path": "/api/v1/member"
}
```

#### 401 Unauthorized

```json
{
  "statusCode": 401,
  "message": "Invalid or missing authentication token",
  "error": "Unauthorized",
  "timestamp": "2023-06-18T10:30:00.000Z",
  "path": "/api/v1/member"
}
```

#### 403 Forbidden

```json
{
  "statusCode": 403,
  "message": "Insufficient permissions for this operation",
  "error": "Forbidden",
  "timestamp": "2023-06-18T10:30:00.000Z",
  "path": "/api/v1/member"
}
```

#### 404 Not Found

```json
{
  "statusCode": 404,
  "message": "Member not found",
  "error": "Not Found",
  "timestamp": "2023-06-18T10:30:00.000Z",
  "path": "/api/v1/member/invalid-id"
}
```

#### 409 Conflict

```json
{
  "statusCode": 409,
  "message": "Email already exists in this business",
  "error": "Conflict",
  "timestamp": "2023-06-18T10:30:00.000Z",
  "path": "/api/v1/member"
}
```

#### 422 Unprocessable Entity

```json
{
  "statusCode": 422,
  "message": "Cannot delete member with active orders",
  "error": "Unprocessable Entity",
  "timestamp": "2023-06-18T10:30:00.000Z",
  "path": "/api/v1/member/648f8f2e1234567890abcdef"
}
```

### Member-Specific Errors

#### Member Not Found

```json
{
  "statusCode": 404,
  "message": "Member not found: 648f8f2e1234567890abcdef",
  "error": "MemberNotFoundException"
}
```

#### Email Already Exists

```json
{
  "statusCode": 409,
  "message": "Member with email 'john@example.com' already exists",
  "error": "MemberEmailExistsException"
}
```

#### Cannot Delete Self

```json
{
  "statusCode": 422,
  "message": "Members cannot delete themselves",
  "error": "MemberCannotDeleteItselfException"
}
```

#### Has Active Orders

```json
{
  "statusCode": 422,
  "message": "Cannot delete member with active orders or appointments",
  "error": "MemberHasActiveEventsException"
}
```

#### Tariff Plan Limit Reached

```json
{
  "statusCode": 422,
  "message": "Maximum number of team members reached for current plan",
  "error": "TenantTariffPlanMaxMembersReachedException"
}
```

## Rate Limiting

API endpoints are rate-limited to prevent abuse:

* **General endpoints**: 100 requests per minute per IP
* **File upload endpoints**: 10 requests per minute per user
* **Bulk operations**: 5 requests per minute per user

Rate limit headers are included in responses:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1623456789
```

## Caching

Member data is cached for performance optimization:

* **Member details**: Cached for 5 minutes
* **Member lists**: Cached for 1 minute
* **Search results**: Cached for 3 minutes

Cache headers indicate freshness:

```
Cache-Control: public, max-age=300
ETag: "member-12345-v2"
Last-Modified: Wed, 18 Jun 2023 10:30:00 GMT
```

## API Versioning

The API uses URL-based versioning:

* Current version: `/api/v1/`
* Version format: `v{major}`
* Backward compatibility maintained within major versions

## Integration Examples

### JavaScript/TypeScript Client

```typescript
class MemberApiClient {
  constructor(private baseUrl: string, private token: string, private tenantId: string) {}

  async getMembers(params?: MemberPaginationDto): Promise<PaginationResponseDto<MemberDto>> {
    const queryString = new URLSearchParams(params as any).toString();
    const response = await fetch(`${this.baseUrl}/api/v1/member/paged?${queryString}`, {
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'x-business-tenant-id': this.tenantId
      }
    });
    return response.json();
  }

  async createMember(member: Partial<MemberDto>): Promise<MemberDto> {
    const response = await fetch(`${this.baseUrl}/api/v1/member`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'x-business-tenant-id': this.tenantId,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(member)
    });
    return response.json();
  }
}
```

### cURL Examples

```bash
# Get paginated members
curl -X GET \
  "${API_BASE_URL}/api/v1/member/paged?page=1&pageSize=10" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "x-business-tenant-id: ${TENANT_ID}"

# Create new member
curl -X POST \
  "${API_BASE_URL}/api/v1/member" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "x-business-tenant-id: ${TENANT_ID}" \
  -H "Content-Type: application/json" \
  -d '{
    "firstName": "John",
    "lastName": "Doe",
    "email": "john.doe@example.com",
    "role": "SPECIALIST"
  }'

# Update member assignments
curl -X PATCH \
  "${API_BASE_URL}/api/v1/member/${MEMBER_ID}/assignments" \
  -H "Authorization: Bearer ${TOKEN}" \
  -H "x-business-tenant-id: ${TENANT_ID}" \
  -H "Content-Type: application/json" \
  -d '{
    "service": {
      "full": false,
      "include": [
        {"serviceId": "haircut-basic"},
        {"serviceId": "haircut-premium"}
      ]
    }
  }'
```

## Best Practices

### API Usage Guidelines

1. **Pagination**: Always use pagination for member lists to avoid performance issues
2. **Caching**: Implement client-side caching with appropriate TTL
3. **Error Handling**: Handle all error responses gracefully
4. **Rate Limiting**: Respect rate limits and implement exponential backoff
5. **Validation**: Validate data on client side before API calls

### Security Considerations

1. **Token Management**: Secure storage and rotation of authentication tokens
2. **HTTPS Only**: Always use HTTPS in production environments
3. **Input Validation**: Validate and sanitize all inputs
4. **Tenant Isolation**: Always include tenant ID header
5. **Permission Checking**: Verify user permissions before UI actions

### Performance Optimization

1. **Selective Loading**: Only request needed fields using field selection
2. **Batch Operations**: Group related API calls when possible
3. **Lazy Loading**: Load member details on demand
4. **Image Optimization**: Compress avatar images before upload
5. **Connection Pooling**: Reuse HTTP connections for multiple requests

***

For additional information about member management workflows and business logic, see the [Use Case Documentation](/services/member-management/usecase) and [Interface Documentation](/services/member-management/interface).


# Interface Documentation

## Overview

This document provides comprehensive TypeScript interface definitions, DTOs (Data Transfer Objects), enums, and contracts for the Member Management module. These interfaces define the structure of data used throughout the member management system.

## Core Interfaces

### IMember

The core interface defining a team member entity.

```typescript
interface IMember extends IBase {
  roles: IRole[];                   // Advanced role system with permissions
  firstName?: string;               // Member's first name (optional)
  lastName?: string;                // Member's last name (optional)
  phone?: string;                   // Contact phone number (optional)
  email: string;                    // Primary email address (required, unique)
  avatar?: IMedia;                  // Profile avatar image reference
  memberContext: IMemberContext;    // Connection to account and business
  language?: LanguageCodeEnum;      // Preferred interface language
  referal?: IReferal;               // Referral information
  assignments?: IAssignments;       // Service and responsibility assignments
  role: RoleEnum;                   // Primary role (legacy, kept for compatibility)
  profileStatus?: MemberProfileStatusEnum; // Current member status
  createdAt?: string;               // Record creation timestamp
  updatedAt?: string;               // Last modification timestamp
}
```

### IMemberContext

Interface defining the relationship between a member, their account, and business client.

```typescript
interface IMemberContext extends IBase {
  account: IAccount;                // Reference to user account
  client: IClient;                  // Reference to business client
  stateHistory?: StateHistory[];    // State change tracking
  createdAt?: string;               // Context creation timestamp
  updatedAt?: string;               // Last modification timestamp
}
```

### IMemberRepository

Repository interface for member data operations.

```typescript
interface IMemberRepository extends IRepository<IMember> {
  findById(id: string): Promise<IMember | null>;
  findByEmail(email: string): Promise<IMember | null>;
  findByTenant(tenantId: string): Promise<IMember[]>;
  findPopulatedById(id: string): Promise<IMember | null>;
  updateItem(id: string, item: Partial<IMember>): Promise<IMember>;
  createItem(item: IMember): Promise<IMember>;
  all(): Promise<IMember[]>;
  // Additional repository methods...
}
```

## Data Transfer Objects (DTOs)

### MemberDto

Primary DTO for member data transfer in API operations.

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

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

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

  @ApiProperty()
  @IsString()
  @Expose()
  email: string;                    // Required field

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

  @ApiProperty()
  @Type(() => MediaDto)
  @IsOptional()
  @Expose()
  avatar?: MediaDto;

  @ApiProperty({
    enum: RoleEnum,
    default: RoleEnum.SPECIALIST
  })
  @IsEnum(RoleEnum)
  @IsOptional()
  @Expose()
  role?: RoleEnum;

  @ApiProperty({
    isArray: true,
    type: () => RoleDto,
    description: 'Array of roles assigned to the member. Each role can have its own set of permissions.'
  })
  @IsArray()
  @Type(() => RoleDto)
  @IsOptional()
  @Expose()
  roles?: RoleDto[];

  @ApiProperty({
    enum: MemberProfileStatusEnum,
    default: MemberProfileStatusEnum.active
  })
  @IsEnum(MemberProfileStatusEnum)
  @IsOptional()
  @Expose()
  profileStatus?: MemberProfileStatusEnum;

  @ApiProperty()
  @Type(() => AssignmentsDto)
  @IsOptional()
  @Expose()
  assignments?: AssignmentsDto;

  @ApiProperty({
    enum: LanguageCodeEnum,
    default: LanguageCodeEnum.en
  })
  @IsEnum(LanguageCodeEnum)
  @IsOptional()
  @Expose()
  language?: LanguageCodeEnum;

  @ApiProperty()
  @Type(() => ReferalDto)
  @IsOptional()
  @Expose()
  referal?: ReferalDto;
}
```

### AddMemberDto

DTO specifically for member creation operations.

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

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

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

  @ApiProperty()
  @IsString()
  @IsEmail()
  @Expose()
  email: string;                    // Required for creation

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

  @ApiProperty({
    enum: RoleEnum,
    default: RoleEnum.SPECIALIST
  })
  @IsEnum(RoleEnum)
  @IsOptional()
  @Expose()
  role?: RoleEnum;

  @ApiProperty({
    enum: LanguageCodeEnum,
    default: LanguageCodeEnum.en
  })
  @IsEnum(LanguageCodeEnum)
  @IsOptional()
  @Expose()
  language?: LanguageCodeEnum;

  @ApiProperty()
  @Type(() => ReferalDto)
  @IsOptional()
  @Expose()
  referal?: ReferalDto;
}
```

### MemberPaginationDto

DTO for paginated member list requests with filtering and sorting.

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

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  search?: string;                  // Search in name and email

  @ApiProperty({
    enum: RoleEnum,
    required: false
  })
  @IsEnum(RoleEnum)
  @IsOptional()
  @Expose()
  role?: RoleEnum;                  // Filter by role

  @ApiProperty({
    enum: MemberProfileStatusEnum,
    required: false
  })
  @IsEnum(MemberProfileStatusEnum)
  @IsOptional()
  @Expose()
  profileStatus?: MemberProfileStatusEnum; // Filter by status

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  sortBy?: string;                  // Field to sort by

  @ApiProperty({
    enum: ['asc', 'desc'],
    required: false
  })
  @IsEnum(['asc', 'desc'])
  @IsOptional()
  @Expose()
  sortDirection?: 'asc' | 'desc';   // Sort direction
}
```

### MemberContextDto

DTO for member context operations linking accounts to business clients.

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

  @ApiProperty()
  @Type(() => AccountDto)
  @IsOptional()
  @Expose()
  account?: AccountDto;

  @ApiProperty()
  @Type(() => ClientDto)
  @IsOptional()
  @Expose()
  client?: ClientDto;

  @ApiProperty()
  @IsString()
  @IsOptional()
  @Expose()
  status?: string;
}
```

### MemberContextPaginationDto

DTO for paginated member context requests.

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

  @ApiProperty({ required: false })
  @IsOptional()
  @Expose()
  account?: ObjectId;               // Filter by account

  @ApiProperty({ required: false })
  @IsBoolean()
  @IsOptional()
  @Expose()
  populateClient?: boolean;         // Include client details

  @ApiProperty({ required: false })
  @IsBoolean()
  @IsOptional()
  @Expose()
  populateAccount?: boolean;        // Include account details
}
```

## Assignment DTOs

### AssignmentsDto

DTO for managing member service assignments.

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

  @ApiProperty()
  @IsOptional()
  @Type(() => AssignmentServiceDto)
  @Expose()
  service?: AssignmentServiceDto;   // Service assignment configuration
}
```

### AssignmentServiceDto

DTO for service assignment configuration.

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

  @ApiProperty()
  @IsBoolean()
  @Expose()
  full: boolean;                    // Can provide all services

  @ApiProperty({
    type: AssignedServiceDto,
    isArray: true
  })
  @Type(() => AssignedServiceDto)
  @IsArray()
  @IsOptional()
  @Expose()
  include?: AssignedServiceDto[];   // Specific service assignments
}
```

### AssignedServiceDto

DTO for individual service assignment references.

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

  @ApiProperty()
  @IsString()
  @IsOptional()
  @Expose()
  service?: string;                 // Service ObjectId reference

  @ApiProperty()
  @IsString()
  @IsOptional()
  @Expose()
  serviceId?: string;               // Service identifier
}
```

## Value Objects

### IAssignments

Interface for member assignments and responsibilities.

```typescript
interface IAssignments {
  service: IAssignmentService;      // Service assignment configuration
}
```

### IAssignmentService

Interface for service assignment configuration.

```typescript
interface IAssignmentService {
  full: boolean;                    // Member can provide all services
  include?: IAssignedService[];     // Specific service assignments
}
```

### IAssignedService

Interface for individual service assignment.

```typescript
interface IAssignedService {
  service?: ObjectId;               // Reference to Service entity
  serviceId?: string;               // Service identifier string
}
```

### IReferal

Interface for member referral information.

```typescript
interface IReferal {
  code?: string;                    // Referral code
  source?: string;                  // Referral source
  referredBy?: string;              // Who referred this member
  referralDate?: string;            // When referral was made
  incentiveApplied?: boolean;       // Whether referral incentive was applied
}
```

### ReferalDto

DTO for referral information.

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

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

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

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

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

  @ApiProperty()
  @IsBoolean()
  @IsOptional()
  @Expose()
  incentiveApplied?: boolean;
}
```

## Enumerations

### RoleEnum

Enumeration defining member roles within the business.

```typescript
export enum RoleEnum {
  ADMIN = 'ADMIN',                  // Full business administration access
  SPECIALIST = 'SPECIALIST',        // Service provider with specific assignments
  RECEPTION = 'RECEPTION',          // Front desk and customer service
  MANAGER = 'MANAGER',              // Management level access
  OWNER = 'OWNER'                   // Business owner with full control
}
```

**Role Descriptions:**

* **ADMIN**: Complete business administration, user management, settings
* **SPECIALIST**: Service delivery, schedule management, customer interaction
* **RECEPTION**: Customer service, appointment booking, basic administration
* **MANAGER**: Team oversight, reporting, operational management
* **OWNER**: Ultimate authority, business configuration, financial access

### MemberProfileStatusEnum

Enumeration defining member profile status states.

```typescript
export enum MemberProfileStatusEnum {
  active = 'active',                // Member is active and available
  deleted = 'deleted',              // Member has been soft deleted
  suspended = 'suspended'           // Member is temporarily suspended
}
```

**Status Descriptions:**

* **active**: Member can access the system and provide services
* **deleted**: Member has been removed but data is preserved for audit
* **suspended**: Member access is temporarily disabled

### LanguageCodeEnum

Enumeration for supported interface languages.

```typescript
export enum LanguageCodeEnum {
  en = 'en',                        // English
  es = 'es',                        // Spanish
  fr = 'fr',                        // French
  de = 'de',                        // German
  it = 'it',                        // Italian
  pt = 'pt',                        // Portuguese
  nl = 'nl',                        // Dutch
  pl = 'pl',                        // Polish
  ru = 'ru',                        // Russian
  zh = 'zh',                        // Chinese
  ja = 'ja',                        // Japanese
  ko = 'ko',                        // Korean
  ar = 'ar',                        // Arabic
  hi = 'hi',                        // Hindi
  tr = 'tr',                        // Turkish
  sv = 'sv',                        // Swedish
  da = 'da',                        // Danish
  no = 'no',                        // Norwegian
  fi = 'fi',                        // Finnish
  cs = 'cs',                        // Czech
  hu = 'hu',                        // Hungarian
  ro = 'ro',                        // Romanian
  bg = 'bg',                        // Bulgarian
  hr = 'hr',                        // Croatian
  sk = 'sk',                        // Slovak
  sl = 'sl',                        // Slovenian
  et = 'et',                        // Estonian
  lv = 'lv',                        // Latvian
  lt = 'lt',                        // Lithuanian
  uk = 'uk',                        // Ukrainian
  el = 'gr',                        // Greek
  he = 'he',                        // Hebrew
  th = 'th',                        // Thai
  vi = 'vi',                        // Vietnamese
  id = 'id',                        // Indonesian
  ms = 'ms',                        // Malay
  tl = 'tl',                        // Filipino
  sw = 'sw',                        // Swahili
  am = 'am',                        // Amharic
  bn = 'bn',                        // Bengali
  gu = 'gu',                        // Gujarati
  kn = 'kn',                        // Kannada
  ml = 'ml',                        // Malayalam
  mr = 'mr',                        // Marathi
  ne = 'ne',                        // Nepali
  or = 'or',                        // Odia
  pa = 'pa',                        // Punjabi
  si = 'si',                        // Sinhala
  ta = 'ta',                        // Tamil
  te = 'te',                        // Telugu
  ur = 'ur',                        // Urdu
  my = 'my',                        // Myanmar
  km = 'km',                        // Khmer
  lo = 'lo',                        // Lao
  ka = 'ka',                        // Georgian
  hy = 'hy',                        // Armenian
  az = 'az',                        // Azerbaijani
  kk = 'kk',                        // Kazakh
  ky = 'ky',                        // Kyrgyz
  mn = 'mn',                        // Mongolian
  ps = 'ps',                        // Pashto
  fa = 'fa',                        // Persian
  sd = 'sd',                        // Sindhi
  uz = 'uz',                        // Uzbek
  tk = 'tk',                        // Turkmen
  tg = 'tg'                         // Tajik
}
```

## Use Case Parameter Interfaces

### AddMemberUseCaseParams

Parameters for the add new member use case.

```typescript
interface AddMemberUseCaseParams {
  ctx: TenantActorContext;          // Request context with tenant and actor
  accountId: string;                // Account ID for member association
  member: MemberDto;                // Member data for creation
}
```

### DeleteMemberUseCaseParams

Parameters for the delete member use case.

```typescript
interface DeleteMemberUseCaseParams {
  ctx: TenantActorContext;          // Request context with tenant and actor
  memberId: string;                 // ID of member to delete
}
```

### GetMemberByIdUseCaseParams

Parameters for getting a member by ID.

```typescript
interface GetMemberByIdUseCaseParams {
  ctx: TenantActorContext;          // Request context with tenant and actor
  memberId: string;                 // ID of member to retrieve
}
```

### GetPagedMembersUseCaseParams

Parameters for getting paginated member list.

```typescript
interface GetPagedMembersUseCaseParams {
  ctx: TenantActorContext;          // Request context with tenant and actor
  params: MemberPaginationDto;      // Pagination and filtering parameters
}
```

### UpdateMemberUseCaseParams

Parameters for updating member information.

```typescript
interface UpdateMemberUseCaseParams {
  ctx: TenantActorContext;          // Request context with tenant and actor
  member: MemberDto;                // Updated member data
}
```

### UpdateMemberAssignmentUseCaseParams

Parameters for updating member service assignments.

```typescript
interface UpdateMemberAssignmentUseCaseParams {
  ctx: TenantActorContext;          // Request context with tenant and actor
  memberId: string;                 // ID of member to update
  assignment: AssignmentsDto;       // New assignment configuration
}
```

## CQRS Command Interfaces

### CreateMemberCommand

Command for creating a new member.

```typescript
interface CreateMemberCommand {
  tenantId: string;                 // Business tenant ID
  member: IMember;                  // Member data to create
}
```

### UpdateMemberCommand

Command for updating member information.

```typescript
interface UpdateMemberCommand {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of member to update
  updates: Partial<IMember>;        // Fields to update
}
```

### DeleteMemberCommand

Command for deleting a member.

```typescript
interface DeleteMemberCommand {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of member to delete
  actorId: string;                  // ID of user performing deletion
}
```

### UpdateMemberAssignmentCommand

Command for updating member assignments.

```typescript
interface UpdateMemberAssignmentCommand {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of member to update
  assignments: IAssignments;        // New assignment configuration
}
```

## CQRS Query Interfaces

### GetMemberByIdQuery

Query for retrieving a member by ID.

```typescript
interface GetMemberByIdQuery {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of member to retrieve
}
```

### GetPagedMembersQuery

Query for retrieving paginated member list.

```typescript
interface GetPagedMembersQuery {
  tenantId: string;                 // Business tenant ID
  pagination: MemberPaginationDto;  // Pagination parameters
}
```

### CheckMemberHasActiveOrdersQuery

Query for checking if member has active orders.

```typescript
interface CheckMemberHasActiveOrdersQuery {
  tenantId: string;                 // Business tenant ID
  specialistId: string;             // ID of specialist/member to check
}
```

### FetchMembersByIdsQuery

Query for fetching multiple members by their IDs.

```typescript
interface FetchMembersByIdsQuery {
  tenantId: string;                 // Business tenant ID
  memberIds: string[];              // Array of member IDs to fetch
}
```

### GetOwnerMemberQuery

Query for retrieving the business owner member.

```typescript
interface GetOwnerMemberQuery {
  tenantId: string;                 // Business tenant ID
}
```

## Event Interfaces

### MemberAddedMessage

Event message for member creation.

```typescript
interface MemberAddedMessage {
  tenantId: string;                 // Business tenant ID
  member: MemberDto;                // Created member data
  createdBy: ActorDto;              // Who created the member
  timestamp: string;                // When the member was created
  invitationSent?: boolean;         // Whether invitation email was sent
}
```

### MemberUpdatedMessage

Event message for member updates.

```typescript
interface MemberUpdatedMessage {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of updated member
  changes: Partial<MemberDto>;      // What changed
  updatedBy: ActorDto;              // Who made the update
  timestamp: string;                // When the update occurred
}
```

### MemberDeletedMessage

Event message for member deletion.

```typescript
interface MemberDeletedMessage {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of deleted member
  memberEmail: string;              // Email of deleted member
  deletedBy: ActorDto;              // Who performed the deletion
  timestamp: string;                // When the deletion occurred
  reason?: string;                  // Optional deletion reason
}
```

### MemberAssignmentUpdatedMessage

Event message for assignment updates.

```typescript
interface MemberAssignmentUpdatedMessage {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of member with updated assignments
  assignments: AssignmentsDto;      // New assignment configuration
  updatedBy: ActorDto;              // Who made the update
  timestamp: string;                // When the update occurred
}
```

## Media Management Interfaces

### MemberAvatarDto

DTO for member avatar operations.

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

  @ApiProperty()
  @IsString()
  @Expose()
  memberId: string;                 // ID of member

  @ApiProperty()
  @Type(() => MediaDto)
  @IsOptional()
  @Expose()
  avatar?: MediaDto;                // Avatar media object

  @ApiProperty()
  @IsString()
  @IsOptional()
  @Expose()
  avatarUrl?: string;               // Direct URL to avatar image
}
```

### UpsertMemberAvatarCommand

Command for uploading/updating member avatar.

```typescript
interface UpsertMemberAvatarCommand {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of member
  file: Express.Multer.File;        // Uploaded file
  uploadedBy: string;               // ID of user uploading
}
```

### DeleteMemberAvatarCommand

Command for deleting member avatar.

```typescript
interface DeleteMemberAvatarCommand {
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of member
  deletedBy: string;                // ID of user deleting
}
```

## Notification Interfaces

### MemberDeletedNotification

Notification interface for member deletion events.

```typescript
interface MemberDeletedNotification {
  type: 'MEMBER_DELETED';
  tenantId: string;                 // Business tenant ID
  memberId: string;                 // ID of deleted member
  memberName: string;               // Name of deleted member
  memberEmail: string;              // Email of deleted member
  deletedBy: string;                // Who performed deletion
  deletedAt: string;                // When deletion occurred
  notifyChannels: string[];         // Which channels to notify
}
```

## Exception Interfaces

### MemberNotFoundException

Exception for when a member is not found.

```typescript
interface MemberNotFoundException extends NotFoundException {
  memberId: string;                 // ID of member that wasn't found
  message: string;                  // Error message
}
```

### MemberEmailExistsException

Exception for when a member email already exists.

```typescript
interface MemberEmailExistsException extends ConflictException {
  email: string;                    // Email that already exists
  existingMemberId: string;         // ID of existing member with this email
  message: string;                  // Error message
}
```

### MemberCannotDeleteItselfException

Exception for when a member tries to delete themselves.

```typescript
interface MemberCannotDeleteItselfException extends UnprocessableEntityException {
  memberId: string;                 // ID of member attempting self-deletion
  message: string;                  // Error message
}
```

### MemberHasActiveEventsException

Exception for when trying to delete a member with active orders.

```typescript
interface MemberHasActiveEventsException extends UnprocessableEntityException {
  memberId: string;                 // ID of member with active events
  activeOrderCount: number;         // Number of active orders
  message: string;                  // Error message
}
```

### TenantTariffPlanMaxMembersReachedException

Exception for when tariff plan member limit is reached.

```typescript
interface TenantTariffPlanMaxMembersReachedException extends UnprocessableEntityException {
  tenantId: string;                 // Business tenant ID
  currentMemberCount: number;       // Current number of members
  maxAllowed: number;               // Maximum allowed by plan
  planName: string;                 // Name of current tariff plan
  message: string;                  // Error message
}
```

## Cache Key Interfaces

### MemberCacheKeys

Enumeration of cache keys used in member management.

```typescript
export enum MemberCacheKeys {
  GET_MEMBER = 'member:get',        // Individual member cache
  GET_PAGED_MEMBERS = 'member:paged', // Paginated member list cache
  MEMBER_ASSIGNMENTS = 'member:assignments', // Member assignments cache
  MEMBER_AVATAR = 'member:avatar'   // Member avatar cache
}
```

## Validation Interfaces

### MemberValidationResult

Interface for member validation results.

```typescript
interface MemberValidationResult {
  isValid: boolean;                 // Whether validation passed
  errors: string[];                 // Array of validation error messages
  warnings: string[];              // Array of validation warnings
  field?: string;                   // Specific field that failed validation
}
```

### EmailValidationResult

Interface for email validation results.

```typescript
interface EmailValidationResult {
  isValid: boolean;                 // Whether email is valid
  exists: boolean;                  // Whether email already exists
  format: boolean;                  // Whether format is correct
  domain: boolean;                  // Whether domain is valid
  message?: string;                 // Validation message
}
```

## API Response Interfaces

### MemberResponse

Standard response wrapper for member operations.

```typescript
interface MemberResponse<T = MemberDto> {
  success: boolean;                 // Operation success status
  data?: T;                         // Response data
  message?: string;                 // Response message
  error?: string;                   // Error message if failed
  timestamp: string;                // Response timestamp
}
```

### PaginatedMemberResponse

Response interface for paginated member lists.

```typescript
interface PaginatedMemberResponse {
  items: MemberDto[];               // Array of member items
  pagination: {
    page: number;                   // Current page number
    pageSize: number;               // Items per page
    total: number;                  // Total number of items
    totalPages: number;             // Total number of pages
    hasNextPage: boolean;           // Whether there's a next page
    hasPreviousPage: boolean;       // Whether there's a previous page
  };
  filters?: {
    search?: string;                // Applied search filter
    role?: RoleEnum;                // Applied role filter
    profileStatus?: MemberProfileStatusEnum; // Applied status filter
  };
  sort?: {
    field: string;                  // Sort field
    direction: 'asc' | 'desc';      // Sort direction
  };
}
```

## Integration Interfaces

### MemberServiceAssignment

Interface for member-service assignment relationships.

```typescript
interface MemberServiceAssignment {
  memberId: string;                 // ID of assigned member
  serviceId: string;                // ID of assigned service
  canProvide: boolean;              // Whether member can provide this service
  isPreferred: boolean;             // Whether member is preferred for this service
  skillLevel?: number;              // Skill level (1-5 scale)
  assignedAt: string;               // When assignment was made
  assignedBy: string;               // Who made the assignment
}
```

### MemberAvailability

Interface for member availability information.

```typescript
interface MemberAvailability {
  memberId: string;                 // ID of member
  date: string;                     // Date for availability
  timeSlots: {
    start: string;                  // Start time (ISO string)
    end: string;                    // End time (ISO string)
    available: boolean;             // Whether available in this slot
    reason?: string;                // Reason if not available
  }[];
  workingHours: {
    start: string;                  // Working day start time
    end: string;                    // Working day end time
  };
  breaks: {
    start: string;                  // Break start time
    end: string;                    // Break end time
    type: 'lunch' | 'coffee' | 'personal'; // Break type
  }[];
}
```

## Type Definitions

### Member Type Guards

Type guard functions for member-related interfaces.

```typescript
// Type guard for checking if object is a valid MemberDto
function isMemberDto(obj: any): obj is MemberDto {
  return obj && 
         typeof obj === 'object' && 
         typeof obj.email === 'string' &&
         (obj.object === undefined || obj.object === 'MemberDto');
}

// Type guard for checking if member has active status
function isActiveMember(member: IMember): boolean {
  return member.profileStatus === MemberProfileStatusEnum.active;
}

// Type guard for checking if member has specific role
function hasMemberRole(member: IMember, role: RoleEnum): boolean {
  return member.role === role || 
         (member.roles && member.roles.some(r => r.name === role));
}

// Type guard for checking if member can provide service
function canProvideService(member: IMember, serviceId: string): boolean {
  if (!member.assignments?.service) return false;
  
  if (member.assignments.service.full) return true;
  
  return member.assignments.service.include?.some(
    service => service.serviceId === serviceId || service.service === serviceId
  ) || false;
}
```

### Utility Types

Utility types for member management operations.

```typescript
// Partial member for updates
type MemberUpdate = Partial<Pick<IMember, 
  'firstName' | 'lastName' | 'phone' | 'language' | 'profileStatus' | 'assignments'
>>;

// Member creation data
type MemberCreate = Pick<IMember, 'email'> & 
  Partial<Pick<IMember, 'firstName' | 'lastName' | 'phone' | 'role' | 'language'>>;

// Member search criteria
type MemberSearchCriteria = {
  email?: string;
  name?: string;
  role?: RoleEnum;
  profileStatus?: MemberProfileStatusEnum;
  hasAssignments?: boolean;
};

// Member summary for lists
type MemberSummary = Pick<IMember, 
  '_id' | 'firstName' | 'lastName' | 'email' | 'role' | 'profileStatus' | 'createdAt'
>;
```

## Constants

### Default Values

```typescript
export const MEMBER_DEFAULTS = {
  role: RoleEnum.SPECIALIST,
  profileStatus: MemberProfileStatusEnum.active,
  language: LanguageCodeEnum.en,
  assignments: {
    service: {
      full: false,
      include: []
    }
  }
} as const;
```

### Validation Constraints

```typescript
export const MEMBER_CONSTRAINTS = {
  firstName: {
    minLength: 1,
    maxLength: 50
  },
  lastName: {
    minLength: 1,
    maxLength: 50
  },
  email: {
    maxLength: 100,
    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  },
  phone: {
    minLength: 10,
    maxLength: 20,
    pattern: /^[\+]?[1-9][\d]{0,15}$/
  }
} as const;
```

***

This interface documentation provides a comprehensive reference for all TypeScript interfaces, DTOs, enums, and contracts used in the Member Management module. These definitions ensure type safety and clear contracts between different layers of the application.

For implementation details and business logic, refer to the [Use Case Documentation](/services/member-management/usecase) and [API Documentation](/services/member-management/api).


# 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


# Database Schema

## Overview

The member management module uses MongoDB with Mongoose ODM for data persistence. The schema follows Domain-Driven Design principles with proper separation between domain models and persistence models.

## Core Entities

### Member Entity

**Collection**: `member`

**Schema Definition**: `MemberSchema`

| Field           | Type                        | Required | Default   | Description                         |
| --------------- | --------------------------- | -------- | --------- | ----------------------------------- |
| `_id`           | `ObjectId`                  | Auto     | Generated | Unique identifier                   |
| `firstName`     | `String`                    | No       | -         | Member's first name                 |
| `lastName`      | `String`                    | No       | -         | Member's last name                  |
| `phone`         | `String`                    | No       | -         | Contact phone number                |
| `email`         | `String`                    | Yes      | -         | Email address (unique per tenant)   |
| `avatar`        | `ObjectId`                  | No       | -         | Reference to Media entity           |
| `memberContext` | `ObjectId`                  | No       | -         | Reference to MemberContext entity   |
| `profileStatus` | `String`                    | No       | `active`  | Current status of member profile    |
| `language`      | `String`                    | No       | `en`      | Preferred language code             |
| `referal`       | `ReferalSchema`             | No       | -         | Invitation and referral information |
| `role`          | `String`                    | No       | `ADMIN`   | Legacy role field (deprecated)      |
| `roles`         | `Array<RoleSchema>`         | No       | `[]`      | New role-based permissions          |
| `assignments`   | `AssignmentsSchema`         | No       | -         | Service assignment configuration    |
| `stateHistory`  | `Array<StateHistorySchema>` | No       | `[]`      | State change tracking               |
| `createdAt`     | `Date`                      | Auto     | Current   | Creation timestamp                  |
| `updatedAt`     | `Date`                      | Auto     | Current   | Last update timestamp               |

### Profile Status Enum

```typescript
enum MemberProfileStatusEnum {
    active = 'active',
    deleted = 'deleted', 
    suspended = 'suspended'
}
```

**Usage**: Tracks the current state of a member's profile for access control and filtering.

### Language Code Enum

Follows ISO 639-1 standard language codes for internationalization support.

## Sub-Schemas

### Referral Schema (`ReferalSchema`)

**Purpose**: Manages invitation codes and referral tracking for member onboarding.

| Field            | Type     | Required | Default          | Description                  |
| ---------------- | -------- | -------- | ---------------- | ---------------------------- |
| `invitationCode` | `String` | Yes      | Generated        | Unique invitation code       |
| `active`         | `Number` | No       | `ActiveEnum.YES` | Whether invitation is active |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps

**Business Rules**:

* Invitation codes are auto-generated using secure random generation
* Active status controls whether invitation can be used
* Used for member invitation workflows

### Assignments Schema (`AssignmentsSchema`)

**Purpose**: Defines which services and features a member has access to.

| Field     | Type                      | Required | Default | Description                  |
| --------- | ------------------------- | -------- | ------- | ---------------------------- |
| `service` | `AssignmentServiceSchema` | Yes      | -       | Service access configuration |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps

### Assignment Service Schema (`AssignmentServiceSchema`)

**Purpose**: Configures service-level access permissions.

| Field     | Type                           | Required | Default | Description                            |
| --------- | ------------------------------ | -------- | ------- | -------------------------------------- |
| `full`    | `Boolean`                      | Yes      | `false` | Whether member has full service access |
| `include` | `Array<AssignedServiceSchema>` | No       | `[]`    | Specific services if not full access   |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps

**Business Logic**:

* When `full: true`, member has access to all services
* When `full: false`, only services in `include` array are accessible
* Provides granular service-level permission control

### Assigned Service Schema (`AssignedServiceSchema`)

**Purpose**: References specific services for granular access control.

| Field     | Type       | Required | Default | Description                 |
| --------- | ---------- | -------- | ------- | --------------------------- |
| `service` | `ObjectId` | Yes      | -       | Reference to Service entity |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps
* `ref: Service.name` - References Service collection

## Relationships

### Member → Media (Avatar)

* **Type**: One-to-One (Optional)
* **Field**: `avatar`
* **Collection**: `media`
* **Description**: References uploaded avatar image file

### Member → MemberContext

* **Type**: One-to-One (Optional)
* **Field**: `memberContext`
* **Collection**: `member-context`
* **Description**: Links member to authentication context and account

### Member → Roles

* **Type**: One-to-Many
* **Field**: `roles`
* **Schema**: `RoleSchema`
* **Description**: New role-based permission system

### AssignedService → Service

* **Type**: Many-to-One
* **Field**: `assignments.service.include[].service`
* **Collection**: `service`
* **Description**: References specific services for access control

## Indexes

### Recommended Indexes

```javascript
// Unique email per tenant (compound index)
{ "email": 1, "tenantId": 1 }

// Profile status for filtering
{ "profileStatus": 1 }

// Role-based queries
{ "roles.name": 1 }

// Full text search on name and email
{ 
  "firstName": "text", 
  "lastName": "text", 
  "email": "text" 
}

// Timestamp queries
{ "createdAt": 1 }
{ "updatedAt": 1 }

// Member context relationship
{ "memberContext": 1 }
```

### Performance Considerations

* **Email Uniqueness**: Compound index with tenant ensures email uniqueness per tenant
* **Text Search**: Full-text search index for member discovery
* **Status Filtering**: Index on profileStatus for active/deleted member queries
* **Role Queries**: Index on role names for permission-based filtering

## Data Integrity

### Validation Rules

1. **Email Format**: Must be valid email format
2. **Profile Status**: Must be one of defined enum values
3. **Language Code**: Must be valid ISO 639-1 code
4. **Role References**: Must reference existing roles
5. **Service References**: Must reference existing services

### Constraints

1. **Email Uniqueness**: Email must be unique within tenant
2. **Referral Code Uniqueness**: Invitation codes must be globally unique
3. **Required Fields**: Email is the only strictly required field
4. **Soft Delete**: Use profileStatus instead of physical deletion

### Data Migration Considerations

1. **Role Migration**: Legacy `role` field being replaced by `roles` array
2. **Assignment Structure**: Support for both full and granular access patterns
3. **Context Linking**: MemberContext may be optional during migration
4. **State History**: Preserved for audit and rollback capabilities

## Audit and History

### State History

The `stateHistory` field tracks all significant state changes:

* Profile status changes
* Role modifications
* Assignment updates
* Email changes

### Timestamps

* `createdAt`: Automatic creation timestamp
* `updatedAt`: Automatic update timestamp
* Used for audit trails and data analysis

## Multi-Tenancy

### Tenant Isolation

* Members belong to specific tenants
* Email uniqueness enforced per tenant
* Queries must include tenant context
* Cross-tenant access is prevented

### Tenant-Aware Operations

All database operations include tenant context:

* Create operations include tenant ID
* Read operations filter by tenant
* Update/Delete operations validate tenant ownership

## Backup and Recovery

### Backup Strategy

1. **Document Integrity**: Full document backup including sub-schemas
2. **Relationship Preservation**: Maintain ObjectId references
3. **State History**: Include complete audit trail
4. **Media References**: Coordinate with media storage backup

### Recovery Considerations

1. **Role Dependencies**: Ensure role definitions exist before member restore
2. **Service Dependencies**: Validate service references during restore
3. **Context Linking**: Restore member contexts before members
4. **Invitation Codes**: Maintain uniqueness during recovery

## Security Considerations

### Data Protection

1. **PII Handling**: First name, last name, phone, email are PII
2. **Access Control**: Role-based access to member data
3. **Audit Logging**: State history for compliance
4. **Soft Delete**: Maintain data for compliance while marking as deleted

### Permission Model

1. **Role-Based**: New roles array supports complex permission inheritance
2. **Service-Based**: Granular service access control
3. **Owner Protection**: Special validation for owner role changes
4. **Self-Service**: Limited self-editing capabilities

## Performance Monitoring

### Query Patterns

1. **Paginated Lists**: Monitor pagination query performance
2. **Search Operations**: Track full-text search efficiency
3. **Role Filtering**: Monitor role-based filtering performance
4. **Assignment Lookups**: Track service assignment query patterns

### Optimization Strategies

1. **Index Utilization**: Ensure proper index usage
2. **Population Strategy**: Optimize related data loading
3. **Caching Strategy**: Cache frequently accessed member data
4. **Query Aggregation**: Use aggregation for complex reporting

## Development Guidelines

### Schema Evolution

1. **Backward Compatibility**: Maintain compatibility during updates
2. **Migration Scripts**: Provide migration for schema changes
3. **Default Values**: Use appropriate defaults for new fields
4. **Validation Updates**: Update validation with schema changes

### Testing Strategies

1. **Unit Tests**: Test schema validation rules
2. **Integration Tests**: Test with real MongoDB instance
3. **Migration Tests**: Validate schema migration scripts
4. **Performance Tests**: Load test with realistic data volumes


# Order Management

## Overview

This directory contains comprehensive documentation for the Order Management module of the Bee O'clock panel service. The order management system handles the complete lifecycle of customer orders, including services and products, with advanced scheduling, payment tracking, and multi-tenant support within the SaaS platform.

## Documentation Structure

### [API Documentation](/services/order-management/api)

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

**Key Topics Covered:**

* Order CRUD operations with validation
* Paginated order listing with advanced filtering
* Order service and product management
* Status management and workflow transitions
* Comprehensive data schemas and validation
* Error handling and business rule enforcement
* Performance optimization and monitoring

### [Interface Documentation](/services/order-management/interface)

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

**Key Topics Covered:**

* Data Transfer Objects (DTOs) with validation
* Domain interfaces and entity definitions
* Enum definitions and business constants
* Type definitions and utility types
* Validation constraints and business rules
* Event interfaces for system integration
* Repository contracts and specifications

### [Use Case Documentation](/services/order-management/usecase)

Business logic and use case implementations following Clean Architecture principles and CQRS pattern with comprehensive saga workflows.

**Key Topics Covered:**

* Core business use cases with permission validation
* Saga pattern implementation with rollback capabilities
* Error handling strategies and compensation logic
* Event publishing and system integration
* Performance considerations and optimization
* Integration patterns with external services

### [Database Schema Documentation](/services/order-management/db_schema)

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

**Key Topics Covered:**

* Entity schemas and sub-document structures
* Index strategies and query optimization
* Multi-tenancy support and data isolation
* Data validation and business constraints
* Audit trail and state history tracking
* Performance optimization and monitoring

## Module Architecture

### Technology Stack

* **Framework**: NestJS with TypeScript
* **Database**: MongoDB with Mongoose ODM
* **Architecture**: Clean Architecture + CQRS + DDD
* **Patterns**: Repository Pattern, Saga Pattern, Event-Driven Architecture
* **Caching**: Redis for performance optimization
* **Queue System**: AMQP for async processing
* **Monitoring**: Comprehensive logging and metrics

### Core Features

#### Order Lifecycle Management

* Comprehensive order creation with validation and conflict detection
* Multi-step update workflows with change tracking and audit trails
* Status management with predefined transition rules and business validation
* Soft deletion with dependency checking and data preservation

#### Service Management

* Individual service scheduling within orders
* Specialist assignment and availability validation
* Appointment conflict prevention and resolution
* Service-specific status tracking and workflow management

#### Product Management

* Product inclusion in orders with quantity management
* Service-associated products with relationship tracking
* Inventory integration and stock validation
* Product-specific payment status tracking

#### Advanced Scheduling

* Real-time specialist availability checking
* Appointment conflict detection and prevention
* Multi-timezone support with proper date handling
* Flexible appointment rescheduling with validation

#### Payment Integration

* Order-level and item-level payment status tracking
* Payment workflow integration with external services
* Payment constraint validation for order modifications
* Comprehensive payment audit trails

#### Multi-Tenant Architecture

* Complete tenant data isolation with security
* Tenant-specific business rule configuration
* Scalable database partitioning strategies
* Performance optimization per tenant size

## Business Rules

### Order Creation

1. **Comprehensive Validation**: All services and products must be valid and available
2. **Conflict Prevention**: Specialist availability validation prevents double booking
3. **Customer Management**: Automatic customer creation and validation workflows
4. **Business Rule Enforcement**: Compliance with tenant-specific configuration
5. **Payment Requirements**: Payment policy validation and enforcement

### Order Updates

1. **Change Validation**: Strict validation of what can be changed and when
2. **Status Transitions**: Predefined valid status transition workflows
3. **Time Constraints**: Cannot modify past appointments or completed orders
4. **Payment Constraints**: Cannot modify orders with completed payments
5. **Permission Validation**: User must have appropriate permissions for scope of changes

### Order Deletion

1. **Soft Deletion**: Orders are marked as deleted rather than physically removed
2. **Dependency Checking**: Cannot delete orders with active dependencies or references
3. **Payment Protection**: Cannot delete orders with active or completed payments
4. **Data Preservation**: Historical data maintained for compliance and audit requirements
5. **Cleanup Coordination**: Automatic cleanup of related resources and notifications

### Service Management

1. **Specialist Assignment**: At least one specialist must be assigned to each service
2. **Availability Validation**: Specialists must be available during requested times
3. **Conflict Prevention**: Cannot create overlapping appointments for same specialist
4. **Status Dependencies**: Service status changes must follow valid transition rules
5. **Customer Communication**: Automatic notifications for status changes

### Permission Management

1. **Role-Based Access**: Different permission levels for different user roles
2. **Scope-Based Filtering**: OWN scope restricts access to user's assigned orders
3. **Tenant Isolation**: Complete data isolation between different tenants
4. **Audit Logging**: All access attempts and changes are logged for security
5. **Permission Inheritance**: Service permissions inherit from order permissions

## API Integration Examples

### Creating a Complex Order

```typescript
POST /api/v1/order
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "services": [
    {
      "serviceSnapshot": {
        "_id": "64fa1c71b19d6d001c88a921",
        "languageVersions": [
          {
            "language": "en",
            "title": "Premium Massage Therapy",
            "description": "90-minute therapeutic massage with aromatherapy"
          }
        ],
        "durationVersions": [
          {
            "durationInSeconds": 5400,
            "breakInSeconds": 300,
            "prices": [
              {
                "price": 120.00,
                "currency": "USD",
                "preferredLanguages": ["en"]
              }
            ]
          }
        ]
      },
      "orderAppointmentDetails": {
        "start": "2024-07-26T14:00:00.000Z",
        "end": "2024-07-26T15:30:00.000Z",
        "type": "service",
        "languageCodes": ["en"],
        "specialists": [
          {
            "_id": "64fa1c71b19d6d001c88a922",
            "member": {
              "_id": "64fa1c71b19d6d001c88a923"
            }
          }
        ],
        "attendants": [
          {
            "customer": {
              "firstName": "Jane",
              "lastName": "Smith",
              "email": "jane.smith@example.com",
              "phone": "+1-555-123-4567"
            },
            "firstTime": true
          }
        ],
        "location": {
          "address": "123 Wellness Street, Health City, HC 12345",
          "coordinates": {
            "latitude": 40.7128,
            "longitude": -74.0060
          },
          "roomNumber": "Room 201",
          "buildingInfo": "Wellness Center - Second Floor"
        }
      },
      "customerNote": "Client prefers lavender oil for aromatherapy. Has mild allergy to eucalyptus.",
      "status": "requested"
    }
  ],
  "products": [
    {
      "productSnapshot": {
        "_id": "64fa1c71b19d6d001c88a926",
        "title": "Premium Aromatherapy Oil Set",
        "description": "Organic essential oils for therapeutic massage",
        "price": 35.00,
        "currency": "USD",
        "category": "aromatherapy"
      },
      "quantity": 1
    },
    {
      "productSnapshot": {
        "_id": "64fa1c71b19d6d001c88a927",
        "title": "Relaxation Gift Card",
        "description": "$50 gift card for future services",
        "price": 50.00,
        "currency": "USD",
        "category": "gift-cards"
      },
      "quantity": 1
    }
  ],
  "businessNote": "VIP customer - provide extra attention and premium amenities",
  "notificationSettings": {
    "emailNotifications": true,
    "smsNotifications": true,
    "pushNotifications": true,
    "reminderSettings": {
      "enabled": true,
      "timeBeforeInMinutes": 120
    }
  }
}
```

### Advanced Order Filtering

```typescript
GET /api/v1/order/paged?page=1&size=20&statuses[]=confirmed&statuses[]=inProgress&start=2024-07-01T00:00:00.000Z&end=2024-07-31T23:59:59.999Z&memberIds[]=64fa1c71b19d6d001c88a922&memberIds[]=64fa1c71b19d6d001c88a924
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

### Updating Order Status with Workflow

```typescript
PUT /api/v1/order/64fa1c71b19d6d001c88a91f
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "_id": "64fa1c71b19d6d001c88a91f",
  "status": "confirmed",
  "services": [
    {
      "_id": "64fa1c71b19d6d001c88a920",
      "status": "accepted",
      "customerNote": "Updated: Client confirmed aromatherapy preferences"
    }
  ],
  "businessNote": "Updated: Customer confirmed appointment and special requests",
  "notificationSettings": {
    "emailNotifications": true,
    "smsNotifications": true,
    "pushNotifications": true,
    "reminderSettings": {
      "enabled": true,
      "timeBeforeInMinutes": 60
    }
  }
}
```

## Development Guidelines

### Testing Strategy

* **Unit Tests**: Business logic validation and domain rule enforcement
* **Integration Tests**: Database operations and external service integration
* **E2E Tests**: Complete order workflow validation from creation to completion
* **Performance Tests**: Load testing and scalability validation under high concurrency
* **Security Tests**: Permission validation and data isolation verification

### Error Handling

* Domain-specific exceptions with clear error codes and messages
* Consistent error response format across all endpoints with detailed context
* Proper HTTP status codes for different error categories and business scenarios
* Comprehensive logging for debugging and monitoring with correlation IDs
* Graceful degradation for non-critical failures with fallback mechanisms

### Performance Considerations

* Comprehensive database indexing strategy for optimal query performance
* Multi-level caching with intelligent invalidation and cache warming
* Optimized queries with proper data loading and projection strategies
* Asynchronous processing for non-critical operations and notifications
* Connection pooling and resource management for high concurrency

### Security Best Practices

* Input validation and sanitization at all API and business logic levels
* Role-based access control with granular permissions and scope enforcement
* Audit logging for all sensitive operations with complete traceability
* Rate limiting and abuse prevention with intelligent throttling
* Data encryption for sensitive information in transit and at rest

## Related Modules

### Dependencies

* **Permission Module**: Role and permission management with scope-based access control
* **Customer Module**: Customer creation, validation, and profile management
* **Service Module**: Service configuration, availability, and scheduling validation
* **Member Module**: Specialist assignment, availability checking, and workload management
* **Product Module**: Product catalog, inventory management, and pricing validation
* **Business Client Module**: Tenant management, configuration, and business rules
* **Payment Module**: Payment processing, status tracking, and financial workflows

### Integration Points

* **Cache Module**: Performance optimization with intelligent cache management
* **Event Bus**: Async processing and cross-module communication
* **Notification Module**: Order-related notifications and customer communication
* **Analytics Module**: Business intelligence and performance metrics
* **Audit Module**: Compliance tracking and change history management
* **Workflow Module**: Business process automation and approval workflows

## Performance Metrics

### Key Performance Indicators

* Order creation/update response times and throughput metrics
* Search and filtering query performance with optimization tracking
* Database query performance analysis and slow query identification
* Cache hit rates and effectiveness measurement across different data types
* Error rate monitoring and categorization for business and technical issues

### Monitoring and Alerting

* Real-time API endpoint response time monitoring with SLA tracking
* Database performance and query analysis with automated optimization suggestions
* Cache performance and hit rate tracking with capacity planning
* Business workflow success rates and completion metrics
* Comprehensive error rate monitoring with intelligent alerting and escalation

## Scalability Considerations

### Horizontal Scaling

* Stateless service design for easy horizontal scaling across multiple instances
* Database sharding strategies for large datasets with tenant-based partitioning
* Distributed caching for multi-instance deployment with consistency guarantees
* Load balancing for API endpoints with intelligent request routing
* Microservice-ready architecture with clear service boundaries

### Vertical Scaling

* Database optimization and indexing with continuous performance monitoring
* Query performance tuning with automated query plan analysis
* Memory usage optimization with efficient data structures and caching
* CPU-intensive operation optimization with async processing and batching
* Storage efficiency improvements with data compression and archival strategies

## Future Enhancements

### Planned Features

* **AI-Powered Scheduling**: Intelligent appointment suggestions based on historical data and preferences
* **Dynamic Pricing**: Time and demand-based pricing models with real-time adjustment
* **Advanced Analytics**: Comprehensive business intelligence with predictive analytics
* **Mobile Optimization**: Enhanced mobile API support with offline capabilities
* **Integration Marketplace**: Third-party service integrations with standardized APIs

### Technical Improvements

* **Event Sourcing**: Complete audit trail with event replay capabilities for compliance
* **GraphQL API**: Enhanced query capabilities and client-specific data fetching
* **Microservice Architecture**: Split into focused microservices with clear boundaries
* **Real-time Updates**: WebSocket integration for live order status updates
* **Advanced Search**: Elasticsearch integration for complex search and analytics

## Troubleshooting Guide

### Common Issues

* **Order Creation Failures**: Validation errors, specialist conflicts, and resolution strategies
* **Permission Denied Errors**: Access control troubleshooting and permission verification
* **Performance Issues**: Query optimization, caching improvements, and resource scaling
* **Data Consistency**: Multi-tenant isolation problems and data integrity validation
* **Integration Failures**: External service communication and fallback mechanisms

### Debugging Tools

* Structured error messages with correlation IDs for request tracing
* Comprehensive logging with request context and business operation tracking
* Database query analysis tools with performance profiling
* Cache inspection utilities with hit rate and eviction monitoring
* Performance profiling tools with bottleneck identification

### Support Resources

* Comprehensive API documentation with interactive examples and use cases
* Error code reference guide with resolution strategies and best practices
* Performance optimization guide with specific recommendations and benchmarks
* Best practices documentation with coding standards and architectural guidelines
* Community forums and support channels with expert assistance

## Contributing Guidelines

### Code Standards

* TypeScript strict mode compliance with comprehensive type safety
* ESLint and Prettier configuration with automated formatting and linting
* Comprehensive test coverage requirements with minimum thresholds
* Clean Architecture principles adherence with clear layer separation
* Domain-Driven Design patterns with rich domain models

### Documentation Requirements

* Update documentation with all code changes and new features
* Include comprehensive API examples with real-world use cases
* Maintain schema documentation accuracy with automated validation
* Document business rule changes with impact analysis
* Provide migration guides for breaking changes with step-by-step instructions

### Review Process

* Mandatory code review for all changes with multiple reviewer approval
* Testing validation and coverage verification with automated quality gates
* Documentation update validation with completeness checking
* Performance impact assessment with benchmarking requirements
* Security review for sensitive changes with threat modeling

## Migration and Deployment

### Database Migrations

* Schema evolution and backwards compatibility with version management
* Data migration scripts and validation with rollback procedures
* Index management and optimization with performance impact assessment
* Performance impact assessment with before/after benchmarking
* Rollback procedures and safety measures with automated recovery

### Deployment Strategies

* Blue-green deployment for zero downtime with automated health checks
* Feature flags for gradual rollouts with real-time monitoring
* Database migration coordination with application deployment
* Cache warming strategies with performance optimization
* Comprehensive health check validation with automated rollback triggers

### Monitoring and Rollback

* Real-time deployment monitoring with comprehensive metrics and alerting
* Automated rollback triggers with intelligent failure detection
* Data integrity validation with comprehensive consistency checking
* Performance regression detection with automated benchmarking
* User impact assessment with real-time feedback and metrics


# API Documentation

## Overview

The Order Management API provides comprehensive functionality for managing orders within the Bee O'clock panel service. This module handles the complete order lifecycle, including creation, updates, status management, and deletion of orders containing services and products.

## Base Configuration

### Authentication

All endpoints require Bearer token authentication.

### Headers

* `Authorization: Bearer <token>` - Required for all endpoints
* `x-business-tenant-id: <tenant_id>` - Required for multi-tenancy support
* `Content-Type: application/json` - For POST/PUT requests

### Base URL

```
/api/v1/order
```

## Endpoints

### 1. Get Paginated Orders

**Endpoint:** `GET /api/v1/order/paged`

**Description:** Retrieves a paginated list of orders with advanced filtering capabilities.

**Query Parameters:**

```typescript
{
  page?: number;           // Page number (default: 1)
  size?: number;           // Items per page (default: 10)
  phrase?: string;         // Search phrase for order content
  start?: string;          // Start date filter (ISO string)
  end?: string;            // End date filter (ISO string)
  customerId?: string;     // Filter by customer ID
  statuses?: OrderStatusEnum[]; // Filter by order statuses
  memberIds?: string[];    // Filter by assigned member IDs
}
```

**Response:**

```typescript
{
  items: OrderDto[];
  totalSize: number;
}
```

**Example Request:**

```bash
GET /api/v1/order/paged?page=1&size=10&statuses[]=inProgress&statuses[]=confirmed&start=2024-01-01T00:00:00.000Z&end=2024-12-31T23:59:59.999Z
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64fa1c71b19d6d001c88a91f",
      "status": "confirmed",
      "services": [
        {
          "_id": "64fa1c71b19d6d001c88a920",
          "orderId": "64fa1c71b19d6d001c88a91f",
          "serviceSnapshot": {
            "_id": "64fa1c71b19d6d001c88a921",
            "languageVersions": [
              {
                "language": "en",
                "title": "Premium Massage Therapy",
                "description": "Relaxing therapeutic massage"
              }
            ]
          },
          "orderAppointmentDetails": {
            "start": "2024-07-26T10:00:00.000Z",
            "end": "2024-07-26T11:00:00.000Z",
            "specialists": [
              {
                "_id": "64fa1c71b19d6d001c88a922",
                "profile": {
                  "firstName": "John",
                  "lastName": "Doe"
                }
              }
            ]
          },
          "status": "confirmed",
          "paymentStatus": "pending"
        }
      ],
      "products": [],
      "paymentStatus": "pending",
      "businessNote": "VIP customer",
      "customer": {
        "_id": "64fa1c71b19d6d001c88a923",
        "firstName": "Jane",
        "lastName": "Smith",
        "email": "jane.smith@example.com"
      },
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:30:00.000Z"
    }
  ],
  "totalSize": 25
}
```

### 2. Get Order by ID

**Endpoint:** `GET /api/v1/order/{id}`

**Description:** Retrieves a specific order by its ID with permission validation.

**Path Parameters:**

* `id` (string, required) - Order ID

**Response:** `OrderDto`

**Example Request:**

```bash
GET /api/v1/order/64fa1c71b19d6d001c88a91f
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a91f",
  "status": "confirmed",
  "services": [
    {
      "_id": "64fa1c71b19d6d001c88a920",
      "orderId": "64fa1c71b19d6d001c88a91f",
      "serviceSnapshot": {
        "_id": "64fa1c71b19d6d001c88a921",
        "languageVersions": [
          {
            "language": "en",
            "title": "Premium Massage Therapy",
            "description": "Relaxing therapeutic massage with aromatherapy"
          }
        ],
        "durationVersions": [
          {
            "durationInSeconds": 3600,
            "breakInSeconds": 300,
            "prices": [
              {
                "price": 80.00,
                "currency": "USD",
                "preferredLanguages": ["en"]
              }
            ]
          }
        ]
      },
      "orderAppointmentDetails": {
        "start": "2024-07-26T10:00:00.000Z",
        "end": "2024-07-26T11:00:00.000Z",
        "type": "service",
        "languageCodes": ["en"],
        "specialists": [
          {
            "_id": "64fa1c71b19d6d001c88a922",
            "profile": {
              "firstName": "John",
              "lastName": "Doe",
              "email": "john.doe@example.com"
            }
          }
        ],
        "attendants": [
          {
            "customer": {
              "_id": "64fa1c71b19d6d001c88a923",
              "firstName": "Jane",
              "lastName": "Smith",
              "email": "jane.smith@example.com"
            },
            "firstTime": true
          }
        ],
        "location": {
          "address": "123 Wellness Street, Health City",
          "coordinates": {
            "latitude": 40.7128,
            "longitude": -74.0060
          }
        }
      },
      "status": "confirmed",
      "customerNote": "Please use lavender oil for aromatherapy",
      "paymentStatus": "pending",
      "meta": {
        "source": "panel",
        "createdBy": "64fa1c71b19d6d001c88a924"
      },
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:30:00.000Z"
    }
  ],
  "products": [
    {
      "_id": "64fa1c71b19d6d001c88a925",
      "orderId": "64fa1c71b19d6d001c88a91f",
      "orderServiceId": "64fa1c71b19d6d001c88a920",
      "productSnapshot": {
        "_id": "64fa1c71b19d6d001c88a926",
        "title": "Aromatherapy Oil Set",
        "description": "Premium essential oils for massage therapy",
        "price": 25.00,
        "currency": "USD"
      },
      "quantity": 1,
      "paymentStatus": "pending",
      "meta": {
        "addedBy": "64fa1c71b19d6d001c88a924"
      }
    }
  ],
  "paymentStatus": "pending",
  "businessNote": "VIP customer - extra attention required",
  "notificationSettings": {
    "emailNotifications": true,
    "smsNotifications": false,
    "pushNotifications": true
  },
  "customer": {
    "_id": "64fa1c71b19d6d001c88a923",
    "firstName": "Jane",
    "lastName": "Smith",
    "email": "jane.smith@example.com",
    "phone": "+1-555-123-4567"
  },
  "meta": {
    "source": "panel",
    "createdBy": "64fa1c71b19d6d001c88a924",
    "lastModifiedBy": "64fa1c71b19d6d001c88a924"
  },
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:30:00.000Z"
}
```

### 3. Create Order

**Endpoint:** `POST /api/v1/order`

**Description:** Creates a new order with services and products through a saga pattern with validation and rollback capabilities.

**Request Body:** `OrderDto`

**Response:** `OrderDto`

**Example Request:**

```bash
POST /api/v1/order
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "services": [
    {
      "serviceSnapshot": {
        "_id": "64fa1c71b19d6d001c88a921",
        "languageVersions": [
          {
            "language": "en",
            "title": "Premium Massage Therapy",
            "description": "Relaxing therapeutic massage with aromatherapy"
          }
        ],
        "durationVersions": [
          {
            "durationInSeconds": 3600,
            "breakInSeconds": 300,
            "prices": [
              {
                "price": 80.00,
                "currency": "USD",
                "preferredLanguages": ["en"]
              }
            ]
          }
        ]
      },
      "orderAppointmentDetails": {
        "start": "2024-07-26T10:00:00.000Z",
        "end": "2024-07-26T11:00:00.000Z",
        "type": "service",
        "languageCodes": ["en"],
        "specialists": [
          {
            "_id": "64fa1c71b19d6d001c88a922"
          }
        ],
        "attendants": [
          {
            "customer": {
              "_id": "64fa1c71b19d6d001c88a923"
            },
            "firstTime": true
          }
        ],
        "location": {
          "address": "123 Wellness Street, Health City",
          "coordinates": {
            "latitude": 40.7128,
            "longitude": -74.0060
          }
        }
      },
      "customerNote": "Please use lavender oil for aromatherapy",
      "status": "requested"
    }
  ],
  "products": [
    {
      "productSnapshot": {
        "_id": "64fa1c71b19d6d001c88a926",
        "title": "Aromatherapy Oil Set",
        "description": "Premium essential oils for massage therapy",
        "price": 25.00,
        "currency": "USD"
      },
      "quantity": 1
    }
  ],
  "businessNote": "VIP customer - extra attention required",
  "notificationSettings": {
    "emailNotifications": true,
    "smsNotifications": false,
    "pushNotifications": true
  },
  "customer": {
    "_id": "64fa1c71b19d6d001c88a923"
  }
}
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a91f",
  "status": "requested",
  "services": [...],
  "products": [...],
  "paymentStatus": "pending",
  "businessNote": "VIP customer - extra attention required",
  "customer": {...},
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:00:00.000Z"
}
```

### 4. Update Order

**Endpoint:** `PUT /api/v1/order/{id}`

**Description:** Updates an existing order with validation and permission checks.

**Path Parameters:**

* `id` (string, required) - Order ID

**Request Body:** `OrderDto`

**Response:** `OrderDto`

**Example Request:**

```bash
PUT /api/v1/order/64fa1c71b19d6d001c88a91f
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "_id": "64fa1c71b19d6d001c88a91f",
  "status": "confirmed",
  "services": [
    {
      "_id": "64fa1c71b19d6d001c88a920",
      "status": "confirmed",
      "customerNote": "Updated note: Please use eucalyptus oil instead"
    }
  ],
  "businessNote": "Updated: VIP customer confirmed for premium service"
}
```

### 5. Delete Order

**Endpoint:** `DELETE /api/v1/order/{id}`

**Description:** Soft deletes an order with permission validation and dependency checking.

**Path Parameters:**

* `id` (string, required) - Order ID

**Response:** `void` (204 No Content)

**Example Request:**

```bash
DELETE /api/v1/order/64fa1c71b19d6d001c88a91f
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Data Models

### OrderDto

```typescript
{
  _id?: string;                              // Order ID
  status?: OrderStatusEnum;                  // Order status
  meta?: MetaDto;                           // Metadata information
  products?: OrderProductDto[];              // Order products
  services?: OrderServiceDto[];              // Order services
  paymentStatus?: PaymentStatusEnum;         // Payment status
  businessNote?: string;                     // Internal business note
  notificationSettings?: OrderNotificationSettingsDto; // Notification preferences
  customer?: CustomerDto;                    // Customer information
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### OrderServiceDto

```typescript
{
  _id?: string;                              // Service ID
  orderId?: string;                          // Parent order ID
  serviceSnapshot?: ServiceDto;              // Service configuration snapshot
  orderAppointmentDetails?: OrderAppointmentDetailsDto; // Appointment details
  status: OrderServiceStatusEnum;            // Service status
  customerNote?: string;                     // Customer note for service
  meta?: MetaDto;                           // Service metadata
  paymentStatus?: PaymentStatusEnum;         // Service payment status
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### OrderProductDto

```typescript
{
  _id?: string;                              // Product ID
  orderId?: string;                          // Parent order ID
  orderServiceId?: string;                   // Associated service ID
  productSnapshot: ProductDto;               // Product configuration snapshot
  quantity: number;                          // Product quantity
  meta?: MetaDto;                           // Product metadata
  paymentStatus?: PaymentStatusEnum;         // Product payment status
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### OrderAppointmentDetailsDto

```typescript
{
  start: string;                             // Appointment start time (ISO string)
  end: string;                               // Appointment end time (ISO string)
  type?: ReservationTypeEnum;                // Reservation type
  languageCodes?: LanguageCodeEnum[];        // Preferred languages
  specialists: SpecialistDto[];              // Assigned specialists
  attendants?: AttendantDto[];               // Service attendants
  location?: LocationDto;                    // Service location
  attachments?: AttachmentDto[];             // Additional attachments
}
```

### OrderPaginationDto

```typescript
{
  page?: number;                             // Page number
  size?: number;                             // Items per page
  phrase?: string;                           // Search phrase
  start?: string;                            // Start date filter
  end?: string;                              // End date filter
  customerId?: string;                       // Customer ID filter
  statuses?: OrderStatusEnum[];              // Status filters
  memberIds?: string[];                      // Member ID filters
}
```

## Enums

### OrderStatusEnum

```typescript
enum OrderStatusEnum {
  draft = 'draft',                           // Order in draft state
  deleted = 'deleted',                       // Order deleted
  requested = 'requested',                   // Order requested
  confirmed = 'confirmed',                   // Order confirmed
  inProgress = 'inProgress',                 // Order in progress
  done = 'done',                            // Order completed
  cancelled = 'cancelled',                   // Order cancelled
  rejected = 'rejected',                     // Order rejected
  waitingForPayment = 'waitingForPayment'    // Awaiting payment
}
```

### OrderServiceStatusEnum

```typescript
enum OrderServiceStatusEnum {
  requested = 'requested',                   // Service requested
  accepted = 'accepted',                     // Service accepted
  ready = 'ready',                          // Service ready
  inProgress = 'inProgress',                 // Service in progress
  done = 'done',                            // Service completed
  rejected = 'rejected',                     // Service rejected
  cancelled = 'cancelled',                   // Service cancelled
  deleted = 'deleted'                        // Service deleted
}
```

### ReservationTypeEnum

```typescript
enum ReservationTypeEnum {
  service = 'service',                       // Service reservation
  event = 'event',                          // Event reservation
  consultation = 'consultation'              // Consultation reservation
}
```

### PaymentStatusEnum

```typescript
enum PaymentStatusEnum {
  pending = 'pending',                       // Payment pending
  processing = 'processing',                 // Payment processing
  completed = 'completed',                   // Payment completed
  failed = 'failed',                        // Payment failed
  refunded = 'refunded',                    // Payment refunded
  cancelled = 'cancelled'                    // Payment cancelled
}
```

## Error Handling

### Common Error Responses

#### 400 Bad Request

```json
{
  "statusCode": 400,
  "message": "Validation failed",
  "error": "Bad Request",
  "details": [
    {
      "field": "services[0].orderAppointmentDetails.start",
      "message": "Start time must be a valid ISO string"
    }
  ]
}
```

#### 401 Unauthorized

```json
{
  "statusCode": 401,
  "message": "Unauthorized",
  "error": "Authentication required"
}
```

#### 403 Forbidden

```json
{
  "statusCode": 403,
  "message": "Access denied",
  "error": "Insufficient permissions to access this order"
}
```

#### 404 Not Found

```json
{
  "statusCode": 404,
  "message": "Order not found",
  "error": "Order with ID 64fa1c71b19d6d001c88a91f does not exist"
}
```

#### 409 Conflict

```json
{
  "statusCode": 409,
  "message": "Order creation conflict",
  "error": "Specialist is not available during the requested time slot"
}
```

#### 422 Unprocessable Entity

```json
{
  "statusCode": 422,
  "message": "Business validation failed",
  "error": "Cannot cancel order with confirmed payment"
}
```

## Business Rules

### Order Creation

1. **Service Validation**: All services must be valid and available
2. **Time Slot Validation**: Appointment times must not conflict with existing bookings
3. **Specialist Availability**: Assigned specialists must be available during requested times
4. **Customer Validation**: Customer must exist and be valid
5. **Product Validation**: All products must be available in inventory

### Order Updates

1. **Status Transitions**: Updates must follow valid status transition rules
2. **Service Modification**: Changes to services require specialist availability validation
3. **Payment Constraints**: Cannot modify orders with completed payments
4. **Time Constraints**: Cannot modify past appointments
5. **Permission Validation**: User must have appropriate permissions for the scope of changes

### Order Deletion

1. **Soft Delete**: Orders are marked as deleted rather than physically removed
2. **Payment Check**: Cannot delete orders with active or completed payments
3. **Dependency Validation**: Cannot delete orders with dependent records
4. **History Preservation**: All historical data is maintained for audit purposes

### Permission Scopes

1. **OWN**: Users can only access orders assigned to them
2. **TEAM**: Users can access orders within their team
3. **BUSINESS**: Users can access all orders within the business
4. **ADMIN**: Full access to all order operations

## Performance Considerations

### Pagination

* Default page size: 10 items
* Maximum page size: 100 items
* Use pagination for large datasets to maintain performance

### Filtering

* Date range filters are optimized with database indexes
* Status filtering uses enum indexes for fast queries
* Member ID filtering supports array-based queries

### Caching

* Order data is cached for frequently accessed items
* Cache invalidation occurs on order updates
* Cache warming for dashboard queries

### Database Optimization

* Compound indexes on status, dates, and member IDs
* Separate collections for order services and products
* Optimized queries with projection for large orders

## Rate Limiting

* **Read Operations**: 100 requests per minute per user
* **Write Operations**: 30 requests per minute per user
* **Bulk Operations**: 10 requests per minute per user

## Monitoring and Logging

### Request Logging

All API requests are logged with:

* Request ID for tracing
* User context and permissions
* Performance metrics
* Error details and stack traces

### Business Event Logging

* Order status changes
* Payment status updates
* Service assignments and modifications
* Customer interactions and notes

### Performance Monitoring

* Response time tracking
* Database query performance
* Cache hit rates
* Error rate monitoring


# Interface Documentation

## Overview

This document provides comprehensive documentation of TypeScript interfaces, DTOs, enums, and contracts used throughout the Order Management module. All interfaces are based on real implementations from the codebase.

## Data Transfer Objects (DTOs)

### Core Order DTOs

#### OrderDto

```typescript
import { BaseEntityDto } from '@root/common/application/dto/base-entity.dto';
import { MetaDto } from '@root/common/application/dto/meta.dto';
import { PaymentStatusEnum } from '../../payment/domain/enums/payment.status.enum';
import { OrderStatusEnum } from '../domain/enums/order.status.enum';
import { OrderNotificationSettingsDto } from './sub/notification-settings';
import { OrderProductDto } from './sub/order-product.dto';
import { OrderServiceDto } from './sub/order-service.dto';
import { CustomerDto } from '../../customer/dtos/customer.dto';

@Exclude()
export class OrderDto extends BaseEntityDto {
  @ApiProperty({ example: 'OrderDto', required: false })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'OrderDto';

  @ApiProperty({
    enum: OrderStatusEnum,
    default: OrderStatusEnum.inProgress,
    required: false
  })
  @IsEnum(OrderStatusEnum)
  @Expose()
  status?: OrderStatusEnum;

  @ApiProperty({
    type: () => MetaDto,
    required: false
  })
  @Type(() => MetaDto)
  @IsOptional()
  @Expose()
  meta?: MetaDto;

  @ApiProperty({
    type: () => OrderProductDto,
    isArray: true,
    required: false
  })
  @IsArray()
  @Type(() => OrderProductDto)
  @IsOptional()
  @Expose()
  products?: OrderProductDto[];

  @ApiProperty({
    type: () => OrderServiceDto,
    isArray: true,
    required: false
  })
  @IsArray()
  @Type(() => OrderServiceDto)
  @IsOptional()
  @Expose()
  services?: OrderServiceDto[];

  @ApiProperty({
    enum: PaymentStatusEnum, 
    default: PaymentStatusEnum.pending,
    required: false
  })
  @IsEnum(PaymentStatusEnum)
  @IsOptional()
  @Expose()
  paymentStatus?: PaymentStatusEnum;

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  businessNote?: string;

  @ApiProperty({
    type: () => OrderNotificationSettingsDto,
    required: false
  })
  @Type(() => OrderNotificationSettingsDto)
  @IsOptional()
  @Expose()
  notificationSettings?: OrderNotificationSettingsDto;

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

#### OrderServiceDto

```typescript
import { BaseEntityDto } from '@root/common/application/dto/base-entity.dto';
import { MetaDto } from '@root/common/application/dto/meta.dto';
import { PaymentStatusEnum } from '@root/common/module/payment/domain/enums/payment.status.enum';
import { ServiceDto } from "@root/common/module/service/dtos/service.dto";
import { OrderServiceStatusEnum } from '../../domain/enums/order-service.status.enum';
import { OrderAppointmentDetailsDto } from './order-service-details.dto';

@Exclude()
export class OrderServiceDto extends BaseEntityDto {
  @ApiProperty({ example: 'OrderServiceDto', required: false })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'OrderServiceDto';

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  orderId?: string;

  @ApiProperty({
    type: () => ServiceDto,
    required: false
  })
  @Type(() => ServiceDto)
  @IsOptional()
  @Expose()
  serviceSnapshot?: ServiceDto;

  @ApiProperty({
    type: () => OrderAppointmentDetailsDto,
    required: false
  })
  @Type(() => OrderAppointmentDetailsDto)
  @IsOptional()
  @Expose()
  orderAppointmentDetails?: OrderAppointmentDetailsDto;

  @ApiProperty({
    enum: OrderServiceStatusEnum,
    default: OrderServiceStatusEnum.inProgress
  })
  @IsEnum(OrderServiceStatusEnum)
  @Expose()
  status: OrderServiceStatusEnum;

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  customerNote?: string;

  @ApiProperty({ required: false })
  @Type(() => MetaDto)
  @IsOptional()
  @Expose()
  meta?: MetaDto;

  @ApiProperty({
    enum: PaymentStatusEnum, 
    default: PaymentStatusEnum.pending,
    required: false
  })
  @IsEnum(PaymentStatusEnum)
  @IsOptional()
  @Expose()
  paymentStatus?: PaymentStatusEnum;
}
```

#### OrderProductDto

```typescript
import { BaseEntityDto } from '@root/common/application/dto/base-entity.dto';
import { MetaDto } from '@root/common/application/dto/meta.dto';
import { PaymentStatusEnum } from '@root/common/module/payment/domain/enums/payment.status.enum';
import { ProductDto } from '@root/common/module/product/product/dtos/product.dto';

@Exclude()
export class OrderProductDto extends BaseEntityDto {
  @ApiProperty({ example: 'OrderProductDto', required: false })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'OrderProductDto';

  @ApiProperty()
  @IsNumber()
  @Expose()
  quantity: number;

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  orderId?: string;

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  orderServiceId?: string;

  @ApiProperty({
    type: () => ProductDto
  })
  @Type(() => ProductDto)
  @ValidateNested()
  @Expose()
  productSnapshot: ProductDto;

  @ApiProperty({
    type: () => MetaDto,
    required: false
  })
  @Type(() => MetaDto)
  @IsOptional()
  @Expose()
  meta?: MetaDto;

  @ApiProperty({
    enum: PaymentStatusEnum,
    default: PaymentStatusEnum.pending,
    required: false
  })
  @IsEnum(PaymentStatusEnum)
  @IsOptional()
  @Expose()
  paymentStatus?: PaymentStatusEnum;
}
```

#### OrderAppointmentDetailsDto

```typescript
import { LocationDto } from '@root/common/application/dto/location.dto';
import { LanguageCodeEnum } from '@root/common/core/enum/language-code.enum';
import { AttachmentDto } from '@root/common/module/order/dtos/sub/attachment.dto';
import { AttendantDto } from '@root/common/module/order/dtos/sub/attendant.dto';
import { SpecialistDto } from '@root/common/module/specialist/dtos/specialist.dto';
import { ReservationTypeEnum } from '../../domain/enums/reservation.type.enum';

@Exclude()
export class OrderAppointmentDetailsDto {
  @ApiProperty({ example: 'OrderAppointmentDetailsDto' })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'OrderAppointmentDetailsDto';

  @ApiProperty()
  @IsString()
  @Expose()
  start: string;

  @ApiProperty()
  @IsString()
  @Expose()
  end: string;

  @ApiProperty({
    enum: ReservationTypeEnum,
    default: ReservationTypeEnum.service
  })
  @IsEnum(ReservationTypeEnum)
  @IsOptional()
  @Expose()
  type?: ReservationTypeEnum;

  @ApiProperty({
    enum: LanguageCodeEnum,
    isArray: true,
    default: [LanguageCodeEnum.uk]
  })
  @Expose()
  @IsArray()
  @IsEnum(LanguageCodeEnum, { each: true })
  @IsOptional()
  languageCodes?: LanguageCodeEnum[];

  @ApiProperty({
    type: () => SpecialistDto,
    isArray: true
  })
  @IsArray()
  @Type(() => SpecialistDto)
  @ValidateNested({ each: true })
  @Expose()
  specialists: SpecialistDto[];

  @ApiProperty({
    type: () => AttendantDto,
    isArray: true,
    required: false
  })
  @IsArray()
  @Type(() => AttendantDto)
  @ValidateNested({ each: true })
  @IsOptional()
  @Expose()
  attendants?: AttendantDto[];

  @ApiProperty({
    type: () => LocationDto,
    required: false
  })
  @Type(() => LocationDto)
  @ValidateNested()
  @IsOptional()
  @Expose()
  location?: LocationDto;

  @ApiProperty({
    type: () => AttachmentDto,
    isArray: true,
    required: false
  })
  @IsArray()
  @Type(() => AttachmentDto)
  @ValidateNested({ each: true })
  @IsOptional()
  @Expose()
  attachments?: AttachmentDto[];
}
```

### Pagination DTOs

#### OrderPaginationDto

```typescript
import { PaginationDto } from '@root/common/application/dto/pagination/pagination.dto';
import { OrderStatusEnum } from '../domain/enums/order.status.enum';

@Exclude()
export class OrderPaginationDto extends PaginationDto {
  @ApiPropertyOptional({
    example: (new Date()).toISOString(),
    default: (new Date()).toISOString()
  })
  @IsString()
  @IsOptional()
  @Expose()
  start?: string;

  @ApiPropertyOptional()
  @IsString()
  @IsOptional()
  @Expose()
  customerId?: string;

  @ApiPropertyOptional({
    example: (new Date()).toISOString(),
    default: (new Date()).toISOString()
  })
  @IsString()
  @IsOptional()
  @Expose()
  end?: string;

  @ApiPropertyOptional({
    type: () => [OrderStatusEnum],
    isArray: true,
    example: [
      OrderStatusEnum.inProgress,
      OrderStatusEnum.cancelled
    ],
    description: 'Array of order statuses to filter by. If not provided, all statuses will be included.'
  })
  @IsArray()
  @IsOptional()
  @Expose()
  @Transform(({ value }) => {
    const statuses = Array.isArray(value) ? value : [value];
    return statuses.reduce((acc, status) => {
      if (OrderStatusEnum[status]) {
        acc.push(OrderStatusEnum[status]);
      }
      return acc;
    }, []);
  })
  statuses?: OrderStatusEnum[];

  @ApiPropertyOptional({
    type: [String],
    example: ['64fa1c71b19d6d001c88a91f', '64fa1c71b19d6d001c88a91e'],
    description: 'Filter orders by assigned member IDs',
  })
  @IsArray()
  @IsOptional()
  @Expose()
  @Transform(({ value }) => Array.isArray(value) ? value : [value])
  memberIds?: string[];
}
```

### Supporting DTOs

#### AttendantDto

```typescript
import { CustomerDto } from '@root/common/module/customer/dtos/customer.dto';

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

  @ApiProperty()
  @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;
}
```

#### AttachmentDto

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

  @ApiProperty()
  @IsString()
  @Expose()
  filename: string;

  @ApiProperty()
  @IsString()
  @Expose()
  url: string;

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  description?: string;

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  mimeType?: string;

  @ApiProperty({ required: false })
  @IsNumber()
  @IsOptional()
  @Expose()
  size?: number;
}
```

### Public Order DTOs

#### PublicOrderDto

```typescript
import { OrderStatusEnum } from '../domain/enums/order.status.enum';
import { PublicOrderProductDto } from './sub/public-order-product.dto';
import { PublicOrderServiceDto } from './sub/public-order-service.dto';

@Exclude()
export class PublicOrderDto {
  @ApiProperty({ example: 'PublicOrderDto' })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'PublicOrderDto';

  @ApiProperty()
  @IsString()
  @Transform(from_object_id)
  @Expose()
  _id: string;

  @ApiProperty({
    enum: OrderStatusEnum,
    default: OrderStatusEnum.inProgress
  })
  @IsEnum(OrderStatusEnum)
  @Expose()
  status: OrderStatusEnum;

  @ApiProperty({
    type: () => PublicOrderProductDto,
    isArray: true,
    required: false
  })
  @IsArray()
  @Type(() => PublicOrderProductDto)
  @IsOptional()
  @Expose()
  products?: PublicOrderProductDto[];

  @ApiProperty({
    type: () => PublicOrderServiceDto,
    isArray: true,
    required: false
  })
  @IsArray()
  @Type(() => PublicOrderServiceDto)
  @IsOptional()
  @Expose()
  services?: PublicOrderServiceDto[];
}
```

#### PublicOrderServiceDto

```typescript
import { PublicServiceDto } from '@root/common/module/service/dtos/public-service.dto';
import { OrderServiceStatusEnum } from '../../domain/enums/order-service.status.enum';
import { PublicOrderAppointmentDetailsDto } from './public-order-appointment-details.dto';

@Exclude()
export class PublicOrderServiceDto {
  @ApiProperty({ example: 'PublicOrderServiceDto' })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'PublicOrderServiceDto';

  @ApiProperty()
  @IsString()
  @Transform(from_object_id)
  @Expose()
  _id: string;

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  orderId?: string;

  @ApiProperty({
    type: () => PublicServiceDto,
    required: false
  })
  @Type(() => PublicServiceDto)
  @IsOptional()
  @Expose()
  serviceSnapshot?: PublicServiceDto;

  @ApiProperty({
    type: () => PublicOrderAppointmentDetailsDto,
    required: false
  })
  @Type(() => PublicOrderAppointmentDetailsDto)
  @IsOptional()
  @Expose()
  orderAppointmentDetails?: PublicOrderAppointmentDetailsDto;

  @ApiProperty({
    enum: OrderServiceStatusEnum,
    default: OrderServiceStatusEnum.inProgress
  })
  @IsEnum(OrderServiceStatusEnum)
  @Expose()
  status: OrderServiceStatusEnum;

  @ApiProperty({ required: false })
  @IsString()
  @IsOptional()
  @Expose()
  customerNote?: string;
}
```

### Use Case DTOs

#### CreatePublicOrderDto

```typescript
import { OrderProductDto } from '../../../dtos/sub/order-product.dto';
import { CreatePublicOrderServiceDto } from './create-public-order-service.dto';

@Exclude()
export class CreatePublicOrderDto {
  @ApiProperty({ example: 'CreatePublicOrderDto' })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'CreatePublicOrderDto';

  @ApiProperty()
  @IsString()
  @Expose()
  _id: string;

  @ApiProperty({
    type: () => OrderProductDto,
    isArray: true
  })
  @IsArray()
  @Type(() => OrderProductDto)
  @ValidateNested({ each: true })
  @IsOptional()
  @Expose()
  products?: OrderProductDto[];

  @ApiProperty({
    type: () => CreatePublicOrderServiceDto,
    isArray: true
  })
  @IsArray()
  @Type(() => CreatePublicOrderServiceDto)
  @IsOptional()
  @ValidateNested({ each: true })
  @Expose()
  services?: CreatePublicOrderServiceDto[];
}
```

#### CreatePublicOrderServiceDto

```typescript
import { RequestPublicServiceDto } from '@root/common/module/service/dtos/request-public-service.dto';
import { CreatePublicOrderAppointmentDetailsDto } from './public-order-service-details.dto';

@Exclude()
export class CreatePublicOrderServiceDto {
  @ApiProperty({ example: 'CreatePublicOrderServiceDto' })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'CreatePublicOrderServiceDto';

  @ApiProperty({
    type: () => RequestPublicServiceDto
  })
  @Type(() => RequestPublicServiceDto)
  @ValidateNested()
  @IsOptional()
  @Expose()
  serviceSnapshot?: RequestPublicServiceDto;

  @ApiProperty({
    type: () => CreatePublicOrderAppointmentDetailsDto
  })
  @Type(() => CreatePublicOrderAppointmentDetailsDto)
  @ValidateNested()
  @IsOptional()
  @Expose()
  orderAppointmentDetails?: CreatePublicOrderAppointmentDetailsDto;

  @ApiProperty()
  @IsString()
  @IsOptional()
  @Expose()
  customerNote?: string;
}
```

#### ChangeOrderStatusDto

```typescript
import { OrderStatusEnum } from '../../../domain/enums/order.status.enum';

@Exclude()
export class ChangeOrderStatusDto {
  @ApiProperty({ example: 'ChangeOrderStatusDto' })
  @IsString()
  @IsOptional()
  @Expose()
  object?: 'ChangeOrderStatusDto';

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

  @ApiProperty({
    enum: OrderStatusEnum,
    default: OrderStatusEnum.inProgress,
  })
  @IsEnum(OrderStatusEnum)
  @IsOptional()
  @Expose()
  status?: OrderStatusEnum;
}
```

#### CancelOrderDto

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

  @ApiProperty()
  @IsOptional()
  @IsString()
  @Expose()
  orderId?: string;
}
```

## Domain Interfaces

### Core Domain Interfaces

#### IOrder

```typescript
import { IBase } from '@root/common/core/entities/entity';
import { IMeta } from '@root/common/core/value-objects/meta.value';
import { PaymentStatusEnum } from '@root/common/module/payment/domain/enums/payment.status.enum';
import { OrderStatusEnum } from '../enums/order.status.enum';
import { IOrderProduct } from './IOrderProduct';
import { IOrderService } from './IOrderService';
import { IOrderNotificationSettings } from '../values/sub/notification-settings.value';

export interface IOrder extends IBase {
  status: OrderStatusEnum;
  meta?: IMeta;
  services?: IOrderService[];
  businessNote?: string;
  products?: IOrderProduct[];
  paymentStatus?: PaymentStatusEnum;
  notificationSettings?: IOrderNotificationSettings;
  createdAt?: string;
  updatedAt?: string;
}
```

#### IOrderService

```typescript
import { IBase } from '@root/common/core/entities/entity';
import { IMeta } from '@root/common/core/value-objects/meta.value';
import { PaymentStatusEnum } from '@root/common/module/payment/domain/enums/payment.status.enum';
import { IService } from '@root/common/module/service/domain/persistance/IService';
import { OrderServiceStatusEnum } from '../enums/order-service.status.enum';
import { IOrderAppointmentDetails } from '../values/ordered-appointment-details.value';

export interface IOrderService extends IBase {
  orderId: string;
  serviceSnapshot: IService;
  orderAppointmentDetails: IOrderAppointmentDetails;
  status: OrderServiceStatusEnum;
  customerNote?: string;
  meta?: IMeta;
  paymentStatus?: PaymentStatusEnum;
}
```

#### IOrderProduct

```typescript
import { IBase } from '@root/common/core/entities/entity';
import { IMeta } from '@root/common/core/value-objects/meta.value';
import { PaymentStatusEnum } from '@root/common/module/payment/domain/enums/payment.status.enum';
import { IProduct } from '@root/common/module/product/product/domain/persistance/IProduct';

export interface IOrderProduct extends IBase {
  orderId?: string;
  orderServiceId?: string;
  productSnapshot: IProduct;
  meta?: IMeta;
  quantity: number;
  saleDate?: string;
  paymentStatus?: PaymentStatusEnum;
}
```

## Enumerations

### OrderStatusEnum

```typescript
export enum OrderStatusEnum {
  draft = 'draft',                      // Order in draft state
  deleted = 'deleted',                  // Order soft deleted
  requested = 'requested',              // Order requested by customer
  confirmed = 'confirmed',              // Order confirmed by business
  inProgress = 'inProgress',            // Order currently being processed
  done = 'done',                       // Order completed successfully
  cancelled = 'cancelled',              // Order cancelled
  rejected = 'rejected',                // Order rejected by business
  waitingForPayment = 'waitingForPayment' // Order awaiting payment
}
```

### OrderServiceStatusEnum

```typescript
export enum OrderServiceStatusEnum {
  requested = 'requested',              // Service has been requested but not yet accepted
  accepted = 'accepted',                // Service request has been accepted by the specialist
  ready = 'ready',                      // Service is ready to be provided by the specialist
  inProgress = 'inProgress',            // Service is currently being provided by the specialist
  done = 'done',                       // Service has been successfully completed
  rejected = 'rejected',                // Service request has been rejected
  cancelled = 'cancelled',              // Service has been cancelled by customer or specialist
  deleted = 'deleted'                   // Service has been removed or marked as deleted
}
```

### ReservationTypeEnum

```typescript
export enum ReservationTypeEnum {
  service = 'service',                  // Standard service reservation
  event = 'event',                     // Event-based reservation
  consultation = 'consultation'         // Consultation appointment
}
```

### PaymentStatusEnum

```typescript
export enum PaymentStatusEnum {
  pending = 'pending',                  // Payment is pending
  processing = 'processing',            // Payment is being processed
  completed = 'completed',              // Payment completed successfully
  failed = 'failed',                   // Payment failed
  refunded = 'refunded',               // Payment has been refunded
  cancelled = 'cancelled'               // Payment was cancelled
}
```

### ResponseStatusEnum

```typescript
export enum ResponseStatusEnum {
  confirmed = 'confirmed',              // Response confirmed
  declined = 'declined',                // Response declined
  pending = 'pending',                  // Response pending
  cancelled = 'cancelled'               // Response cancelled
}
```

## Use Case Interfaces

### Use Case Parameter Interfaces

#### GetOrderUseCaseParams

```typescript
import { TenantActorContext } from '@root/common/application/context/tenant-actor.context';

export interface GetOrderUseCaseParams {
  ctx: TenantActorContext;
  orderId: string;
}
```

#### GetPagedOrdersUseCaseParams

```typescript
import { TenantActorContext } from '@root/common/application/context/tenant-actor.context';
import { OrderPaginationDto } from '../../dtos/order-pagination.dto';

export interface GetPagedOrdersUseCaseParams {
  ctx: TenantActorContext;
  pagination: OrderPaginationDto;
}
```

#### CreateOrderSagaParams

```typescript
import { TenantActorContext } from '@root/common/application/context/tenant-actor.context';
import { OrderDto } from '../../dtos/order.dto';

export type CreateOrderSagaParams = {
  ctx: TenantActorContext;
  order: OrderDto;
};
```

#### UpdateOrderSagaParams

```typescript
import { TenantActorContext } from '@root/common/application/context/tenant-actor.context';
import { OrderDto } from '../../dtos/order.dto';

export type UpdateOrderSagaParams = {
  ctx: TenantActorContext;
  orderToUpdate: OrderDto;
};
```

#### DeleteOrderSagaParams

```typescript
import { TenantActorContext } from '@root/common/application/context/tenant-actor.context';

export type DeleteOrderSagaParams = {
  ctx: TenantActorContext;
  orderId: string;
};
```

## Repository Interfaces

### IOrderRepository

```typescript
import { IBaseRepository } from '@root/common/core/persistance/i-base.repository';
import { IOrder } from './IOrder';

export interface IOrderRepository extends IBaseRepository<IOrder> {
  findByCustomerId(customerId: string): Promise<IOrder[]>;
  findByMemberId(memberId: string): Promise<IOrder[]>;
  findByStatus(status: OrderStatusEnum): Promise<IOrder[]>;
  findByDateRange(start: Date, end: Date): Promise<IOrder[]>;
  findWithServices(orderId: string): Promise<IOrder | null>;
  findWithProducts(orderId: string): Promise<IOrder | null>;
}
```

### IOrderServiceRepository

```typescript
import { IBaseRepository } from '@root/common/core/persistance/i-base.repository';
import { IOrderService } from './IOrderService';

export interface IOrderServiceRepository extends IBaseRepository<IOrderService> {
  findByOrderId(orderId: string): Promise<IOrderService[]>;
  findBySpecialistId(specialistId: string): Promise<IOrderService[]>;
  findByStatus(status: OrderServiceStatusEnum): Promise<IOrderService[]>;
  findByDateRange(start: Date, end: Date): Promise<IOrderService[]>;
  findConflictingAppointments(start: Date, end: Date, specialistId: string): Promise<IOrderService[]>;
}
```

### IOrderProductRepository

```typescript
import { IBaseRepository } from '@root/common/core/persistance/i-base.repository';
import { IOrderProduct } from './IOrderProduct';

export interface IOrderProductRepository extends IBaseRepository<IOrderProduct> {
  findByOrderId(orderId: string): Promise<IOrderProduct[]>;
  findByOrderServiceId(orderServiceId: string): Promise<IOrderProduct[]>;
  findByProductId(productId: string): Promise<IOrderProduct[]>;
}
```

## Value Object Interfaces

### IOrderAppointmentDetails

```typescript
import { LanguageCodeEnum } from '@root/common/core/enum/language-code.enum';
import { ReservationTypeEnum } from '../enums/reservation.type.enum';
import { IAttendant } from './sub/attendant.value';
import { IAttachment } from './sub/attachment.value';
import { ILocation } from './sub/location.value';

export interface IOrderAppointmentDetails {
  start: string;
  end: string;
  type?: ReservationTypeEnum;
  languageCodes?: LanguageCodeEnum[];
  specialists: string[]; // Specialist IDs
  attendants?: IAttendant[];
  location?: ILocation;
  attachments?: IAttachment[];
}
```

### IOrderNotificationSettings

```typescript
export interface IOrderNotificationSettings {
  emailNotifications: boolean;
  smsNotifications: boolean;
  pushNotifications: boolean;
  reminderSettings?: {
    enabled: boolean;
    timeBeforeInMinutes: number;
  };
}
```

### IAttendant

```typescript
export interface IAttendant {
  customerId: string;
  firstTime?: boolean;
  specialRequests?: string;
  notes?: string;
}
```

### IAttachment

```typescript
export interface IAttachment {
  filename: string;
  url: string;
  description?: string;
  mimeType?: string;
  size?: number;
  uploadedBy?: string;
  uploadedAt?: string;
}
```

### ILocation

```typescript
export interface ILocation {
  address?: string;
  coordinates?: {
    latitude: number;
    longitude: number;
  };
  roomNumber?: string;
  buildingInfo?: string;
  accessInstructions?: string;
}
```

## Event Interfaces

### Order Events

#### OrderCreatedEvent

```typescript
export interface OrderCreatedEvent {
  orderId: string;
  tenantId: string;
  customerId?: string;
  orderStatus: OrderStatusEnum;
  totalServices: number;
  totalProducts: number;
  createdBy: string;
  createdAt: string;
}
```

#### OrderUpdatedEvent

```typescript
export interface OrderUpdatedEvent {
  orderId: string;
  tenantId: string;
  changes: {
    status?: {
      from: OrderStatusEnum;
      to: OrderStatusEnum;
    };
    services?: {
      added?: string[];
      removed?: string[];
      modified?: string[];
    };
    products?: {
      added?: string[];
      removed?: string[];
      modified?: string[];
    };
  };
  updatedBy: string;
  updatedAt: string;
}
```

#### OrderStatusChangedEvent

```typescript
export interface OrderStatusChangedEvent {
  orderId: string;
  tenantId: string;
  previousStatus: OrderStatusEnum;
  newStatus: OrderStatusEnum;
  changedBy: string;
  changedAt: string;
  reason?: string;
}
```

#### OrderDeletedEvent

```typescript
export interface OrderDeletedEvent {
  orderId: string;
  tenantId: string;
  deletedBy: string;
  deletedAt: string;
  reason?: string;
}
```

### Order Service Events

#### OrderServiceStatusChangedEvent

```typescript
export interface OrderServiceStatusChangedEvent {
  orderServiceId: string;
  orderId: string;
  tenantId: string;
  previousStatus: OrderServiceStatusEnum;
  newStatus: OrderServiceStatusEnum;
  specialistId?: string;
  changedBy: string;
  changedAt: string;
}
```

#### OrderServiceAcceptedEvent

```typescript
export interface OrderServiceAcceptedEvent {
  orderServiceId: string;
  orderId: string;
  tenantId: string;
  specialistId: string;
  acceptedBy: string;
  acceptedAt: string;
}
```

#### OrderServiceCancelledEvent

```typescript
export interface OrderServiceCancelledEvent {
  orderServiceId: string;
  orderId: string;
  tenantId: string;
  specialistId?: string;
  cancelledBy: string;
  cancelledAt: string;
  reason?: string;
}
```

## Validation Constraints

### Order Validation

```typescript
export interface OrderValidationConstraints {
  maxServicesPerOrder: number;           // Maximum 10 services per order
  maxProductsPerService: number;         // Maximum products per service
  maxAttendeesPerService: number;        // Maximum attendees per service
  minAdvanceBookingHours: number;        // Minimum hours in advance for booking
  maxAdvanceBookingDays: number;         // Maximum days in advance for booking
  allowPastDateModification: boolean;    // Allow modification of past appointments
  requireCustomerForOrder: boolean;      // Customer required for order creation
}
```

### Service Validation

```typescript
export interface ServiceValidationConstraints {
  maxAppointmentDurationHours: number;   // Maximum appointment duration
  minAppointmentDurationMinutes: number; // Minimum appointment duration
  maxSimultaneousBookings: number;       // Max bookings per specialist per time slot
  requireSpecialistAssignment: boolean;  // Specialist assignment required
  allowDoubleBooking: boolean;           // Allow overlapping appointments
}
```

## Type Guards and Utility Types

### Type Guards

```typescript
export function isOrderDto(obj: any): obj is OrderDto {
  return obj && typeof obj === 'object' && obj.object === 'OrderDto';
}

export function isOrderServiceDto(obj: any): obj is OrderServiceDto {
  return obj && typeof obj === 'object' && obj.object === 'OrderServiceDto';
}

export function isOrderProductDto(obj: any): obj is OrderProductDto {
  return obj && typeof obj === 'object' && obj.object === 'OrderProductDto';
}

export function isValidOrderStatus(status: string): status is OrderStatusEnum {
  return Object.values(OrderStatusEnum).includes(status as OrderStatusEnum);
}

export function isValidOrderServiceStatus(status: string): status is OrderServiceStatusEnum {
  return Object.values(OrderServiceStatusEnum).includes(status as OrderServiceStatusEnum);
}
```

### Utility Types

```typescript
// Partial order for updates
export type PartialOrder = Partial<Omit<OrderDto, '_id' | 'createdAt' | 'updatedAt'>>;

// Order creation payload
export type CreateOrderPayload = Omit<OrderDto, '_id' | 'createdAt' | 'updatedAt' | 'status'>;

// Order update payload
export type UpdateOrderPayload = PartialOrder & { _id: string };

// Order service creation payload
export type CreateOrderServicePayload = Omit<OrderServiceDto, '_id' | 'createdAt' | 'updatedAt' | 'orderId'>;

// Order search criteria
export type OrderSearchCriteria = {
  customerId?: string;
  memberIds?: string[];
  statuses?: OrderStatusEnum[];
  dateRange?: {
    start: string;
    end: string;
  };
  phrase?: string;
};

// Order aggregation result
export type OrderAggregationResult = {
  totalOrders: number;
  ordersByStatus: Record<OrderStatusEnum, number>;
  totalRevenue: number;
  averageOrderValue: number;
  topServices: Array<{
    serviceId: string;
    serviceName: string;
    bookingCount: number;
  }>;
};
```

## Error Types

### Domain Error Types

```typescript
export class OrderDomainError extends Error {
  constructor(
    public code: string,
    message: string,
    public context?: Record<string, any>
  ) {
    super(message);
    this.name = 'OrderDomainError';
  }
}

export class OrderNotFoundError extends OrderDomainError {
  constructor(orderId: string) {
    super('ORDER_NOT_FOUND', `Order with ID ${orderId} not found`, { orderId });
  }
}

export class OrderValidationError extends OrderDomainError {
  constructor(field: string, message: string) {
    super('ORDER_VALIDATION_ERROR', message, { field });
  }
}

export class OrderConflictError extends OrderDomainError {
  constructor(message: string, context?: Record<string, any>) {
    super('ORDER_CONFLICT', message, context);
  }
}

export class OrderPermissionError extends OrderDomainError {
  constructor(userId: string, orderId: string, action: string) {
    super('ORDER_PERMISSION_DENIED', 
          `User ${userId} does not have permission to ${action} order ${orderId}`,
          { userId, orderId, action });
  }
}
```

## Constants and Configuration

### Order Configuration

```typescript
export const ORDER_CONSTANTS = {
  MAX_SERVICES_PER_ORDER: 10,
  MAX_PRODUCTS_PER_ORDER: 50,
  MAX_ATTENDEES_PER_SERVICE: 20,
  MAX_ATTACHMENTS_PER_SERVICE: 5,
  MAX_ATTACHMENT_SIZE_MB: 10,
  DEFAULT_PAGE_SIZE: 10,
  MAX_PAGE_SIZE: 100,
  MIN_ADVANCE_BOOKING_MINUTES: 30,
  MAX_ADVANCE_BOOKING_DAYS: 365
} as const;

export const ORDER_STATUS_TRANSITIONS: Record<OrderStatusEnum, OrderStatusEnum[]> = {
  [OrderStatusEnum.draft]: [OrderStatusEnum.requested, OrderStatusEnum.cancelled],
  [OrderStatusEnum.requested]: [OrderStatusEnum.confirmed, OrderStatusEnum.rejected, OrderStatusEnum.cancelled],
  [OrderStatusEnum.confirmed]: [OrderStatusEnum.inProgress, OrderStatusEnum.cancelled],
  [OrderStatusEnum.inProgress]: [OrderStatusEnum.done, OrderStatusEnum.cancelled],
  [OrderStatusEnum.done]: [],
  [OrderStatusEnum.cancelled]: [],
  [OrderStatusEnum.rejected]: [],
  [OrderStatusEnum.deleted]: [],
  [OrderStatusEnum.waitingForPayment]: [OrderStatusEnum.confirmed, OrderStatusEnum.cancelled]
};

export const ORDER_SERVICE_STATUS_TRANSITIONS: Record<OrderServiceStatusEnum, OrderServiceStatusEnum[]> = {
  [OrderServiceStatusEnum.requested]: [OrderServiceStatusEnum.accepted, OrderServiceStatusEnum.rejected],
  [OrderServiceStatusEnum.accepted]: [OrderServiceStatusEnum.ready, OrderServiceStatusEnum.cancelled],
  [OrderServiceStatusEnum.ready]: [OrderServiceStatusEnum.inProgress, OrderServiceStatusEnum.cancelled],
  [OrderServiceStatusEnum.inProgress]: [OrderServiceStatusEnum.done, OrderServiceStatusEnum.cancelled],
  [OrderServiceStatusEnum.done]: [],
  [OrderServiceStatusEnum.rejected]: [],
  [OrderServiceStatusEnum.cancelled]: [],
  [OrderServiceStatusEnum.deleted]: []
};
```


# Use Case Documentation

## Overview

This document provides comprehensive documentation of business logic and use case implementations for the Order Management module. All use cases follow Clean Architecture principles and implement the CQRS pattern with proper permission validation and error handling.

## Architecture Overview

### Design Patterns

* **Clean Architecture**: Separation of concerns with clear dependency inversion
* **CQRS (Command Query Responsibility Segregation)**: Separate models for read and write operations
* **Saga Pattern**: Complex business transactions with compensation logic
* **Domain-Driven Design**: Rich domain models with business rules enforcement
* **Event-Driven Architecture**: Asynchronous processing through domain events

### Core Components

* **Use Cases**: Business logic implementation with single responsibility
* **Sagas**: Multi-step business processes with rollback capabilities
* **Handlers**: CQRS command and query handlers
* **Steps**: Atomic operations within sagas
* **Validators**: Permission and business rule validation
* **Events**: Domain events for system integration

## Read Use Cases

### Get Order Use Case

**Purpose:** Retrieve a single order by ID with permission validation and scope-based access control.

**Implementation:**

```typescript
export interface GetOrderUseCaseParams {
  ctx: TenantActorContext;
  orderId: string;
}

export class GetOrderUseCase implements IUseCase<GetOrderUseCaseParams, OrderDto> {
  private readonly logger = new Logger(GetOrderUseCase.name);

  constructor(
    private readonly queryBus: QueryBus,
    private readonly permissionValidator: PermissionValidatorUseCase,
  ) {}

  public async execute({ ctx, orderId }: GetOrderUseCaseParams): Promise<OrderDto> {
    return this.permissionValidator.executeOrReturn<OrderDto>({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.READ_ORDER],

      fallback: () => {
        this.logger.warn(
          `Member ${ctx.actor.issuerId} lacks READ_ORDER permission for order ${orderId}`,
        );
        return null;
      },

      onSuccess: async (scope: PermissionScopeEnum) => {
        try {
          const order: OrderDto = await this.queryBus.execute(
            new GetOrderByIdQuery(ctx.tenantId, orderId),
          );

          if (!order) {
            this.logger.warn(`Order ${orderId} not found`);
            throw new AccessPermissionException('Order not found or access denied');
          }
          
          // Scope-based access control
          if (scope === PermissionScopeEnum.OWN &&
              order.services.some((service) =>
                service.orderAppointmentDetails.specialists.some(
                  (spec) => spec.member._id.toString() !== ctx.actor.issuerId,
                )
              )
          ) {
            this.logger.warn(
              `Member ${ctx.actor.issuerId} tried to access order ${orderId} not assigned to them`,
            );
            throw new AccessPermissionException('You can only view your own orders');
          }

          return order;
        } catch (error) {
          this.logger.error(`Error fetching order ${orderId}`, error);
          throw error;
        }
      },
    });
  }
}
```

**Business Rules:**

1. **Permission Validation**: User must have READ\_ORDER permission
2. **Scope Enforcement**: OWN scope restricts access to user's assigned orders only
3. **Data Privacy**: Orders not assigned to user are hidden in OWN scope
4. **Error Handling**: Proper logging and exception management
5. **Audit Trail**: All access attempts are logged for security

**Permission Scopes:**

* **OWN**: Access only orders where user is assigned as specialist
* **TEAM**: Access orders within user's team
* **BUSINESS**: Access all orders within the business tenant
* **ADMIN**: Full administrative access

### Get Paged Orders Use Case

**Purpose:** Retrieve paginated list of orders with advanced filtering and permission-based scope restrictions.

**Implementation:**

```typescript
export interface GetPagedOrdersUseCaseParams {
  ctx: TenantActorContext;
  pagination: OrderPaginationDto;
}

export class GetPagedOrdersUseCase 
  implements IUseCase<GetPagedOrdersUseCaseParams, PaginationResponseDto<OrderDto> | null> {
  
  private readonly logger = new Logger(GetPagedOrdersUseCase.name);

  constructor(
    private readonly queryBus: QueryBus,
    private readonly permissionValidator: PermissionValidatorUseCase,
  ) {}

  public async execute({
    ctx,
    pagination,
  }: GetPagedOrdersUseCaseParams): Promise<PaginationResponseDto<OrderDto> | null> {
    return this.permissionValidator.executeOrReturn({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.READ_ORDER],

      fallback: () => {
        this.logger.warn(
          `Access denied for actor ${ctx.actor.issuerId} to read paged orders`,
        );
        return { items: [], totalSize: 0 };
      },

      onSuccess: async (scope: PermissionScopeEnum) => {
        try {
          // Apply scope-based filtering
          if (scope === PermissionScopeEnum.OWN) {
            pagination.memberIds = [ctx.actor.issuerId];
          }

          return await this.queryBus.execute(
            new GetPagedOrdersQuery(ctx.tenantId, pagination),
          );
        } catch (error) {
          this.logger.error('Error fetching paged orders', error);
          throw error;
        }
      },
    });
  }
}
```

**Business Rules:**

1. **Automatic Scope Filtering**: OWN scope automatically filters by user's member ID
2. **Flexible Pagination**: Configurable page size and sorting options
3. **Advanced Filtering**: Support for date ranges, statuses, customer filters
4. **Performance Optimization**: Database indexes optimize common query patterns
5. **Consistent Results**: Stable pagination with consistent ordering

**Filtering Capabilities:**

* **Date Range**: Filter orders by creation date or appointment dates
* **Status Filter**: Multiple order statuses with array support
* **Customer Filter**: Filter by specific customer ID
* **Member Filter**: Filter by assigned specialist members
* **Text Search**: Search across order content and notes

## Write Use Cases (Sagas)

### Create Order Saga

**Purpose:** Create a new order with comprehensive validation, attendee management, and rollback capabilities.

**Implementation:**

```typescript
export type CreateOrderSagaParams = {
  ctx: TenantActorContext;
  order: OrderDto;
};

export class CreateOrderSaga {
  private readonly logger = new Logger(CreateOrderSaga.name);
  private rollbackActions: (() => Promise<void>)[] = [];

  constructor(
    private readonly addAttendeesStep: AddAttendeesStep,
    private readonly createOrderStep: CreateOrderStep,
    private readonly orderValidationStep: OrderValidationStep,
    private readonly permissionValidator: PermissionValidatorUseCase,
  ) {}

  async execute(params: CreateOrderSagaParams): Promise<OrderDto> {
    try {
      const { ctx, order } = params;

      // Step 0: Permission validation
      const { scope } = await this.permissionValidator.execute({
        actor: ctx.actor,
        requiredPermissions: [ModulePermissionEnum.CREATE_ORDER],
      });

      // Step 1: Comprehensive order validation
      await this.orderValidationStep.execute(ctx.tenantId, order, ctx.actor);

      // Step 2: Add and validate attendees
      const orderWithAttendees = await this.addAttendeesStep.execute(
        ctx.tenantId,
        order,
        ctx.actor,
      );

      // Step 3: Create the order
      const createdOrder = await this.createOrderStep.execute(
        ctx.tenantId,
        orderWithAttendees,
        ctx.actor,
      );

      this.logger.log(`Order ${createdOrder._id} created successfully`);
      return createdOrder;

    } catch (error) {
      this.logger.error('Error in CreateOrderSaga, executing rollback', error);
      await this.executeRollback();
      throw new OrderCreationException(
        `Failed to create order: ${error.message}`,
        error,
      );
    }
  }

  private async executeRollback(): Promise<void> {
    for (const rollbackAction of this.rollbackActions.reverse()) {
      try {
        await rollbackAction();
      } catch (rollbackError) {
        this.logger.error('Error during rollback action', rollbackError);
      }
    }
  }
}
```

**Saga Steps:**

#### 1. Order Validation Step

```typescript
export class OrderValidationStep {
  async execute(tenantId: string, order: OrderDto, actor: ActorDto): Promise<void> {
    // Validate order structure
    this.validateOrderStructure(order);
    
    // Validate services
    await this.validateServices(tenantId, order.services);
    
    // Validate products
    await this.validateProducts(tenantId, order.products);
    
    // Validate appointment conflicts
    await this.validateAppointmentConflicts(tenantId, order.services);
    
    // Validate business rules
    await this.validateBusinessRules(tenantId, order);
  }

  private validateOrderStructure(order: OrderDto): void {
    if (!order.services?.length && !order.products?.length) {
      throw new OrderValidationError('Order must contain at least one service or product');
    }

    if (order.services?.length > ORDER_CONSTANTS.MAX_SERVICES_PER_ORDER) {
      throw new OrderValidationError(
        `Order cannot contain more than ${ORDER_CONSTANTS.MAX_SERVICES_PER_ORDER} services`
      );
    }
  }

  private async validateServices(tenantId: string, services: OrderServiceDto[]): Promise<void> {
    for (const service of services || []) {
      // Validate service exists and is active
      const serviceSnapshot = await this.getServiceSnapshot(tenantId, service.serviceSnapshot._id);
      if (!serviceSnapshot || !serviceSnapshot.isActive) {
        throw new OrderValidationError(`Service ${service.serviceSnapshot._id} is not available`);
      }

      // Validate appointment details
      this.validateAppointmentDetails(service.orderAppointmentDetails);
      
      // Validate specialists
      await this.validateSpecialists(tenantId, service.orderAppointmentDetails.specialists);
    }
  }

  private async validateAppointmentConflicts(
    tenantId: string, 
    services: OrderServiceDto[]
  ): Promise<void> {
    for (const service of services || []) {
      const { start, end, specialists } = service.orderAppointmentDetails;
      
      for (const specialist of specialists) {
        const conflicts = await this.queryBus.execute(
          new GetConflictingAppointmentsQuery(tenantId, specialist._id, start, end)
        );
        
        if (conflicts.length > 0) {
          throw new OrderConflictError(
            `Specialist ${specialist._id} is not available during ${start} - ${end}`
          );
        }
      }
    }
  }
}
```

#### 2. Add Attendees Step

```typescript
export class AddAttendeesStep {
  async execute(
    tenantId: string,
    order: OrderDto,
    actor: ActorDto,
  ): Promise<OrderDto> {
    const updatedServices = await Promise.all(
      order.services?.map(async (service) => {
        const processedAttendees = await this.processAttendees(
          tenantId,
          service.orderAppointmentDetails.attendants || [],
        );

        return {
          ...service,
          orderAppointmentDetails: {
            ...service.orderAppointmentDetails,
            attendants: processedAttendees,
          },
        };
      }) || [],
    );

    return { ...order, services: updatedServices };
  }

  private async processAttendees(
    tenantId: string,
    attendants: AttendantDto[],
  ): Promise<AttendantDto[]> {
    return Promise.all(
      attendants.map(async (attendant) => {
        // Create customer if not exists
        if (!attendant.customer?._id) {
          const customer = await this.customerService.createCustomer(
            tenantId,
            attendant.customer,
          );
          return { ...attendant, customer };
        }

        // Validate existing customer
        const existingCustomer = await this.customerService.getCustomer(
          tenantId,
          attendant.customer._id,
        );
        
        if (!existingCustomer) {
          throw new OrderValidationError(`Customer ${attendant.customer._id} not found`);
        }

        return { ...attendant, customer: existingCustomer };
      }),
    );
  }
}
```

#### 3. Create Order Step

```typescript
export class CreateOrderStep {
  async execute(
    tenantId: string,
    order: OrderDto,
    actor: ActorDto,
  ): Promise<OrderDto> {
    // Create order entity
    const createdOrder = await this.commandBus.execute(
      new CreateOrderCommand(tenantId, order, actor),
    );

    // Publish order created event
    await this.eventBus.publish(
      new OrderConfirmedEvent(tenantId, createdOrder._id, actor),
    );

    return createdOrder;
  }

  async compensate(
    tenantId: string,
    createdOrderDto: OrderDto,
    actor: ActorDto,
  ): Promise<void> {
    try {
      await this.commandBus.execute(
        new DeleteOrderCommand(tenantId, createdOrderDto._id, actor),
      );
    } catch (error) {
      this.logger.error('Failed to compensate order creation', error);
    }
  }
}
```

**Business Rules:**

1. **Validation First**: Comprehensive validation before any data changes
2. **Atomic Operations**: Each step is atomic with compensation capabilities
3. **Conflict Prevention**: Specialist availability validation prevents double booking
4. **Customer Management**: Automatic customer creation and validation
5. **Event Publishing**: Domain events for system integration
6. **Rollback Support**: Full compensation for failed transactions

### Update Order Saga

**Purpose:** Update existing order with validation, change tracking, and event publishing.

**Implementation:**

```typescript
export type UpdateOrderSagaParams = {
  ctx: TenantActorContext;
  orderToUpdate: OrderDto;
};

export class UpdateOrderSaga {
  private readonly logger = new Logger(UpdateOrderSaga.name);
  private rollbackActions: (() => Promise<void>)[] = [];

  async execute(params: UpdateOrderSagaParams): Promise<OrderDto> {
    try {
      const { ctx, orderToUpdate } = params;

      // Step 0: Get existing order for comparison
      const existingOrder = await this.queryBus.execute(
        new GetOrderByIdQuery(ctx.tenantId, orderToUpdate._id)
      );

      if (!existingOrder) {
        throw new OrderNotFountException(orderToUpdate._id);
      }

      // Step 1: Permission validation with ownership check
      await this.orderPermissionValidator.validateOrderAccess(
        ctx.actor,
        existingOrder,
        [ModulePermissionEnum.UPDATE_ORDER],
      );

      // Step 2: Validate update constraints
      await this.validateUpdateConstraints(existingOrder, orderToUpdate);

      // Step 3: Process attendee updates
      const orderWithUpdatedAttendees = await this.addAttendeesStep.execute(
        ctx.tenantId,
        orderToUpdate,
        ctx.actor,
      );

      // Step 4: Update the order
      const updatedOrder = await this.updateOrderStep.execute(
        ctx.tenantId,
        orderWithUpdatedAttendees,
        ctx.actor,
      );

      // Step 5: Publish update events
      await this.publishOrderUpdatedStep.execute(
        ctx.tenantId,
        existingOrder,
        updatedOrder,
        ctx.actor,
      );

      return updatedOrder;

    } catch (error) {
      this.logger.error('Error in UpdateOrderSaga, executing rollback', error);
      await this.executeRollback();
      throw error;
    }
  }

  private async validateUpdateConstraints(
    existingOrder: OrderDto,
    orderToUpdate: OrderDto,
  ): Promise<void> {
    // Cannot update completed orders
    if (existingOrder.status === OrderStatusEnum.done) {
      throw new OrderValidationError('Cannot update completed orders');
    }

    // Cannot update past appointments
    const now = new Date();
    for (const service of orderToUpdate.services || []) {
      const appointmentStart = new Date(service.orderAppointmentDetails.start);
      if (appointmentStart < now) {
        throw new OrderValidationError('Cannot update past appointments');
      }
    }

    // Validate status transitions
    if (existingOrder.status !== orderToUpdate.status) {
      this.validateStatusTransition(existingOrder.status, orderToUpdate.status);
    }
  }

  private validateStatusTransition(
    fromStatus: OrderStatusEnum,
    toStatus: OrderStatusEnum,
  ): void {
    const allowedTransitions = ORDER_STATUS_TRANSITIONS[fromStatus] || [];
    if (!allowedTransitions.includes(toStatus)) {
      throw new OrderValidationError(
        `Invalid status transition from ${fromStatus} to ${toStatus}`
      );
    }
  }
}
```

**Update Step Implementation:**

```typescript
export class UpdateOrderStep {
  async execute(
    tenantId: string,
    order: OrderDto,
    actor: ActorDto,
  ): Promise<OrderDto> {
    // Track changes for audit
    const changeTracker = new OrderChangeTracker();
    
    // Update order with change tracking
    const updatedOrder = await this.commandBus.execute(
      new UpdateOrderCommand(tenantId, order, actor, changeTracker),
    );

    // Add history entry
    await this.addHistoryEntry(updatedOrder, changeTracker.getChanges(), actor);

    return updatedOrder;
  }

  private async addHistoryEntry(
    order: OrderDto,
    changes: OrderChanges,
    actor: ActorDto,
  ): Promise<void> {
    const historyEntry: IHistoryEntry = {
      timestamp: new Date().toISOString(),
      changedBy: actor.issuerId,
      changes: changes,
      reason: 'Order updated through panel',
    };

    await this.commandBus.execute(
      new AddOrderHistoryEntryCommand(order._id, historyEntry),
    );
  }
}
```

**Business Rules:**

1. **Change Validation**: Strict validation of what can be changed and when
2. **Status Transition Rules**: Predefined valid status transitions
3. **Time Constraints**: Cannot modify past appointments
4. **Permission Checks**: User must have appropriate permissions for changes
5. **Audit Trail**: Complete tracking of changes with actor information
6. **Event Publishing**: Change events for system integration

### Delete Order Saga

**Purpose:** Soft delete order with dependency checking and cleanup coordination.

**Implementation:**

```typescript
export type DeleteOrderSagaParams = {
  ctx: TenantActorContext;
  orderId: string;
};

export class DeleteOrderSaga {
  private readonly logger = new Logger(DeleteOrderSaga.name);

  async execute(params: DeleteOrderSagaParams): Promise<void> {
    try {
      const { ctx, orderId } = params;

      // Step 0: Get order to validate existence
      const order = await this.queryBus.execute(
        new GetOrderByIdQuery(ctx.tenantId, orderId)
      );

      if (!order) {
        throw new OrderNotFountException(orderId);
      }

      // Step 1: Permission validation
      const { scope } = await this.permissionValidator.execute({
        actor: ctx.actor,
        requiredPermissions: [ModulePermissionEnum.DELETE_ORDER],
      });

      // Step 2: Validate deletion constraints
      await this.validateDeletionConstraints(order);

      // Step 3: Check order ownership for OWN scope
      if (scope === PermissionScopeEnum.OWN) {
        await this.orderPermissionValidator.validateOrderOwnership(
          ctx.actor,
          order,
        );
      }

      // Step 4: Perform soft deletion
      await this.deleteOrderStep.execute(ctx.tenantId, orderId, ctx.actor);

      this.logger.log(`Order ${orderId} deleted successfully`);

    } catch (error) {
      this.logger.error(`Error deleting order ${orderId}`, error);
      throw error;
    }
  }

  private async validateDeletionConstraints(order: OrderDto): Promise<void> {
    // Cannot delete completed orders
    if (order.status === OrderStatusEnum.done) {
      throw new OrderValidationError('Cannot delete completed orders');
    }

    // Cannot delete orders with completed payments
    if (order.paymentStatus === PaymentStatusEnum.completed) {
      throw new OrderValidationError('Cannot delete orders with completed payments');
    }

    // Cannot delete orders in progress
    if (order.status === OrderStatusEnum.inProgress) {
      throw new OrderValidationError('Cannot delete orders currently in progress');
    }

    // Check for active dependencies
    await this.checkActiveDependencies(order);
  }

  private async checkActiveDependencies(order: OrderDto): Promise<void> {
    // Check for active related records
    const dependencies = await this.dependencyChecker.checkOrderDependencies(order._id);
    
    if (dependencies.hasActiveDependencies) {
      throw new OrderValidationError(
        `Cannot delete order with active dependencies: ${dependencies.details.join(', ')}`
      );
    }
  }
}
```

**Delete Step Implementation:**

```typescript
export class DeleteOrderStep {
  async execute(
    tenantId: string,
    orderId: string,
    actor: ActorDto,
  ): Promise<void> {
    // Soft delete the order
    await this.commandBus.execute(
      new DeleteOrderCommand(tenantId, orderId, actor),
    );

    // Publish deletion event
    await this.eventBus.publish(
      new OrderStatusChangedEvent(
        tenantId,
        orderId,
        OrderStatusEnum.deleted,
        actor.issuerId,
        new Date().toISOString(),
      ),
    );

    // Schedule cleanup tasks
    await this.scheduleCleanupTasks(tenantId, orderId);
  }

  private async scheduleCleanupTasks(
    tenantId: string,
    orderId: string,
  ): Promise<void> {
    // Schedule cache invalidation
    await this.cacheService.invalidateOrderCache(orderId);
    
    // Schedule notification cleanup
    await this.notificationService.cancelOrderNotifications(orderId);
    
    // Schedule related data cleanup
    await this.cleanupService.scheduleOrderCleanup(orderId);
  }
}
```

**Business Rules:**

1. **Soft Deletion**: Orders are marked as deleted, not physically removed
2. **Dependency Checking**: Cannot delete orders with active dependencies
3. **Payment Protection**: Cannot delete orders with completed payments
4. **Status Restrictions**: Cannot delete completed or in-progress orders
5. **Cleanup Coordination**: Automatic cleanup of related resources
6. **Audit Preservation**: Historical data is preserved for compliance

## Service Status Management Use Cases

### Change Order Service Status Saga

**Purpose:** Update individual service status within an order with proper validation and event publishing.

**Implementation:**

```typescript
export class ChangeOrderServiceStatusSaga {
  async execute(params: ChangeOrderServiceStatusParams): Promise<void> {
    try {
      const { ctx, orderServiceId, newStatus, reason } = params;

      // Step 1: Get order service
      const orderService = await this.queryBus.execute(
        new GetOrderServiceByIdQuery(ctx.tenantId, orderServiceId)
      );

      if (!orderService) {
        throw new OrderServiceNotFoundError(orderServiceId);
      }

      // Step 2: Permission validation
      await this.permissionValidator.execute({
        actor: ctx.actor,
        requiredPermissions: [ModulePermissionEnum.UPDATE_ORDER_SERVICE],
      });

      // Step 3: Validate status transition
      this.validateServiceStatusTransition(orderService.status, newStatus);

      // Step 4: Update service status
      await this.changeOrderServiceStatusStep.execute(
        ctx.tenantId,
        orderServiceId,
        newStatus,
        reason,
        ctx.actor,
      );

      // Step 5: Publish status change event
      await this.publishOrderServiceStatusChangedStep.execute(
        ctx.tenantId,
        orderServiceId,
        orderService.status,
        newStatus,
        ctx.actor,
      );

    } catch (error) {
      this.logger.error('Error changing order service status', error);
      throw error;
    }
  }

  private validateServiceStatusTransition(
    currentStatus: OrderServiceStatusEnum,
    newStatus: OrderServiceStatusEnum,
  ): void {
    const allowedTransitions = ORDER_SERVICE_STATUS_TRANSITIONS[currentStatus] || [];
    if (!allowedTransitions.includes(newStatus)) {
      throw new OrderValidationError(
        `Invalid service status transition from ${currentStatus} to ${newStatus}`
      );
    }
  }
}
```

**Business Rules:**

1. **Status Transition Validation**: Only valid transitions are allowed
2. **Permission Requirements**: User must have service update permissions
3. **Atomic Updates**: Service status changes are atomic operations
4. **Event Publishing**: Status changes trigger system-wide events
5. **Audit Trail**: All status changes are logged with actor and reason

## Permission Validation

### Order Permission Validator

**Purpose:** Centralized permission validation logic for order operations with scope-based access control.

**Implementation:**

```typescript
export class OrderPermissionValidator {
  async validateOrderAccess(
    actor: ActorDto,
    order: OrderDto,
    requiredPermissions: ModulePermissionEnum[],
  ): Promise<PermissionScopeEnum> {
    const { scope } = await this.permissionValidator.execute({
      actor,
      requiredPermissions,
    });

    // Apply scope-based restrictions
    if (scope === PermissionScopeEnum.OWN) {
      await this.validateOrderOwnership(actor, order);
    }

    return scope;
  }

  async validateOrderOwnership(actor: ActorDto, order: OrderDto): Promise<void> {
    const isOwner = order.services?.some((service) =>
      service.orderAppointmentDetails.specialists.some(
        (specialist) => specialist.member?._id === actor.issuerId,
      ),
    );

    if (!isOwner) {
      throw new OrderPermissionError(
        actor.issuerId,
        order._id,
        'access - user is not assigned to this order',
      );
    }
  }

  async validateServiceAccess(
    actor: ActorDto,
    orderService: OrderServiceDto,
    requiredPermissions: ModulePermissionEnum[],
  ): Promise<void> {
    const { scope } = await this.permissionValidator.execute({
      actor,
      requiredPermissions,
    });

    if (scope === PermissionScopeEnum.OWN) {
      const isAssigned = orderService.orderAppointmentDetails.specialists.some(
        (specialist) => specialist.member?._id === actor.issuerId,
      );

      if (!isAssigned) {
        throw new OrderPermissionError(
          actor.issuerId,
          orderService._id,
          'access service - user is not assigned specialist',
        );
      }
    }
  }
}
```

## Error Handling Strategies

### Exception Hierarchy

```typescript
export class OrderDomainError extends Error {
  constructor(
    public code: string,
    message: string,
    public context?: Record<string, any>,
  ) {
    super(message);
    this.name = 'OrderDomainError';
  }
}

export class OrderValidationError extends OrderDomainError {
  constructor(message: string, field?: string) {
    super('ORDER_VALIDATION_ERROR', message, { field });
  }
}

export class OrderConflictError extends OrderDomainError {
  constructor(message: string, context?: Record<string, any>) {
    super('ORDER_CONFLICT', message, context);
  }
}

export class OrderNotFoundError extends OrderDomainError {
  constructor(orderId: string) {
    super('ORDER_NOT_FOUND', `Order ${orderId} not found`, { orderId });
  }
}

export class OrderPermissionError extends OrderDomainError {
  constructor(userId: string, orderId: string, action: string) {
    super(
      'ORDER_PERMISSION_DENIED',
      `User ${userId} does not have permission to ${action} order ${orderId}`,
      { userId, orderId, action },
    );
  }
}
```

### Error Recovery Strategies

1. **Validation Errors**: Return detailed validation messages to user
2. **Conflict Errors**: Suggest alternative time slots or specialists
3. **Permission Errors**: Log security events and return generic access denied
4. **Not Found Errors**: Return 404 with safe error message
5. **System Errors**: Log full details, return generic error to user

## Event Publishing

### Domain Events

#### Order Events

```typescript
export class OrderCreatedEvent {
  constructor(
    public readonly tenantId: string,
    public readonly orderId: string,
    public readonly customerId: string,
    public readonly createdBy: string,
    public readonly createdAt: string,
  ) {}
}

export class OrderStatusChangedEvent {
  constructor(
    public readonly tenantId: string,
    public readonly orderId: string,
    public readonly previousStatus: OrderStatusEnum,
    public readonly newStatus: OrderStatusEnum,
    public readonly changedBy: string,
    public readonly changedAt: string,
    public readonly reason?: string,
  ) {}
}

export class OrderUpdatedEvent {
  constructor(
    public readonly tenantId: string,
    public readonly orderId: string,
    public readonly changes: OrderChanges,
    public readonly updatedBy: string,
    public readonly updatedAt: string,
  ) {}
}
```

#### Service Events

```typescript
export class OrderServiceStatusChangedEvent {
  constructor(
    public readonly tenantId: string,
    public readonly orderServiceId: string,
    public readonly orderId: string,
    public readonly previousStatus: OrderServiceStatusEnum,
    public readonly newStatus: OrderServiceStatusEnum,
    public readonly changedBy: string,
    public readonly changedAt: string,
  ) {}
}

export class OrderServiceAcceptedEvent {
  constructor(
    public readonly tenantId: string,
    public readonly orderServiceId: string,
    public readonly orderId: string,
    public readonly specialistId: string,
    public readonly acceptedBy: string,
    public readonly acceptedAt: string,
  ) {}
}
```

### Event Handlers

```typescript
@EventsHandler(OrderCreatedEvent)
export class OrderCreatedHandler implements IEventHandler<OrderCreatedEvent> {
  async handle(event: OrderCreatedEvent): Promise<void> {
    // Send confirmation email
    await this.emailService.sendOrderConfirmation(event);
    
    // Update business analytics
    await this.analyticsService.recordOrderCreation(event);
    
    // Schedule reminders
    await this.reminderService.scheduleOrderReminders(event);
  }
}

@EventsHandler(OrderStatusChangedEvent)
export class OrderStatusChangedHandler implements IEventHandler<OrderStatusChangedEvent> {
  async handle(event: OrderStatusChangedEvent): Promise<void> {
    // Notify stakeholders
    await this.notificationService.notifyStatusChange(event);
    
    // Update order timeline
    await this.timelineService.recordStatusChange(event);
    
    // Trigger status-specific workflows
    await this.workflowService.handleStatusChange(event);
  }
}
```

## Performance Considerations

### Optimization Strategies

1. **Database Indexes**: Optimized queries with compound indexes
2. **Caching**: Multi-level caching with intelligent invalidation
3. **Pagination**: Efficient pagination for large datasets
4. **Async Processing**: Non-critical operations handled asynchronously
5. **Connection Pooling**: Optimized database connection management

### Monitoring Metrics

1. **Use Case Execution Time**: Track performance of business operations
2. **Permission Validation Time**: Monitor permission check performance
3. **Database Query Performance**: Track slow queries and optimization opportunities
4. **Cache Hit Rates**: Monitor cache effectiveness
5. **Error Rates**: Track business rule violations and system errors

### Scalability Patterns

1. **CQRS Separation**: Read and write models can scale independently
2. **Event Sourcing**: Complete audit trail with replay capabilities
3. **Saga Pattern**: Complex workflows with compensation logic
4. **Microservice Ready**: Clean boundaries for service extraction
5. **Database Sharding**: Tenant-based data partitioning support

## Integration Patterns

### External Service Integration

1. **Payment Services**: Payment processing and validation
2. **Notification Services**: Email, SMS, and push notifications
3. **Calendar Services**: Calendar integration for appointments
4. **Analytics Services**: Business intelligence and reporting
5. **Audit Services**: Compliance and audit trail management

### Internal Module Integration

1. **Customer Module**: Customer creation and validation
2. **Service Module**: Service availability and configuration
3. **Member Module**: Specialist assignment and availability
4. **Business Module**: Business rules and configuration
5. **Permission Module**: Role-based access control


# Database Schema

## Overview

This document provides comprehensive documentation of the MongoDB schema definitions, relationships, indexes, and data integrity rules for the Order Management module. The schemas are designed to support a multi-tenant SaaS architecture with proper data isolation and performance optimization.

## Technology Stack

* **Database**: MongoDB with Mongoose ODM
* **Schema Definition**: Mongoose Schema with TypeScript typing
* **Indexing Strategy**: Compound indexes for optimal query performance
* **Data Validation**: Schema-level validation with business rules
* **Multi-tenancy**: Tenant-based data isolation
* **Audit Trail**: State history tracking for all entities

## Core Schemas

### Order Schema

**Collection Name**: `order`

**Purpose**: Main order entity containing order metadata, status, and relationships to services and products.

**Schema Definition**:

```typescript
import { MetaSchema } from '@root/common/infrastructure/repository/base-schemas/meta.schema';
import { PaymentStatusEnum } from '@root/common/module/payment/domain/enums/payment.status.enum';
import { Schema } from 'mongoose';
import { IOrder } from '../../domain/persistance/IOrder';
import { OrderProduct } from '../../domain/root/order-product.root';
import { OrderService } from '../../domain/root/order-service.root';
import { Order } from '../../domain/root/order.root';
import { OrderNotificationSettingsSchema } from './sub/notification-settings.scheme';
import { StateHistorySchema } from '@root/common/infrastructure/repository/base-schemas/state-history.scheme';

export type OrderDocument = IOrder & Document;

export const OrderSchema = new Schema<IOrder>({
  // Order status using enum validation
  status: { 
    type: String, 
    required: true,
    enum: Object.values(OrderStatusEnum),
    default: OrderStatusEnum.requested
  },
  
  // Metadata for tracking and analytics
  meta: { 
    type: MetaSchema,
    required: false
  },
  
  // References to order products (separate collection)
  products: [{ 
    type: Schema.Types.ObjectId, 
    ref: OrderProduct.name,
    validate: {
      validator: function(products) {
        return !products || products.length <= ORDER_CONSTANTS.MAX_PRODUCTS_PER_ORDER;
      },
      message: `Order cannot contain more than ${ORDER_CONSTANTS.MAX_PRODUCTS_PER_ORDER} products`
    }
  }],
  
  // References to order services (separate collection)  
  services: [{ 
    type: Schema.Types.ObjectId, 
    ref: OrderService.name,
    validate: {
      validator: function(services) {
        return !services || services.length <= ORDER_CONSTANTS.MAX_SERVICES_PER_ORDER;
      },
      message: `Order cannot contain more than ${ORDER_CONSTANTS.MAX_SERVICES_PER_ORDER} services`
    }
  }],
  
  // Internal business notes (not visible to customers)
  businessNote: { 
    type: String,
    maxlength: 1000,
    trim: true
  },
  
  // Payment status tracking
  paymentStatus: { 
    type: String, 
    enum: Object.values(PaymentStatusEnum),
    default: PaymentStatusEnum.pending,
    required: false 
  },
  
  // Customer notification preferences
  notificationSettings: { 
    type: OrderNotificationSettingsSchema,
    required: false
  },
  
  // Complete audit trail with state changes
  stateHistory: { 
    type: [StateHistorySchema], 
    default: [] 
  }
}, {
  timestamps: true,                    // Automatic createdAt/updatedAt
  collection: Order.name.toLowerCase(), // Collection name: 'order'
  discriminatorKey: '__type'           // Support for inheritance
});
```

**Indexes**:

```typescript
// Compound index for common queries
OrderSchema.index({ 
  tenantId: 1, 
  status: 1, 
  createdAt: -1 
});

// Customer-based queries
OrderSchema.index({ 
  tenantId: 1, 
  'meta.customerId': 1, 
  createdAt: -1 
});

// Payment status queries
OrderSchema.index({ 
  tenantId: 1, 
  paymentStatus: 1, 
  updatedAt: -1 
});

// Member assignment queries (through services)
OrderSchema.index({ 
  tenantId: 1, 
  services: 1, 
  status: 1 
});

// Date range queries for reporting
OrderSchema.index({ 
  tenantId: 1, 
  createdAt: 1, 
  status: 1 
});
```

**Business Rules**:

1. **Required Fields**: Status is mandatory for all orders
2. **Status Validation**: Only valid enum values are accepted
3. **Service Limits**: Maximum 10 services per order (configurable)
4. **Product Limits**: Maximum 50 products per order (configurable)
5. **Note Length**: Business notes limited to 1000 characters
6. **State History**: All status changes are automatically tracked

### Order Service Schema

**Collection Name**: `orderservice`

**Purpose**: Individual service within an order with appointment details, specialist assignments, and status tracking.

**Schema Definition**:

```typescript
import { MetaSchema } from '@root/common/infrastructure/repository/base-schemas/meta.schema';
import { PaymentStatusEnum } from '@root/common/module/payment/domain/enums/payment.status.enum';
import { ServiceSchema } from '@root/common/module/service/repos/service.scheme';
import { Schema } from 'mongoose';
import { OrderServiceStatusEnum } from '../../domain/enums/order-service.status.enum';
import { IOrderService } from '../../domain/persistance/IOrderService';
import { OrederedServiceDetailsSchema } from './sub/order-service-details.schema';
import { StateHistorySchema } from '@root/common/infrastructure/repository/base-schemas/state-history.scheme';

export const OrderServiceSchema = new Schema<IOrderService>({
  // Parent order reference
  orderId: { 
    type: String, 
    required: true,
    validate: {
      validator: function(orderId) {
        return mongoose.Types.ObjectId.isValid(orderId);
      },
      message: 'Invalid order ID format'
    }
  },
  
  // Service configuration snapshot at booking time
  serviceSnapshot: { 
    type: ServiceSchema, 
    required: true,
    validate: {
      validator: function(service) {
        return service && service.isActive !== false;
      },
      message: 'Service must be active for booking'
    }
  },
  
  // Appointment details with specialists and attendees
  orderAppointmentDetails: { 
    type: OrederedServiceDetailsSchema, 
    required: true,
    validate: {
      validator: function(details) {
        const start = new Date(details.start);
        const end = new Date(details.end);
        return start < end && start > new Date();
      },
      message: 'Appointment must have valid start/end times in the future'
    }
  },
  
  // Service-specific status
  status: { 
    type: String, 
    enum: Object.values(OrderServiceStatusEnum),
    default: OrderServiceStatusEnum.requested,
    required: true
  },
  
  // Customer notes for this specific service
  customerNote: { 
    type: String,
    maxlength: 500,
    trim: true
  },
  
  // Service metadata
  meta: { 
    type: MetaSchema,
    required: false
  },
  
  // Payment status for this service
  paymentStatus: { 
    type: String, 
    enum: Object.values(PaymentStatusEnum),
    default: PaymentStatusEnum.pending,
    required: false 
  },
  
  // Service state change history
  stateHistory: { 
    type: [StateHistorySchema], 
    default: [] 
  }
}, { 
  timestamps: true,
  collection: 'orderService'
});

export type OrderServiceDocument = IOrderService & Document;
```

**Indexes**:

```typescript
// Primary lookup by order
OrderServiceSchema.index({ 
  orderId: 1, 
  status: 1 
});

// Specialist assignment queries
OrderServiceSchema.index({ 
  'orderAppointmentDetails.specialists.member': 1, 
  'orderAppointmentDetails.start': 1 
});

// Date range queries for scheduling
OrderServiceSchema.index({ 
  'orderAppointmentDetails.start': 1, 
  'orderAppointmentDetails.end': 1 
});

// Status and payment queries
OrderServiceSchema.index({ 
  status: 1, 
  paymentStatus: 1, 
  updatedAt: -1 
});

// Service type queries
OrderServiceSchema.index({ 
  'serviceSnapshot._id': 1, 
  status: 1, 
  createdAt: -1 
});
```

**Business Rules**:

1. **Valid Order Reference**: orderId must be a valid ObjectId
2. **Active Service**: Service snapshot must be from an active service
3. **Future Appointments**: Appointment start time must be in the future
4. **Valid Time Range**: End time must be after start time
5. **Specialist Assignment**: At least one specialist must be assigned
6. **Note Limits**: Customer notes limited to 500 characters

### Order Product Schema

**Collection Name**: `orderproduct`

**Purpose**: Products included in an order, either standalone or associated with specific services.

**Schema Definition**:

```typescript
import { ProductSchema } from '@root/common/module/product/product/repos/product.scheme';
import { Schema } from 'mongoose';
import { IOrderProduct } from '../../domain/persistance/IOrderProduct';
import { MetaSchema } from '@root/common/infrastructure/repository/base-schemas/meta.schema';
import { OrderProduct } from '../../domain/root/order-product.root';
import { PaymentStatusEnum } from '@root/common/module/payment/domain/enums/payment.status.enum';
import { StateHistorySchema } from '@root/common/infrastructure/repository/base-schemas/state-history.scheme';

export const OrderProductSchema = new Schema<IOrderProduct>({
  // Optional association with specific service
  orderServiceId: { 
    type: String, 
    required: false,
    validate: {
      validator: function(serviceId) {
        return !serviceId || mongoose.Types.ObjectId.isValid(serviceId);
      },
      message: 'Invalid service ID format'
    }
  },
  
  // Parent order reference
  orderId: { 
    type: String, 
    required: false,
    validate: {
      validator: function(orderId) {
        return !orderId || mongoose.Types.ObjectId.isValid(orderId);
      },
      message: 'Invalid order ID format'
    }
  },
  
  // Product configuration snapshot at order time
  productSnapshot: { 
    type: ProductSchema, 
    required: true,
    validate: {
      validator: function(product) {
        return product && product.isActive !== false;
      },
      message: 'Product must be active for ordering'
    }
  },
  
  // Quantity ordered
  quantity: { 
    type: Number, 
    required: true,
    min: [1, 'Quantity must be at least 1'],
    max: [100, 'Quantity cannot exceed 100'],
    validate: {
      validator: Number.isInteger,
      message: 'Quantity must be a whole number'
    }
  },
  
  // Product metadata
  meta: { 
    type: MetaSchema,
    required: false
  },
  
  // Payment status for this product
  paymentStatus: { 
    type: String, 
    enum: Object.values(PaymentStatusEnum),
    default: PaymentStatusEnum.pending,
    required: false 
  },
  
  // Sale timestamp (when product was sold/delivered)
  saleDate: {
    type: Date,
    required: false
  },
  
  // Product state change history
  stateHistory: { 
    type: [StateHistorySchema], 
    default: [] 
  }
}, { 
  timestamps: true,
  collection: 'orderProduct'
});

export type OrderProductDocument = IOrderProduct & Document;
```

**Indexes**:

```typescript
// Order-based product queries
OrderProductSchema.index({ 
  orderId: 1, 
  createdAt: -1 
});

// Service-associated product queries
OrderProductSchema.index({ 
  orderServiceId: 1, 
  paymentStatus: 1 
});

// Product type queries
OrderProductSchema.index({ 
  'productSnapshot._id': 1, 
  saleDate: -1 
});

// Inventory and sales queries
OrderProductSchema.index({ 
  'productSnapshot._id': 1, 
  quantity: 1, 
  createdAt: -1 
});

// Payment tracking queries
OrderProductSchema.index({ 
  paymentStatus: 1, 
  saleDate: 1 
});
```

**Business Rules**:

1. **Active Product**: Product snapshot must be from an active product
2. **Valid Quantity**: Quantity must be positive integer between 1-100
3. **Valid References**: Order and service IDs must be valid ObjectIds when provided
4. **Sale Date**: Sale date can only be set when product is delivered
5. **Payment Consistency**: Payment status must align with order payment status

## Sub-Schemas

### Order Service Details Schema

**Purpose**: Detailed appointment information including specialists, attendees, location, and attachments.

**Schema Definition**:

```typescript
import { Schema } from 'mongoose';
import { LocationSchema } from './location.scheme';
import { AttendantSchema } from './attendant.scheme';
import { AttachmentSchema } from './attachment.scheme';
import { SpecialistSchema } from './specialist.scheme';
import { LanguageCodeEnum } from '@root/common/core/enum/language-code.enum';
import { ReservationTypeEnum } from '../../../domain/enums/reservation.type.enum';

export const OrederedServiceDetailsSchema = new Schema({
  // Appointment timing
  start: {
    type: String,
    required: true,
    validate: {
      validator: function(start) {
        return !isNaN(Date.parse(start));
      },
      message: 'Start time must be a valid ISO date string'
    }
  },
  
  end: {
    type: String,
    required: true,
    validate: {
      validator: function(end) {
        const start = new Date(this.start);
        const endDate = new Date(end);
        return endDate > start;
      },
      message: 'End time must be after start time'
    }
  },
  
  // Reservation type classification
  type: {
    type: String,
    enum: Object.values(ReservationTypeEnum),
    default: ReservationTypeEnum.service
  },
  
  // Preferred languages for service delivery
  languageCodes: [{
    type: String,
    enum: Object.values(LanguageCodeEnum),
    default: [LanguageCodeEnum.en]
  }],
  
  // Assigned specialists (required)
  specialists: {
    type: [SpecialistSchema],
    required: true,
    validate: {
      validator: function(specialists) {
        return specialists && specialists.length > 0;
      },
      message: 'At least one specialist must be assigned'
    }
  },
  
  // Service attendees (customers)
  attendants: {
    type: [AttendantSchema],
    required: false,
    validate: {
      validator: function(attendants) {
        return !attendants || attendants.length <= ORDER_CONSTANTS.MAX_ATTENDEES_PER_SERVICE;
      },
      message: `Cannot have more than ${ORDER_CONSTANTS.MAX_ATTENDEES_PER_SERVICE} attendees per service`
    }
  },
  
  // Service location details
  location: {
    type: LocationSchema,
    required: false
  },
  
  // Additional attachments and files
  attachments: {
    type: [AttachmentSchema],
    required: false,
    validate: {
      validator: function(attachments) {
        return !attachments || attachments.length <= ORDER_CONSTANTS.MAX_ATTACHMENTS_PER_SERVICE;
      },
      message: `Cannot have more than ${ORDER_CONSTANTS.MAX_ATTACHMENTS_PER_SERVICE} attachments per service`
    }
  }
}, {
  _id: false  // Embedded document, no separate ID
});
```

### Notification Settings Schema

**Purpose**: Customer notification preferences for order updates and reminders.

**Schema Definition**:

```typescript
import { Schema } from 'mongoose';

export const OrderNotificationSettingsSchema = new Schema({
  // Email notification preferences
  emailNotifications: {
    type: Boolean,
    default: true
  },
  
  // SMS notification preferences
  smsNotifications: {
    type: Boolean,
    default: false
  },
  
  // Push notification preferences
  pushNotifications: {
    type: Boolean,
    default: true
  },
  
  // Reminder configuration
  reminderSettings: {
    enabled: {
      type: Boolean,
      default: true
    },
    timeBeforeInMinutes: {
      type: Number,
      default: 60,
      min: [15, 'Reminder must be at least 15 minutes before'],
      max: [1440, 'Reminder cannot be more than 24 hours before']
    }
  },
  
  // Notification language preference
  preferredLanguage: {
    type: String,
    enum: Object.values(LanguageCodeEnum),
    default: LanguageCodeEnum.en
  }
}, {
  _id: false
});
```

### Supporting Sub-Schemas

#### Specialist Schema

```typescript
export const SpecialistSchema = new Schema({
  member: {
    type: Schema.Types.ObjectId,
    ref: 'Member',
    required: true
  },
  role: {
    type: String,
    default: 'primary'
  },
  assignedAt: {
    type: Date,
    default: Date.now
  }
}, { _id: false });
```

#### Attendant Schema

```typescript
export const AttendantSchema = new Schema({
  customer: {
    type: Schema.Types.ObjectId,
    ref: 'Customer',
    required: true
  },
  firstTime: {
    type: Boolean,
    default: false
  },
  specialRequests: {
    type: String,
    maxlength: 200
  }
}, { _id: false });
```

#### Location Schema

```typescript
export const LocationSchema = new Schema({
  address: {
    type: String,
    maxlength: 200
  },
  coordinates: {
    latitude: {
      type: Number,
      min: -90,
      max: 90
    },
    longitude: {
      type: Number,
      min: -180,
      max: 180
    }
  },
  roomNumber: {
    type: String,
    maxlength: 20
  },
  buildingInfo: {
    type: String,
    maxlength: 100
  }
}, { _id: false });
```

#### Attachment Schema

```typescript
export const AttachmentSchema = new Schema({
  filename: {
    type: String,
    required: true,
    maxlength: 255
  },
  url: {
    type: String,
    required: true,
    validate: {
      validator: function(url) {
        return /^https?:\/\/.+/.test(url);
      },
      message: 'URL must be a valid HTTP/HTTPS URL'
    }
  },
  mimeType: {
    type: String,
    validate: {
      validator: function(mimeType) {
        return /^[a-zA-Z]+\/[a-zA-Z0-9\-\+\.]+$/.test(mimeType);
      },
      message: 'Invalid MIME type format'
    }
  },
  size: {
    type: Number,
    min: 0,
    max: ORDER_CONSTANTS.MAX_ATTACHMENT_SIZE_MB * 1024 * 1024
  },
  uploadedBy: {
    type: Schema.Types.ObjectId,
    ref: 'Member'
  },
  uploadedAt: {
    type: Date,
    default: Date.now
  }
}, { _id: false });
```

## Index Strategy

### Performance Optimization

#### Compound Indexes

```typescript
// Multi-tenant queries with status filtering
db.order.createIndex({ 
  "tenantId": 1, 
  "status": 1, 
  "createdAt": -1 
});

// Customer order history
db.order.createIndex({ 
  "tenantId": 1, 
  "meta.customerId": 1, 
  "createdAt": -1 
});

// Member assignment queries
db.orderservice.createIndex({ 
  "orderAppointmentDetails.specialists.member": 1, 
  "orderAppointmentDetails.start": 1,
  "status": 1
});

// Date range queries for scheduling
db.orderservice.createIndex({ 
  "orderAppointmentDetails.start": 1, 
  "orderAppointmentDetails.end": 1,
  "orderAppointmentDetails.specialists.member": 1
});

// Payment status tracking
db.order.createIndex({ 
  "tenantId": 1, 
  "paymentStatus": 1, 
  "updatedAt": -1 
});
```

#### Sparse Indexes

```typescript
// Optional field indexes
db.order.createIndex({ 
  "meta.customerId": 1 
}, { 
  sparse: true 
});

db.orderproduct.createIndex({ 
  "orderServiceId": 1 
}, { 
  sparse: true 
});

db.orderproduct.createIndex({ 
  "saleDate": 1 
}, { 
  sparse: true 
});
```

#### Text Indexes

```typescript
// Full-text search capabilities
db.order.createIndex({
  "businessNote": "text",
  "meta.notes": "text"
}, {
  name: "order_text_search",
  default_language: "english"
});

db.orderservice.createIndex({
  "customerNote": "text"
}, {
  name: "service_text_search"
});
```

### Index Monitoring

```typescript
// Index usage statistics
db.order.aggregate([
  { $indexStats: {} }
]);

// Query performance analysis
db.order.explain("executionStats").find({
  tenantId: "tenant123",
  status: "confirmed",
  createdAt: { $gte: new Date("2024-01-01") }
});
```

## Data Integrity Rules

### Referential Integrity

#### Order Relationships

```typescript
// Pre-save middleware for order validation
OrderSchema.pre('save', async function(next) {
  // Validate service references
  if (this.services?.length) {
    const serviceCount = await OrderService.countDocuments({
      _id: { $in: this.services },
      orderId: this._id
    });
    
    if (serviceCount !== this.services.length) {
      throw new Error('Invalid service references in order');
    }
  }
  
  // Validate product references
  if (this.products?.length) {
    const productCount = await OrderProduct.countDocuments({
      _id: { $in: this.products },
      orderId: this._id
    });
    
    if (productCount !== this.products.length) {
      throw new Error('Invalid product references in order');
    }
  }
  
  next();
});
```

#### Cascade Operations

```typescript
// Cascade delete for order services and products
OrderSchema.pre('deleteOne', { document: true, query: false }, async function() {
  // Delete associated services
  await OrderService.deleteMany({ orderId: this._id });
  
  // Delete associated products
  await OrderProduct.deleteMany({ orderId: this._id });
  
  // Clean up related data
  await NotificationService.cancelOrderNotifications(this._id);
  await CacheService.invalidateOrderCache(this._id);
});
```

### Data Validation

#### Business Rule Validation

```typescript
// Custom validators for business rules
const validateAppointmentConflict = async function(value) {
  if (!this.orderAppointmentDetails) return true;
  
  const { start, end, specialists } = this.orderAppointmentDetails;
  
  for (const specialist of specialists) {
    const conflicts = await OrderService.find({
      'orderAppointmentDetails.specialists.member': specialist.member,
      'orderAppointmentDetails.start': { $lt: end },
      'orderAppointmentDetails.end': { $gt: start },
      status: { $nin: ['cancelled', 'deleted'] },
      _id: { $ne: this._id }
    });
    
    if (conflicts.length > 0) {
      throw new Error(`Specialist ${specialist.member} has conflicting appointments`);
    }
  }
  
  return true;
};

OrderServiceSchema.path('orderAppointmentDetails').validate(
  validateAppointmentConflict,
  'Appointment conflicts with existing bookings'
);
```

#### Multi-field Validation

```typescript
// Cross-field validation
const validateOrderConsistency = function() {
  // Validate payment status consistency
  if (this.status === 'done' && this.paymentStatus === 'pending') {
    throw new Error('Completed orders must have resolved payment status');
  }
  
  // Validate service count limits
  if (this.services?.length > ORDER_CONSTANTS.MAX_SERVICES_PER_ORDER) {
    throw new Error(`Order cannot contain more than ${ORDER_CONSTANTS.MAX_SERVICES_PER_ORDER} services`);
  }
  
  return true;
};

OrderSchema.pre('validate', validateOrderConsistency);
```

## Multi-tenancy Support

### Tenant Isolation

#### Schema Design

```typescript
// Tenant field in all schemas
const baseTenantSchema = {
  tenantId: {
    type: String,
    required: true,
    immutable: true,  // Cannot be changed after creation
    validate: {
      validator: function(tenantId) {
        return /^[a-f\d]{24}$/i.test(tenantId);
      },
      message: 'Tenant ID must be a valid ObjectId'
    }
  }
};

// Apply to all order schemas
OrderSchema.add(baseTenantSchema);
OrderServiceSchema.add(baseTenantSchema);
OrderProductSchema.add(baseTenantSchema);
```

#### Query Middleware

```typescript
// Automatic tenant filtering
function addTenantFilter(schema) {
  schema.pre(/^find/, function() {
    if (!this.getQuery().tenantId) {
      throw new Error('Tenant ID is required for all queries');
    }
  });
  
  schema.pre('countDocuments', function() {
    if (!this.getQuery().tenantId) {
      throw new Error('Tenant ID is required for count queries');
    }
  });
  
  schema.pre('aggregate', function() {
    // Add tenant filter to aggregation pipeline
    this.pipeline().unshift({
      $match: { tenantId: this.options.tenantId }
    });
  });
}

// Apply tenant filtering to all schemas
addTenantFilter(OrderSchema);
addTenantFilter(OrderServiceSchema);
addTenantFilter(OrderProductSchema);
```

### Data Partitioning

```typescript
// Collection naming strategy for large tenants
function getCollectionName(baseName, tenantId) {
  // For high-volume tenants, use separate collections
  const highVolumeTenants = ['tenant1', 'tenant2', 'tenant3'];
  
  if (highVolumeTenants.includes(tenantId)) {
    return `${baseName}_${tenantId}`;
  }
  
  return baseName;
}

// Dynamic model creation
function getOrderModel(tenantId) {
  const collectionName = getCollectionName('order', tenantId);
  return mongoose.model('Order', OrderSchema, collectionName);
}
```

## Audit Trail and State History

### State History Schema

```typescript
export const StateHistorySchema = new Schema({
  // Previous state information
  previousState: {
    type: Schema.Types.Mixed,
    required: true
  },
  
  // New state information
  newState: {
    type: Schema.Types.Mixed,
    required: true
  },
  
  // Who made the change
  changedBy: {
    type: Schema.Types.ObjectId,
    ref: 'Member',
    required: true
  },
  
  // When the change occurred
  changedAt: {
    type: Date,
    default: Date.now,
    required: true
  },
  
  // Reason for change
  reason: {
    type: String,
    maxlength: 200
  },
  
  // Change source (panel, api, system, etc.)
  source: {
    type: String,
    enum: ['panel', 'api', 'system', 'migration'],
    default: 'panel'
  },
  
  // IP address of change originator
  ipAddress: {
    type: String,
    validate: {
      validator: function(ip) {
        return !ip || /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$|^(?:[a-fA-F0-9]{0,4}:){1,7}[a-fA-F0-9]{0,4}$/.test(ip);
      },
      message: 'Invalid IP address format'
    }
  },
  
  // User agent information
  userAgent: {
    type: String,
    maxlength: 500
  }
}, {
  _id: true,  // Give each history entry an ID
  timestamps: false  // We have our own timestamp
});
```

### Automatic History Tracking

```typescript
// Middleware to track state changes
function addHistoryTracking(schema, entityName) {
  schema.pre('save', function(next) {
    if (this.isNew) {
      // For new documents, add creation history
      this.stateHistory.push({
        previousState: null,
        newState: this.toObject(),
        changedBy: this.meta?.createdBy || this.meta?.lastModifiedBy,
        changedAt: new Date(),
        reason: `${entityName} created`,
        source: this.meta?.source || 'panel'
      });
    } else if (this.isModified()) {
      // For updates, track the changes
      const changes = {};
      const modifiedPaths = this.modifiedPaths();
      
      for (const path of modifiedPaths) {
        if (path !== 'stateHistory' && path !== 'updatedAt') {
          changes[path] = {
            from: this._original?.[path],
            to: this[path]
          };
        }
      }
      
      this.stateHistory.push({
        previousState: this._original,
        newState: this.toObject(),
        changedBy: this.meta?.lastModifiedBy,
        changedAt: new Date(),
        reason: `${entityName} updated`,
        source: this.meta?.source || 'panel',
        changes: changes
      });
    }
    
    next();
  });
  
  schema.post('init', function() {
    // Store original state for comparison
    this._original = this.toObject();
  });
}

// Apply history tracking to all schemas
addHistoryTracking(OrderSchema, 'Order');
addHistoryTracking(OrderServiceSchema, 'OrderService');
addHistoryTracking(OrderProductSchema, 'OrderProduct');
```

## Performance Optimization

### Connection Management

```typescript
// Optimized connection configuration
const connectionOptions = {
  maxPoolSize: 50,          // Maximum number of connections
  minPoolSize: 5,           // Minimum number of connections
  maxIdleTimeMS: 30000,     // Close connections after 30 seconds of inactivity
  serverSelectionTimeoutMS: 5000,  // How long to try selecting a server
  socketTimeoutMS: 45000,   // How long to wait for a response
  bufferMaxEntries: 0,      // Disable mongoose buffering
  bufferCommands: false,    // Disable mongoose buffering
  heartbeatFrequencyMS: 10000,  // How often to check server health
  retryWrites: true,        // Retry failed writes
  writeConcern: {
    w: 'majority',          // Wait for majority acknowledgment
    wtimeout: 5000          // Timeout for write concern
  },
  readConcern: {
    level: 'majority'       // Read concern level
  }
};
```

### Query Optimization

```typescript
// Optimized aggregation pipelines
const getOrdersByDateRange = (tenantId, startDate, endDate) => [
  // Match stage with indexes
  {
    $match: {
      tenantId: tenantId,
      createdAt: {
        $gte: new Date(startDate),
        $lte: new Date(endDate)
      }
    }
  },
  
  // Lookup with indexed fields
  {
    $lookup: {
      from: 'orderservice',
      localField: 'services',
      foreignField: '_id',
      as: 'serviceDetails',
      pipeline: [
        {
          $match: {
            tenantId: tenantId
          }
        },
        {
          $project: {
            status: 1,
            orderAppointmentDetails: 1,
            serviceSnapshot: 1
          }
        }
      ]
    }
  },
  
  // Project only needed fields
  {
    $project: {
      status: 1,
      paymentStatus: 1,
      createdAt: 1,
      updatedAt: 1,
      serviceDetails: 1,
      businessNote: 1
    }
  },
  
  // Sort with indexed field
  {
    $sort: {
      createdAt: -1
    }
  }
];
```

### Memory Optimization

```typescript
// Stream processing for large datasets
const processLargeOrderDataset = async (tenantId, processor) => {
  const cursor = Order.find({ tenantId })
    .lean()  // Return plain objects instead of Mongoose documents
    .cursor();
    
  for (let order = await cursor.next(); order != null; order = await cursor.next()) {
    await processor(order);
  }
};

// Batch operations for better performance
const bulkUpdateOrders = async (tenantId, updates) => {
  const bulkOps = updates.map(update => ({
    updateOne: {
      filter: { _id: update.orderId, tenantId },
      update: { $set: update.changes },
      upsert: false
    }
  }));
  
  // Process in batches of 1000
  const batchSize = 1000;
  for (let i = 0; i < bulkOps.length; i += batchSize) {
    const batch = bulkOps.slice(i, i + batchSize);
    await Order.bulkWrite(batch, { ordered: false });
  }
};
```

## Backup and Recovery

### Backup Strategy

```typescript
// Incremental backup configuration
const backupConfig = {
  // Daily full backup
  fullBackup: {
    schedule: "0 2 * * *",  // 2 AM daily
    retention: 30,          // Keep 30 days
    collections: ['order', 'orderservice', 'orderproduct']
  },
  
  // Hourly incremental backup
  incrementalBackup: {
    schedule: "0 * * * *",  // Every hour
    retention: 24,          // Keep 24 hours
    query: {
      updatedAt: { $gte: "lastBackupTime" }
    }
  },
  
  // Point-in-time recovery
  oplogBackup: {
    enabled: true,
    retention: 7            // Keep 7 days of oplog
  }
};
```

### Recovery Procedures

```typescript
// Point-in-time recovery
const recoverToTimestamp = async (targetTimestamp) => {
  // Stop application
  await stopApplication();
  
  // Restore from last full backup before target time
  const backupFile = findBackupBeforeTimestamp(targetTimestamp);
  await restoreFromBackup(backupFile);
  
  // Apply oplog entries up to target timestamp
  await replayOplogToTimestamp(targetTimestamp);
  
  // Verify data integrity
  await verifyDataIntegrity();
  
  // Restart application
  await startApplication();
};
```

## Monitoring and Maintenance

### Health Checks

```typescript
// Database health monitoring
const performHealthCheck = async () => {
  const checks = {
    connection: false,
    indexes: false,
    replication: false,
    performance: false
  };
  
  try {
    // Test connection
    await mongoose.connection.db.admin().ping();
    checks.connection = true;
    
    // Check indexes
    const orderIndexes = await Order.collection.indexes();
    checks.indexes = orderIndexes.length >= 5;  // Expected minimum indexes
    
    // Check replication lag
    const replStatus = await mongoose.connection.db.admin().command({
      replSetGetStatus: 1
    });
    checks.replication = replStatus.ok === 1;
    
    // Check performance metrics
    const stats = await mongoose.connection.db.stats();
    checks.performance = stats.avgObjSize < 10000;  // Objects under 10KB average
    
  } catch (error) {
    console.error('Health check failed:', error);
  }
  
  return checks;
};
```

### Maintenance Tasks

```typescript
// Automated maintenance routines
const performMaintenance = async () => {
  // Compact collections
  await Order.collection.compact();
  await OrderService.collection.compact();
  await OrderProduct.collection.compact();
  
  // Rebuild indexes
  await Order.collection.reIndex();
  await OrderService.collection.reIndex();
  await OrderProduct.collection.reIndex();
  
  // Clean up old state history (older than 1 year)
  const oneYearAgo = new Date();
  oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
  
  await Order.updateMany(
    {},
    {
      $pull: {
        stateHistory: {
          changedAt: { $lt: oneYearAgo }
        }
      }
    }
  );
  
  // Update statistics
  await updateCollectionStatistics();
};
```


# Product Management

## Overview

This directory contains comprehensive documentation for the Product Management module of the Bee O'clock panel service. The product management system handles the complete lifecycle of products and their associated tags, including creation, updates, status management, image management, and categorization within the multi-tenant SaaS platform.

## Documentation Structure

### [API Documentation](/services/product-management/api)

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

**Key Topics Covered:**

* Product CRUD operations with comprehensive validation
* Paginated product listing with advanced filtering and search
* Product tag management with categorization support
* Product image upload and management operations
* Comprehensive data schemas and validation rules
* Error handling and business rule enforcement
* Performance optimization and monitoring guidelines
* Rate limiting and security considerations

### [Interface Documentation](/services/product-management/interface)

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

**Key Topics Covered:**

* Data Transfer Objects (DTOs) with validation constraints
* Domain interfaces and entity definitions
* Enum definitions and business constants
* Type definitions and utility types
* Validation constraints and business rules
* Repository contracts and specifications
* Use case parameter interfaces
* Media and file handling interfaces

### [Use Case Documentation](/services/product-management/usecase)

Business logic and use case implementations following Clean Architecture principles and CQRS pattern with comprehensive permission validation.

**Key Topics Covered:**

* Core business use cases with permission validation
* CQRS pattern implementation with command/query separation
* Error handling strategies and exception management
* Event publishing and system integration patterns
* Performance considerations and optimization strategies
* Business rule enforcement and validation logic
* Multi-tenant security and data isolation

### [Database Schema Documentation](/services/product-management/db_schema)

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

**Key Topics Covered:**

* Entity schemas and sub-document structures
* Index strategies and query optimization
* Multi-tenancy support and data isolation
* Data validation and business constraints
* Audit trail and state history tracking
* Performance optimization and monitoring
* Backup and recovery strategies

## Module Architecture

### Technology Stack

* **Framework**: NestJS with TypeScript
* **Database**: MongoDB with Mongoose ODM
* **Architecture**: Clean Architecture + CQRS + DDD
* **Patterns**: Repository Pattern, Command Pattern, Event-Driven Architecture
* **File Storage**: CDN integration for image management
* **Caching**: Redis for performance optimization
* **Search**: MongoDB text indexes with full-text search capabilities
* **Monitoring**: Comprehensive logging and metrics

### Core Features

#### Product Lifecycle Management

* Comprehensive product creation with multi-language support
* Advanced update workflows with change tracking and audit trails
* SKU-based identification with uniqueness validation
* Soft deletion with dependency checking and data preservation
* Multi-language content management with validation

#### Product Categorization

* Tag-based categorization system with hierarchical support
* Advanced filtering and search capabilities
* Tag management with usage tracking and validation
* Bulk tag operations with performance optimization
* Tag-based product discovery and organization

#### Image Management

* Multi-image support with CDN integration
* Automatic image optimization and thumbnail generation
* File type validation and size constraints
* Image metadata extraction and storage
* Progressive loading and responsive image delivery

#### Advanced Search and Filtering

* Full-text search across multiple language versions
* Tag-based filtering with complex boolean logic
* Price range filtering with currency conversion
* Sorting by multiple criteria (name, price, date, popularity)
* Pagination with efficient cursor-based navigation

#### Multi-Language Support

* Comprehensive internationalization with language-specific content
* Title and description localization with validation
* Language-specific search and filtering capabilities
* Content management with translation workflow support
* Fallback language handling for missing translations

#### Multi-Tenant Architecture

* Complete tenant data isolation with security validation
* Tenant-specific business rule configuration
* Scalable database partitioning strategies
* Performance optimization per tenant size and usage patterns
* Cross-tenant analytics and reporting capabilities

## Business Rules

### Product Creation

1. **SKU Uniqueness**: Product SKU must be unique within the tenant scope
2. **Language Requirements**: At least one language version is mandatory for all products
3. **Price Validation**: Price must be positive with valid currency from supported list
4. **Tag Validation**: All assigned tags must exist in the product tag collection
5. **Image Constraints**: Maximum 10 images per product with size and format validation

### Product Updates

1. **SKU Immutability**: Product SKU cannot be changed after initial creation
2. **Language Preservation**: Cannot remove all language versions from a product
3. **Price History**: All price changes are tracked for audit and compliance purposes
4. **Tag Synchronization**: Tag updates propagate to all products using those tags
5. **Permission Validation**: User must have appropriate permissions for update scope

### Product Deletion

1. **Soft Deletion**: Products are marked as deleted rather than physically removed
2. **Dependency Validation**: Cannot delete products referenced in active orders or reservations
3. **Cascade Management**: Related images and references are properly handled during deletion
4. **Data Preservation**: All historical data maintained for compliance and audit requirements
5. **Cleanup Coordination**: Automatic cleanup of related resources and cache invalidation

### Tag Management

1. **Name Uniqueness**: Tag names must be unique within tenant with case-insensitive comparison
2. **Usage Tracking**: Cannot delete tags currently assigned to active products
3. **Character Validation**: Tag names must follow specific character and length constraints
4. **Bulk Operations**: Support for efficient bulk tag creation and management operations
5. **Reference Integrity**: Maintain referential integrity between products and tags

### Image Management

1. **File Format Validation**: Only JPEG, PNG, and WebP formats are supported
2. **Size Constraints**: Maximum 5MB per image with automatic optimization
3. **Dimension Validation**: Reasonable minimum and maximum pixel dimensions
4. **Count Limits**: Maximum 10 images per product with efficient storage
5. **CDN Integration**: Automatic upload to CDN with global distribution

### Permission Management

1. **Role-Based Access**: Different permission levels for different user roles and responsibilities
2. **Operation-Specific Permissions**: Granular permissions for create, read, update, delete operations
3. **Tenant Isolation**: Complete data isolation between different tenants with security validation
4. **Audit Logging**: All access attempts and changes are logged for security and compliance
5. **Permission Inheritance**: Logical permission hierarchy with inheritance rules

## API Integration Examples

### Creating a Multi-Language Product

```typescript
POST /api/v1/product
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "sku": "SPA-ESSENTIAL-001",
  "languageVersions": [
    {
      "language": "en",
      "title": "Essential Oils Aromatherapy Kit",
      "description": "Complete aromatherapy kit with 6 premium essential oils, diffuser, and instruction guide for relaxation and wellness."
    },
    {
      "language": "es",
      "title": "Kit de Aromaterapia con Aceites Esenciales",
      "description": "Kit completo de aromaterapia con 6 aceites esenciales premium, difusor y guía de instrucciones para relajación y bienestar."
    },
    {
      "language": "fr",
      "title": "Kit d'Aromathérapie aux Huiles Essentielles",
      "description": "Kit d'aromathérapie complet avec 6 huiles essentielles premium, diffuseur et guide d'instructions pour la relaxation et le bien-être."
    }
  ],
  "price": {
    "value": 89.99,
    "currency": "USD"
  },
  "tags": ["aromatherapy", "wellness", "essential-oils", "relaxation", "spa"],
  "order": 1
}
```

### Advanced Product Search with Filters

```typescript
GET /api/v1/product/paged?
  phrase=aromatherapy&
  tags[]=wellness&
  tags[]=spa&
  page=1&
  size=20
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

### Bulk Image Upload Workflow

```typescript
// 1. Create product
const product = await createProduct(productData);

// 2. Upload multiple images
const imageUploadPromises = imageFiles.map(async (file, index) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('alt', `${product.languageVersions[0].title} - Image ${index + 1}`);
  
  return uploadProductImage(product._id, formData);
});

const uploadedImages = await Promise.all(imageUploadPromises);

// 3. Verify all uploads completed successfully
console.log(`Successfully uploaded ${uploadedImages.length} images for product ${product._id}`);
```

### Product Tag Management

```typescript
// Create new tags
const wellnessTags = [
  { name: "aromatherapy" },
  { name: "wellness" },
  { name: "spa" },
  { name: "relaxation" },
  { name: "essential-oils" }
];

const createdTags = await Promise.all(
  wellnessTags.map(tag => createProductTag(tag))
);

// Assign tags to products
await updateProduct(productId, {
  ...existingProduct,
  tags: createdTags.map(tag => tag.name)
});
```

## Performance Metrics

### Key Performance Indicators

* Product creation/update response times with detailed performance tracking
* Search and filtering query performance with optimization recommendations
* Database query performance analysis with slow query identification
* Image upload and processing times with CDN distribution metrics
* Cache hit rates and effectiveness measurement across different data types
* Error rate monitoring and categorization for business and technical issues

### Monitoring and Alerting

* Real-time API endpoint response time monitoring with SLA tracking
* Database performance and query analysis with automated optimization suggestions
* Image processing and CDN performance tracking with global distribution metrics
* Cache performance and hit rate tracking with capacity planning recommendations
* Comprehensive error rate monitoring with intelligent alerting and escalation procedures

## Scalability Considerations

### Horizontal Scaling

* Stateless service design for easy horizontal scaling across multiple instances
* Database sharding strategies for large product catalogs with tenant-based partitioning
* Distributed caching for multi-instance deployment with consistency guarantees
* Load balancing for API endpoints with intelligent request routing and failover
* Microservice-ready architecture with clear service boundaries and communication patterns

### Vertical Scaling

* Database optimization and indexing with continuous performance monitoring
* Query performance tuning with automated query plan analysis and recommendations
* Memory usage optimization with efficient data structures and caching strategies
* CPU-intensive operation optimization with async processing and intelligent batching
* Storage efficiency improvements with data compression and intelligent archival strategies

## Integration Patterns

### Event-Driven Integration

* **Product Lifecycle Events**: Creation, updates, and deletion events for system integration
* **Tag Management Events**: Tag creation, updates, and usage tracking for analytics
* **Image Processing Events**: Upload, optimization, and deletion events for media workflows
* **Search Index Events**: Automatic search index updates for improved discoverability
* **Audit Events**: Comprehensive audit trail events for compliance and monitoring

### Cache Integration

* **Product Data Caching**: Frequently accessed products cached with intelligent invalidation
* **Search Result Caching**: Common search queries cached with automatic refresh
* **Tag Data Caching**: Tag collections heavily cached due to infrequent changes
* **Image URL Caching**: CDN URLs cached for fast access with proper expiration
* **Metadata Caching**: Product metadata cached for dashboard and analytics

### External Service Integration

* **CDN Services**: Image storage and delivery with global distribution
* **Search Services**: External search engines for advanced full-text search capabilities
* **Analytics Services**: Product performance and usage analytics integration
* **Notification Services**: Product-related notifications and customer communication
* **Payment Services**: Product pricing integration with payment processing systems

## Security Considerations

### Data Protection

* **Input Validation**: Comprehensive validation of all input data with sanitization
* **Access Control**: Role-based permission system with granular operation control
* **Tenant Isolation**: Complete data isolation between tenants with security validation
* **Audit Logging**: All access attempts and changes logged for security monitoring
* **Data Encryption**: Sensitive data encrypted in transit and at rest

### File Security

* **Upload Validation**: Comprehensive file type, size, and content validation
* **Virus Scanning**: Automatic virus scanning for all uploaded files
* **CDN Security**: Secure file storage with access controls and monitoring
* **Content Filtering**: Inappropriate content detection and filtering
* **Access Logging**: All file access attempts logged for security monitoring

### API Security

* **Authentication**: Bearer token authentication with proper validation
* **Authorization**: Role-based access control with operation-specific permissions
* **Rate Limiting**: Intelligent rate limiting with abuse prevention
* **Input Sanitization**: XSS and injection attack prevention
* **CORS Configuration**: Proper cross-origin resource sharing configuration

## Development Guidelines

### Testing Strategy

* **Unit Tests**: Business logic validation and domain rule enforcement with high coverage
* **Integration Tests**: Database operations and external service integration with realistic scenarios
* **E2E Tests**: Complete product workflow validation from creation to deletion
* **Performance Tests**: Load testing and scalability validation under realistic load conditions
* **Security Tests**: Permission validation and data isolation verification with penetration testing

### Error Handling

* Domain-specific exceptions with clear error codes and user-friendly messages
* Consistent error response format across all endpoints with detailed context
* Proper HTTP status codes for different error categories and business scenarios
* Comprehensive logging for debugging and monitoring with correlation IDs and context
* Graceful degradation for non-critical failures with appropriate fallback mechanisms

### Code Quality Standards

* TypeScript strict mode compliance with comprehensive type safety
* ESLint and Prettier configuration with automated formatting and linting
* Comprehensive test coverage requirements with minimum thresholds and quality gates
* Clean Architecture principles adherence with clear layer separation and dependencies
* Domain-Driven Design patterns with rich domain models and proper encapsulation

## Deployment and Operations

### Deployment Strategy

* **Blue-Green Deployment**: Zero downtime deployments with automatic health checks
* **Database Migrations**: Schema evolution with backwards compatibility and rollback procedures
* **Feature Flags**: Gradual feature rollouts with real-time monitoring and instant rollback
* **Environment Management**: Consistent environments across development, staging, and production
* **Health Monitoring**: Comprehensive health checks with automated failure detection and recovery

### Monitoring and Observability

* **Application Metrics**: Business and technical metrics with real-time dashboards
* **Performance Monitoring**: Response time, throughput, and resource utilization tracking
* **Error Tracking**: Comprehensive error tracking with automatic categorization and alerting
* **Business Intelligence**: Product usage analytics and performance insights
* **Infrastructure Monitoring**: Database, cache, and CDN performance monitoring

### Backup and Disaster Recovery

* **Automated Backups**: Regular automated backups with verification and testing
* **Point-in-Time Recovery**: Database point-in-time recovery with minimal data loss
* **Cross-Region Replication**: Geographic distribution for disaster recovery
* **Recovery Testing**: Regular disaster recovery testing with documented procedures
* **Data Integrity**: Continuous data integrity monitoring with automatic correction

## Future Enhancements

### Planned Features

* **AI-Powered Recommendations**: Intelligent product recommendations based on user behavior and preferences
* **Advanced Analytics**: Comprehensive business intelligence with predictive analytics and insights
* **Bulk Operations**: Enhanced bulk import/export capabilities with validation and error handling
* **API Versioning**: Comprehensive API versioning strategy with backwards compatibility
* **Mobile Optimization**: Enhanced mobile API support with offline capabilities and synchronization

### Technical Improvements

* **GraphQL API**: Enhanced query capabilities with client-specific data fetching optimization
* **Event Sourcing**: Complete audit trail with event replay capabilities for compliance
* **Microservice Architecture**: Split into focused microservices with clear boundaries and contracts
* **Advanced Search**: Elasticsearch integration for complex search and analytics capabilities
* **Real-time Updates**: WebSocket integration for live product updates and notifications

## Troubleshooting Guide

### Common Issues

* **Product Creation Failures**: Validation errors, SKU conflicts, and resolution strategies
* **Permission Denied Errors**: Access control troubleshooting and permission verification procedures
* **Image Upload Issues**: File validation problems, CDN integration failures, and workarounds
* **Performance Issues**: Query optimization, caching improvements, and resource scaling strategies
* **Integration Failures**: External service communication problems and fallback mechanisms

### Debugging Tools

* Structured error messages with correlation IDs for request tracing across services
* Comprehensive logging with request context and business operation tracking
* Database query analysis tools with performance profiling and optimization recommendations
* Cache inspection utilities with hit rate monitoring and eviction tracking
* Performance profiling tools with bottleneck identification and optimization suggestions

### Support Resources

* Comprehensive API documentation with interactive examples and real-world use cases
* Error code reference guide with resolution strategies and best practices
* Performance optimization guide with specific recommendations and benchmarks
* Best practices documentation with coding standards and architectural guidelines
* Community forums and support channels with expert assistance and knowledge sharing

## Contributing Guidelines

### Code Standards

* TypeScript strict mode compliance with comprehensive type safety and error handling
* ESLint and Prettier configuration with automated formatting and linting rules
* Comprehensive test coverage requirements with minimum thresholds and quality gates
* Clean Architecture principles adherence with clear layer separation and dependency rules
* Domain-Driven Design patterns with rich domain models and proper encapsulation

### Documentation Requirements

* Update documentation with all code changes and new features
* Include comprehensive API examples with real-world use cases and edge cases
* Maintain schema documentation accuracy with automated validation and verification
* Document business rule changes with impact analysis and migration guides
* Provide migration guides for breaking changes with step-by-step instructions

### Review Process

* Mandatory code review for all changes with multiple reviewer approval
* Testing validation and coverage verification with automated quality gates
* Documentation update validation with completeness checking and accuracy verification
* Performance impact assessment with benchmarking requirements and thresholds
* Security review for sensitive changes with threat modeling and penetration testing

This comprehensive documentation provides developers, architects, and stakeholders with everything needed to understand, maintain, extend, and operate the Product Management module effectively and efficiently.


# API Documentation

## Overview

The Product Management API provides comprehensive functionality for managing products and product tags within the Bee O'clock panel service. This module handles the complete product lifecycle, including creation, updates, status management, deletion, and image management for products and their associated tags.

## Base Configuration

### Authentication

All endpoints require Bearer token authentication.

### Headers

* `Authorization: Bearer <token>` - Required for all endpoints
* `x-business-tenant-id: <tenant_id>` - Required for multi-tenancy support
* `Content-Type: application/json` - For POST/PUT requests
* `Content-Type: multipart/form-data` - For image upload requests

### Base URLs

```
/api/v1/product          # Product management
/api/v1/product-tag      # Product tag management
/api/v1/product-media    # Product image management
```

## Product Endpoints

### 1. Get Paginated Products

**Endpoint:** `GET /api/v1/product/paged`

**Description:** Retrieves a paginated list of products with advanced filtering capabilities.

**Query Parameters:**

```typescript
{
  page?: number;           // Page number (default: 1)
  size?: number;           // Items per page (default: 10)
  phrase?: string;         // Search phrase for product title/description
  tags?: string[];         // Filter by product tags
}
```

**Response:**

```typescript
{
  items: ProductDto[];
  totalSize: number;
}
```

**Example Request:**

```bash
GET /api/v1/product/paged?page=1&size=10&phrase=massage&tags[]=wellness&tags[]=therapy
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64fa1c71b19d6d001c88a91f",
      "object": "ProductDto",
      "sku": "WELLNESS-001",
      "languageVersions": [
        {
          "language": "en",
          "title": "Premium Aromatherapy Oil Set",
          "description": "Organic essential oils perfect for therapeutic massage and relaxation"
        },
        {
          "language": "es", 
          "title": "Set de Aceites de Aromaterapia Premium",
          "description": "Aceites esenciales orgánicos perfectos para masajes terapéuticos y relajación"
        }
      ],
      "price": {
        "object": "ProductPriceDto",
        "value": 49.99,
        "currency": "USD"
      },
      "tags": ["wellness", "therapy", "aromatherapy", "organic"],
      "images": [
        {
          "_id": "64fa1c71b19d6d001c88a920",
          "url": "https://cdn.beeoclock.com/products/aromatherapy-set-main.jpg",
          "type": "image",
          "mimeType": "image/jpeg",
          "size": 256000,
          "alt": "Premium Aromatherapy Oil Set"
        }
      ],
      "order": 1,
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:30:00.000Z"
    }
  ],
  "totalSize": 25
}
```

### 2. Get Product by ID

**Endpoint:** `GET /api/v1/product/{id}`

**Description:** Retrieves a specific product by its ID with permission validation.

**Path Parameters:**

* `id` (string, required) - Product ID

**Response:** `ProductDto`

**Example Request:**

```bash
GET /api/v1/product/64fa1c71b19d6d001c88a91f
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a91f",
  "object": "ProductDto",
  "sku": "WELLNESS-001",
  "languageVersions": [
    {
      "language": "en",
      "title": "Premium Aromatherapy Oil Set",
      "description": "Organic essential oils perfect for therapeutic massage and relaxation. Each bottle contains 10ml of pure essential oil extracted using traditional methods."
    },
    {
      "language": "es",
      "title": "Set de Aceites de Aromaterapia Premium", 
      "description": "Aceites esenciales orgánicos perfectos para masajes terapéuticos y relajación. Cada botella contiene 10ml de aceite esencial puro extraído usando métodos tradicionales."
    }
  ],
  "price": {
    "object": "ProductPriceDto",
    "value": 49.99,
    "currency": "USD"
  },
  "tags": ["wellness", "therapy", "aromatherapy", "organic"],
  "images": [
    {
      "_id": "64fa1c71b19d6d001c88a920",
      "url": "https://cdn.beeoclock.com/products/aromatherapy-set-main.jpg",
      "type": "image",
      "mimeType": "image/jpeg",
      "size": 256000,
      "alt": "Premium Aromatherapy Oil Set - Main Image"
    },
    {
      "_id": "64fa1c71b19d6d001c88a921",
      "url": "https://cdn.beeoclock.com/products/aromatherapy-set-detail.jpg",
      "type": "image", 
      "mimeType": "image/jpeg",
      "size": 198000,
      "alt": "Premium Aromatherapy Oil Set - Detail View"
    }
  ],
  "order": 1,
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:30:00.000Z"
}
```

### 3. Create Product

**Endpoint:** `POST /api/v1/product`

**Description:** Creates a new product with validation and permission checks.

**Request Body:** `ProductDto`

**Response:** `ProductDto`

**Example Request:**

```bash
POST /api/v1/product
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "sku": "WELLNESS-002",
  "languageVersions": [
    {
      "language": "en",
      "title": "Himalayan Salt Scrub",
      "description": "Exfoliating body scrub made with pure Himalayan pink salt and organic oils"
    },
    {
      "language": "es",
      "title": "Exfoliante de Sal del Himalaya",
      "description": "Exfoliante corporal hecho con sal rosa pura del Himalaya y aceites orgánicos"
    }
  ],
  "price": {
    "value": 29.99,
    "currency": "USD"
  },
  "tags": ["exfoliation", "himalayan", "organic", "spa"],
  "order": 2
}
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a922",
  "object": "ProductDto",
  "sku": "WELLNESS-002",
  "languageVersions": [
    {
      "language": "en",
      "title": "Himalayan Salt Scrub",
      "description": "Exfoliating body scrub made with pure Himalayan pink salt and organic oils"
    },
    {
      "language": "es",
      "title": "Exfoliante de Sal del Himalaya",
      "description": "Exfoliante corporal hecho con sal rosa pura del Himalaya y aceites orgánicos"
    }
  ],
  "price": {
    "object": "ProductPriceDto",
    "value": 29.99,
    "currency": "USD"
  },
  "tags": ["exfoliation", "himalayan", "organic", "spa"],
  "images": [],
  "order": 2,
  "createdAt": "2024-07-26T09:00:00.000Z",
  "updatedAt": "2024-07-26T09:00:00.000Z"
}
```

### 4. Update Product

**Endpoint:** `PUT /api/v1/product/{id}`

**Description:** Updates an existing product with validation and permission checks.

**Path Parameters:**

* `id` (string, required) - Product ID

**Request Body:** `ProductDto`

**Response:** `ProductDto`

**Example Request:**

```bash
PUT /api/v1/product/64fa1c71b19d6d001c88a922
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "_id": "64fa1c71b19d6d001c88a922",
  "sku": "WELLNESS-002",
  "languageVersions": [
    {
      "language": "en",
      "title": "Premium Himalayan Salt Scrub",
      "description": "Luxury exfoliating body scrub made with pure Himalayan pink salt, organic oils, and vitamin E"
    },
    {
      "language": "es",
      "title": "Exfoliante Premium de Sal del Himalaya",
      "description": "Exfoliante corporal de lujo hecho con sal rosa pura del Himalaya, aceites orgánicos y vitamina E"
    }
  ],
  "price": {
    "value": 39.99,
    "currency": "USD"
  },
  "tags": ["exfoliation", "himalayan", "organic", "spa", "premium", "vitamin-e"],
  "order": 2
}
```

### 5. Delete Product

**Endpoint:** `DELETE /api/v1/product/{id}`

**Description:** Soft deletes a product with permission validation and dependency checking.

**Path Parameters:**

* `id` (string, required) - Product ID

**Response:** `void` (204 No Content)

**Example Request:**

```bash
DELETE /api/v1/product/64fa1c71b19d6d001c88a922
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Product Tag Endpoints

### 1. Get Paginated Product Tags

**Endpoint:** `GET /api/v1/product-tag/paged`

**Description:** Retrieves a paginated list of product tags with filtering capabilities.

**Query Parameters:**

```typescript
{
  page?: number;           // Page number (default: 1)
  size?: number;           // Items per page (default: 10)
  phrase?: string;         // Search phrase for tag names
}
```

**Response:**

```typescript
{
  items: TagDto[];
  totalSize: number;
}
```

**Example Request:**

```bash
GET /api/v1/product-tag/paged?page=1&size=10&phrase=therapy
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64fa1c71b19d6d001c88a923",
      "object": "ProductTagDto",
      "name": "aromatherapy",
      "createdAt": "2024-07-26T08:00:00.000Z",
      "updatedAt": "2024-07-26T08:00:00.000Z"
    },
    {
      "_id": "64fa1c71b19d6d001c88a924",
      "object": "ProductTagDto",
      "name": "therapy",
      "createdAt": "2024-07-26T08:05:00.000Z",
      "updatedAt": "2024-07-26T08:05:00.000Z"
    }
  ],
  "totalSize": 8
}
```

### 2. Get Product Tag by ID

**Endpoint:** `GET /api/v1/product-tag/{id}`

**Description:** Retrieves a specific product tag by its ID.

**Path Parameters:**

* `id` (string, required) - Tag ID

**Response:** `TagDto`

**Example Request:**

```bash
GET /api/v1/product-tag/64fa1c71b19d6d001c88a923
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a923",
  "object": "ProductTagDto",
  "name": "aromatherapy",
  "createdAt": "2024-07-26T08:00:00.000Z",
  "updatedAt": "2024-07-26T08:00:00.000Z"
}
```

### 3. Create Product Tag

**Endpoint:** `POST /api/v1/product-tag`

**Description:** Creates a new product tag with validation.

**Request Body:** `TagDto`

**Response:** `TagDto`

**Example Request:**

```bash
POST /api/v1/product-tag
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "name": "luxury"
}
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a925",
  "object": "ProductTagDto",
  "name": "luxury",
  "createdAt": "2024-07-26T09:00:00.000Z",
  "updatedAt": "2024-07-26T09:00:00.000Z"
}
```

### 4. Update Product Tag

**Endpoint:** `PUT /api/v1/product-tag/{id}`

**Description:** Updates an existing product tag.

**Path Parameters:**

* `id` (string, required) - Tag ID

**Request Body:** `TagDto`

**Response:** `TagDto`

**Example Request:**

```bash
PUT /api/v1/product-tag/64fa1c71b19d6d001c88a925
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "_id": "64fa1c71b19d6d001c88a925",
  "name": "premium-luxury"
}
```

### 5. Delete Product Tag

**Endpoint:** `DELETE /api/v1/product-tag/{id}`

**Description:** Deletes a product tag with dependency validation.

**Path Parameters:**

* `id` (string, required) - Tag ID

**Response:** `void` (204 No Content)

**Example Request:**

```bash
DELETE /api/v1/product-tag/64fa1c71b19d6d001c88a925
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Product Media Endpoints

### 1. Upload/Update Product Image

**Endpoint:** `PATCH /api/v1/product-media/{productId}/images`

**Description:** Uploads a new image or updates an existing image for a product.

**Path Parameters:**

* `productId` (string, required) - Product ID

**Request Body:** `multipart/form-data`

* `file` (File, required) - Image file to upload
* Additional media metadata fields

**Response:** `MediaDto`

**Example Request:**

```bash
PATCH /api/v1/product-media/64fa1c71b19d6d001c88a91f/images
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: multipart/form-data

--boundary123
Content-Disposition: form-data; name="file"; filename="aromatherapy-oils.jpg"
Content-Type: image/jpeg

[binary image data]
--boundary123
Content-Disposition: form-data; name="alt"

Premium Aromatherapy Oil Set - Updated Image
--boundary123--
```

**Example Response:**

```json
{
  "_id": "64fa1c71b19d6d001c88a926",
  "url": "https://cdn.beeoclock.com/products/aromatherapy-oils-updated.jpg",
  "type": "image",
  "mimeType": "image/jpeg",
  "size": 312000,
  "alt": "Premium Aromatherapy Oil Set - Updated Image",
  "createdAt": "2024-07-26T09:30:00.000Z",
  "updatedAt": "2024-07-26T09:30:00.000Z"
}
```

### 2. Delete Product Image

**Endpoint:** `DELETE /api/v1/product-media/{productId}/{id}`

**Description:** Deletes a specific image from a product.

**Path Parameters:**

* `productId` (string, required) - Product ID
* `id` (string, required) - Image ID

**Response:** `void` (204 No Content)

**Example Request:**

```bash
DELETE /api/v1/product-media/64fa1c71b19d6d001c88a91f/64fa1c71b19d6d001c88a926
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Data Models

### ProductDto

```typescript
{
  _id?: string;                              // Product ID
  object?: 'ProductDto';                     // Object type identifier
  sku?: string;                              // Product SKU/identifier
  languageVersions: LanguageVersionDto[];    // Multi-language content
  price: ProductPriceDto;                    // Product pricing information
  tags?: string[];                           // Product tags for categorization
  images?: MediaDto[];                       // Product images
  order?: number;                            // Display order priority
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### ProductPriceDto

```typescript
{
  object?: 'ProductPriceDto';                // Object type identifier
  value: number;                             // Price value
  currency: CurrencyCodeEnum;                // Currency code (USD, EUR, etc.)
}
```

### ProductPaginationDto

```typescript
{
  page?: number;                             // Page number (default: 1)
  size?: number;                             // Items per page (default: 10)
  phrase?: string;                           // Search phrase for title/description
  tags?: string[];                           // Filter by product tags
}
```

### TagDto

```typescript
{
  _id?: string;                              // Tag ID
  object?: 'ProductTagDto';                  // Object type identifier
  name?: string;                             // Tag name
  createdAt?: string;                        // Creation timestamp
  updatedAt?: string;                        // Last update timestamp
}
```

### TagPaginationDto

```typescript
{
  page?: number;                             // Page number (default: 1)
  size?: number;                             // Items per page (default: 10)
  phrase?: string;                           // Search phrase for tag names
}
```

### LanguageVersionDto

```typescript
{
  language: string;                          // Language code (en, es, fr, etc.)
  title: string;                             // Product title in specified language
  description?: string;                      // Product description in specified language
}
```

### MediaDto

```typescript
{
  _id: string;                               // Media ID
  url: string;                               // CDN URL for the image
  type: string;                              // Media type (image, video, etc.)
  mimeType: string;                          // MIME type (image/jpeg, image/png, etc.)
  size: number;                              // File size in bytes
  alt?: string;                              // Alternative text for accessibility
  createdAt: string;                         // Creation timestamp
  updatedAt: string;                         // Last update timestamp
}
```

## Enums

### CurrencyCodeEnum

```typescript
enum CurrencyCodeEnum {
  USD = 'USD',                               // US Dollar
  EUR = 'EUR',                               // Euro
  GBP = 'GBP',                               // British Pound
  CAD = 'CAD',                               // Canadian Dollar
  AUD = 'AUD',                               // Australian Dollar
  JPY = 'JPY',                               // Japanese Yen
  CHF = 'CHF',                               // Swiss Franc
  CNY = 'CNY',                               // Chinese Yuan
  INR = 'INR',                               // Indian Rupee
  BRL = 'BRL',                               // Brazilian Real
  MXN = 'MXN',                               // Mexican Peso
  ZAR = 'ZAR',                               // South African Rand
}
```

## Error Handling

### Common Error Responses

#### 400 Bad Request

```json
{
  "statusCode": 400,
  "message": "Validation failed",
  "error": "Bad Request",
  "details": [
    {
      "field": "price.value",
      "message": "Price must be a positive number"
    },
    {
      "field": "languageVersions",
      "message": "At least one language version is required"
    }
  ]
}
```

#### 401 Unauthorized

```json
{
  "statusCode": 401,
  "message": "Unauthorized",
  "error": "Authentication required"
}
```

#### 403 Forbidden

```json
{
  "statusCode": 403,
  "message": "Access denied",
  "error": "Insufficient permissions to access product management"
}
```

#### 404 Not Found

```json
{
  "statusCode": 404,
  "message": "Product not found",
  "error": "Product with ID 64fa1c71b19d6d001c88a91f does not exist"
}
```

#### 409 Conflict

```json
{
  "statusCode": 409,
  "message": "Product creation conflict",
  "error": "Product with SKU 'WELLNESS-001' already exists"
}
```

#### 413 Payload Too Large

```json
{
  "statusCode": 413,
  "message": "File too large",
  "error": "Image file size exceeds maximum limit of 5MB"
}
```

#### 415 Unsupported Media Type

```json
{
  "statusCode": 415,
  "message": "Unsupported file type",
  "error": "Only JPEG, PNG, and WebP images are supported"
}
```

#### 422 Unprocessable Entity

```json
{
  "statusCode": 422,
  "message": "Business validation failed",
  "error": "Cannot delete product that is currently used in active orders"
}
```

## Business Rules

### Product Creation

1. **SKU Uniqueness**: Each product must have a unique SKU within the tenant
2. **Language Validation**: At least one language version is required
3. **Price Validation**: Price value must be positive and currency must be valid
4. **Tag Validation**: All tags must exist in the product tag collection
5. **Image Constraints**: Maximum 10 images per product, each under 5MB

### Product Updates

1. **SKU Immutability**: SKU cannot be changed after product creation
2. **Language Preservation**: Cannot remove all language versions
3. **Price History**: Price changes are tracked for audit purposes
4. **Tag Management**: Tags are managed separately and referenced by name
5. **Image Management**: Images can be added, updated, or removed independently

### Product Deletion

1. **Soft Delete**: Products are marked as deleted rather than physically removed
2. **Order Dependency**: Cannot delete products that are used in active orders
3. **History Preservation**: All historical data is maintained for audit purposes
4. **Cascade Rules**: Associated images are also soft deleted

### Tag Management

1. **Name Uniqueness**: Tag names must be unique within the tenant
2. **Case Sensitivity**: Tag names are case-insensitive
3. **Usage Tracking**: Cannot delete tags that are currently used by products
4. **Bulk Operations**: Support for bulk tag creation and management

### Permission Requirements

1. **Product Operations**:
   * `READ_PRODUCT` (11001) - View products
   * `CREATE_PRODUCT` (11002) - Create new products
   * `EDIT_PRODUCT` (11003) - Update existing products
   * `DELETE_PRODUCT` (11004) - Delete products
   * `CRUD_PRODUCT` (11000) - All product operations
2. **Tag Operations**:
   * `READ_PRODUCT_TAG` (12001) - View product tags
   * `CREATE_PRODUCT_TAG` (12002) - Create new tags
   * `EDIT_PRODUCT_TAG` (12003) - Update existing tags
   * `DELETE_PRODUCT_TAG` (12004) - Delete tags
   * `CRUD_PRODUCT_TAG` (12000) - All tag operations

### Image Management

1. **File Types**: Only JPEG, PNG, and WebP formats are supported
2. **File Size**: Maximum 5MB per image
3. **Image Count**: Maximum 10 images per product
4. **Resolution**: Recommended minimum 800x600 pixels
5. **Optimization**: Images are automatically optimized and resized

## Performance Considerations

### Pagination

* Default page size: 10 items
* Maximum page size: 100 items
* Use pagination for large product catalogs

### Filtering and Search

* Text search is optimized with MongoDB text indexes
* Tag filtering uses indexed arrays for fast queries
* Multi-language search supports all language versions

### Caching

* Product data is cached for frequently accessed items
* Image CDN caching with long expiration times
* Tag data is heavily cached due to infrequent changes

### Database Optimization

* Compound indexes on commonly filtered fields
* Text indexes for search functionality
* Optimized queries with proper field projection

## Rate Limiting

* **Read Operations**: 100 requests per minute per user
* **Write Operations**: 30 requests per minute per user
* **Image Upload**: 10 requests per minute per user
* **Bulk Operations**: 5 requests per minute per user

## File Upload Specifications

### Supported Image Formats

* **JPEG** (.jpg, .jpeg) - Recommended for photographs
* **PNG** (.png) - Recommended for graphics with transparency
* **WebP** (.webp) - Modern format with excellent compression

### Image Processing

* **Automatic Optimization**: Images are automatically compressed and optimized
* **Multiple Sizes**: Thumbnails and preview sizes are generated automatically
* **CDN Distribution**: Images are distributed via CDN for fast global access
* **Format Conversion**: Images may be converted to WebP for better performance

### Upload Constraints

* **Maximum File Size**: 5MB per image
* **Maximum Dimensions**: 4000x4000 pixels
* **Minimum Dimensions**: 200x200 pixels (recommended)
* **Image Count**: Maximum 10 images per product

## Monitoring and Logging

### Request Logging

All API requests are logged with:

* Request ID for tracing
* User context and permissions
* Performance metrics
* Error details and stack traces

### Business Event Logging

* Product creation, updates, and deletions
* Tag management operations
* Image upload and management activities
* Permission validation events

### Performance Monitoring

* Response time tracking for all endpoints
* Database query performance analysis
* Cache hit rates and effectiveness
* Image processing and upload metrics
* Error rate monitoring and alerting

## Security Considerations

### Input Validation

* Comprehensive validation of all input data
* SQL injection prevention through parameterized queries
* XSS prevention through output encoding
* File upload security with type and size validation

### Access Control

* Role-based permission system
* Tenant-based data isolation
* API rate limiting and abuse prevention
* Audit logging for all sensitive operations

### Image Security

* Virus scanning for uploaded files
* Content type validation
* File size and dimension limits
* Secure file storage with access controls

## Integration Examples

### Creating a Product with Multiple Languages

```typescript
const newProduct = {
  sku: "SPA-ESSENTIALS-001",
  languageVersions: [
    {
      language: "en",
      title: "Essential Oils Starter Kit",
      description: "Complete starter kit with 6 essential oils and diffuser"
    },
    {
      language: "es",
      title: "Kit Iniciador de Aceites Esenciales",
      description: "Kit iniciador completo con 6 aceites esenciales y difusor"
    },
    {
      language: "fr",
      title: "Kit de Démarrage aux Huiles Essentielles",
      description: "Kit de démarrage complet avec 6 huiles essentielles et diffuseur"
    }
  ],
  price: {
    value: 89.99,
    currency: "USD"
  },
  tags: ["essential-oils", "starter-kit", "diffuser", "aromatherapy"],
  order: 1
};
```

### Advanced Product Search

```typescript
// Search for wellness products with specific tags
GET /api/v1/product/paged?
  phrase=wellness&
  tags[]=organic&
  tags[]=therapy&
  page=1&
  size=20
```

### Bulk Image Upload Workflow

```typescript
// 1. Create product
const product = await createProduct(productData);

// 2. Upload multiple images
const images = [];
for (const imageFile of imageFiles) {
  const uploadedImage = await uploadProductImage(product._id, imageFile);
  images.push(uploadedImage);
}

// 3. Update product with image references
await updateProduct(product._id, { ...product, images });
```


# Interface Documentation

## Overview

This document provides comprehensive details on TypeScript interfaces, DTOs, enums, and contracts used throughout the Product Management module. All interfaces are derived from the actual codebase and reflect the current implementation.

## Table of Contents

1. [Core Interfaces](#core-interfaces)
2. [Data Transfer Objects (DTOs)](#data-transfer-objects-dtos)
3. [Domain Value Objects](#domain-value-objects)
4. [Repository Interfaces](#repository-interfaces)
5. [Use Case Interfaces](#use-case-interfaces)
6. [Enums and Constants](#enums-and-constants)
7. [Media and File Interfaces](#media-and-file-interfaces)
8. [Validation Constraints](#validation-constraints)

## Core Interfaces

### IProduct

**File:** `common/module/product/product/domain/persistance/IProduct.ts`

Core product entity interface extending base entity functionality.

```typescript
export interface IProduct extends IBase {
  sku: string;                               // Unique product identifier
  languageVersions: ILanguageVersion[];      // Multi-language content
  price?: IProductPrice;                     // Product pricing information
  tags?: string[];                           // Product categorization tags
  images?: IMedia[];                         // Associated product images
  order?: number;                            // Display order priority
}
```

**Key Features:**

* Extends `IBase` for standard entity properties (\_id, createdAt, updatedAt, etc.)
* Supports multi-language content through `ILanguageVersion`
* Optional pricing with structured price object
* Tag-based categorization system
* Image management through media references
* Ordering support for display purposes

### IProductPrice

**File:** `common/module/product/product/domain/values/product-price.value.ts`

Value object interface for product pricing information.

```typescript
export interface IProductPrice {
  value: number;                             // Price amount
  currency: CurrencyCodeEnum;                // Currency code (USD, EUR, etc.)
}
```

**Key Features:**

* Immutable value object for price representation
* Support for international currencies
* Validation for non-negative values
* Type-safe currency handling

### IProductRepository

**File:** `common/module/product/product/domain/persistance/IProductRepository.ts`

Repository interface defining product data access operations.

```typescript
export interface IProductRepository extends IRepository<IProduct> {
  getPopulatedProductById(id: string): Promise<IProduct>;
  createProduct(product: IProduct): Promise<IProduct>;
  searchProductsWithCriteria(criteria: ProductPaginationDto): Promise<PaginationResultValue<IProduct>>;
}
```

**Key Features:**

* Extends base repository with product-specific operations
* Populated queries for related data (images, etc.)
* Advanced search with pagination and filtering
* CRUD operations with proper typing

### ITag

**File:** `common/module/product/tag/domain/persistance/i-tag.ts`

Product tag entity interface for categorization.

```typescript
export interface ITag extends IBase {
  name: string;                              // Tag name/identifier
}
```

**Key Features:**

* Simple tag structure with unique names
* Extends base entity for standard properties
* Used for product categorization and filtering

## Data Transfer Objects (DTOs)

### ProductDto

**File:** `common/module/product/product/dtos/product.dto.ts`

Main DTO for product data transfer with comprehensive validation.

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

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

  @ApiProperty({
    type: () => LanguageVersionDto,
    isArray: true
  })
  @IsArray()
  @Type(() => LanguageVersionDto)
  @Expose()
  languageVersions: LanguageVersionDto[];
  
  @ApiProperty({
    type: () => ProductPriceDto,
  })
  @Type(() => ProductPriceDto)
  @Expose()
  price: ProductPriceDto;

  @ApiProperty({ type: [String] })
  @IsString({ each: true })
  @IsOptional()
  @Expose()
  tags?: string[];

  @ApiProperty({ type: [MediaDto] })
  @IsOptional()
  @IsArray()
  @Expose()
  images?: MediaDto[];

  @ApiProperty()
  @IsNumber()
  @IsOptional()
  @Expose()
  order?: number | null;
}
```

**Validation Rules:**

* `sku`: Optional string for product identification
* `languageVersions`: Required array of language-specific content
* `price`: Required pricing information with currency
* `tags`: Optional array of string tags for categorization
* `images`: Optional array of media objects for product images
* `order`: Optional numeric value for display ordering

**Features:**

* Class-transformer decorators for serialization control
* Class-validator decorators for input validation
* Swagger/OpenAPI documentation decorators
* Proper type transformation for nested objects

### ProductPriceDto

**File:** `common/module/product/product/dtos/product-price.dto.ts`

DTO for product pricing information with currency support.

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

  @ApiProperty()
  @IsNumber()
  @Expose()
  value: number;

  @ApiProperty({
    enum: CurrencyCodeEnum,
    default: CurrencyCodeEnum.USD
  })
  @IsEnum(CurrencyCodeEnum)
  @Expose()
  currency: CurrencyCodeEnum;
}
```

**Validation Rules:**

* `value`: Required numeric price amount
* `currency`: Required currency code from enum
* `object`: Optional type identifier

**Features:**

* Enum validation for currency codes
* Numeric validation for price values
* Default currency support (USD)
* Type-safe currency handling

### ProductPaginationDto

**File:** `common/module/product/product/dtos/product.pagination.dto.ts`

DTO for paginated product queries with filtering capabilities.

```typescript
@Exclude()
export class ProductPaginationDto extends PaginationDto {
  @ApiPropertyOptional({
    description: 'Search phrase for filtering products by title, description',
    example: 'Product title',
  })
  @IsOptional()
  @IsString()
  @Expose()
  phrase?: string;

  @ApiPropertyOptional()
  @IsOptional()
  @IsString({ each: true })
  @IsArray()
  @Transform(({ value }) => {
    if (Array.isArray(value)) return value;
    return typeof value === 'string' ? value.split(',') : value;
  })
  @Expose()
  tags?: string[];
}
```

**Validation Rules:**

* `phrase`: Optional string for text search across title/description
* `tags`: Optional array of tag names for filtering
* Inherits pagination properties (page, size) from `PaginationDto`

**Features:**

* Text search functionality
* Tag-based filtering with array support
* Automatic string-to-array transformation for tags
* Extends base pagination with product-specific filters

### TagDto

**File:** `common/module/product/tag/dtos/tag.dto.ts`

DTO for product tag management operations.

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

  @ApiProperty()
  @IsString()
  @IsOptional()
  @Expose()
  name?: string;
}
```

**Validation Rules:**

* `name`: Optional string for tag name
* `object`: Optional type identifier
* Inherits base entity properties from `BaseEntityDto`

**Features:**

* Simple tag structure for categorization
* String validation for tag names
* Extends base entity for standard properties

### TagPaginationDto

**File:** `common/module/product/tag/dtos/tag.pagination.dto.ts`

DTO for paginated tag queries with search functionality.

```typescript
@Exclude()
export class TagPaginationDto extends PaginationDto {
  @ApiPropertyOptional({
    description: 'Search phrase for filtering tags by name',
    example: 'wellness',
  })
  @IsOptional()
  @IsString()
  @Expose()
  phrase?: string;
}
```

**Validation Rules:**

* `phrase`: Optional string for tag name search
* Inherits pagination properties from `PaginationDto`

**Features:**

* Text search for tag names
* Simple pagination support
* Lightweight filtering for tag management

## Domain Value Objects

### ProductPrice

**File:** `common/module/product/product/domain/values/product-price.value.ts`

Domain value object implementing price logic with validation.

```typescript
export class ProductPrice extends ValueObject<IProductPrice> implements IProductPrice {
  private constructor(props: IProductPrice) {
    super(props);
  }

  public static create(props: IProductPrice): Result<ProductPrice> {
    // Validation: ensure price is non-negative
    if (props.value < 0) {
      return Result.fail<ProductPrice>('Price must be non-negative.');
    }

    return Result.ok<ProductPrice>(new ProductPrice(props));
  }

  get value(): number {
    return this.props.value;
  }

  get currency(): CurrencyCodeEnum {
    return this.props.currency;
  }
}
```

**Key Features:**

* Immutable value object implementation
* Factory method with validation
* Price non-negativity validation
* Type-safe property access
* Proper error handling with Result pattern

## Repository Interfaces

### Product Repository Operations

The product repository extends the base repository pattern with specialized operations:

```typescript
interface IProductRepository extends IRepository<IProduct> {
  // Get product with populated references (images, etc.)
  getPopulatedProductById(id: string): Promise<IProduct>;
  
  // Create new product with validation
  createProduct(product: IProduct): Promise<IProduct>;
  
  // Advanced search with filtering and pagination
  searchProductsWithCriteria(criteria: ProductPaginationDto): Promise<PaginationResultValue<IProduct>>;
}
```

**Key Operations:**

* **Population**: Automatically populate related data (images, tags)
* **Creation**: Handle product creation with proper validation
* **Search**: Advanced filtering with text search and tag filtering
* **Pagination**: Efficient pagination for large product catalogs

## Use Case Interfaces

### Product Use Case Parameters

Each use case defines specific parameter interfaces for type safety:

#### CreateProductParams

**File:** `common/module/product/product/usecases/create-product.usecase.ts`

```typescript
export interface CreateProductParams {
  ctx: TenantActorContext;                   // Request context with tenant/user info
  product: ProductDto;                       // Product data to create
}
```

#### GetProductParams

**File:** `common/module/product/product/usecases/get-product.usecase.ts`

```typescript
export interface GetProductParams {
  ctx: TenantActorContext;                   // Request context
  productId: string;                         // Product ID to retrieve
}
```

#### UpdateProductParams

**File:** `common/module/product/product/usecases/update-product.usecase.ts`

```typescript
export interface UpdateProductParams {
  ctx: TenantActorContext;                   // Request context
  productId: string;                         // Product ID to update
  product: ProductDto;                       // Updated product data
}
```

#### DeleteProductParams

**File:** `common/module/product/product/usecases/delete-product.usecase.ts`

```typescript
export interface DeleteProductParams {
  ctx: TenantActorContext;                   // Request context
  productId: string;                         // Product ID to delete
}
```

#### GetPagedProductsParams

**File:** `common/module/product/product/usecases/get-paged-products.usecase.ts`

```typescript
export interface GetPagedProductsParams {
  ctx: TenantActorContext;                   // Request context
  pagination: ProductPaginationDto;          // Pagination and filtering criteria
}
```

### Product Tag Use Case Parameters

#### CreateProductTagParams

**File:** `common/module/product/tag/usecases/create-product-tag.usecase.ts`

```typescript
export interface CreateProductTagParams {
  ctx: TenantActorContext;                   // Request context
  tag: TagDto;                               // Tag data to create
}
```

#### GetPagedProductTagsParams

**File:** `common/module/product/tag/usecases/get-paged-product-tags.usecase.ts`

```typescript
export interface GetPagedProductTagsParams {
  ctx: TenantActorContext;                   // Request context
  pagination: TagPaginationDto;              // Pagination and search criteria
}
```

### Product Image Use Case Parameters

#### UpsertProductImageParams

**File:** `common/module/product/product/usecases/upsert-product-image.usecase.ts`

```typescript
export interface UpsertProductImageParams {
  ctx: TenantActorContext;                   // Request context
  productId: string;                         // Product ID for image association
  media: UploadMediaDto;                     // Media metadata
  file: Express.Multer.File;                 // Uploaded file data
}
```

#### DeleteProductImageParams

**File:** `common/module/product/product/usecases/delete-product-image.usecase.ts`

```typescript
export interface DeleteProductImageParams {
  ctx: TenantActorContext;                   // Request context
  productId: string;                         // Product ID
  id: string;                                // Image ID to delete
}
```

## Enums and Constants

### CurrencyCodeEnum

**File:** `common/core/enum/currency-code.enum.ts`

Comprehensive currency code enumeration for international support.

```typescript
export enum CurrencyCodeEnum {
  USD = 'USD',                               // US Dollar
  EUR = 'EUR',                               // Euro
  GBP = 'GBP',                               // British Pound Sterling
  CAD = 'CAD',                               // Canadian Dollar
  AUD = 'AUD',                               // Australian Dollar
  JPY = 'JPY',                               // Japanese Yen
  CHF = 'CHF',                               // Swiss Franc
  CNY = 'CNY',                               // Chinese Yuan
  INR = 'INR',                               // Indian Rupee
  BRL = 'BRL',                               // Brazilian Real
  MXN = 'MXN',                               // Mexican Peso
  ZAR = 'ZAR',                               // South African Rand
  // Additional currencies supported by the platform
}
```

### Permission Enums

**File:** `common/module/permission/domain/enums/permission.enum.ts`

Product-related permission constants for access control.

```typescript
export enum ModulePermissionEnum {
  // Product Management Permissions
  CRUD_PRODUCT = 11000,                      // All product operations
  READ_PRODUCT = 11001,                      // View products
  CREATE_PRODUCT = 11002,                    // Create new products
  EDIT_PRODUCT = 11003,                      // Update existing products
  DELETE_PRODUCT = 11004,                    // Delete products

  // Product Tag Management Permissions
  CRUD_PRODUCT_TAG = 12000,                  // All tag operations
  READ_PRODUCT_TAG = 12001,                  // View product tags
  CREATE_PRODUCT_TAG = 12002,                // Create new tags
  EDIT_PRODUCT_TAG = 12003,                  // Update existing tags
  DELETE_PRODUCT_TAG = 12004,                // Delete tags
}
```

**Permission Hierarchy:**

* `CRUD_*` permissions include all sub-permissions
* Each operation requires specific permission validation
* Permissions are checked at use case level
* Multi-tenant isolation enforced automatically

## Media and File Interfaces

### MediaDto

**File:** `common/module/media/dtos/media.dto.ts`

DTO for media file management and metadata.

```typescript
export interface MediaDto {
  _id: string;                               // Media file ID
  url: string;                               // CDN URL for file access
  type: string;                              // Media type (image, video, etc.)
  mimeType: string;                          // MIME type (image/jpeg, etc.)
  size: number;                              // File size in bytes
  alt?: string;                              // Alternative text for accessibility
  createdAt: string;                         // Creation timestamp
  updatedAt: string;                         // Last update timestamp
}
```

### UploadMediaDto

**File:** `common/module/media/dtos/upload.media.dto.ts`

DTO for media upload operations with metadata.

```typescript
export interface UploadMediaDto {
  alt?: string;                              // Alternative text
  description?: string;                      // Media description
  tags?: string[];                           // Media tags for organization
  // Additional metadata fields as needed
}
```

### File Upload Constraints

**Supported File Types:**

* `image/jpeg` - JPEG images
* `image/png` - PNG images with transparency support
* `image/webp` - Modern WebP format

**Size Limits:**

* Maximum file size: 5MB per image
* Maximum dimensions: 4000x4000 pixels
* Minimum dimensions: 200x200 pixels (recommended)

## Validation Constraints

### Product Validation Rules

#### SKU Validation

```typescript
@IsString()
@IsOptional()
@Length(1, 100)
sku?: string;
```

#### Language Versions Validation

```typescript
@IsArray()
@ArrayNotEmpty()
@ValidateNested({ each: true })
@Type(() => LanguageVersionDto)
languageVersions: LanguageVersionDto[];
```

#### Price Validation

```typescript
@ValidateNested()
@Type(() => ProductPriceDto)
@IsNotEmpty()
price: ProductPriceDto;
```

#### Tags Validation

```typescript
@IsOptional()
@IsArray()
@IsString({ each: true })
@ArrayMaxSize(20)
tags?: string[];
```

#### Order Validation

```typescript
@IsOptional()
@IsNumber()
@Min(0)
@Max(999999)
order?: number;
```

### Price Validation Rules

#### Value Validation

```typescript
@IsNumber()
@IsPositive()
@Max(999999.99)
value: number;
```

#### Currency Validation

```typescript
@IsEnum(CurrencyCodeEnum)
@IsNotEmpty()
currency: CurrencyCodeEnum;
```

### Tag Validation Rules

#### Name Validation

```typescript
@IsString()
@IsNotEmpty()
@Length(1, 50)
@Matches(/^[a-zA-Z0-9-_\s]+$/)
name: string;
```

## Advanced Type Definitions

### Pagination Result Types

```typescript
interface PaginationResultValue<T> {
  items: T[];                                // Array of items
  totalSize: number;                         // Total number of items
  page: number;                              // Current page number
  size: number;                              // Items per page
}
```

### Context Types

```typescript
interface TenantActorContext {
  tenantId: string;                          // Business tenant identifier
  actor: {                                   // User/actor information
    _id: string;                            // User ID
    permissions: string[];                   // User permissions
    roles: string[];                        // User roles
  };
  // Additional context properties
}
```

### Result Pattern Types

```typescript
interface Result<T> {
  isSuccess: boolean;                        // Operation success flag
  isFailure: boolean;                        // Operation failure flag
  error?: string;                           // Error message if failed
  value?: T;                                // Result value if successful
}
```

## Integration Interfaces

### Event Interfaces

Product management integrates with the event system for notifications and auditing:

```typescript
interface ProductCreatedEvent {
  type: 'ProductCreated';
  tenantId: string;
  productId: string;
  product: ProductDto;
  createdBy: string;
  timestamp: Date;
}

interface ProductUpdatedEvent {
  type: 'ProductUpdated';
  tenantId: string;
  productId: string;
  changes: Partial<ProductDto>;
  updatedBy: string;
  timestamp: Date;
}

interface ProductDeletedEvent {
  type: 'ProductDeleted';
  tenantId: string;
  productId: string;
  deletedBy: string;
  timestamp: Date;
}
```

### Cache Interfaces

```typescript
interface ProductCacheKey {
  type: 'product';
  tenantId: string;
  productId: string;
}

interface ProductListCacheKey {
  type: 'product-list';
  tenantId: string;
  criteria: string;                          // Serialized search criteria
}
```

## Type Safety Features

### Strict Typing

* All interfaces use strict TypeScript typing
* Optional vs required properties clearly defined
* Enum constraints for categorical data
* Generic type support for reusable patterns

### Validation Integration

* Class-validator decorators for runtime validation
* Type-safe validation error handling
* Comprehensive error messages
* Custom validation rules for business logic

### Serialization Control

* Class-transformer decorators for data transformation
* Selective property exposure/exclusion
* Nested object transformation
* Type conversion for complex objects

## Migration and Versioning

### Interface Evolution

* Backward compatibility maintained through optional properties
* Deprecation notices for removed features
* Version-specific interface definitions
* Migration guides for breaking changes

### Schema Compatibility

* Database schema evolution support
* Field addition/removal strategies
* Data migration scripts
* Version-aware serialization

This interface documentation provides a complete reference for all types, validation rules, and contracts used in the Product Management module, ensuring type safety and proper integration across the system.


# Use Case Documentation

## Overview

This document outlines the business logic and use case implementations for the Product Management module. All use cases follow Clean Architecture principles with CQRS pattern implementation, comprehensive permission validation, and event-driven architecture for system integration.

## Table of Contents

1. [Product Use Cases](#product-use-cases)
2. [Product Tag Use Cases](#product-tag-use-cases)
3. [Product Image Use Cases](#product-image-use-cases)
4. [CQRS Implementation](#cqrs-implementation)
5. [Permission System](#permission-system)
6. [Event Publishing](#event-publishing)
7. [Error Handling](#error-handling)
8. [Business Rules](#business-rules)

## Product Use Cases

### CreateProductUseCase

**File:** `common/module/product/product/usecases/create-product.usecase.ts`

Creates a new product with comprehensive validation and permission checks.

#### Implementation

```typescript
export class CreateProductUseCase implements IUseCase<CreateProductParams, ProductDto> {
  @Inject()
  private readonly commandBus: CommandBus;

  @Inject()
  private readonly queryBus: QueryBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(CreateProductUseCase.name);

  public async execute({ ctx, product }: CreateProductParams): Promise<ProductDto> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.CREATE_PRODUCT],
    });

    // 2. Execute create command through CQRS
    const createdProductId = await this.commandBus.execute(
      new AddProductCommand(ctx.tenantId, product)
    );

    // 3. Return populated product data
    return this.queryBus.execute(
      new GetProductByIdQuery(ctx.tenantId, createdProductId)
    );
  }
}
```

#### Business Logic Flow

1. **Permission Validation**: Validates user has `CREATE_PRODUCT` permission
2. **Command Execution**: Dispatches `AddProductCommand` through command bus
3. **Data Retrieval**: Queries created product with populated relationships
4. **Event Publishing**: Automatic event publishing for product creation
5. **Response**: Returns complete product DTO with all related data

#### Key Features

* **Permission-based Access Control**: Validates user permissions before execution
* **CQRS Pattern**: Separates command (create) from query (read) operations
* **Event-Driven**: Publishes events for system integration and auditing
* **Transaction Management**: Ensures data consistency across operations
* **Comprehensive Logging**: Tracks all operations for debugging and auditing

#### Business Rules

* User must have `CREATE_PRODUCT` permission
* Product SKU must be unique within tenant
* At least one language version is required
* Price information is mandatory
* Tags must exist in the system before assignment

### GetProductUseCase

**File:** `common/module/product/product/usecases/get-product.usecase.ts`

Retrieves a specific product by ID with permission validation.

#### Implementation

```typescript
export class GetProductUseCase implements IUseCase<GetProductParams, ProductDto> {
  @Inject()
  private readonly queryBus: QueryBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(GetProductUseCase.name);

  public async execute({ ctx, productId }: GetProductParams): Promise<ProductDto> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.READ_PRODUCT],
    });

    // 2. Execute query with populated data
    return this.queryBus.execute(
      new GetProductByIdQuery(ctx.tenantId, productId)
    );
  }
}
```

#### Business Logic Flow

1. **Permission Validation**: Validates user has `READ_PRODUCT` permission
2. **Query Execution**: Retrieves product with populated relationships
3. **Data Enrichment**: Includes images, tag details, and metadata
4. **Response**: Returns complete product information

#### Key Features

* **Efficient Data Loading**: Optimized queries with relationship population
* **Permission Enforcement**: Ensures data access security
* **Cache Integration**: Utilizes caching for frequently accessed products
* **Error Handling**: Proper error handling for non-existent products

### GetPagedProductsUseCase

**File:** `common/module/product/product/usecases/get-paged-products.usecase.ts`

Retrieves paginated list of products with advanced filtering capabilities.

#### Implementation

```typescript
export class GetPagedProductsUseCase implements IUseCase<GetPagedProductsParams, any> {
  @Inject()
  private readonly queryBus: QueryBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(GetPagedProductsUseCase.name);

  public async execute({ ctx, pagination }: GetPagedProductsParams): Promise<any> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.READ_PRODUCT],
    });

    // 2. Execute paginated query with filtering
    return this.queryBus.execute(
      new GetPagedProductsQuery(ctx.tenantId, pagination)
    );
  }
}
```

#### Business Logic Flow

1. **Permission Validation**: Validates user has `READ_PRODUCT` permission
2. **Query Construction**: Builds complex query with filters and pagination
3. **Search Execution**: Performs text search across multiple language versions
4. **Tag Filtering**: Applies tag-based filtering with array matching
5. **Result Pagination**: Returns paginated results with metadata

#### Advanced Features

* **Multi-language Search**: Searches across all language versions
* **Tag Filtering**: Supports multiple tag filtering with AND/OR logic
* **Text Search**: Full-text search across titles and descriptions
* **Performance Optimization**: Efficient database queries with proper indexing
* **Cache Integration**: Caches frequently accessed product lists

#### Filtering Capabilities

* **Text Search**: Phrase-based search across product content
* **Tag Filtering**: Filter by one or more product tags
* **Pagination**: Configurable page size and navigation
* **Sorting**: Support for various sorting criteria

### UpdateProductUseCase

**File:** `common/module/product/product/usecases/update-product.usecase.ts`

Updates an existing product with validation and change tracking.

#### Implementation

```typescript
export class UpdateProductUseCase implements IUseCase<UpdateProductParams, ProductDto> {
  @Inject()
  private readonly commandBus: CommandBus;

  @Inject()
  private readonly queryBus: QueryBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(UpdateProductUseCase.name);

  public async execute({ ctx, productId, product }: UpdateProductParams): Promise<ProductDto> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.EDIT_PRODUCT],
    });

    // 2. Execute update command
    await this.commandBus.execute(
      new UpdateProductCommand(ctx.tenantId, productId, product)
    );

    // 3. Return updated product data
    return this.queryBus.execute(
      new GetProductByIdQuery(ctx.tenantId, productId)
    );
  }
}
```

#### Business Logic Flow

1. **Permission Validation**: Validates user has `EDIT_PRODUCT` permission
2. **Existence Check**: Verifies product exists and is accessible
3. **Change Validation**: Validates proposed changes against business rules
4. **Command Execution**: Applies changes through command pattern
5. **Event Publishing**: Publishes update events for system integration
6. **Response**: Returns updated product with fresh data

#### Business Rules for Updates

* SKU cannot be modified after creation
* At least one language version must remain
* Price changes are tracked for audit purposes
* Tag assignments are validated for existence
* Image references are validated for accessibility

### DeleteProductUseCase

**File:** `common/module/product/product/usecases/delete-product.usecase.ts`

Performs soft deletion of products with dependency validation.

#### Implementation

```typescript
export class DeleteProductUseCase implements IUseCase<DeleteProductParams, void> {
  @Inject()
  private readonly commandBus: CommandBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(DeleteProductUseCase.name);

  public async execute({ ctx, productId }: DeleteProductParams): Promise<void> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.DELETE_PRODUCT],
    });

    // 2. Execute delete command with dependency checking
    return this.commandBus.execute(
      new DeleteProductCommand(ctx.tenantId, productId)
    );
  }
}
```

#### Business Logic Flow

1. **Permission Validation**: Validates user has `DELETE_PRODUCT` permission
2. **Dependency Check**: Verifies no active orders reference the product
3. **Soft Delete**: Marks product as deleted while preserving data
4. **Cascade Operations**: Handles related data (images, references)
5. **Event Publishing**: Publishes deletion events for cleanup
6. **Audit Logging**: Records deletion for compliance and tracking

#### Dependency Validation

* Checks for active orders containing the product
* Validates no pending reservations reference the product
* Ensures data integrity across the system
* Prevents deletion of products with financial implications

## Product Tag Use Cases

### CreateProductTagUseCase

**File:** `common/module/product/tag/usecases/create-product-tag.usecase.ts`

Creates new product tags for categorization and filtering.

#### Implementation

```typescript
export class CreateProductTagUseCase implements IUseCase<CreateProductTagParams, TagDto> {
  @Inject()
  private readonly commandBus: CommandBus;

  @Inject()
  private readonly queryBus: QueryBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(CreateProductTagUseCase.name);

  public async execute({ ctx, tag }: CreateProductTagParams): Promise<TagDto> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.CREATE_PRODUCT_TAG],
    });

    // 2. Execute create command
    const createdTagId = await this.commandBus.execute(
      new AddProductTagCommand(ctx.tenantId, tag)
    );

    // 3. Return created tag
    return this.queryBus.execute(
      new GetProductTagByIdQuery(ctx.tenantId, createdTagId)
    );
  }
}
```

#### Business Logic Flow

1. **Permission Validation**: Validates user has `CREATE_PRODUCT_TAG` permission
2. **Uniqueness Check**: Ensures tag name is unique within tenant
3. **Command Execution**: Creates tag through command pattern
4. **Response**: Returns created tag with generated ID

#### Tag Creation Rules

* Tag names must be unique within tenant
* Tag names are case-insensitive
* Special characters are validated and sanitized
* Maximum length constraints are enforced

### GetPagedProductTagsUseCase

**File:** `common/module/product/tag/usecases/get-paged-product-tags.usecase.ts`

Retrieves paginated list of product tags with search functionality.

#### Implementation

```typescript
export class GetPagedProductTagsUseCase implements IUseCase<GetPagedProductTagsParams, any> {
  @Inject()
  private readonly queryBus: QueryBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(GetPagedProductTagsUseCase.name);

  public async execute({ ctx, pagination }: GetPagedProductTagsParams): Promise<any> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.READ_PRODUCT_TAG],
    });

    // 2. Execute paginated query
    return this.queryBus.execute(
      new GetPagedProductTagsQuery(ctx.tenantId, pagination)
    );
  }
}
```

#### Features

* Search functionality for tag names
* Efficient pagination for large tag lists
* Usage statistics for each tag
* Sorting by name, creation date, or usage frequency

### UpdateProductTagUseCase

**File:** `common/module/product/tag/usecases/update-product-tag.usecase.ts`

Updates existing product tags with validation.

#### Business Logic

1. **Permission Validation**: Validates `EDIT_PRODUCT_TAG` permission
2. **Uniqueness Check**: Ensures updated name doesn't conflict
3. **Usage Validation**: Checks if tag is currently in use
4. **Update Propagation**: Updates all products using the tag
5. **Cache Invalidation**: Clears relevant caches

### DeleteProductTagUseCase

**File:** `common/module/product/tag/usecases/delete-product-tag.usecase.ts`

Deletes product tags with usage validation.

#### Business Logic

1. **Permission Validation**: Validates `DELETE_PRODUCT_TAG` permission
2. **Usage Check**: Prevents deletion of tags in use
3. **Cascade Options**: Offers tag removal from products or prevention
4. **Audit Logging**: Records tag deletion activities

## Product Image Use Cases

### UpsertProductImageUseCase

**File:** `common/module/product/product/usecases/upsert-product-image.usecase.ts`

Handles product image upload and management operations.

#### Implementation

```typescript
export class UpsertProductImageUseCase implements IUseCase<UpsertProductImageParams, MediaDto> {
  @Inject()
  private readonly commandBus: CommandBus;

  @Inject()
  private readonly queryBus: QueryBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(UpsertProductImageUseCase.name);

  public async execute({ ctx, productId, media, file }: UpsertProductImageParams): Promise<MediaDto> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.EDIT_PRODUCT],
    });

    // 2. File validation and processing
    const processedFile = await this.validateAndProcessImage(file);

    // 3. Execute image upsert command
    const imageId = await this.commandBus.execute(
      new UpsertProductImageCommand(ctx.tenantId, productId, media, processedFile)
    );

    // 4. Return media information
    return this.queryBus.execute(
      new GetMediaByIdQuery(ctx.tenantId, imageId)
    );
  }

  private async validateAndProcessImage(file: Express.Multer.File): Promise<ProcessedFile> {
    // File type validation
    if (!this.isValidImageType(file.mimetype)) {
      throw new UnsupportedMediaTypeException('Only JPEG, PNG, and WebP images are supported');
    }

    // File size validation
    if (file.size > MAX_IMAGE_SIZE) {
      throw new PayloadTooLargeException('Image file size exceeds 5MB limit');
    }

    // Image processing (resize, optimize, generate thumbnails)
    return this.imageProcessor.process(file);
  }
}
```

#### Business Logic Flow

1. **Permission Validation**: Validates user has `EDIT_PRODUCT` permission
2. **File Validation**: Checks file type, size, and format
3. **Image Processing**: Resizes, optimizes, and generates thumbnails
4. **Upload to CDN**: Stores image in CDN with proper naming
5. **Database Update**: Links image to product in database
6. **Cache Invalidation**: Clears product caches
7. **Response**: Returns media information with CDN URLs

#### Image Processing Features

* **Format Validation**: Supports JPEG, PNG, and WebP formats
* **Size Optimization**: Automatic compression and optimization
* **Thumbnail Generation**: Creates multiple size variants
* **CDN Integration**: Direct upload to content delivery network
* **Metadata Extraction**: Extracts image dimensions and properties

### DeleteProductImageUseCase

**File:** `common/module/product/product/usecases/delete-product-image.usecase.ts`

Handles product image deletion with cleanup.

#### Implementation

```typescript
export class DeleteProductImageUseCase implements IUseCase<DeleteProductImageParams, void> {
  @Inject()
  private readonly commandBus: CommandBus;

  @Inject()
  private readonly permissionValidator: PermissionValidatorUseCase;

  private readonly logger = new Logger(DeleteProductImageUseCase.name);

  public async execute({ ctx, productId, id }: DeleteProductImageParams): Promise<void> {
    // 1. Permission validation
    await this.permissionValidator.execute({
      actor: ctx.actor,
      requiredPermissions: [ModulePermissionEnum.EDIT_PRODUCT],
    });

    // 2. Execute delete command with cleanup
    return this.commandBus.execute(
      new DeleteProductImageCommand(ctx.tenantId, productId, id)
    );
  }
}
```

#### Business Logic Flow

1. **Permission Validation**: Validates user has `EDIT_PRODUCT` permission
2. **Image Verification**: Confirms image belongs to specified product
3. **CDN Cleanup**: Removes image files from CDN
4. **Database Cleanup**: Removes image references from product
5. **Cache Invalidation**: Clears relevant caches
6. **Audit Logging**: Records image deletion activity

## CQRS Implementation

### Command Pattern

The product management module implements CQRS (Command Query Responsibility Segregation) for clear separation of read and write operations.

#### Commands

* **AddProductCommand**: Creates new products
* **UpdateProductCommand**: Modifies existing products
* **DeleteProductCommand**: Soft deletes products
* **UpsertProductImageCommand**: Manages product images
* **AddProductTagCommand**: Creates product tags

#### Queries

* **GetProductByIdQuery**: Retrieves single product
* **GetPagedProductsQuery**: Retrieves paginated product lists
* **GetProductTagByIdQuery**: Retrieves single tag
* **GetPagedProductTagsQuery**: Retrieves paginated tag lists

### Command Handlers

Each command has a dedicated handler that implements the business logic:

```typescript
@CommandHandler(AddProductCommand)
export class AddProductCommandHandler implements ICommandHandler<AddProductCommand> {
  constructor(
    @Inject('IProductRepository')
    private readonly productRepository: IProductRepository,
    private readonly eventBus: EventBus
  ) {}

  async execute(command: AddProductCommand): Promise<string> {
    // 1. Validate business rules
    await this.validateProductCreation(command.product);

    // 2. Create product entity
    const product = await this.productRepository.createProduct(command.product);

    // 3. Publish domain events
    await this.eventBus.publish(new ProductCreatedEvent(product));

    return product._id;
  }
}
```

### Query Handlers

Query handlers focus on data retrieval and optimization:

```typescript
@QueryHandler(GetPagedProductsQuery)
export class GetPagedProductsQueryHandler implements IQueryHandler<GetPagedProductsQuery> {
  constructor(
    @Inject('IProductRepository')
    private readonly productRepository: IProductRepository,
    private readonly cacheService: CacheService
  ) {}

  async execute(query: GetPagedProductsQuery): Promise<PaginationResultValue<ProductDto>> {
    // 1. Check cache first
    const cacheKey = this.buildCacheKey(query);
    const cached = await this.cacheService.get(cacheKey);
    if (cached) return cached;

    // 2. Execute database query
    const result = await this.productRepository.searchProductsWithCriteria(query.criteria);

    // 3. Cache result
    await this.cacheService.set(cacheKey, result, CACHE_TTL);

    return result;
  }
}
```

## Permission System

### Permission-Based Access Control

All use cases implement comprehensive permission validation:

```typescript
interface PermissionValidationParams {
  actor: {
    _id: string;
    permissions: string[];
    roles: string[];
  };
  requiredPermissions: ModulePermissionEnum[];
}
```

### Permission Hierarchy

```typescript
// Permission levels for products
const PRODUCT_PERMISSIONS = {
  CRUD_PRODUCT: 11000,      // All operations
  READ_PRODUCT: 11001,      // View only
  CREATE_PRODUCT: 11002,    // Create new
  EDIT_PRODUCT: 11003,      // Modify existing
  DELETE_PRODUCT: 11004     // Remove products
};

// Permission levels for tags
const TAG_PERMISSIONS = {
  CRUD_PRODUCT_TAG: 12000,  // All tag operations
  READ_PRODUCT_TAG: 12001,  // View tags
  CREATE_PRODUCT_TAG: 12002,// Create tags
  EDIT_PRODUCT_TAG: 12003,  // Modify tags
  DELETE_PRODUCT_TAG: 12004 // Delete tags
};
```

### Multi-Tenant Security

* **Tenant Isolation**: All operations are scoped to specific tenants
* **Data Segregation**: Database queries include tenant filtering
* **Permission Scoping**: Permissions are validated within tenant context
* **Audit Trails**: All operations are logged with tenant and user context

## Event Publishing

### Domain Events

The system publishes events for integration and auditing:

```typescript
// Product lifecycle events
interface ProductCreatedEvent {
  type: 'ProductCreated';
  tenantId: string;
  productId: string;
  product: ProductDto;
  createdBy: string;
  timestamp: Date;
}

interface ProductUpdatedEvent {
  type: 'ProductUpdated';
  tenantId: string;
  productId: string;
  changes: Partial<ProductDto>;
  updatedBy: string;
  timestamp: Date;
}

interface ProductDeletedEvent {
  type: 'ProductDeleted';
  tenantId: string;
  productId: string;
  deletedBy: string;
  timestamp: Date;
}
```

### Event Handlers

External modules can subscribe to product events:

```typescript
@EventsHandler(ProductCreatedEvent)
export class ProductCreatedEventHandler implements IEventHandler<ProductCreatedEvent> {
  async handle(event: ProductCreatedEvent) {
    // Update search indexes
    await this.searchService.indexProduct(event.product);
    
    // Send notifications
    await this.notificationService.notifyProductCreated(event);
    
    // Update analytics
    await this.analyticsService.trackProductCreation(event);
  }
}
```

## Error Handling

### Exception Types

The system defines specific exceptions for different error scenarios:

```typescript
// Business logic exceptions
class ProductNotFoundException extends NotFoundException {
  constructor(productId: string) {
    super(`Product with ID ${productId} not found`);
  }
}

class ProductAlreadyExistsException extends ConflictException {
  constructor(sku: string) {
    super(`Product with SKU ${sku} already exists`);
  }
}

class InvalidProductDataException extends BadRequestException {
  constructor(errors: ValidationError[]) {
    super('Product validation failed', errors);
  }
}

// File handling exceptions
class UnsupportedImageTypeException extends UnsupportedMediaTypeException {
  constructor(supportedTypes: string[]) {
    super(`Unsupported image type. Supported: ${supportedTypes.join(', ')}`);
  }
}

class ImageTooLargeException extends PayloadTooLargeException {
  constructor(maxSize: number) {
    super(`Image size exceeds maximum limit of ${maxSize}MB`);
  }
}
```

### Error Recovery

Use cases implement proper error handling and recovery:

```typescript
public async execute(params: CreateProductParams): Promise<ProductDto> {
  try {
    // Business logic execution
    return await this.performOperation(params);
  } catch (error) {
    // Log error with context
    this.logger.error('Product creation failed', {
      error: error.message,
      stack: error.stack,
      params: this.sanitizeParams(params)
    });

    // Publish error event for monitoring
    await this.eventBus.publish(new ProductOperationFailedEvent(error, params));

    // Re-throw with proper classification
    throw this.classifyError(error);
  }
}
```

## Business Rules

### Product Management Rules

#### Creation Rules

1. **SKU Uniqueness**: Product SKU must be unique within tenant
2. **Language Requirements**: At least one language version required
3. **Price Validation**: Price must be positive with valid currency
4. **Tag Validation**: All referenced tags must exist
5. **Image Limits**: Maximum 10 images per product

#### Update Rules

1. **SKU Immutability**: SKU cannot be changed after creation
2. **Language Preservation**: Cannot remove all language versions
3. **Active Order Protection**: Cannot modify products in active orders
4. **Price History**: All price changes are tracked for audit
5. **Tag Synchronization**: Tag updates propagate to all using products

#### Deletion Rules

1. **Soft Delete Only**: Products are never physically deleted
2. **Dependency Validation**: Cannot delete products with active references
3. **Order Protection**: Products in orders cannot be deleted
4. **Audit Preservation**: All historical data is maintained
5. **Cascade Management**: Related images and references are handled

### Tag Management Rules

#### Tag Creation

1. **Name Uniqueness**: Tag names must be unique within tenant
2. **Character Validation**: Only alphanumeric and specific special characters
3. **Length Limits**: Tag names have maximum length constraints
4. **Case Insensitivity**: Tag names are treated case-insensitively

#### Tag Usage

1. **Referential Integrity**: Cannot delete tags in use by products
2. **Bulk Operations**: Support for efficient bulk tag management
3. **Usage Tracking**: Track which products use which tags
4. **Search Optimization**: Tags are indexed for fast filtering

### Image Management Rules

#### Upload Constraints

1. **File Types**: Only JPEG, PNG, and WebP formats supported
2. **Size Limits**: Maximum 5MB per image file
3. **Dimension Limits**: Reasonable minimum and maximum dimensions
4. **Count Limits**: Maximum 10 images per product
5. **Quality Standards**: Automatic optimization and compression

#### Processing Rules

1. **Format Conversion**: Images may be converted for optimization
2. **Thumbnail Generation**: Multiple size variants created automatically
3. **CDN Integration**: Images stored in CDN for global access
4. **Metadata Extraction**: Image properties extracted and stored
5. **Progressive Loading**: Support for progressive image loading

### Performance Optimization Rules

#### Caching Strategy

1. **Product Data**: Frequently accessed products are cached
2. **Search Results**: Common search results are cached
3. **Tag Lists**: Tag collections are heavily cached
4. **Image URLs**: CDN URLs are cached for fast access
5. **Cache Invalidation**: Smart cache invalidation on updates

#### Database Optimization

1. **Indexing Strategy**: Comprehensive indexing for all query patterns
2. **Query Optimization**: Efficient queries with proper field selection
3. **Relationship Loading**: Optimized loading of related data
4. **Pagination Efficiency**: Efficient pagination for large datasets
5. **Search Performance**: Text search optimization with proper indexes

This use case documentation provides a comprehensive guide to the business logic, implementation patterns, and rules governing the Product Management module, ensuring consistent and reliable operation across all product-related operations.


# Database Schema

## Overview

This document provides comprehensive details about the database schema design for the Product Management module. The schema is implemented using MongoDB with Mongoose ODM, following document-oriented design principles with embedded sub-documents and strategic referencing for optimal performance.

## Table of Contents

1. [Schema Architecture](#schema-architecture)
2. [Product Schema](#product-schema)
3. [Product Tag Schema](#product-tag-schema)
4. [Price Sub-Schema](#price-sub-schema)
5. [Indexing Strategy](#indexing-strategy)
6. [Relationships and References](#relationships-and-references)
7. [Data Validation](#data-validation)
8. [Performance Optimization](#performance-optimization)
9. [Multi-Tenancy Implementation](#multi-tenancy-implementation)
10. [Audit and State Management](#audit-and-state-management)

## Schema Architecture

### Document-Oriented Design

The product management schema leverages MongoDB's document-oriented nature for efficient data storage and retrieval:

* **Embedded Documents**: Language versions and pricing information are embedded for atomic operations
* **Reference Strategy**: Media files and large collections use references for flexibility
* **Denormalization**: Strategic denormalization for performance optimization
* **Schema Validation**: Mongoose schema validation ensures data integrity

### Collections Overview

```
├── products                 # Main product collection
├── product-tags            # Product tag collection  
├── media                   # Media files (images, videos)
└── state-history           # Audit trail sub-documents
```

## Product Schema

### Main Product Document

**File:** `common/module/product/product/repos/product.scheme.ts`

```typescript
export const ProductSchema = new Schema<IProduct>({
  sku: { 
    type: String, 
    required: true,
    unique: true,
    index: true,
    trim: true,
    maxlength: 100
  },
  
  languageVersions: { 
    type: [LanguageVersionSchema], 
    required: true,
    validate: {
      validator: function(v: any[]) {
        return v && v.length > 0;
      },
      message: 'At least one language version is required'
    }
  },
  
  price: { 
    type: ProductPriceSchema, 
    required: true 
  },
  
  tags: { 
    type: [String], 
    required: false,
    index: true,
    validate: {
      validator: function(v: string[]) {
        return !v || v.length <= 20;
      },
      message: 'Maximum 20 tags allowed per product'
    }
  },
  
  images: [{ 
    type: Schema.Types.ObjectId, 
    ref: Media.name,
    validate: {
      validator: function(v: any[]) {
        return !v || v.length <= 10;
      },
      message: 'Maximum 10 images allowed per product'
    }
  }],
  
  order: { 
    type: Number, 
    required: false,
    min: 0,
    max: 999999,
    index: true
  },
  
  stateHistory: { 
    type: [StateHistorySchema], 
    default: [] 
  }
}, {
  timestamps: true,                          // Automatic createdAt/updatedAt
  collection: Product.name.toLowerCase(),    // Collection name: 'product'
  versionKey: false                          // Disable __v field
});
```

### Field Specifications

#### SKU (Stock Keeping Unit)

```typescript
sku: {
  type: String,
  required: true,
  unique: true,              // Unique constraint within collection
  index: true,               // Indexed for fast lookups
  trim: true,                // Remove whitespace
  maxlength: 100,            // Maximum length constraint
  match: /^[A-Z0-9-_]{1,100}$/ // Alphanumeric with hyphens/underscores
}
```

**Business Rules:**

* Must be unique across all products within the tenant
* Cannot be modified after product creation
* Used for external system integration
* Format: Uppercase letters, numbers, hyphens, underscores only

#### Language Versions

```typescript
languageVersions: {
  type: [LanguageVersionSchema],
  required: true,
  validate: {
    validator: (v: any[]) => v && v.length > 0,
    message: 'At least one language version is required'
  }
}
```

**Structure:**

```typescript
interface LanguageVersion {
  language: string;          // ISO language code (en, es, fr, etc.)
  title: string;             // Product title in specific language
  description?: string;      // Product description in specific language
}
```

**Business Rules:**

* At least one language version is mandatory
* Language codes must be valid ISO codes
* Titles are required for each language version
* Descriptions are optional but recommended
* Maximum 10 language versions per product

#### Pricing Information

```typescript
price: {
  type: ProductPriceSchema,
  required: true,
  validate: {
    validator: function(price: any) {
      return price && price.value > 0;
    },
    message: 'Price must be positive'
  }
}
```

#### Tags Array

```typescript
tags: {
  type: [String],
  required: false,
  index: true,               // Indexed for filtering
  validate: {
    validator: (v: string[]) => !v || v.length <= 20,
    message: 'Maximum 20 tags allowed'
  }
}
```

**Tag Constraints:**

* Maximum 20 tags per product
* Each tag must exist in the product-tag collection
* Tags are case-insensitive for matching
* Indexed for efficient filtering operations

#### Images Array

```typescript
images: [{
  type: Schema.Types.ObjectId,
  ref: Media.name,           // Reference to Media collection
  validate: {
    validator: (v: any[]) => !v || v.length <= 10,
    message: 'Maximum 10 images allowed'
  }
}]
```

**Image Constraints:**

* Maximum 10 images per product
* References stored as ObjectIds to Media collection
* Images are populated on query when needed
* Automatic cleanup when images are deleted

#### Display Order

```typescript
order: {
  type: Number,
  required: false,
  min: 0,                    // Non-negative values
  max: 999999,               // Reasonable upper limit
  index: true,               // Indexed for sorting
  default: null              // Default to end of list
}
```

### State History

```typescript
stateHistory: {
  type: [StateHistorySchema],
  default: [],
  select: false              // Excluded from queries by default
}
```

**Audit Trail Features:**

* Tracks all changes to product data
* Includes user information and timestamps
* Stores previous values for rollback capability
* Used for compliance and debugging

## Product Tag Schema

### Tag Document Structure

**File:** `common/module/product/tag/repos/product-tag.scheme.ts`

```typescript
export const TagSchema = new Schema<ITag>({
  name: { 
    type: String, 
    required: true,
    unique: true,              // Unique within tenant
    index: true,               // Indexed for fast lookups
    trim: true,                // Remove whitespace
    lowercase: true,           // Convert to lowercase
    maxlength: 50,             // Maximum length
    match: /^[a-z0-9-_\s]+$/   // Alphanumeric with hyphens, underscores, spaces
  },
  
  stateHistory: { 
    type: [StateHistorySchema], 
    default: [] 
  }
}, {
  timestamps: true,
  collection: 'product-tag',   // Explicit collection name
  versionKey: false
});
```

### Tag Validation Rules

#### Name Constraints

```typescript
name: {
  type: String,
  required: true,
  unique: true,               // Unique constraint
  trim: true,                 // Remove leading/trailing whitespace
  lowercase: true,            // Convert to lowercase for consistency
  minlength: 1,               // Minimum length
  maxlength: 50,              // Maximum length
  match: /^[a-z0-9-_\s]+$/   // Allowed characters
}
```

**Business Rules:**

* Tag names must be unique within the tenant
* Automatically converted to lowercase for consistency
* Only alphanumeric characters, hyphens, underscores, and spaces allowed
* Minimum 1 character, maximum 50 characters
* Leading and trailing whitespace automatically trimmed

### Tag Usage Tracking

```typescript
// Virtual field for usage count
TagSchema.virtual('usageCount', {
  ref: 'Product',
  localField: 'name',
  foreignField: 'tags',
  count: true
});
```

## Price Sub-Schema

### Price Document Structure

**File:** `common/module/product/product/repos/sub/product-price.scheme.ts`

```typescript
export const ProductPriceSchema = new Schema<IProductPrice>({
  value: { 
    type: Number,
    required: true,
    min: 0,                    // Non-negative values only
    max: 999999.99,            // Reasonable upper limit
    validate: {
      validator: function(v: number) {
        return Number.isFinite(v) && v >= 0;
      },
      message: 'Price must be a finite non-negative number'
    }
  },
  
  currency: { 
    type: String, 
    enum: Object.values(CurrencyCodeEnum),
    required: true,
    default: CurrencyCodeEnum.USD
  }
}, {
  timestamps: true,           // Track price change history
  _id: false                  // No separate _id for sub-document
});
```

### Currency Support

```typescript
enum CurrencyCodeEnum {
  USD = 'USD',               // US Dollar
  EUR = 'EUR',               // Euro
  GBP = 'GBP',               // British Pound
  CAD = 'CAD',               // Canadian Dollar
  AUD = 'AUD',               // Australian Dollar
  JPY = 'JPY',               // Japanese Yen
  CHF = 'CHF',               // Swiss Franc
  CNY = 'CNY',               // Chinese Yuan
  INR = 'INR',               // Indian Rupee
  BRL = 'BRL',               // Brazilian Real
  MXN = 'MXN',               // Mexican Peso
  ZAR = 'ZAR'                // South African Rand
}
```

### Price Validation

* **Value Range**: 0 to 999,999.99 (adjustable based on business needs)
* **Precision**: Two decimal places for monetary values
* **Currency Validation**: Must be from supported currency enum
* **Change Tracking**: Timestamps track when prices are modified

## Indexing Strategy

### Product Collection Indexes

#### Primary Indexes

```typescript
// Unique indexes
ProductSchema.index({ sku: 1 }, { unique: true });
ProductSchema.index({ _id: 1 });              // Default MongoDB index

// Query optimization indexes
ProductSchema.index({ tags: 1 });             // Tag filtering
ProductSchema.index({ order: 1 });            // Sorting by display order
ProductSchema.index({ createdAt: -1 });       // Recent products first
ProductSchema.index({ updatedAt: -1 });       // Recently updated

// Text search index
ProductSchema.index({
  'languageVersions.title': 'text',
  'languageVersions.description': 'text',
  'sku': 'text'
}, {
  name: 'product_text_search',
  weights: {
    'languageVersions.title': 10,    // Higher weight for titles
    'languageVersions.description': 5,
    'sku': 8
  }
});
```

#### Compound Indexes

```typescript
// Multi-field filtering
ProductSchema.index({ tags: 1, order: 1 });   // Tag + order filtering
ProductSchema.index({ tags: 1, createdAt: -1 }); // Tag + recency
ProductSchema.index({ order: 1, createdAt: -1 }); // Order + recency

// Tenant-specific indexes (for multi-tenancy)
ProductSchema.index({ tenantId: 1, sku: 1 }, { unique: true });
ProductSchema.index({ tenantId: 1, tags: 1 });
ProductSchema.index({ tenantId: 1, order: 1 });
```

### Tag Collection Indexes

```typescript
// Primary indexes for tags
TagSchema.index({ name: 1 }, { unique: true });
TagSchema.index({ _id: 1 });

// Search and filtering
TagSchema.index({ name: 'text' });            // Text search on tag names
TagSchema.index({ createdAt: -1 });           // Recently created tags
TagSchema.index({ updatedAt: -1 });           // Recently updated tags

// Multi-tenant indexes
TagSchema.index({ tenantId: 1, name: 1 }, { unique: true });
```

### Index Performance Considerations

#### Query Patterns Optimized

1. **Product Lookup by SKU**: O(1) lookup with unique index
2. **Tag Filtering**: Efficient array index scanning
3. **Text Search**: Full-text search across multiple language versions
4. **Sorting**: Pre-sorted indexes for order and date fields
5. **Pagination**: Efficient skip/limit operations

#### Index Maintenance

* **Selective Indexing**: Only indexes that support actual query patterns
* **Index Monitoring**: Regular analysis of index usage and performance
* **Compound Index Optimization**: Left-prefix rule consideration
* **Memory Usage**: Balance between query performance and memory consumption

## Relationships and References

### Product-Media Relationship

#### Reference Strategy

```typescript
// Product references media files
images: [{
  type: Schema.Types.ObjectId,
  ref: 'Media'
}]

// Population query
Product.findById(id).populate('images');
```

#### Media Document Structure

```typescript
interface MediaDocument {
  _id: ObjectId;
  url: string;               // CDN URL
  type: 'image' | 'video';   // Media type
  mimeType: string;          // MIME type
  size: number;              // File size in bytes
  alt?: string;              // Alternative text
  metadata: {                // Image metadata
    width?: number;
    height?: number;
    format?: string;
  };
  createdAt: Date;
  updatedAt: Date;
}
```

### Product-Tag Relationship

#### Embedding Strategy

```typescript
// Tags are embedded as strings in products
tags: [String]             // Array of tag names

// Tag names reference the Tag collection
const tagDoc = await Tag.findOne({ name: tagName });
```

#### Benefits of This Approach

* **Performance**: Fast filtering without joins
* **Simplicity**: Direct array operations for tag management
* **Consistency**: Tag names are normalized in Tag collection
* **Flexibility**: Easy to add/remove tags from products

### Multi-Tenant Relationships

#### Tenant Isolation

```typescript
// All documents include tenant identifier
interface TenantDocument {
  tenantId: ObjectId;        // Reference to tenant
  // ... other fields
}

// Query patterns always include tenant filter
Product.find({ tenantId: currentTenantId });
```

## Data Validation

### Schema-Level Validation

#### Built-in Validators

```typescript
{
  sku: {
    type: String,
    required: [true, 'SKU is required'],
    unique: true,
    minlength: [1, 'SKU must be at least 1 character'],
    maxlength: [100, 'SKU cannot exceed 100 characters'],
    match: [/^[A-Z0-9-_]+$/, 'SKU can only contain uppercase letters, numbers, hyphens, and underscores']
  },
  
  'price.value': {
    type: Number,
    required: [true, 'Price value is required'],
    min: [0, 'Price must be non-negative'],
    max: [999999.99, 'Price cannot exceed 999,999.99']
  }
}
```

#### Custom Validators

```typescript
// Language version validation
languageVersions: {
  type: [LanguageVersionSchema],
  validate: {
    validator: function(versions: any[]) {
      if (!versions || versions.length === 0) {
        return false;
      }
      
      // Check for duplicate languages
      const languages = versions.map(v => v.language);
      return languages.length === new Set(languages).size;
    },
    message: 'Language versions must be unique and at least one is required'
  }
}

// Tag validation
tags: {
  type: [String],
  validate: {
    validator: async function(tags: string[]) {
      if (!tags || tags.length === 0) return true;
      
      // Verify all tags exist
      const existingTags = await Tag.find({ name: { $in: tags } });
      return existingTags.length === tags.length;
    },
    message: 'All tags must exist in the tag collection'
  }
}
```

### Application-Level Validation

#### Business Rule Validation

```typescript
// Pre-save middleware for business rules
ProductSchema.pre('save', async function(next) {
  const product = this;
  
  // SKU uniqueness within tenant
  if (product.isModified('sku')) {
    const existing = await Product.findOne({
      tenantId: product.tenantId,
      sku: product.sku,
      _id: { $ne: product._id }
    });
    
    if (existing) {
      return next(new Error('SKU must be unique within tenant'));
    }
  }
  
  // Price change validation
  if (product.isModified('price') && !product.isNew) {
    // Log price changes for audit
    product.stateHistory.push({
      field: 'price',
      oldValue: product.getOriginal('price'),
      newValue: product.price,
      changedBy: product.modifiedBy,
      changedAt: new Date()
    });
  }
  
  next();
});
```

## Performance Optimization

### Query Optimization Patterns

#### Efficient Product Queries

```typescript
// Optimized product listing with projection
Product.find(
  { tenantId, tags: { $in: filterTags } },
  { 
    sku: 1, 
    'languageVersions.title': 1, 
    'price.value': 1, 
    order: 1 
  }
).sort({ order: 1, createdAt: -1 }).limit(20);

// Populated query with select
Product.findById(id)
  .populate('images', 'url alt metadata')
  .select('-stateHistory');
```

#### Pagination Optimization

```typescript
// Cursor-based pagination for better performance
const cursor = req.query.cursor;
const query = cursor 
  ? { _id: { $gt: cursor }, tenantId }
  : { tenantId };

Product.find(query)
  .sort({ _id: 1 })
  .limit(pageSize + 1);
```

### Aggregation Pipelines

#### Product Statistics

```typescript
// Product count by tag
Product.aggregate([
  { $match: { tenantId: ObjectId(tenantId) } },
  { $unwind: '$tags' },
  { $group: { _id: '$tags', count: { $sum: 1 } } },
  { $sort: { count: -1 } }
]);

// Price statistics
Product.aggregate([
  { $match: { tenantId: ObjectId(tenantId) } },
  { $group: {
    _id: '$price.currency',
    avgPrice: { $avg: '$price.value' },
    minPrice: { $min: '$price.value' },
    maxPrice: { $max: '$price.value' },
    count: { $sum: 1 }
  }}
]);
```

### Memory and Storage Optimization

#### Document Size Management

* **Embedded vs Referenced**: Strategic choice based on access patterns
* **Field Selection**: Use projection to limit transferred data
* **Archive Strategy**: Move old products to archive collection
* **Image Optimization**: Store only references, actual files in CDN

#### Connection Pooling

```typescript
// Optimized MongoDB connection
mongoose.connect(uri, {
  maxPoolSize: 10,           // Maximum connections
  serverSelectionTimeoutMS: 5000,
  socketTimeoutMS: 45000,
  bufferMaxEntries: 0        // Disable mongoose buffering
});
```

## Multi-Tenancy Implementation

### Tenant Isolation Strategy

#### Document-Level Isolation

```typescript
// All schemas include tenant identifier
const baseSchema = {
  tenantId: {
    type: Schema.Types.ObjectId,
    required: true,
    ref: 'Tenant',
    index: true
  }
};

// Merge with specific schema
const ProductSchema = new Schema({
  ...baseSchema,
  sku: { /* field definition */ },
  // ... other fields
});
```

#### Query Middleware

```typescript
// Automatic tenant filtering
ProductSchema.pre(/^find/, function() {
  if (!this.getQuery().tenantId) {
    throw new Error('Tenant ID is required for all queries');
  }
});

// Ensure tenant ID on save
ProductSchema.pre('save', function(next) {
  if (!this.tenantId) {
    return next(new Error('Tenant ID is required'));
  }
  next();
});
```

### Tenant-Specific Indexes

```typescript
// Compound indexes starting with tenantId
ProductSchema.index({ tenantId: 1, sku: 1 }, { unique: true });
ProductSchema.index({ tenantId: 1, tags: 1 });
ProductSchema.index({ tenantId: 1, order: 1 });
ProductSchema.index({ tenantId: 1, createdAt: -1 });

TagSchema.index({ tenantId: 1, name: 1 }, { unique: true });
```

### Data Security

#### Access Control

* **Tenant Validation**: Every operation validates tenant access
* **Data Isolation**: Queries automatically scoped to tenant
* **Audit Logging**: All operations logged with tenant context
* **Permission Checking**: User permissions validated within tenant scope

## Audit and State Management

### State History Schema

#### StateHistory Sub-Document

```typescript
const StateHistorySchema = new Schema({
  field: {
    type: String,
    required: true
  },
  oldValue: {
    type: Schema.Types.Mixed,   // Any type for flexibility
    required: false
  },
  newValue: {
    type: Schema.Types.Mixed,
    required: false
  },
  changedBy: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  changedAt: {
    type: Date,
    required: true,
    default: Date.now
  },
  reason: {
    type: String,
    required: false,
    maxlength: 500
  }
}, {
  _id: true,                    // Each history entry has its own ID
  timestamps: false             // Use changedAt instead
});
```

### Change Tracking Implementation

#### Automatic Change Detection

```typescript
ProductSchema.pre('save', function(next) {
  const product = this;
  const modifiedPaths = product.modifiedPaths();
  
  modifiedPaths.forEach(path => {
    if (path !== 'stateHistory' && path !== 'updatedAt') {
      const oldValue = product.getOriginal(path);
      const newValue = product.get(path);
      
      product.stateHistory.push({
        field: path,
        oldValue: oldValue,
        newValue: newValue,
        changedBy: product.modifiedBy || product.createdBy,
        changedAt: new Date(),
        reason: product.changeReason
      });
    }
  });
  
  next();
});
```

### Compliance Features

#### Data Retention

* **Audit Trail**: Complete history of all changes maintained
* **User Tracking**: All modifications linked to specific users
* **Timestamp Accuracy**: Precise timestamps for all operations
* **Reason Codes**: Optional reason codes for changes

#### Privacy Compliance

* **Data Anonymization**: Support for anonymizing user references
* **Right to Deletion**: Compliance with data deletion requirements
* **Data Export**: Support for exporting user-related data
* **Consent Tracking**: Track consent for data processing

## Backup and Recovery

### Backup Strategy

#### Regular Backups

```typescript
// MongoDB backup configuration
{
  collections: ['product', 'product-tag', 'media'],
  schedule: '0 2 * * *',        // Daily at 2 AM
  retention: '30d',             // Keep for 30 days
  compression: true,
  encryption: true
}
```

#### Point-in-Time Recovery

* **Oplog Archival**: MongoDB oplog archival for point-in-time recovery
* **Snapshot Backups**: Regular collection snapshots
* **Cross-Region Replication**: Geographic distribution for disaster recovery
* **Testing**: Regular backup restoration testing

### Data Migration

#### Schema Evolution

```typescript
// Migration script example
async function migrateProductSchema_v2_to_v3() {
  const products = await Product.find({ schemaVersion: { $lt: 3 } });
  
  for (const product of products) {
    // Add new fields with default values
    product.newField = getDefaultValue();
    
    // Transform existing data
    product.transformedField = transformData(product.oldField);
    
    // Update schema version
    product.schemaVersion = 3;
    
    await product.save();
  }
}
```

This database schema documentation provides a complete reference for the data structure, relationships, and optimization strategies used in the Product Management module, ensuring efficient and scalable data management for the application.


# Service Management

## Overview

This directory contains comprehensive documentation for the Service Management module of the Bee O'clock panel service. The service management system handles the complete lifecycle of bookable services, including creation, configuration, pricing, scheduling, and presentation within the multi-tenant SaaS platform.

## Documentation Structure

### [API Documentation](/services/service-management/api)

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

**Key Topics Covered:**

* Service CRUD operations
* Pagination and search functionality
* Media and banner management
* Required resource management
* Comprehensive data schemas
* Error handling and status codes

### [Interface Documentation](/services/service-management/interface)

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

**Key Topics Covered:**

* Data Transfer Objects (DTOs)
* Domain interfaces and entities
* Enum definitions and constants
* Type definitions and contracts
* Validation constraints
* Utility functions and type guards

### [Use Case Documentation](/services/service-management/usecase)

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
* Performance considerations
* Integration patterns

### [Database Schema Documentation](/services/service-management/db_schema)

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

**Key Topics Covered:**

* Entity schemas and relationships
* Sub-document structures
* Index strategies and optimization
* Multi-tenancy considerations
* Data validation and constraints
* Performance optimization

## Module Architecture

### Technology Stack

* **Framework**: NestJS with TypeScript
* **Database**: MongoDB with Mongoose ODM
* **Architecture**: Clean Architecture + CQRS + DDD
* **Patterns**: Repository Pattern, Event-Driven Architecture
* **Caching**: Redis for performance optimization
* **Storage**: Cloud storage for media files
* **Event System**: AMQP for async processing

### Core Features

#### Service Lifecycle Management

* Service creation with comprehensive validation
* Multi-version service updates with history tracking
* Soft deletion with dependency checking
* State management and audit trails

#### Multilingual Support

* Multiple language versions per service
* Language-specific pricing options
* Localized service descriptions
* International currency support

#### Flexible Pricing Models

* Multiple duration options per service
* Currency-specific pricing
* Language-targeted pricing
* Prepayment policy configuration

#### Rich Presentation

* Banner image management with optimization
* Color theming and branding
* Media upload and processing
* CDN integration for performance

#### Advanced Configuration

* Flexible duration management (fixed/variable)
* Resource requirement specifications
* Schedule and availability management
* Integration with specialist assignments

## Business Rules

### Service Creation

1. **Language Requirements**: At least one language version mandatory
2. **Duration Configuration**: Proper duration and pricing setup required
3. **Presentation**: Valid presentation configuration with optional media
4. **Business Validation**: Compliance with tenant-specific rules
5. **Resource Management**: Optional but validated resource requirements

### Service Updates

1. **Data Integrity**: Cannot remove all language or duration versions
2. **Active Booking Protection**: Restrictions on services with active bookings
3. **Change Tracking**: Complete audit trail of modifications
4. **Media Management**: Proper handling of media updates and deletions
5. **Cache Coordination**: Automatic cache invalidation on changes

### Service Deletion

1. **Dependency Checking**: Cannot delete services with active references
2. **Soft Delete**: Services archived rather than physically removed
3. **Data Preservation**: Historical data maintained for compliance
4. **Cleanup Coordination**: Proper cleanup of related resources

### Media Management

1. **File Validation**: Strict file format and size validation
2. **Image Processing**: Automatic optimization and thumbnail generation
3. **Storage Integration**: Efficient cloud storage utilization
4. **CDN Optimization**: Performance-optimized media delivery

## API Integration Examples

### Creating a Service

```typescript
POST /api/v1/service
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json

{
  "languageVersions": [
    {
      "language": "en",
      "title": "Premium Massage Therapy",
      "description": "Relaxing therapeutic massage with aromatherapy"
    },
    {
      "language": "es", 
      "title": "Terapia de Masaje Premium",
      "description": "Masaje terapéutico relajante con aromaterapia"
    }
  ],
  "durationVersions": [
    {
      "durationInSeconds": 3600,
      "breakInSeconds": 300,
      "prices": [
        {
          "price": 80.00,
          "currency": "USD",
          "preferredLanguages": ["en"]
        },
        {
          "price": 75.00,
          "currency": "EUR", 
          "preferredLanguages": ["es"]
        }
      ]
    }
  ],
  "presentation": {
    "color": "#4A90E2"
  },
  "configuration": {
    "duration": {
      "durationVersionType": "RANGE"
    }
  },
  "prepaymentPolicy": {
    "isRequired": true,
    "isPercentage": true,
    "value": "25",
    "minimalCancelTime": "86400"
  },
  "schedules": [
    {
      "weekDays": [1, 2, 3, 4, 5],
      "startTime": "09:00",
      "endTime": "18:00"
    }
  ]
}
```

### Updating Service Media

```typescript
POST /api/v1/service/{id}/media
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
Content-Type: multipart/form-data

--boundary
Content-Disposition: form-data; name="file"; filename="service-banner.jpg"
Content-Type: image/jpeg

[binary image data]
--boundary
Content-Disposition: form-data; name="description"

Main promotional banner for massage therapy service
--boundary--
```

### Paginated Service Listing

```typescript
GET /api/v1/service/paged?page=1&size=10&phrase=massage
Authorization: Bearer <token>
x-business-tenant-id: <tenant_id>
```

## Development Guidelines

### Testing Strategy

* **Unit Tests**: Business logic validation and domain rules
* **Integration Tests**: Database operations and external services
* **E2E Tests**: Complete API workflows and user scenarios
* **Performance Tests**: Load testing and scalability validation
* **Media Tests**: File upload and processing validation

### Error Handling

* Domain-specific exceptions with clear error messages
* Consistent error response format across all endpoints
* Proper HTTP status codes for different error types
* Detailed logging for debugging and monitoring
* Graceful degradation for non-critical failures

### Performance Considerations

* Comprehensive database indexing strategy
* Multi-level caching with intelligent invalidation
* Optimized queries with proper data loading
* Asynchronous media processing
* CDN integration for static content delivery

### Security Best Practices

* Input validation and sanitization at all levels
* Role-based access control with granular permissions
* Secure file upload handling with validation
* Audit logging for all sensitive operations
* Rate limiting and abuse prevention

## Related Modules

### Dependencies

* **Permission Module**: Role and permission management
* **Media Module**: File storage and processing
* **Business Client Module**: Tenant management and settings
* **Specialist Module**: Service provider assignments
* **Resource Module**: Resource requirement management
* **Order Module**: Service booking and reservation

### Integration Points

* **Cache Module**: Performance optimization
* **Event Bus**: Async processing and notifications
* **Storage Service**: Media file management
* **Search Service**: Enhanced search capabilities
* **Notification Module**: Service-related notifications

## Performance Metrics

### Key Performance Indicators

* Service creation/update response times
* Search query performance and accuracy
* Media upload and processing speeds
* Cache hit rates and effectiveness
* Database query optimization metrics

### Monitoring and Alerting

* API endpoint response time monitoring
* Database performance and query analysis
* Cache performance and hit rate tracking
* Media processing success rates
* Error rate monitoring and alerting

## Scalability Considerations

### Horizontal Scaling

* Stateless service design for easy scaling
* Database sharding strategies for large datasets
* Distributed caching for multi-instance deployment
* Load balancing for API endpoints
* CDN scaling for media delivery

### Vertical Scaling

* Database optimization and indexing
* Query performance tuning
* Memory usage optimization
* CPU-intensive operation optimization
* Storage efficiency improvements

## Future Enhancements

### Planned Features

* **AI-Powered Recommendations**: Service suggestion algorithms
* **Dynamic Pricing**: Time and demand-based pricing models
* **Service Templates**: Reusable service configuration templates
* **Advanced Analytics**: Service performance and usage insights
* **Bulk Operations**: Mass service management capabilities

### Technical Improvements

* **GraphQL API**: Enhanced query capabilities and flexibility
* **Event Sourcing**: Complete audit trail with event streams
* **Microservice Architecture**: Split into focused microservices
* **Real-time Updates**: WebSocket integration for live updates
* **Advanced Search**: Elasticsearch integration for complex queries

## Troubleshooting Guide

### Common Issues

* **Service Creation Failures**: Validation errors and resolution
* **Media Upload Problems**: File format and size issues
* **Permission Denied Errors**: Access control troubleshooting
* **Performance Issues**: Query optimization and caching
* **Data Consistency**: Multi-tenant isolation problems

### Debugging Tools

* Structured error messages with correlation IDs
* Comprehensive logging with request tracing
* Database query analysis tools
* Cache inspection utilities
* Performance profiling tools

### Support Resources

* API documentation and examples
* Error code reference guide
* Performance optimization guide
* Best practices documentation
* Community forums and support channels

## Contributing Guidelines

### Code Standards

* TypeScript strict mode compliance
* ESLint and Prettier configuration
* Comprehensive test coverage requirements
* Clean Architecture principles adherence
* Domain-Driven Design patterns

### Documentation Requirements

* Update documentation with code changes
* Include comprehensive API examples
* Maintain schema documentation accuracy
* Document business rule changes
* Provide migration guides for breaking changes

### Review Process

* Mandatory code review for all changes
* Testing validation and coverage verification
* Documentation update validation
* Performance impact assessment
* Security review for sensitive changes

## Migration and Deployment

### Database Migrations

* Schema evolution and backwards compatibility
* Data migration scripts and validation
* Index management and optimization
* Performance impact assessment
* Rollback procedures and safety measures

### Deployment Strategies

* Blue-green deployment for zero downtime
* Feature flags for gradual rollouts
* Database migration coordination
* Cache warming strategies
* Health check validation

### Monitoring and Rollback

* Real-time deployment monitoring
* Automated rollback triggers
* Data integrity validation
* Performance regression detection
* User impact assessment


# API Documentation

## Overview

The Service Management API provides comprehensive service lifecycle management for the Bee O'clock platform. Services represent bookable offerings provided by businesses, including their configuration, pricing, scheduling, and presentation details.

## Base URL

```
{api_base_url}/api/v1/service
```

## Authentication

All endpoints require Bearer token authentication and business tenant identification.

**Headers Required:**

```http
Authorization: Bearer <access_token>
x-business-tenant-id: <tenant_id>
Content-Type: application/json
```

## Endpoints

### 1. Get Paged Services

Retrieve a paginated list of services with optional search functionality.

**Endpoint:** `GET /paged`

**Query Parameters:**

| Parameter | Type     | Required | Default | Description                                                 |
| --------- | -------- | -------- | ------- | ----------------------------------------------------------- |
| `page`    | `number` | No       | `1`     | Page number for pagination                                  |
| `size`    | `number` | No       | `10`    | Number of items per page                                    |
| `phrase`  | `string` | No       | -       | Search phrase for filtering by service title or description |

**Example Request:**

```http
GET /api/v1/service/paged?page=1&size=10&phrase=haircut
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
x-business-tenant-id: 12345
```

**Response Schema:**

```typescript
interface PaginatedServicesResponse {
  items: ServiceDto[];
  totalSize : number;
}
```

**Example Response:**

```json
{
  "items": [
    {
      "_id": "64a7b8f123456789abcdef01",
      "object": "ServiceDto",
      "languageVersions": [
        {
          "language": "en",
          "title": "Haircut and Styling",
          "description": "Professional haircut and styling service"
        }
      ],
      "durationVersions": [
        {
          "durationInSeconds": 3600,
          "breakInSeconds": 300,
          "prices": [
            {
              "price": 50.00,
              "currency": "USD"
            }
          ]
        }
      ],
      "presentation": {
        "color": "#FF5733",
        "media": []
      },
      "configuration": {
        "duration": {
          "durationVersionType": "RANGE"
        }
      },
      "prepaymentPolicy": {
        "isRequired": false
      },
      "schedules": [],
      "order": 1,
      "createdAt": "2024-01-15T10:30:00Z",
      "updatedAt": "2024-01-15T10:30:00Z"
    }
  ],
  "totalSize": 1
}
```

### 2. Get Service by ID

Retrieve detailed information about a specific service.

**Endpoint:** `GET /{id}`

**Path Parameters:**

| Parameter | Type     | Required | Description               |
| --------- | -------- | -------- | ------------------------- |
| `id`      | `string` | Yes      | Unique service identifier |

**Example Request:**

```http
GET /api/v1/service/64a7b8f123456789abcdef01
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
x-business-tenant-id: 12345
```

**Response Schema:** `ServiceDto`

**Example Response:**

```json
{
  "_id": "64a7b8f123456789abcdef01",
  "object": "ServiceDto",
  "languageVersions": [
    {
      "language": "en",
      "title": "Haircut and Styling",
      "description": "Professional haircut and styling service with consultation"
    },
    {
      "language": "es",
      "title": "Corte y Peinado",
      "description": "Servicio profesional de corte y peinado con consulta"
    }
  ],
  "durationVersions": [
    {
      "durationInSeconds": 3600,
      "breakInSeconds": 300,
      "prices": [
        {
          "price": 50.00,
          "currency": "USD",
          "preferredLanguages": ["en"]
        },
        {
          "price": 45.00,
          "currency": "EUR",
          "preferredLanguages": ["es"]
        }
      ]
    }
  ],
  "presentation": {
    "color": "#FF5733",
    "media": [
      {
        "_id": "64a7b8f123456789abcdef02",
        "url": "https://storage.example.com/service-images/haircut.jpg",
        "mimeType": "image/jpeg"
      }
    ]
  },
  "configuration": {
    "duration": {
      "durationVersionType": "RANGE"
    }
  },
  "prepaymentPolicy": {
    "isRequired": true,
    "isPercentage": true,
    "value": "25",
    "minimalCancelTime": "86400"
  },
  "schedules": [
    {
      "weekDays": [1, 2, 3, 4, 5],
      "startTime": "09:00",
      "endTime": "17:00"
    }
  ],
  "order": 1,
  "createdAt": "2024-01-15T10:30:00Z",
  "updatedAt": "2024-01-20T14:45:00Z"
}
```

### 3. Create Service

Create a new service with complete configuration.

**Endpoint:** `POST /`

**Request Schema:** `ServiceDto`

**Example Request:**

```http
POST /api/v1/service
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
x-business-tenant-id: 12345
Content-Type: application/json

{
  "languageVersions": [
    {
      "language": "en",
      "title": "Deep Tissue Massage",
      "description": "Therapeutic deep tissue massage for muscle relief"
    }
  ],
  "durationVersions": [
    {
      "durationInSeconds": 5400,
      "breakInSeconds": 600,
      "prices": [
        {
          "price": 80.00,
          "currency": "USD"
        }
      ]
    }
  ],
  "presentation": {
    "color": "#4A90E2"
  },
  "configuration": {
    "duration": {
      "durationVersionType": "FIXED"
    }
  },
  "prepaymentPolicy": {
    "isRequired": false
  },
  "schedules": [
    {
      "weekDays": [1, 2, 3, 4, 5, 6],
      "startTime": "08:00",
      "endTime": "20:00"
    }
  ],
  "order": 2
}
```

**Response Schema:** `ServiceDto` (created service with generated ID)

**Example Response:**

```json
{
  "_id": "64a7b8f123456789abcdef03",
  "object": "ServiceDto",
  "languageVersions": [
    {
      "language": "en",
      "title": "Deep Tissue Massage",
      "description": "Therapeutic deep tissue massage for muscle relief"
    }
  ],
  "durationVersions": [
    {
      "durationInSeconds": 5400,
      "breakInSeconds": 600,
      "prices": [
        {
          "price": 80.00,
          "currency": "USD"
        }
      ]
    }
  ],
  "presentation": {
    "color": "#4A90E2",
    "media": []
  },
  "configuration": {
    "duration": {
      "durationVersionType": "FIXED"
    }
  },
  "prepaymentPolicy": {
    "isRequired": false
  },
  "schedules": [
    {
      "weekDays": [1, 2, 3, 4, 5, 6],
      "startTime": "08:00",
      "endTime": "20:00"
    }
  ],
  "order": 2,
  "createdAt": "2024-01-25T09:15:00Z",
  "updatedAt": "2024-01-25T09:15:00Z"
}
```

### 4. Update Service

Update an existing service's information.

**Endpoint:** `PUT /{id}`

**Path Parameters:**

| Parameter | Type     | Required | Description               |
| --------- | -------- | -------- | ------------------------- |
| `id`      | `string` | Yes      | Unique service identifier |

**Request Schema:** `ServiceDto`

**Example Request:**

```http
PUT /api/v1/service/64a7b8f123456789abcdef01
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
x-business-tenant-id: 12345
Content-Type: application/json

{
  "_id": "64a7b8f123456789abcdef01",
  "languageVersions": [
    {
      "language": "en",
      "title": "Premium Haircut and Styling",
      "description": "Premium haircut and styling service with luxury consultation"
    }
  ],
  "durationVersions": [
    {
      "durationInSeconds": 4200,
      "breakInSeconds": 300,
      "prices": [
        {
          "price": 65.00,
          "currency": "USD"
        }
      ]
    }
  ],
  "prepaymentPolicy": {
    "isRequired": true,
    "isPercentage": true,
    "value": "30",
    "minimalCancelTime": "172800"
  },
  "order": 1
}
```

**Response Schema:** `ServiceDto` (updated service)

### 5. Update Service Required Resources

Update the list of resources required for a service.

**Endpoint:** `PUT /{id}/required-resources`

**Path Parameters:**

| Parameter | Type     | Required | Description               |
| --------- | -------- | -------- | ------------------------- |
| `id`      | `string` | Yes      | Unique service identifier |

**Request Schema:** `RequiredResourceDto[]`

**Example Request:**

```http
PUT /api/v1/service/64a7b8f123456789abcdef01/required-resources
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
x-business-tenant-id: 12345
Content-Type: application/json

[
  {
    "resourceId": "64a7b8f123456789abcdef04",
    "quantity": 1,
    "isRequired": true
  },
  {
    "resourceId": "64a7b8f123456789abcdef05",
    "quantity": 2,
    "isRequired": false
  }
]
```

**Response:** `204 No Content`

### 6. Delete Service

Soft delete a service (marks as deleted while preserving data).

**Endpoint:** `DELETE /{id}`

**Path Parameters:**

| Parameter | Type     | Required | Description               |
| --------- | -------- | -------- | ------------------------- |
| `id`      | `string` | Yes      | Unique service identifier |

**Example Request:**

```http
DELETE /api/v1/service/64a7b8f123456789abcdef01
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
x-business-tenant-id: 12345
```

**Response Schema:**

```typescript
interface DeleteServiceResponse {
  deletedCount: number;
}
```

**Example Response:**

```json
{
  "deletedCount": 1
}
```

## Service Media Management

### Upload Service Media

**Endpoint:** `POST /{id}/media`

**Path Parameters:**

| Parameter | Type     | Required | Description               |
| --------- | -------- | -------- | ------------------------- |
| `id`      | `string` | Yes      | Unique service identifier |

**Request:** `multipart/form-data`

| Field         | Type     | Required | Description                 |
| ------------- | -------- | -------- | --------------------------- |
| `file`        | `File`   | Yes      | Image file (JPG, PNG, WebP) |
| `description` | `string` | No       | Media description           |

**Example Request:**

```http
POST /api/v1/service/64a7b8f123456789abcdef01/media
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
x-business-tenant-id: 12345
Content-Type: multipart/form-data

--boundary
Content-Disposition: form-data; name="file"; filename="service-image.jpg"
Content-Type: image/jpeg

[binary image data]
--boundary
Content-Disposition: form-data; name="description"

Main service promotional image
--boundary--
```

### Delete Service Media

**Endpoint:** `DELETE /{id}/media/{mediaId}`

**Path Parameters:**

| Parameter | Type     | Required | Description               |
| --------- | -------- | -------- | ------------------------- |
| `id`      | `string` | Yes      | Unique service identifier |
| `mediaId` | `string` | Yes      | Unique media identifier   |

## Data Transfer Objects

### ServiceDto

```typescript
interface ServiceDto {
  _id?: string;
  object?: 'ServiceDto';
  configuration?: ServiceConfigurationDto;
  presentation?: PresentationDto;
  prepaymentPolicy?: PrepaymentPolicyDto;
  languageVersions: LanguageVersionDto[];
  durationVersions?: DurationVersionDto[];
  schedules?: ScheduleDto[];
  order?: number | null;
  createdAt?: string;
  updatedAt?: string;
  entityState?: EntityStateDto[];
}
```

### ServiceConfigurationDto

```typescript
interface ServiceConfigurationDto {
  object?: 'ServiceConfigurationDto';
  duration?: DurationConfigurationDto;
}
```

### DurationConfigurationDto

```typescript
interface DurationConfigurationDto {
  object?: 'DurationConfigurationDto';
  durationVersionType: DurationVersionTypeEnum;
}
```

### PresentationDto

```typescript
interface PresentationDto {
  object?: 'PresentationDto';
  color?: string;
  media?: MediaDto[];
}
```

### PrepaymentPolicyDto

```typescript
interface PrepaymentPolicyDto {
  object?: 'PrepaymentPolicyDto';
  isRequired: boolean;
  isPercentage?: boolean;
  value?: string;
  minimalCancelTime?: string;
}
```

### DurationVersionDto

```typescript
interface DurationVersionDto {
  object?: 'DurationVersionDto';
  breakInSeconds?: number;
  durationInSeconds: number;
  prices?: PriceDto[];
}
```

### PriceDto

```typescript
interface PriceDto {
  object?: 'PriceDto';
  price: number;
  currency?: CurrencyCodeEnum;
  preferredLanguages?: LanguageCodeEnum[];
}
```

## Enums

### DurationVersionTypeEnum

```typescript
enum DurationVersionTypeEnum {
  FIXED = 'FIXED',
  RANGE = 'RANGE'
}
```

### CurrencyCodeEnum

```typescript
enum CurrencyCodeEnum {
  USD = 'USD',
  EUR = 'EUR',
  GBP = 'GBP',
  // ... other currency codes
}
```

### LanguageCodeEnum

```typescript
enum LanguageCodeEnum {
  en = 'en',
  es = 'es',
  fr = 'fr',
  de = 'de',
  // ... other language codes
}
```

## Error Responses

### Common Error Format

```typescript
interface ApiErrorResponse {
  statusCode: number;
  message: string;
  error: string;
  timestamp: string;
  path: string;
}
```

### Error Status Codes

| Status Code | Error Type            | Description                                       |
| ----------- | --------------------- | ------------------------------------------------- |
| `400`       | Bad Request           | Invalid request data or validation errors         |
| `401`       | Unauthorized          | Missing or invalid authentication token           |
| `403`       | Forbidden             | Insufficient permissions for the operation        |
| `404`       | Not Found             | Service not found                                 |
| `409`       | Conflict              | Service title conflict or business rule violation |
| `422`       | Unprocessable Entity  | Invalid service configuration                     |
| `500`       | Internal Server Error | Unexpected server error                           |

### Example Error Responses

**400 Bad Request - Validation Error:**

```json
{
  "statusCode": 400,
  "message": [
    "languageVersions should not be empty",
    "durationVersions[0].durationInSeconds must be a positive number"
  ],
  "error": "Bad Request",
  "timestamp": "2024-01-25T10:15:30Z",
  "path": "/api/v1/service"
}
```

**404 Not Found:**

```json
{
  "statusCode": 404,
  "message": "Service with ID 64a7b8f123456789abcdef01 not found",
  "error": "Not Found",
  "timestamp": "2024-01-25T10:15:30Z",
  "path": "/api/v1/service/64a7b8f123456789abcdef01"
}
```

**403 Forbidden:**

```json
{
  "statusCode": 403,
  "message": "Insufficient permissions to manage services",
  "error": "Forbidden",
  "timestamp": "2024-01-25T10:15:30Z",
  "path": "/api/v1/service"
}
```

## Business Rules

### Service Creation Rules

1. **Language Versions**: At least one language version is required
2. **Duration Versions**: At least one duration version is required
3. **Pricing**: Each duration version must have at least one price
4. **Schedules**: Schedules are optional but if provided must be valid
5. **Order**: Order numbers must be unique within tenant

### Service Update Rules

1. **Immutable Fields**: Service ID cannot be changed
2. **Language Versions**: Cannot remove all language versions
3. **Duration Versions**: Cannot remove all duration versions
4. **Active Orders**: Cannot delete services with active orders
5. **Media**: Media files must be valid image formats

### Validation Rules

1. **Duration**: Duration must be positive integer in seconds
2. **Price**: Price must be positive number
3. **Color**: Must be valid hex color code
4. **Schedule Times**: Start time must be before end time
5. **Prepayment**: Percentage values must be 0-100

## Permission Requirements

All service management operations require appropriate permissions:

* **READ\_SERVICE**: View service information
* **CREATE\_SERVICE**: Create new services
* **EDIT\_SERVICE**: Update existing services
* **DELETE\_SERVICE**: Delete services
* **MANAGE\_SERVICE\_MEDIA**: Upload/delete service media

## Rate Limiting

* **Read Operations**: 100 requests per minute
* **Write Operations**: 30 requests per minute
* **Media Upload**: 10 requests per minute

## Caching

* **Service Lists**: Cached for 5 minutes
* **Individual Services**: Cached for 15 minutes
* **Cache Invalidation**: Automatic on service updates

## Integration Examples

### JavaScript/TypeScript

```typescript
// Create service
const serviceData = {
  languageVersions: [
    {
      language: 'en',
      title: 'Massage Therapy',
      description: 'Relaxing massage therapy session'
    }
  ],
  durationVersions: [
    {
      durationInSeconds: 3600,
      prices: [{ price: 60, currency: 'USD' }]
    }
  ]
};

const response = await fetch('/api/v1/service', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${token}`,
    'x-business-tenant-id': tenantId,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(serviceData)
});

const createdService = await response.json();
```

### cURL Examples

```bash
# Get paged services
curl -X GET "https://api.beeoclock.com/api/v1/service/paged?page=1&size=10" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "x-business-tenant-id: YOUR_TENANT_ID"

# Create service
curl -X POST "https://api.beeoclock.com/api/v1/service" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "x-business-tenant-id: YOUR_TENANT_ID" \
  -H "Content-Type: application/json" \
  -d '{
    "languageVersions": [
      {
        "language": "en",
        "title": "Haircut",
        "description": "Professional haircut service"
      }
    ],
    "durationVersions": [
      {
        "durationInSeconds": 1800,
        "prices": [{"price": 30, "currency": "USD"}]
      }
    ]
  }'

# Update service
curl -X PUT "https://api.beeoclock.com/api/v1/service/SERVICE_ID" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "x-business-tenant-id: YOUR_TENANT_ID" \
  -H "Content-Type: application/json" \
  -d '{"order": 2}'

# Delete service
curl -X DELETE "https://api.beeoclock.com/api/v1/service/SERVICE_ID" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "x-business-tenant-id: YOUR_TENANT_ID"
```


# Interface Documentation

## Overview

This document provides comprehensive TypeScript interface definitions, DTOs, enums, and contracts used throughout the Service Management module. The service management system handles bookable services with complex configuration options, multilingual support, and flexible pricing models.

## Core Data Transfer Objects (DTOs)

### ServiceDto

The main service data transfer object containing all service information.

```typescript
interface ServiceDto extends BaseEntityDto {
  object?: 'ServiceDto';
  configuration?: ServiceConfigurationDto;
  presentation?: PresentationDto;
  prepaymentPolicy?: PrepaymentPolicyDto;
  languageVersions: LanguageVersionDto[];
  durationVersions?: DurationVersionDto[];
  schedules?: ScheduleDto[];
  order?: number | null;
}
```

**Properties:**

* `object`: Object type identifier for serialization
* `configuration`: Service configuration settings
* `presentation`: Visual presentation and branding
* `prepaymentPolicy`: Payment requirements and policies
* `languageVersions`: Service details in multiple languages (required)
* `durationVersions`: Available duration and pricing options
* `schedules`: Available time slots and scheduling rules
* `order`: Display order for service listing

### ServiceConfigurationDto

Configuration settings that define service behavior.

```typescript
interface ServiceConfigurationDto {
  object?: 'ServiceConfigurationDto';
  duration?: DurationConfigurationDto;
}
```

**Properties:**

* `duration`: Duration configuration options

### DurationConfigurationDto

Defines how service duration is managed.

```typescript
interface DurationConfigurationDto {
  object?: 'DurationConfigurationDto';
  durationVersionType: DurationVersionTypeEnum;
}
```

**Properties:**

* `durationVersionType`: Type of duration configuration (RANGE, VARIABLE)

### PresentationDto

Visual presentation and media configuration.

```typescript
interface PresentationDto {
  object?: 'PresentationDto';
  banners: MediaDto[];
  color?: string | null;
}
```

**Properties:**

* `banners`: Array of banner images and media
* `color`: Hex color code or color name for theming

### PrepaymentPolicyDto

Payment policy and prepayment requirements.

```typescript
interface PrepaymentPolicyDto {
  object?: 'PrepaymentPolicyDto';
  isRequired: boolean;
  isPercentage?: boolean;
  value?: string;
  minimalCancelTime?: string;
}
```

**Properties:**

* `isRequired`: Whether prepayment is mandatory
* `isPercentage`: Whether value is percentage or fixed amount
* `value`: Prepayment amount or percentage
* `minimalCancelTime`: Minimum cancellation time in seconds

### DurationVersionDto

Specific duration option with pricing.

```typescript
interface DurationVersionDto {
  object?: 'DurationVersionDto';
  breakInSeconds?: number;
  durationInSeconds: number;
  prices?: PriceDto[];
}
```

**Properties:**

* `breakInSeconds`: Break time after service completion
* `durationInSeconds`: Service duration in seconds (required)
* `prices`: Available pricing options for this duration

### PriceDto

Pricing information for services.

```typescript
interface PriceDto {
  object?: 'PriceDto';
  price: number;
  currency?: CurrencyCodeEnum;
  preferredLanguages?: LanguageCodeEnum[];
}
```

**Properties:**

* `price`: Price amount (required)
* `currency`: Currency code (default: USD)
* `preferredLanguages`: Languages this price applies to

### ServicePaginationDto

Pagination parameters for service listing.

```typescript
interface ServicePaginationDto extends PaginationDto {
  phrase?: string;
}
```

**Properties:**

* `phrase`: Search phrase for filtering services by title or description
* Inherits: `page`, `size` from `PaginationDto`

### PublicServiceDto

Public-facing service information (limited data for client apps).

```typescript
interface PublicServiceDto {
  _id?: string;
  object?: 'PublicServiceDto';
  languageVersions: LanguageVersionDto[];
  durationVersions?: DurationVersionDto[];
  presentation?: PresentationDto;
  schedules?: ScheduleDto[];
  order?: number | null;
}
```

**Properties:**

* Contains only public information (no internal configuration)
* Used for customer-facing service displays

### RequestPublicServiceDto

Service data used in public order creation.

```typescript
interface RequestPublicServiceDto {
  _id: string;
  object?: 'RequestPublicServiceDto';
  languageVersions: LanguageVersionDto[];
  durationVersions?: DurationVersionDto[];
  presentation?: PresentationDto;
}
```

**Properties:**

* Service snapshot for order processing
* Immutable service data preserved in orders

## Domain Interfaces

### IService

Core service domain interface.

```typescript
interface IService extends IBase {
  presentation: IPresentation;
  configuration?: IServiceConfiguration;
  prepaymentPolicy: IPaymentPolicy;
  schedules?: ISchedule[];
  languageVersions: ILanguageVersion[];
  durationVersions: IDurationVersion[];
  specialists?: ISpecialist[];
  requiredResources?: IRequiredResource[];
  createdAt?: string;
  updatedAt?: string;
  order?: number | null;
}
```

**Properties:**

* Extends `IBase` for common entity properties
* Contains all service domain properties
* Used for domain logic and validation

### IPresentation

Presentation value object interface.

```typescript
interface IPresentation {
  color?: string;
  banners: IMedia[];
}
```

**Properties:**

* `color`: Hex color or color name for theming
* `banners`: Array of media items for service display

### IDurationVersion

Duration version value object interface.

```typescript
interface IDurationVersion {
  breakInSeconds: number;
  durationInSeconds: number;
  prices: IPrice[];
}
```

**Properties:**

* `breakInSeconds`: Break time after service
* `durationInSeconds`: Service duration
* `prices`: Array of pricing options

### IServiceConfiguration

Service configuration value object interface.

```typescript
interface IServiceConfiguration {
  duration?: IDurationConfiguration;
}
```

**Properties:**

* `duration`: Duration-related configuration

### IPaymentPolicy

Payment policy value object interface.

```typescript
interface IPaymentPolicy {
  isRequired: boolean;
  isPercentage?: boolean;
  value?: string;
  minimalCancelTime?: string;
}
```

**Properties:**

* Defines prepayment requirements and cancellation policies

### IPrice

Price value object interface.

```typescript
interface IPrice {
  price: number;
  currency: CurrencyCodeEnum;
  preferredLanguages?: LanguageCodeEnum[];
}
```

**Properties:**

* `price`: Numeric price value
* `currency`: Currency code for the price
* `preferredLanguages`: Target languages for this price

## Enumerations

### DurationVersionTypeEnum

Defines how service duration is handled.

```typescript
enum DurationVersionTypeEnum {
  RANGE = 'RANGE',
  VARIABLE = 'VARIABLE'
}
```

**Values:**

* `RANGE`: Fixed duration range with breaks
* `VARIABLE`: Variable duration based on customer needs

### CurrencyCodeEnum

ISO 4217 currency codes for pricing.

```typescript
enum CurrencyCodeEnum {
  USD = 'USD',
  EUR = 'EUR', 
  GBP = 'GBP',
  CAD = 'CAD',
  AUD = 'AUD',
  JPY = 'JPY',
  CHF = 'CHF',
  CNY = 'CNY',
  SEK = 'SEK',
  NOK = 'NOK',
  DKK = 'DKK',
  PLN = 'PLN',
  CZK = 'CZK',
  HUF = 'HUF',
  RUB = 'RUB',
  BRL = 'BRL',
  MXN = 'MXN',
  ZAR = 'ZAR',
  INR = 'INR',
  KRW = 'KRW',
  SGD = 'SGD',
  NZD = 'NZD'
}
```

**Usage:**

* Used for pricing in different currencies
* Supports international businesses
* Validates currency format in pricing

### LanguageCodeEnum

ISO 639-1 language codes for internationalization.

```typescript
enum LanguageCodeEnum {
  en = 'en',
  es = 'es', 
  fr = 'fr',
  de = 'de',
  it = 'it',
  pt = 'pt',
  ru = 'ru',
  ja = 'ja',
  ko = 'ko',
  zh = 'zh',
  ar = 'ar',
  hi = 'hi',
  tr = 'tr',
  pl = 'pl',
  nl = 'nl',
  sv = 'sv',
  da = 'da',
  no = 'no',
  fi = 'fi',
  el = 'gr',
  he = 'he',
  th = 'th',
  vi = 'vi',
  cs = 'cs',
  hu = 'hu',
  ro = 'ro',
  sk = 'sk',
  bg = 'bg',
  hr = 'hr',
  sl = 'si',
  et = 'ee',
  lv = 'lv',
  lt = 'lt',
  uk = 'ua',
  ca = 'ca'
}
```

**Usage:**

* Multilingual service descriptions
* Language-specific pricing
* Localized service information

## Shared DTOs and Interfaces

### LanguageVersionDto

Multilingual content structure.

```typescript
interface LanguageVersionDto {
  object?: 'LanguageVersionDto';
  language: LanguageCodeEnum;
  title: string;
  description?: string;
}
```

**Properties:**

* `language`: Language code for this version
* `title`: Service title in specified language
* `description`: Optional detailed description

### MediaDto

Media file information.

```typescript
interface MediaDto extends BaseEntityDto {
  object?: 'MediaDto';
  url?: string;
  mimeType?: string;
  filename?: string;
  size?: number;
  description?: string;
}
```

**Properties:**

* `url`: Media file URL
* `mimeType`: MIME type of the file
* `filename`: Original filename
* `size`: File size in bytes
* `description`: Media description

### ScheduleDto

Service availability schedule.

```typescript
interface ScheduleDto {
  object?: 'ScheduleDto';
  weekDays: number[];
  startTime: string;
  endTime: string;
  timezone?: string;
}
```

**Properties:**

* `weekDays`: Array of weekday numbers (1=Monday, 7=Sunday)
* `startTime`: Start time in HH:mm format
* `endTime`: End time in HH:mm format
* `timezone`: Optional timezone identifier

### RequiredResourceDto

Resource requirements for services.

```typescript
interface RequiredResourceDto {
  object?: 'RequiredResourceDto';
  resourceId: string;
  quantity: number;
  isRequired: boolean;
}
```

**Properties:**

* `resourceId`: Reference to resource entity
* `quantity`: Number of resources needed
* `isRequired`: Whether resource is mandatory

## Validation Constraints

### Service Validation Rules

```typescript
// Service title validation
@IsString()
@IsNotEmpty()
@MaxLength(200)
title: string;

// Service description validation  
@IsString()
@IsOptional()
@MaxLength(2000)
description?: string;

// Duration validation
@IsInt()
@Min(300) // Minimum 5 minutes
@Max(86400) // Maximum 24 hours
durationInSeconds: number;

// Price validation
@IsNumber()
@Min(0)
@Max(999999.99)
price: number;

// Break time validation
@IsInt()
@Min(0)
@Max(3600) // Maximum 1 hour break
breakInSeconds?: number;

// Order validation
@IsInt()
@Min(0)
@IsOptional()
order?: number;

// Color validation
@IsString()
@IsOptional()
@Matches(/^#[0-9A-Fa-f]{6}$|^[a-zA-Z]+$/)
color?: string;
```

### Language Version Validation

```typescript
// At least one language version required
@IsArray()
@ArrayMinSize(1)
@ValidateNested({ each: true })
@Type(() => LanguageVersionDto)
languageVersions: LanguageVersionDto[];

// Language code validation
@IsEnum(LanguageCodeEnum)
language: LanguageCodeEnum;

// Title validation per language
@IsString()
@IsNotEmpty()
@MaxLength(200)
title: string;
```

### Duration Version Validation

```typescript
// At least one duration version for bookable services
@IsArray()
@ArrayMinSize(1)
@ValidateNested({ each: true })
@Type(() => DurationVersionDto)
durationVersions: DurationVersionDto[];

// Duration must be positive
@IsInt()
@Min(1)
durationInSeconds: number;

// At least one price per duration
@IsArray()
@ArrayMinSize(1)
@ValidateNested({ each: true })
@Type(() => PriceDto)
prices: PriceDto[];
```

## Type Guards and Utilities

### Service Type Guards

```typescript
// Check if service is bookable
function isBookableService(service: ServiceDto): boolean {
  return !!(service.durationVersions && service.durationVersions.length > 0);
}

// Check if service has prepayment requirement
function requiresPrepayment(service: ServiceDto): boolean {
  return service.prepaymentPolicy?.isRequired === true;
}

// Check if service has media
function hasMedia(service: ServiceDto): boolean {
  return !!(service.presentation?.banners?.length);
}

// Check if service is multilingual
function isMultilingual(service: ServiceDto): boolean {
  return service.languageVersions.length > 1;
}
```

### Price Utilities

```typescript
// Get price for specific currency
function getPriceForCurrency(
  durationVersion: DurationVersionDto, 
  currency: CurrencyCodeEnum
): PriceDto | undefined {
  return durationVersion.prices?.find(p => p.currency === currency);
}

// Get price for language
function getPriceForLanguage(
  durationVersion: DurationVersionDto,
  language: LanguageCodeEnum
): PriceDto | undefined {
  return durationVersion.prices?.find(
    p => p.preferredLanguages?.includes(language)
  );
}

// Format price for display
function formatPrice(price: PriceDto): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: price.currency || 'USD'
  }).format(price.price);
}
```

### Duration Utilities

```typescript
// Convert seconds to human readable format
function formatDuration(seconds: number): string {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  
  if (hours > 0) {
    return `${hours}h ${minutes}m`;
  }
  return `${minutes}m`;
}

// Calculate total appointment time (duration + break)
function getTotalAppointmentTime(durationVersion: DurationVersionDto): number {
  return durationVersion.durationInSeconds + (durationVersion.breakInSeconds || 0);
}

// Check if duration is valid
function isValidDuration(seconds: number): boolean {
  return seconds >= 300 && seconds <= 86400; // 5 minutes to 24 hours
}
```

## Error Types

### Service-Specific Exceptions

```typescript
// Service not found
interface ServiceNotFoundException {
  name: 'ServiceNotFoundException';
  message: string;
  serviceId: string;
}

// Service creation failure
interface ServiceCreationException {
  name: 'ServiceCreationException';  
  message: string;
  validationErrors: string[];
}

// Service update failure
interface ServiceUpdationException {
  name: 'ServiceUpdationException';
  message: string;
  serviceId: string;
  validationErrors: string[];
}

// Service deletion failure
interface ServiceDeletionException {
  name: 'ServiceDeletionException';
  message: string;
  serviceId: string;
  reason: string;
}
```

### Validation Error Types

```typescript
// Language version validation error
interface LanguageVersionValidationError {
  field: 'languageVersions';
  code: 'INVALID_LANGUAGE_VERSION';
  message: string;
  language?: LanguageCodeEnum;
  index?: number;
}

// Duration version validation error
interface DurationVersionValidationError {
  field: 'durationVersions';
  code: 'INVALID_DURATION_VERSION';
  message: string;
  index?: number;
  durationInSeconds?: number;
}

// Price validation error
interface PriceValidationError {
  field: 'prices';
  code: 'INVALID_PRICE';
  message: string;
  priceIndex?: number;
  currency?: CurrencyCodeEnum;
  value?: number;
}
```

## Constants and Defaults

### Service Constants

```typescript
const SERVICE_CONSTANTS = {
  MIN_DURATION_SECONDS: 300, // 5 minutes
  MAX_DURATION_SECONDS: 86400, // 24 hours
  MAX_BREAK_SECONDS: 3600, // 1 hour
  MAX_TITLE_LENGTH: 200,
  MAX_DESCRIPTION_LENGTH: 2000,
  DEFAULT_CURRENCY: CurrencyCodeEnum.USD,
  DEFAULT_LANGUAGE: LanguageCodeEnum.en,
  MAX_PRICE: 999999.99,
  MIN_PRICE: 0,
  MAX_MEDIA_SIZE: 10485760, // 10MB
  ALLOWED_MEDIA_TYPES: ['image/jpeg', 'image/png', 'image/webp'],
  DEFAULT_DURATION_TYPE: DurationVersionTypeEnum.RANGE
} as const;
```

### Default Service Template

```typescript
const DEFAULT_SERVICE_TEMPLATE: Partial<ServiceDto> = {
  object: 'ServiceDto',
  configuration: {
    duration: {
      durationVersionType: DurationVersionTypeEnum.RANGE
    }
  },
  prepaymentPolicy: {
    isRequired: false
  },
  presentation: {
    banners: [],
    color: '#007bff'
  },
  languageVersions: [],
  durationVersions: [],
  schedules: [],
  order: null
};
```

## Integration Patterns

### Repository Interface

```typescript
interface IServiceRepository {
  findById(id: string): Promise<IService | null>;
  findByTenant(tenantId: string): Promise<IService[]>;
  findPaged(tenantId: string, pagination: ServicePaginationDto): Promise<PaginatedResult<IService>>;
  create(service: IService): Promise<string>;
  update(id: string, service: Partial<IService>): Promise<void>;
  delete(id: string): Promise<number>;
  search(tenantId: string, phrase: string): Promise<IService[]>;
}
```

### Mapper Interface

```typescript
interface IServiceMapper {
  toDtoFromPersistence(service: IService): ServiceDto;
  toPersistenceFromDto(dto: ServiceDto): IService;
  toPublicDto(service: IService): PublicServiceDto;
  toRequestDto(service: IService): RequestPublicServiceDto;
}
```

### Event Interfaces

```typescript
// Service created event
interface ServiceCreatedEvent {
  type: 'SERVICE_CREATED';
  tenantId: string;
  serviceId: string;
  service: ServiceDto;
  timestamp: string;
}

// Service updated event  
interface ServiceUpdatedEvent {
  type: 'SERVICE_UPDATED';
  tenantId: string;
  serviceId: string;
  previousService: ServiceDto;
  updatedService: ServiceDto;
  timestamp: string;
}

// Service deleted event
interface ServiceDeletedEvent {
  type: 'SERVICE_DELETED';
  tenantId: string;
  serviceId: string;
  service: ServiceDto;
  timestamp: string;
}
```


# 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


# Database Schema

## Overview

The service management module uses MongoDB with Mongoose ODM for data persistence. The schema supports complex service configurations with multilingual content, flexible pricing models, and rich presentation options following Domain-Driven Design principles.

## Core Entities

### Service Entity

**Collection**: `service`

**Schema Definition**: `ServiceSchema`

| Field              | Type                           | Required | Default   | Description                         |
| ------------------ | ------------------------------ | -------- | --------- | ----------------------------------- |
| `_id`              | `ObjectId`                     | Auto     | Generated | Unique identifier                   |
| `presentation`     | `PresentationSchema`           | Yes      | -         | Visual presentation and branding    |
| `configuration`    | `ServiceConfigurationSchema`   | No       | -         | Service behavior configuration      |
| `prepaymentPolicy` | `PaymentPolicySchema`          | Yes      | -         | Payment requirements and policies   |
| `schedules`        | `Array<ScheduleSchema>`        | No       | `[]`      | Available time slots and scheduling |
| `languageVersions` | `Array<LanguageVersionSchema>` | Yes      | -         | Multilingual service descriptions   |
| `durationVersions` | `Array<DurationVersionSchema>` | Yes      | -         | Duration options with pricing       |
| `specialists`      | `Array<SpecialistSchema>`      | No       | `[]`      | Assigned specialists (migration)    |
| `order`            | `Number`                       | No       | `null`    | Display order for service listing   |
| `stateHistory`     | `Array<StateHistorySchema>`    | No       | `[]`      | State change tracking               |
| `createdAt`        | `Date`                         | Auto     | Current   | Creation timestamp                  |
| `updatedAt`        | `Date`                         | Auto     | Current   | Last update timestamp               |

### Service Business Rules

1. **Language Versions**: At least one language version required
2. **Duration Versions**: At least one duration version required for bookable services
3. **Presentation**: Must include valid presentation configuration
4. **Prepayment Policy**: Required for all services
5. **Order Uniqueness**: Order numbers should be unique within tenant

## Sub-Schemas

### Presentation Schema (`PresentationSchema`)

**Purpose**: Manages visual presentation, branding, and media for services.

| Field     | Type              | Required | Default | Description                  |
| --------- | ----------------- | -------- | ------- | ---------------------------- |
| `banners` | `Array<ObjectId>` | No       | `[]`    | References to Media entities |
| `color`   | `String`          | No       | -       | Hex color code or color name |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: true` - Tracks presentation changes
* `ref: Media.name` - References Media collection

**Business Rules**:

* Color must be valid hex format or recognized color name
* Banners reference valid media files
* Media files must be image format (JPEG, PNG, WebP)
* Maximum file size enforcement at application level

### Service Configuration Schema (`ServiceConfigurationSchema`)

**Purpose**: Defines service behavior and operational settings.

| Field      | Type                          | Required | Default | Description                    |
| ---------- | ----------------------------- | -------- | ------- | ------------------------------ |
| `duration` | `DurationConfigurationSchema` | No       | -       | Duration-related configuration |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: true` - Tracks configuration changes

### Duration Configuration Schema (`DurationConfigurationSchema`)

**Purpose**: Configures how service duration is managed and presented.

| Field                 | Type     | Required | Default | Description                 |
| --------------------- | -------- | -------- | ------- | --------------------------- |
| `durationVersionType` | `String` | Yes      | -       | Duration configuration type |

**Enum Values**:

* `RANGE`: Fixed duration with optional breaks
* `VARIABLE`: Variable duration based on customer needs

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps

### Payment Policy Schema (`PaymentPolicySchema`)

**Purpose**: Defines payment requirements and cancellation policies.

| Field               | Type      | Required | Default | Description                          |
| ------------------- | --------- | -------- | ------- | ------------------------------------ |
| `isRequired`        | `Boolean` | Yes      | -       | Whether prepayment is mandatory      |
| `isPercentage`      | `Boolean` | No       | -       | Whether value is percentage or fixed |
| `value`             | `String`  | No       | -       | Prepayment amount or percentage      |
| `minimalCancelTime` | `String`  | No       | -       | Minimum cancellation time in seconds |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps

**Business Rules**:

* When `isRequired: true`, value should be provided
* Percentage values must be 0-100
* Cancellation time must be positive integer
* Value stored as string for precision

### Duration Version Schema (`DurationVersionSchema`)

**Purpose**: Defines specific duration options with associated pricing.

| Field               | Type                 | Required | Default | Description                         |
| ------------------- | -------------------- | -------- | ------- | ----------------------------------- |
| `breakInSeconds`    | `Number`             | No       | -       | Break time after service completion |
| `durationInSeconds` | `Number`             | Yes      | -       | Service duration in seconds         |
| `prices`            | `Array<PriceSchema>` | No       | `[]`    | Available pricing options           |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps

**Validation Rules**:

* Duration must be positive integer
* Break time cannot be negative
* At least one price should be provided for bookable services
* Duration should be reasonable (5 minutes to 24 hours)

### Price Schema (`PriceSchema`)

**Purpose**: Defines pricing information with currency and language targeting.

| Field                | Type            | Required | Default | Description                     |
| -------------------- | --------------- | -------- | ------- | ------------------------------- |
| `price`              | `Number`        | Yes      | -       | Price amount                    |
| `currency`           | `String`        | No       | `USD`   | ISO 4217 currency code          |
| `preferredLanguages` | `Array<String>` | No       | `[]`    | Target languages for this price |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: true` - Tracks price changes
* `enum: CurrencyCodeEnum` - Validates currency codes
* `enum: LanguageCodeEnum` - Validates language codes

**Validation Rules**:

* Price must be positive number
* Currency must be valid ISO 4217 code
* Languages must be valid ISO 639-1 codes
* Supports decimal precision for pricing

## Shared Schemas

### Language Version Schema (`LanguageVersionSchema`)

**Purpose**: Provides multilingual content support for services.

| Field         | Type     | Required | Default | Description                               |
| ------------- | -------- | -------- | ------- | ----------------------------------------- |
| `language`    | `String` | Yes      | -       | ISO 639-1 language code                   |
| `title`       | `String` | Yes      | -       | Service title in specified language       |
| `description` | `String` | No       | -       | Service description in specified language |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps
* `enum: LanguageCodeEnum` - Validates language codes

**Business Rules**:

* At least one language version required per service
* Title is mandatory for each language
* Description is optional but recommended
* Language codes must be unique within service

### Schedule Schema (`ScheduleSchema`)

**Purpose**: Defines service availability and scheduling rules.

| Field       | Type            | Required | Default | Description                             |
| ----------- | --------------- | -------- | ------- | --------------------------------------- |
| `weekDays`  | `Array<Number>` | Yes      | -       | Available weekdays (1=Monday, 7=Sunday) |
| `startTime` | `String`        | Yes      | -       | Start time in HH:mm format              |
| `endTime`   | `String`        | Yes      | -       | End time in HH:mm format                |
| `timezone`  | `String`        | No       | -       | Timezone identifier                     |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - No automatic timestamps

**Validation Rules**:

* Week days must be 1-7
* Times must be valid HH:mm format
* End time must be after start time
* Timezone must be valid identifier

### State History Schema (`StateHistorySchema`)

**Purpose**: Tracks state changes for audit and rollback capabilities.

| Field       | Type       | Required | Default | Description                   |
| ----------- | ---------- | -------- | ------- | ----------------------------- |
| `state`     | `String`   | Yes      | -       | State identifier              |
| `timestamp` | `Date`     | Yes      | Current | When state change occurred    |
| `actor`     | `ObjectId` | No       | -       | Who made the change           |
| `metadata`  | `Object`   | No       | -       | Additional change information |

**Configuration**:

* `_id: false` - No separate ID for sub-document
* `timestamps: false` - Uses explicit timestamp field

## Relationships

### Service → Media (Banners)

* **Type**: One-to-Many
* **Field**: `presentation.banners`
* **Collection**: `media`
* **Description**: References uploaded banner images

### Service → Specialists

* **Type**: Many-to-Many
* **Field**: `specialists`
* **Collection**: `specialist`
* **Description**: Assigned service providers (migration field)

### Service → Required Resources

* **Type**: Many-to-Many (via separate collection)
* **Field**: Not directly in schema
* **Collection**: `service-required-resources`
* **Description**: Resources needed for service delivery

## Indexes

### Primary Indexes

```javascript
// Compound index for tenant-based queries
{ "_tenantId": 1, "createdAt": -1 }

// Order for display sorting
{ "order": 1 }

// Language-based text search
{ 
  "languageVersions.title": "text", 
  "languageVersions.description": "text" 
}

// Price range queries
{ "durationVersions.prices.price": 1 }

// Currency-based filtering
{ "durationVersions.prices.currency": 1 }

// Duration-based queries
{ "durationVersions.durationInSeconds": 1 }
```

### Performance Indexes

```javascript
// Service status and availability
{ "stateHistory.state": 1, "updatedAt": -1 }

// Presentation media queries
{ "presentation.banners": 1 }

// Schedule-based availability
{ 
  "schedules.weekDays": 1, 
  "schedules.startTime": 1, 
  "schedules.endTime": 1 
}

// Configuration type queries
{ "configuration.duration.durationVersionType": 1 }

// Prepayment requirement queries
{ "prepaymentPolicy.isRequired": 1 }
```

### Search Optimization

* **Full-Text Search**: Compound text index on title and description
* **Language-Specific**: Support for language-specific search
* **Price Range**: Efficient price range queries
* **Duration Filtering**: Quick duration-based filtering
* **Availability**: Schedule-based availability queries

## Data Integrity

### Validation Rules

1. **Required Fields**: Language versions and duration versions mandatory
2. **Format Validation**: Times, currencies, languages follow standards
3. **Business Logic**: Duration and pricing constraints
4. **Reference Integrity**: Media and specialist references valid
5. **Range Validation**: Reasonable limits on duration and pricing

### Constraints

1. **Unique Constraints**: Order numbers unique per tenant
2. **Referential Integrity**: Media references must exist
3. **Business Rules**: Prepayment policies consistent
4. **Data Consistency**: Language versions complete

### Migration Considerations

1. **Schema Evolution**: Backwards compatibility for schema changes
2. **Data Migration**: Scripts for structural changes
3. **Index Management**: Efficient index creation and updates
4. **Legacy Support**: Support for old data formats

## Multi-Tenancy

### Tenant Isolation

* Services belong to specific tenants
* Queries include tenant context automatically
* Cross-tenant access prevention
* Tenant-specific indexing strategies

### Tenant-Aware Operations

All database operations include tenant context:

* Create operations include tenant ID
* Read operations filter by tenant
* Update/Delete operations validate tenant ownership
* Aggregation queries include tenant filtering

## Performance Optimization

### Query Performance

1. **Index Utilization**: Proper index design for common queries
2. **Aggregation Pipelines**: Efficient complex queries
3. **Projection**: Return only needed fields
4. **Population Strategy**: Optimize related data loading

### Storage Optimization

1. **Document Size**: Reasonable document size limits
2. **Embedded vs Referenced**: Optimal data structure design
3. **Compression**: MongoDB compression for storage efficiency
4. **Archive Strategy**: Archive old service versions

### Caching Strategy

1. **Query Caching**: Cache frequent service queries
2. **Computed Fields**: Cache calculated values
3. **Invalidation**: Smart cache invalidation on updates
4. **Distributed Caching**: Multi-instance cache coordination

## Backup and Recovery

### Backup Strategy

1. **Document Integrity**: Complete service data backup
2. **Media Coordination**: Sync with media storage backup
3. **Index Preservation**: Recreate indexes after restore
4. **Relationship Consistency**: Maintain reference integrity

### Recovery Procedures

1. **Point-in-Time Recovery**: Restore to specific timestamps
2. **Selective Recovery**: Restore individual services
3. **Data Validation**: Verify data integrity after restore
4. **Index Rebuilding**: Recreate performance indexes

## Security Considerations

### Data Protection

1. **Access Control**: Role-based database access
2. **Encryption**: Encryption at rest and in transit
3. **Audit Logging**: Track all data modifications
4. **PII Handling**: Secure handling of service descriptions

### Query Security

1. **Injection Prevention**: Parameterized queries
2. **Access Validation**: Tenant-aware query filtering
3. **Resource Limits**: Query execution time limits
4. **Rate Limiting**: Database operation rate limiting

## Monitoring and Maintenance

### Performance Monitoring

1. **Query Performance**: Slow query detection and optimization
2. **Index Usage**: Monitor index effectiveness
3. **Storage Growth**: Track collection size growth
4. **Cache Hit Rates**: Monitor caching effectiveness

### Maintenance Tasks

1. **Index Optimization**: Regular index analysis and tuning
2. **Data Archiving**: Archive old service versions
3. **Statistics Updates**: Keep query optimizer statistics current
4. **Cleanup Operations**: Remove orphaned references

## Development Guidelines

### Schema Design

1. **Normalization**: Balance between normalization and performance
2. **Embedding Strategy**: When to embed vs reference
3. **Index Strategy**: Design indexes for query patterns
4. **Validation**: Comprehensive schema validation

### Testing Strategies

1. **Unit Tests**: Test schema validation rules
2. **Integration Tests**: Test with real MongoDB instance
3. **Performance Tests**: Load test with realistic data
4. **Migration Tests**: Validate schema migration scripts

### Best Practices

1. **Document Size**: Keep documents under MongoDB limits
2. **Query Patterns**: Design schema for common queries
3. **Update Patterns**: Minimize document rewrites
4. **Consistency**: Maintain referential integrity


# Customer and Order

Customer and Order Data Structure Documentation


