# Organizational Hierarchy System

Complete implementation of hierarchical organizational structure for user groups with role-based membership management.

## Overview

The organizational hierarchy system extends the existing user groups functionality to support:
- **Hierarchical structure**: Departments > Teams > Sub-teams
- **Role-based membership**: Manager, Leader, Member, Observer
- **Tree visualization**: Similar to menu management interface
- **User avatars**: Visual identification of team members
- **Integration ready**: For opportunities, messaging, projects, and scheduling

## Database Schema

### Migration: `030_enhance_user_groups_hierarchy.sql`

**New Columns:**
- `user_groups.parent_id` - Links to parent group (self-referential)
- `user_groups.display_order` - Sort order within same parent
- `user_group_members.role` - ENUM('manager', 'leader', 'member', 'observer')

**New Group Types:**
- `division` - Top-level organizational divisions
- `department` - Departments (existing, enhanced)
- `team` - Working teams
- `squad` - Cross-functional squads
- Plus existing: system, project, location, custom

**Indexes:**
- `idx_parent_id` on user_groups.parent_id
- `idx_role` on user_group_members.role
- `idx_group_role` composite on (group_id, role)
- `idx_display_order` on user_groups.display_order

## Features

### 1. Hierarchical Tree View
**URL:** `http://localhost:8080/settings/user-groups/tree`

- Collapsible accordion interface similar to menu management
- Visual hierarchy with indentation and colored borders
- Shows member count and subgroup count for each group
- Type badges (Division, Department, Team, Squad)
- Quick links to view/edit each group

**Usage:**
```php
// In controller
$hierarchyTree = $this->userGroupModel->getHierarchyTree(null, true);
```

### 2. Role-Based Membership

**Roles:**
- **Manager** - Department/group manager (highest authority)
- **Leader** - Team leader/coordinator
- **Member** - Regular team member
- **Observer** - Read-only access

**Features:**
- Inline role selection dropdown on member list
- AJAX updates without page reload
- Automatic sorting: Managers first, then leaders, members, observers
- Role badges with color coding

### 3. User Avatar Integration

All member displays now show:
- Initials circles with consistent colors
- Full name next to avatar
- Role badge
- User information

**Implementation:**
```php
<?php 
require_once BASE_PATH . '/views/components/user_avatar.php';
renderUserAvatar($firstName, $lastName, 32, true);
?>
```

### 4. Enhanced Group Management

**Create/Edit Forms:**
- Parent group selector with full hierarchical paths
- New group types (division, team, squad)
- Circular reference prevention
- Move groups in hierarchy

**Group Detail Page:**
- Hierarchical breadcrumb showing ancestry
- Subgroups section (if any children exist)
- Members list with avatars and role selectors
- Quick role updates via AJAX

## Model Methods

### UserGroup Model

#### Hierarchy Methods
```php
// Get full hierarchy tree
$tree = $userGroupModel->getHierarchyTree($parentId = null, $includeInactive = false);

// Get direct children of a group
$children = $userGroupModel->getChildren($groupId, $includeInactive = false);

// Get ancestors (parent chain)
$ancestors = $userGroupModel->getAncestors($groupId);

// Get all groups with full paths
$groups = $userGroupModel->getAllWithPaths($includeInactive = false);
// Returns: ['id' => 1, 'name' => 'Team', 'full_path' => 'Sales Division > Sales Dept > Team']
```

#### Role Management Methods
```php
// Get members with roles (sorted by role hierarchy)
$members = $userGroupModel->getMembersWithRoles($groupId);

// Get members by specific role
$managers = $userGroupModel->getMembersByRole($groupId, 'manager');

// Assign role to member
$success = $userGroupModel->assignRole($groupId, $userId, 'leader');

// Move group to new parent (prevents circular references)
$success = $userGroupModel->moveGroup($groupId, $newParentId);
```

## Controller Endpoints

### New Routes

```php
// Tree view
GET  /settings/user-groups/tree

// Role management
POST /settings/user-groups/{id}/update-role
POST /settings/user-groups/{id}/move-group
```

### AJAX Endpoints

**Update Member Role:**
```javascript
fetch('/settings/user-groups/123/update-role', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'user_id=456&role=leader&csrf_token=' + csrfToken
})
```

**Move Group:**
```javascript
fetch('/settings/user-groups/123/move-group', {
    method: 'POST',
    body: 'parent_id=789&csrf_token=' + csrfToken
})
```

## Views

### Tree View (`views/settings/user_groups/tree.php`)
- Accordion-based hierarchical display
- Recursive rendering of nested groups
- Type-based color coding
- Member and subgroup counts
- Links to list view and detail pages

### Enhanced Show Page (`views/settings/user_groups/show.php`)
- Hierarchical breadcrumb navigation
- Subgroups section
- Member list with:
  - User avatars (initials circles)
  - Role selection dropdowns
  - Email and metadata
  - Remove member button

### Create/Edit Forms
- Parent group selector with hierarchical paths
- All group types (division, department, team, squad, etc.)
- Validation prevents circular references

## Integration Points

### Opportunities
```php
// Assign opportunity to group hierarchy
$groupMembers = $userGroupModel->getMembersWithRoles($groupId);

// Filter by role
$managers = $userGroupModel->getMembersByRole($groupId, 'manager');
```

### Messaging
```php
// @mention with roles
// Future: Support @sales-managers to mention all managers in sales group
$groups = $userGroupModel->getHierarchyTree();
```

### Projects
```php
// Project team selection from org hierarchy
$allGroups = $userGroupModel->getAllWithPaths();
foreach ($allGroups as $group) {
    echo "<option value='{$group['id']}'>{$group['full_path']}</option>";
}
```

### Scheduling
```php
// Team calendars by hierarchy
$teamMembers = $userGroupModel->getMembers($groupId);
// Manager visibility
$manager = $userGroupModel->getMembersByRole($groupId, 'manager');
```

## Security Considerations

### Permissions
- Use existing `settings.view` and `settings.edit` permissions
- Role changes validated on server side
- CSRF protection on all POST endpoints

### Data Integrity
- Circular reference prevention in `moveGroup()`
- Foreign key relationships (via application logic)
- Transaction support for complex operations

### Validation
```php
// Valid roles
$validRoles = ['manager', 'leader', 'member', 'observer'];

// Prevent self-parenting
if ($newParentId == $groupId) return false;

// Prevent circular references
$ancestors = $this->getAncestors($newParentId);
foreach ($ancestors as $ancestor) {
    if ($ancestor['id'] == $groupId) return false;
}
```

## Performance

### Optimization
- Indexed parent_id for hierarchy queries
- Indexed role for filtering
- Composite index on (group_id, role)
- Recursive queries limited by max depth (10 levels)

### Caching (Future)
```php
// Cache hierarchy tree (recommended for large orgs)
$cacheKey = 'org_hierarchy_tree';
$tree = Cache::remember($cacheKey, 3600, function() {
    return $userGroupModel->getHierarchyTree();
});
```

## Sample Data

The migration creates sample hierarchical structure:
```
All Company (system)
├── Sales Division
│   ├── Sales Department
│   │   ├── Enterprise Sales Team
│   │   └── SMB Sales Team
│   └── Marketing Department
├── Operations Division
│   ├── Manufacturing Department
│   └── Logistics Department
└── Technology Division
    ├── Engineering Department
    │   ├── Backend Team
    │   ├── Frontend Team
    │   └── DevOps Squad
    └── IT Department
```

## Usage Examples

### Creating a New Team Under Existing Department
1. Navigate to `/settings/user-groups/tree`
2. Find parent department, click "View"
3. Or go to `/settings/user-groups/create`
4. Select parent from dropdown (shows full path)
5. Set type to "Team"
6. Add members and assign roles

### Assigning Manager Role
1. View group at `/settings/user-groups/{id}`
2. Find member in list
3. Select "Manager" from role dropdown
4. Automatically saves via AJAX
5. Member moves to top of list

### Viewing Org Chart
1. Navigate to `/settings/user-groups/tree`
2. Expand/collapse sections
3. Click group to view members
4. Edit to change parent/position

## Future Enhancements

### Potential Features
- [ ] Drag-and-drop reordering in tree view
- [ ] Visual org chart diagram (D3.js/Mermaid)
- [ ] Export org chart (PDF/PNG)
- [ ] Reporting structure vs functional structure
- [ ] Matrix organization support
- [ ] Historical tracking (org changes over time)
- [ ] Vacancy tracking (groups without managers)
- [ ] Cross-functional team analysis
- [ ] Role-based @mentions (@sales-managers)
- [ ] Cascading notifications up/down hierarchy

### Integration Enhancements
- [ ] Opportunity assignment by team hierarchy
- [ ] Project resource allocation by group
- [ ] Manager approval workflows
- [ ] Team capacity planning
- [ ] Hierarchical reporting

## Troubleshooting

### Common Issues

**1. Circular Reference Error**
- Occurs when trying to set a group's parent to itself or its descendants
- Solution: Choose a different parent or set to null (top-level)

**2. Role Not Updating**
- Check CSRF token is valid
- Verify user has `settings.edit` permission
- Check browser console for JavaScript errors

**3. Tree Not Loading**
- Verify migration ran successfully
- Check `parent_id` column exists
- Ensure no circular references in data

**4. Avatars Not Showing**
- Ensure `user_avatar.php` component is included
- Check `BASE_PATH` is correct
- Verify users have first_name and last_name

## Support

For questions or issues:
- Check WARP.md for framework patterns
- Review database/migrations for schema
- See USER_AVATAR_COMPONENT.md for avatar usage
- Contact development team

## Version History

- **v1.0** (2025-12-04) - Initial implementation
  - Hierarchical structure
  - Role-based membership
  - Tree visualization
  - User avatar integration
  - Full CRUD operations
