# Team Workload Analysis

## Overview

The Team Workload Analysis feature provides comprehensive insights into user workload and team occupancy across departments. It tracks actual time spent on tasks versus allocated time, calculates occupancy percentages, and helps identify over-utilized or under-utilized team members.

## Features

### Core Functionality
- **Real-time Workload Tracking**: Monitor actual hours worked vs. allocated hours
- **Department-based Analysis**: Filter and analyze workload by department
- **User-specific Insights**: Individual user workload status and capacity
- **Time Period Filtering**: Analyze workload for specific date ranges
- **Occupancy Visualization**: Visual progress bars showing workload utilization

### Key Metrics
- **Monthly Capacity**: User's configured monthly hours
- **Actual Hours Worked**: Total hours from completed tasks
- **Occupancy Percentage**: (Actual Hours / Monthly Capacity) × 100
- **Margin Hours**: Remaining available hours
- **Workload Status**: Under-utilized, Optimal, Over-utilized, or Not Configured

## User Interface

### Filters
- **Department**: Filter by specific departments
- **User**: Filter by individual users
- **Date Range**: Select start and end dates for analysis
- **View Mode**: Toggle between table and chart views

### Summary Cards
- **Total Users**: Number of users in the analysis
- **Average Occupancy**: Mean occupancy across all users
- **Over-utilized Users**: Count of users exceeding 100% capacity
- **Under-utilized Users**: Count of users below 80% capacity

### Data Table
- **User Information**: Name, department, role
- **Workload Metrics**: Monthly capacity, actual hours, occupancy percentage
- **Visual Indicators**: Color-coded occupancy bars
- **Status Badges**: Workload status with appropriate colors

## Database Schema

### User Model Extensions
```php
// New fields added to users table
daily_hours: integer (nullable)
hourly_rate: decimal(10,2) (nullable)
```

### Task Integration
```php
// Task model provides actual hours data
estimated_hours: integer
actual_hours: decimal(8,2)
assigned_to: foreign key to users
```

### Department Relationships
```php
// Many-to-many relationship between users and departments
user_departments: pivot table
is_primary: boolean (indicates primary department)
```

## Workload Calculation Logic

### Occupancy Percentage
```php
occupancy_percentage = (actual_hours_worked / monthly_capacity) × 100
```

### Workload Status Classification
- **Not Configured**: Monthly hours or hourly rate not set
- **Under-utilized**: < 80% occupancy
- **Optimal**: 80-100% occupancy
- **Over-utilized**: > 100% occupancy

### Margin Hours
```php
margin_hours = monthly_capacity - actual_hours_worked
```

## API Endpoints

### Team Workload Analysis
- **Route**: `/team-workload`
- **Method**: GET
- **Component**: `TeamWorkloadAnalysis`
- **Access**: Requires authentication

### Query Parameters
- `department`: Filter by department ID
- `user`: Filter by user ID
- `start_date`: Analysis start date
- `end_date`: Analysis end date
- `view_mode`: 'table' or 'chart'

## Livewire Component

### Properties
```php
public $selectedDepartment = '';
public $selectedUser = '';
public $startDate = '';
public $endDate = '';
public $viewMode = 'table';
public $workloadData = [];
public $summaryStats = [];
```

### Methods
- `loadWorkloadData()`: Calculate and load workload statistics
- `applyFilters()`: Apply date and user filters
- `getOccupancyPercentage()`: Calculate user occupancy
- `getWorkloadStatus()`: Determine workload status
- `exportData()`: Export analysis to CSV/Excel

## CSS Styling

### Workload Status Colors
```css
.workload-status.under-utilized { @apply bg-yellow-100 text-yellow-800; }
.workload-status.optimal { @apply bg-green-100 text-green-800; }
.workload-status.over-utilized { @apply bg-red-100 text-red-800; }
.workload-status.not-configured { @apply bg-gray-100 text-gray-800; }
```

### Occupancy Bars
```css
.occupancy-bar { @apply h-2 bg-gray-200 rounded-full; }
.occupancy-fill { @apply h-2 rounded-full transition-all duration-300; }
```

## Usage Examples

### Basic Analysis
1. Navigate to Team Workload Analysis
2. Select date range (defaults to current month)
3. View overall team occupancy statistics
4. Identify over-utilized or under-utilized team members

### Department-specific Analysis
1. Select specific department from filter
2. Analyze workload patterns within department
3. Identify capacity gaps or surpluses
4. Plan resource allocation accordingly

### User-specific Analysis
1. Filter by specific user
2. Review individual workload trends
3. Assess task distribution and capacity
4. Plan workload adjustments if needed

## Future Enhancements

### Planned Features
- **Historical Trends**: Track workload changes over time
- **Capacity Planning**: Predictive workload modeling
- **Automated Alerts**: Notifications for over-utilization
- **Integration**: Connect with project management tools
- **Advanced Analytics**: Machine learning for workload optimization

### Potential Integrations
- **Time Tracking**: Real-time hour logging
- **Project Management**: Task assignment and tracking
- **HR Systems**: Employee capacity and availability
- **Reporting Tools**: Advanced analytics and dashboards

## Testing

### Test Coverage
- Page loading and authentication
- Workload calculation accuracy
- Filter functionality
- Status classification logic
- Edge cases (null values, no tasks)
- Data export functionality

### Test Scenarios
- Users with no monthly hours configured
- Users with no assigned tasks
- Over-utilized users (>100% occupancy)
- Department-specific filtering
- Date range filtering
- Export functionality

## Security Considerations

### Access Control
- Authentication required for all workload data
- Role-based access to sensitive information
- Department-based data filtering
- Audit logging for data access

### Data Privacy
- Personal workload data protection
- Department-level data aggregation
- Secure data export functionality
- Compliance with data protection regulations

## Performance Optimization

### Database Queries
- Optimized joins for user-task relationships
- Indexed queries for date range filtering
- Cached department and user data
- Efficient aggregation queries

### Frontend Performance
- Lazy loading of large datasets
- Debounced filter inputs
- Optimized chart rendering
- Responsive design for mobile devices

## Troubleshooting

### Common Issues
- **No Data Displayed**: Check user permissions and date filters
- **Incorrect Calculations**: Verify task hours and user capacity
- **Slow Performance**: Check database indexes and query optimization
- **Filter Not Working**: Ensure proper filter parameter handling

### Debug Information
- Enable debug mode for detailed error messages
- Check browser console for JavaScript errors
- Review server logs for backend issues
- Validate database data integrity

## Configuration

### Environment Variables
```env
WORKLOAD_ANALYSIS_ENABLED=true
WORKLOAD_EXPORT_ENABLED=true
WORKLOAD_CACHE_TTL=3600
```

### Database Configuration
- Ensure proper indexes on workload-related tables
- Configure appropriate foreign key constraints
- Set up database connection pooling
- Enable query logging for optimization

## Support and Maintenance

### Regular Maintenance
- Monitor database performance
- Update workload calculations
- Review and optimize queries
- Backup and restore procedures

### User Support
- Provide user training and documentation
- Establish support channels
- Create troubleshooting guides
- Monitor user feedback and issues 