# Calendar Management Module

This module provides comprehensive calendar management functionality for the ACoreX Platform, enabling administrators to define, manage, and configure calendar systems with support for multiple calendar types, inheritance, special days, and scoping.

## 🎯 **Core Features**

### **Calendar System**

- **Multiple Calendar Types**: Support for Gregorian, Persian (Jalali), Hijri (Islamic), Chinese, Hebrew, and custom calendar systems
- **Calendar Inheritance**: Hierarchical calendar structure where child calendars inherit from parent calendars
- **No Inheritance Depth Limit**: Unlimited levels of calendar inheritance for complex organizational structures
- **Weekend Configuration**: Flexible weekend patterns (Friday-Saturday, Saturday-Sunday, etc.)
- **Working Hours Management**: Configurable working hours per calendar with daily granularity

### **Date Exception Management**

- **Special Days**: Define holidays, workdays, half-days, events, maintenance days, and deadlines
- **Recurrence Rules**: Support for recurring events with complex patterns
- **Override System**: Child calendars can override parent calendar exceptions
- **Priority-based Resolution**: Conflict resolution using priority system
- **Time Granularity**: Full-day or time-specific exceptions

### **Scoping System**

- **Multi-level Scoping**: Platform, tenant, division, and user-level calendars
- **Scope Permissions**: Granular permission system for calendar access
- **Inheritance Control**: Override capabilities at each scope level

## 📚 **Architecture**

### **Entity Structure**

```
Calendar (Main Entity - Hierarchical)
├── CalendarType (Lookup)
├── DateException (Related)
│   └── RecurrenceRule (Related)
└── CalendarScope (Related)
```

### **Core Entities**

#### **1. Calendar (Main Entity)**

The primary entity representing calendar systems with inheritance support.

**Key Properties:**

- `name`: Unique calendar identifier
- `title`: Display name
- `calendarTypeId`: Calendar system type
- `parentId`: Parent calendar for inheritance
- `scopeType`: Application scope (platform/tenant/division/user)
- `weekendPattern`: Array of weekend days
- `workingHours`: JSON configuration of daily working hours
- `isTemplate`: Can be used as base for other calendars

#### **2. CalendarType (Lookup Entity)**

Defines different calendar system types.

**Key Properties:**

- `title`: Calendar type name
- `code`: System code (gregorian, persian, hijri, etc.)
- `isDefault`: Default calendar type flag

#### **3. DateException (Related Entity)**

Manages special days and exceptions in calendars.

**Key Properties:**

- `calendarId`: Parent calendar reference
- `date`: Exception date
- `exceptionType`: Type of exception (holiday, workday, etc.)
- `isRecurring`: Whether exception repeats
- `overridesParent`: Overrides parent calendar exception
- `priority`: Conflict resolution priority

#### **4. RecurrenceRule (Related Entity)**

Defines recurring patterns for date exceptions.

**Key Properties:**

- `frequency`: Recurrence frequency (daily, weekly, monthly, yearly)
- `interval`: Interval between occurrences
- `endDate`: End date for recurrence
- `byDay`: Day-based rules
- `byMonth`: Month-based rules

#### **5. CalendarScope (Related Entity)**

Manages calendar access and permissions by scope.

**Key Properties:**

- `calendarId`: Calendar reference
- `scopeType`: Scope level
- `scopeEntityId`: Entity ID within scope
- `permissions`: Access permissions

## 🔧 **Configuration Examples**

### **Basic Calendar Setup**

```typescript
// Create a base Persian calendar
const iranNationalCalendar = {
  name: 'iran-national',
  title: 'Iran National Calendar',
  calendarTypeId: 'persian-type-id',
  scopeType: 'platform',
  weekendPattern: ['friday'],
  isTemplate: true,
  isActive: true,
};

// Create company calendar inheriting from national
const companyCalendar = {
  name: 'company-calendar',
  title: 'Company Calendar',
  calendarTypeId: 'persian-type-id',
  parentId: iranNationalCalendar.id,
  scopeType: 'tenant',
  scopeEntityId: 'company-tenant-id',
  weekendPattern: ['friday', 'saturday'], // Override weekend
};
```

### **Date Exception Configuration**

```typescript
// Recurring holiday (Nowruz)
const nowruzException = {
  calendarId: iranNationalCalendar.id,
  date: new Date('2024-03-20'),
  exceptionType: 'holiday',
  title: 'Nowruz',
  isRecurring: true,
  recurrenceRuleId: 'yearly-march-20-rule',
  isAllDay: true,
  priority: 1,
};

// Company-specific working day override
const companyWorkday = {
  calendarId: companyCalendar.id,
  date: new Date('2024-03-21'), // Normally holiday
  exceptionType: 'workday',
  title: 'Special Working Day',
  overridesParent: true,
  isAllDay: false,
  startTime: '09:00',
  endTime: '13:00',
  priority: 2,
};
```

## 🚀 **Usage**

### **Module Installation**

```typescript
import { AXMCalendarManagementModule } from '@acorex/modules/calendar-management';

@NgModule({
  imports: [
    AXMCalendarManagementModule,
    // other modules
  ],
})
export class AppModule {}
```

### **Service Usage**

```typescript
import { Injectable } from '@angular/core';
import { AXMEntityCrudServiceImpl } from '@acorex/platform/layout/entity';
import { RootConfig, AXMCalendarManagementCalendarEntityModel } from '@acorex/modules/calendar-management';

@Injectable()
export class CalendarBusinessService {
  private calendarService = new AXMEntityCrudServiceImpl<string, AXMCalendarManagementCalendarEntityModel>(
    `${RootConfig.module.name}.${RootConfig.entities.calendar.name}`
  );

  async getEffectiveCalendar(calendarId: string): Promise<AXMCalendarManagementCalendarEntityModel> {
    // Gets calendar with resolved inheritance
    return await this.calendarService.getOne(calendarId);
  }

  async isWorkingDay(calendarId: string, date: Date): Promise<boolean> {
    // Business logic to determine if date is working day
    // considering calendar hierarchy and exceptions
  }
}
```

## 🌍 **Internationalization**

The module includes complete translations for:

- **English (en-US)**: Full UI translations
- **Persian (fa-IR)**: Native Persian translations

Translation files are located in:

- `apps/demo/src/assets/i18n/en-US/calendar-management.json`
- `apps/demo/src/assets/i18n/fa-IR/calendar-management.json`

## 🔐 **Permissions**

Granular permission system includes:

- `calendar.view`: View calendars
- `calendar.create`: Create new calendars
- `calendar.update`: Modify existing calendars
- `calendar.delete`: Delete calendars
- `calendar-type.manage`: Manage calendar types
- `date-exception.*`: Date exception permissions
- `calendar.admin`: Full administrative access

## 📋 **Admin UI Features**

### **Calendar Management**

- List view with hierarchical display
- Create/Edit calendar with inheritance dropdown
- Preview effective calendar (merged view from parent)
- Scope-based filtering and access control

### **Date Exception Management**

- Calendar-specific date exception management
- Recurring pattern configuration
- Visual calendar view with exceptions highlighted
- Override conflict resolution interface

### **Calendar Resolution**

When fetching calendar data, the system resolves inheritance recursively:

```
Base Calendar → Parent Calendar → Current Calendar → Final Merged View
```

Child calendars override parent settings for specific dates, providing flexible calendar customization while maintaining consistency through inheritance.

## 🤝 **Contributing**

When extending this module:

1. **Follow ACoreX entity patterns** for consistency
2. **Add comprehensive tests** for calendar resolution logic
3. **Update translations** for new features
4. **Consider backward compatibility** when modifying inheritance logic
5. **Document complex business rules** in code comments

## 📝 **Future Enhancements**

Planned features include:

- **Time Zone Support**: Multi-timezone calendar management
- **Calendar Templates**: Pre-built calendar templates for different regions
- **Import/Export**: ICS/CSV support for external calendar integration
- **Calendar Visualization**: Interactive calendar view components
- **Notification System**: Alerts for upcoming important dates
- **Calendar Analytics**: Usage and exception statistics

---

> 💡 **Note**: This module is designed to be a comprehensive calendar management solution for enterprise applications requiring complex calendar hierarchies and multi-cultural calendar support.
