# Staff Hierarchy View Implementation

## Overview

The Staff Hierarchy View provides a visual tree representation of organizational reporting relationships, allowing administrators to view the complete organizational structure in an intuitive, interactive format.

## Features

### 1. Interactive Tree Visualization
- **Hierarchical Display**: Shows staff members organized by reporting relationships
- **Expand/Collapse**: Each node can be expanded or collapsed to show/hide direct reports
- **Visual Indicators**: 
  - Tree lines connecting parent-child relationships
  - Badges showing number of direct reports
  - Status indicators (Active/Inactive)
  - Avatar placeholders or profile photos

### 2. Search and Filtering
- **Staff Search**: Search by name or employee ID
- **Hospital Filter**: Filter by specific hospital
- **Department Filter**: Filter by department
- **Search Result Highlighting**: Automatically expands and highlights search results

### 3. Quick Actions
- **View Details**: Click on any staff member to view their full profile
- **Expand All**: Expand all nodes in the hierarchy
- **Collapse All**: Collapse all nodes for a cleaner view

### 4. Statistics Dashboard
- Total Staff count
- Top Managers count (staff with no manager)
- Hierarchy Levels indicator

## Implementation Details

### Files Created/Modified

1. **View Function** (`apps/organizations/ui_views.py`)
   - `staff_hierarchy()`: Main view handling hierarchy data and filtering

2. **URL Configuration** (`apps/organizations/urls.py`)
   - Added: `path('staff/hierarchy/', ui_views.staff_hierarchy, name='staff_hierarchy')`

3. **Templates**
   - `templates/organizations/staff_hierarchy.html`: Main hierarchy page
   - `templates/organizations/hierarchy_node.html`: Recursive template for tree nodes

4. **Sidebar Navigation** (`templates/layouts/partials/sidebar.html`)
   - Added Staff submenu with "Staff List" and "Hierarchy" options

### Data Structure

The view builds a hierarchical tree structure:

```python
class HierarchyNode:
    staff: Staff model instance
    direct_reports: List[HierarchyNode]
    has_children: Boolean
    is_search_result: Boolean (for highlighting)
```

### Algorithm

The hierarchy view uses the following logic:

1. **Identify Root Nodes**: Staff members with no `report_to` (top-level managers)
2. **Build Tree Recursively**: For each root node, recursively find all direct reports
3. **Filter Results**: Apply hospital, department, and search filters
4. **Mark Search Results**: Highlight any staff member matching search criteria
5. **Count Statistics**: Calculate total staff and top manager counts

### Database Schema

The `Staff` model already includes the necessary fields:

```python
class Staff(models.Model):
    report_to = models.ForeignKey(
        'self',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='direct_reports'
    )
    # ... other fields
```

## Current Data Status

As of implementation:

- **Total Staff**: 1,968 records
- **Staff with Managers**: 1,951 records (have `report_to` assigned)
- **Top-Level Managers**: 17 records (no manager assigned)

This indicates a well-structured organization with multiple hierarchy levels.

## Usage

### Accessing the Hierarchy View

1. Navigate to **Staff → Hierarchy** in the sidebar
2. Alternatively, access directly at `/organizations/staff/hierarchy/`

### Viewing the Hierarchy

1. **Initial View**: Shows top-level managers with their direct reports collapsed
2. **Expand Nodes**: Click the chevron icon to expand/collapse nodes
3. **View Details**: Click on any staff card to view their full profile
4. **Search**: Enter name or employee ID to find specific staff
5. **Filter**: Use hospital/department dropdowns to filter the view

### Search Functionality

When searching for a staff member:
1. The view automatically expands all parent nodes
2. Scrolls to and highlights the matching staff member
3. Shows an alert indicating the found staff member
4. Applies visual highlighting (green border and glow effect)

## Integration with Existing Data

The provided CSV data format integrates seamlessly:

```csv
Staff ID,Name,Location,Department,Section,Subsection,AlHammadi Job Title,Country,Gender,Manager
4,ABDULAZIZ SALEH ALHAMMADI,Nuzha,Senior Management Offices,COO Office,,Chief Operating Officer,Saudi Arabia,Male,2 - MOHAMMAD SALEH AL HAMMADI
```

### Import Process

1. **Manager Field Parsing**: Extract manager ID from "ID - Name" format
2. **Staff Lookup**: Find the corresponding staff record for the manager ID
3. **Relationship Assignment**: Set `report_to` field appropriately
4. **Hierarchy Building**: The view automatically builds the tree from these relationships

### Example CSV Import

The existing import command (`import_staff_csv`) already handles hierarchy:

```bash
python manage.py import_staff_csv staff_data.csv
```

The command:
- Parses the "Manager" column
- Extracts the manager ID
- Finds the manager record
- Assigns the `report_to` relationship

## Styling and UX

### Visual Design

- **Clean Cards**: Each staff member displayed in a bordered card
- **Avatar**: Initials or profile photo with circular styling
- **Information Hierarchy**: Name prominently displayed, details in smaller text
- **Badges**: Color-coded badges for status, department, and reports count
- **Tree Lines**: Visual connectors showing parent-child relationships

### Animations

- **Expand/Collapse**: Smooth 300ms transition
- **Hover Effects**: Subtle border color change and shadow
- **Search Highlight**: Green glow animation when search result is displayed

### Responsive Design

The hierarchy view is responsive and works well on:
- Desktop: Full tree with all features
- Tablet: Vertical tree with appropriate spacing
- Mobile: Stacked cards with simplified tree structure

## Performance Considerations

### Optimization

1. **Query Efficiency**: Uses `select_related()` for manager relationships
2. **Limited Depth**: Currently displays all levels; consider pagination for very deep hierarchies
3. **Caching**: Could add caching for frequently accessed hierarchies
4. **Lazy Loading**: Children are rendered but collapsed by default

### Scalability

For very large organizations (10,000+ staff):
- Consider implementing pagination for top-level managers
- Add depth limit option (e.g., show only 3 levels)
- Implement server-side search with AJAX loading

## Future Enhancements

### Potential Features

1. **Organization Chart View**: Alternative horizontal tree layout
2. **Export Options**: Export hierarchy as PDF, PNG, or org chart file
3. **Interactive Editing**: Drag-and-drop to change reporting relationships
4. **Statistics Per Manager**: Show team size, span of control, etc.
5. **Filter by Job Title**: Add job title filter to hierarchy view
6. **Timeline View**: Show historical changes in reporting relationships
7. **Team View**: See all members of a manager's team in one view

### API Endpoints

Potential API additions:

```python
# Get hierarchy as JSON
GET /api/organizations/staff/hierarchy/

# Get direct reports of a manager
GET /api/organizations/staff/{id}/direct-reports/

# Get full management chain
GET /api/organizations/staff/{id}/management-chain/
```

## Troubleshooting

### Common Issues

1. **Empty Hierarchy Display**
   - Check if staff have `report_to` relationships
   - Verify hospital/department filters aren't too restrictive
   - Check user permissions

2. **Missing Managers**
   - Ensure manager IDs in CSV correspond to existing staff records
   - Run: `python manage.py import_staff_csv --validate` to check data

3. **Performance Issues**
   - Check for circular references (A reports to B, B reports to A)
   - Consider limiting hierarchy depth
   - Review database indexes on `report_to` field

## Security

### Access Control

- **PX Admin**: Full access to all hierarchies
- **Hospital Admin**: Access to their hospital's hierarchy only
- **Staff**: View-only access to their organization's hierarchy

### Data Privacy

- Staff photos and contact information only shown to authorized users
- Sensitive information (salary, performance) never displayed in hierarchy

## Testing

### Manual Testing Checklist

- [ ] View hierarchy with default filters
- [ ] Expand/collapse nodes
- [ ] Search for specific staff member
- [ ] Filter by hospital
- [ ] Filter by department
- [ ] Click on staff card to view details
- [ ] Use "Expand All" button
- [ ] Use "Collapse All" button
- [ ] Verify tree lines display correctly
- [ ] Check responsive design on different screen sizes
- [ ] Test with different user roles (PX Admin, Hospital Admin)

## Conclusion

The Staff Hierarchy View provides an intuitive, interactive way to visualize organizational structure. It integrates seamlessly with existing staff data and CSV import processes, making it easy to maintain and update as the organization evolves.

The implementation is production-ready and includes all necessary features for viewing, searching, and filtering the organizational hierarchy.
