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

# 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.md) to understand available endpoints and how to interact with the absence management system.

### 2. Integration

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

### 3. Business Logic

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

### 4. Data Layer

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

## Documentation Structure

| Document                                                             | Purpose                                                         | Audience                              |
| -------------------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------- |
| [API Documentation](/services/absence-management/api.md)             | REST API reference with endpoints, authentication, and examples | Frontend developers, API consumers    |
| [Interface Documentation](/services/absence-management/interface.md) | TypeScript interfaces, DTOs, and contracts                      | Backend developers, integration teams |
| [Use Case Documentation](/services/absence-management/usecase.md)    | Business logic, workflows, and application layer                | Backend developers, business analysts |
| [Database Schema](/services/absence-management/db_schema.md)         | 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.*
