# Leave Management Module

## Overview

The Leave Management module provides comprehensive leave tracking and approval workflows, including leave balance management, calendar views, and integration with attendance and payroll systems.

---

## Features

### Core Functionality
- ✅ Multiple leave types (Annual, Sick, Casual, Maternity, Paternity, Unpaid)
- ✅ Leave request submission and approval workflow
- ✅ Leave balance tracking per employee
- ✅ Leave calendar view with FullCalendar
- ✅ Color-coded leave types
- ✅ Manager approval system
- ✅ Leave balance carry-forward
- ✅ Leave reports and analytics
- ✅ Email notifications
- ✅ Leave history tracking
- ✅ Bulk leave allocation

---

## Leave Types

### Standard Leave Types

1. **Annual Leave**
   - Paid time off for vacation
   - Typically 21 days per year (Kenya standard)
   - Can be carried forward (configurable)
   - Requires advance notice

2. **Sick Leave**
   - For illness or medical appointments
   - Typically 14 days per year
   - May require medical certificate
   - Short notice acceptable

3. **Casual Leave**
   - For personal matters
   - Short-term leave (1-3 days)
   - Limited annual allocation
   - Minimal notice required

4. **Maternity Leave**
   - For expectant mothers
   - 90 days (Kenya standard)
   - Paid leave
   - Medical certificate required

5. **Paternity Leave**
   - For new fathers
   - 14 days (Kenya standard)
   - Paid leave
   - Birth certificate required

6. **Unpaid Leave**
   - Extended leave without pay
   - No balance limit
   - Requires approval
   - Affects payroll

7. **Compassionate Leave**
   - For family emergencies
   - Bereavement leave
   - Limited days per year
   - Documentation may be required

8. **Study Leave**
   - For educational purposes
   - May be paid or unpaid
   - Requires proof of enrollment
   - Long-term planning

---

## Leave Workflow

### Leave Request Lifecycle

```
┌──────────────┐
│    Draft     │ ──► Employee creates leave request
└──────┬───────┘
       │
       ▼
┌──────────────┐
│   Pending    │ ──► Submitted, awaiting approval
└──────┬───────┘
       │
       ├──────► Approved ──► Leave granted
       │
       └──────► Rejected ──► Leave denied
       
       ▼ (After approval)
┌──────────────┐
│   Active     │ ──► Leave period started
└──────┬───────┘
       │
       ▼
┌──────────────┐
│  Completed   │ ──► Leave period ended
└──────────────┘
       │
       ▼ (Alternative)
┌──────────────┐
│  Cancelled   │ ──► Cancelled by employee/admin
└──────────────┘
```

---

## Leave Balance Management

### Balance Calculation

**Annual Allocation**:
```
Annual Leave Balance = Base Allocation + Carried Forward - Used
```

**Example**:
```
Base Allocation: 21 days
Carried Forward: 3 days
Used This Year: 8 days
Current Balance: 21 + 3 - 8 = 16 days
```

### Balance Accrual

**Monthly Accrual** (Optional):
```
Monthly Accrual = Annual Allocation / 12
```

**Example**:
```
Annual Allocation: 21 days
Monthly Accrual: 21 / 12 = 1.75 days per month
After 6 months: 1.75 × 6 = 10.5 days available
```

### Carry Forward Rules

**Configurable Options**:
- Enable/disable carry forward
- Maximum days to carry forward
- Expiry date for carried forward days
- Automatic calculation at year-end

**Example**:
```
Unused Leave: 5 days
Max Carry Forward: 5 days
Carried to Next Year: 5 days

Unused Leave: 8 days
Max Carry Forward: 5 days
Carried to Next Year: 5 days (3 days forfeited)
```

---

## User Interface

### Employee Leave Dashboard

**Access**: Dashboard → Leaves

**Sections**:

1. **Leave Balance Summary**
   ```
   ┌─────────────────────────────────────┐
   │ Annual Leave:    16 days remaining  │
   │ Sick Leave:      12 days remaining  │
   │ Casual Leave:     3 days remaining  │
   │ Maternity Leave:  0 days remaining  │
   └─────────────────────────────────────┘
   ```

2. **Quick Actions**
   ```
   [Apply for Leave] [View Calendar] [Leave History]
   ```

3. **Recent Leave Requests**
   - Status indicators
   - Date ranges
   - Approval status
   - Quick view

### Leave Request Form

**Access**: Leaves → Apply for Leave

**Form Fields**:

1. **Leave Details**
   ```
   - Leave Type * (Dropdown)
   - Start Date * (Date picker)
   - End Date * (Date picker)
   - Number of Days (Auto-calculated)
   - Half Day (Checkbox)
   - Return Date (Auto-calculated)
   ```

2. **Additional Information**
   ```
   - Reason * (Textarea)
   - Contact During Leave (Phone/Email)
   - Emergency Contact
   - Handover Notes
   ```

3. **Attachments**
   ```
   - Supporting Documents (Upload)
   - Medical Certificate (for sick leave)
   - Other Documents
   ```

4. **Balance Check**
   ```
   Current Balance: 16 days
   Requested Days: 5 days
   Remaining Balance: 11 days
   ```

### Leave Calendar View

**Access**: Leaves → Calendar

**Features**:
- Monthly/Weekly/Daily views
- Color-coded leave types
- Team leave visibility
- Public holidays
- Click to view details
- Filter by department/employee
- Export calendar

**Color Scheme**:
```
Annual Leave:      Blue (#007bff)
Sick Leave:        Red (#dc3545)
Casual Leave:      Green (#28a745)
Maternity Leave:   Pink (#e83e8c)
Paternity Leave:   Purple (#6f42c1)
Unpaid Leave:      Gray (#6c757d)
```

### Manager Approval Interface

**Access**: Leaves → Pending Approvals

**Features**:
- List of pending requests
- Employee details
- Leave balance check
- Team calendar view
- Approve/Reject actions
- Bulk approval

**Approval Form**:
```
Employee: John Doe
Leave Type: Annual Leave
Dates: Feb 15 - Feb 19, 2024 (5 days)
Reason: Family vacation
Current Balance: 16 days

Team Impact:
- 2 other team members on leave
- Project deadline: Feb 20, 2024

[Approve] [Reject] [Request More Info]

Approval Notes: (Optional)
```

---

## Leave Types Configuration

**Access**: Settings → Leave Types

**Configurable Parameters**:

1. **Basic Settings**
   ```
   - Leave Type Name
   - Color Code
   - Icon
   - Active/Inactive
   ```

2. **Allocation**
   ```
   - Annual Days
   - Accrual Method (Annual/Monthly)
   - Minimum Service Period
   - Pro-rata for New Joiners
   ```

3. **Rules**
   ```
   - Requires Approval (Yes/No)
   - Approver Level (Manager/HR/Both)
   - Minimum Notice Days
   - Maximum Consecutive Days
   - Allow Half Days
   - Allow Negative Balance
   ```

4. **Carry Forward**
   ```
   - Enable Carry Forward
   - Maximum Days to Carry
   - Expiry Period (months)
   - Auto-calculation
   ```

5. **Documentation**
   ```
   - Require Supporting Documents
   - Document Types
   - Mandatory/Optional
   ```

6. **Payroll Impact**
   ```
   - Paid/Unpaid
   - Affect Salary Calculation
   - Deduction Rules
   ```

---

## Approval Workflow

### Single-Level Approval

**Process**:
1. Employee submits leave request
2. Notification sent to direct manager
3. Manager reviews and approves/rejects
4. Employee notified of decision
5. Leave status updated

### Multi-Level Approval

**Process**:
1. Employee submits leave request
2. Level 1: Direct manager approval
3. Level 2: HR approval (if required)
4. Level 3: Department head (for extended leave)
5. Final approval notification
6. Leave status updated

### Approval Criteria

**Factors Considered**:
- Leave balance availability
- Team coverage
- Project deadlines
- Previous leave patterns
- Notice period compliance
- Supporting documentation

### Delegation

**Features**:
- Managers can delegate approval authority
- Temporary delegation during absence
- Approval history maintained
- Audit trail preserved

---

## Leave Balance Tracking

### Balance Types

1. **Opening Balance**
   - Balance at start of year
   - Includes carried forward days

2. **Accrued Balance**
   - Days earned during year
   - Monthly or annual accrual

3. **Used Balance**
   - Days taken
   - Approved and completed leaves

4. **Pending Balance**
   - Days in pending requests
   - Reserved but not confirmed

5. **Available Balance**
   - Current usable balance
   - Opening + Accrued - Used - Pending

### Balance Adjustment

**Manual Adjustments**:
- HR can adjust balances
- Reasons required
- Audit trail maintained
- Notification to employee

**Adjustment Types**:
- Addition (bonus days, compensation)
- Deduction (policy violation, advance)
- Reset (new year, policy change)
- Transfer (leave type conversion)

---

## Leave Reports

### Available Reports

1. **Employee Leave Summary**
   ```
   Employee: John Doe
   Period: Jan - Dec 2024
   
   Leave Type    | Allocated | Used | Pending | Balance
   --------------|-----------|------|---------|--------
   Annual        | 21        | 8    | 2       | 11
   Sick          | 14        | 3    | 0       | 11
   Casual        | 5         | 2    | 0       | 3
   ```

2. **Department Leave Report**
   - Leave usage by department
   - Comparison across departments
   - Trend analysis

3. **Leave Trends Report**
   - Monthly leave patterns
   - Seasonal trends
   - Peak leave periods
   - Planning insights

4. **Leave Balance Report**
   - All employees' balances
   - Expiring balances
   - Negative balances
   - Carry forward summary

5. **Leave Approval Report**
   - Pending approvals
   - Approval turnaround time
   - Rejection reasons
   - Approval patterns

---

## Integration with Other Modules

### Attendance Integration
- Approved leaves marked in attendance
- Status: "On Leave"
- Not counted as absent
- Automatic attendance update

### Payroll Integration
- Unpaid leave affects salary
- Leave days deducted from payroll
- Pro-rata salary calculation
- Automatic deduction processing

### Calendar Integration
- Leave displayed on organization calendar
- Team availability view
- Resource planning
- Conflict detection

---

## Permissions

### Required Permissions

| Action | Permission | Description |
|--------|-----------|-------------|
| View Own Leaves | Default (All employees) | View personal leave requests |
| Apply for Leave | Default (All employees) | Submit leave requests |
| View Team Leaves | `view_team_leaves` | View team member leaves |
| View All Leaves | `view_all_leaves` | View all employee leaves |
| Approve Leaves | `approve_leaves` | Approve/reject leave requests |
| Manage Leave Types | `manage_leave_types` | Configure leave types |
| Adjust Balances | `adjust_leave_balances` | Manually adjust balances |
| Cancel Leaves | `cancel_leaves` | Cancel approved leaves |
| View Reports | `view_leave_reports` | Access leave reports |

---

## API Endpoints

### Get Leave Balance
```http
GET /leaves/balance/{employee_id}
```

**Response**:
```json
{
  "employee_id": 1,
  "balances": [
    {
      "leave_type": "Annual Leave",
      "allocated": 21,
      "used": 8,
      "pending": 2,
      "available": 11
    }
  ]
}
```

### Submit Leave Request
```http
POST /leaves
```

**Request Body**:
```json
{
  "leave_type_id": 1,
  "start_date": "2024-02-15",
  "end_date": "2024-02-19",
  "reason": "Family vacation",
  "contact_phone": "+254712345678",
  "half_day": false
}
```

### Approve Leave
```http
POST /leaves/{id}/approve
```

**Request Body**:
```json
{
  "approval_notes": "Approved. Ensure handover is complete."
}
```

### Reject Leave
```http
POST /leaves/{id}/reject
```

**Request Body**:
```json
{
  "rejection_reason": "Team coverage insufficient during this period."
}
```

### Get Leave Calendar
```http
GET /leaves/calendar/data?start=2024-02-01&end=2024-02-29
```

**Response**:
```json
{
  "events": [
    {
      "id": 1,
      "title": "John Doe - Annual Leave",
      "start": "2024-02-15",
      "end": "2024-02-19",
      "color": "#007bff",
      "employee": "John Doe"
    }
  ]
}
```

---

## Notifications

### Email Notifications

**Triggers**:

1. **Leave Request Submitted**
   - To: Manager, HR
   - Content: Employee details, leave dates, reason

2. **Leave Approved**
   - To: Employee
   - Content: Approval details, return date

3. **Leave Rejected**
   - To: Employee
   - Content: Rejection reason, next steps

4. **Leave Starting Soon**
   - To: Employee, Manager
   - Content: Reminder, handover checklist

5. **Leave Balance Low**
   - To: Employee
   - Content: Current balance, usage tips

6. **Leave Expiring**
   - To: Employee
   - Content: Expiring days, deadline

---

## Best Practices

### For Employees
1. Plan leaves in advance
2. Check team calendar before applying
3. Provide adequate notice
4. Complete handover before leave
5. Keep emergency contact updated
6. Monitor leave balance regularly

### For Managers
1. Review requests promptly
2. Consider team coverage
3. Be fair and consistent
4. Document rejection reasons
5. Plan for team absences
6. Encourage leave utilization

### For HR
1. Configure leave types properly
2. Monitor leave patterns
3. Ensure policy compliance
4. Regular balance audits
5. Timely balance allocation
6. Clear communication of policies

---

## Troubleshooting

### Common Issues

**Issue**: Cannot apply for leave
- **Solution**: Check leave balance, verify leave type is active

**Issue**: Leave request not showing
- **Solution**: Verify submission, check filters, refresh page

**Issue**: Incorrect balance calculation
- **Solution**: Review adjustments, check carry forward settings

**Issue**: Manager not receiving notifications
- **Solution**: Verify email settings, check manager assignment

**Issue**: Calendar not displaying leaves
- **Solution**: Clear cache, check date range, verify permissions

---

## Leave Policies

### Sample Leave Policy

**Annual Leave**:
- Entitlement: 21 working days per year
- Accrual: Monthly (1.75 days)
- Notice: Minimum 2 weeks for 5+ days
- Carry Forward: Maximum 5 days
- Expiry: Carried days expire after 3 months

**Sick Leave**:
- Entitlement: 14 days per year
- Medical Certificate: Required for 3+ consecutive days
- Notice: As soon as possible
- Carry Forward: Not allowed

**Maternity Leave**:
- Entitlement: 90 days
- Notice: 1 month before expected delivery
- Documentation: Medical certificate required
- Pay: Full pay

---

## Future Enhancements

- [ ] Leave forecasting
- [ ] Team leave planning tool
- [ ] Mobile app for leave requests
- [ ] Integration with external calendars
- [ ] Automated leave reminders
- [ ] Leave swap functionality
- [ ] Advanced analytics dashboard
- [ ] Custom leave workflows

---

**Last Updated**: February 2026
