> For the complete documentation index, see [llms.txt](https://docs.beeoclock.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.beeoclock.com/services/expense-management.md).

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

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

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

## 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.md) - Comprehensive API endpoint documentation
* [Interface Documentation](/services/expense-management/interface.md) - Domain interfaces and contracts
* [Use Case Documentation](/services/expense-management/usecase.md) - Business use case implementations
* [Database Schema](/services/expense-management/db_schema.md) - 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.
