# Report Sheets Filter Feature

## Overview
Added comprehensive filtering functionality to the Report Sheets page, allowing users to filter sheets by multiple criteria for better data organization and analysis. This complements the existing filters on the Reports page.

## Filter Options

### ✅ **Available Filters**
1. **Date Range**
   - Date From: Start date for filtering
   - Date To: End date for filtering
   - Max date: Today (prevents future dates)

2. **Status**
   - All Status (default)
   - Pending: Sheets with only one shift
   - Completed: Sheets with both day and night shifts

3. **Area**
   - All Areas (default)
   - Specific operational areas

4. **Employee**
   - All Employees (default)
   - Specific active employees (filters sheets where employee has at least one shift)

5. **Dredger Location**
   - All Dredger Locations (default)
   - Specific dredger locations with class indicators

## User Interface

### ✅ **Filter Panel**
- **Toggle Button**: \"Show Filters\" / \"Hide Filters\" with filter icon
- **Active Filter Indicator**: Shows count of active filters
- **Clear All Button**: Removes all active filters
- **Responsive Grid**: Adapts to screen size (1-5 columns)
- **Results Summary**: Shows filtered result count

### ✅ **Filter Layout**
```
┌─────────────────────────────────────────────────────────────┐
│ [🔍 Show Filters] [3 active] [Clear All Filters]          │
├─────────────────────────────────────────────────────────────┤
│ Date From | Date To | Status | Area | Employee | Dredger   │
│ [______]  | [____]  | [____] | [__] | [______] | [_______] │
├─────────────────────────────────────────────────────────────┤
│ Showing 12 sheets matching your filters                     │
└─────────────────────────────────────────────────────────────┘
```

## Technical Implementation

### ✅ **Server-Side Filtering**
```typescript
// Build dynamic where clause
const whereClause: any = {};

// Date range filter
if (dateFrom || dateTo) {
  if (dateFrom) {
    whereClause.date = { gte: dateFrom };
  }
  if (dateTo) {
    whereClause.date = { ...whereClause.date, lte: dateTo };
  }
}

// Status filter
if (status && status !== 'all') {
  whereClause.status = status;
}

// Area filter
if (areaId && areaId !== 'all') {
  whereClause.areaId = parseInt(areaId);
}

// Dredger location filter
if (dredgerLocationId && dredgerLocationId !== 'all') {
  whereClause.dredgerLocationId = parseInt(dredgerLocationId);
}

// Employee filter (applied post-query due to complex relationship)
if (employeeId && employeeId !== 'all') {
  sheets = sheets.filter((sheet: any) =>
    (sheet.dayShift && sheet.dayShift.employeeId === parseInt(employeeId)) ||
    (sheet.nightShift && sheet.nightShift.employeeId === parseInt(employeeId))
  );
}
```

### ✅ **Client-Side State Management**
```typescript
// Filter state management
const [showFilters, setShowFilters] = useState(false);
const [searchParams, setSearchParams] = useSearchParams();

// Filter change handler
const handleFilterChange = (filterName: string, value: string) => {
  const newSearchParams = new URLSearchParams(searchParams);
  if (value === '' || value === 'all') {
    newSearchParams.delete(filterName);
  } else {
    newSearchParams.set(filterName, value);
  }
  setSearchParams(newSearchParams);
};
```

### ✅ **URL Parameter Mapping**
- `dateFrom` - Start date (YYYY-MM-DD)
- `dateTo` - End date (YYYY-MM-DD)
- `status` - Sheet status (pending/completed)
- `areaId` - Area ID (integer)
- `employeeId` - Employee ID (integer)
- `dredgerLocationId` - Dredger location ID (integer)

## Features

### ✅ **Smart Filtering**
1. **URL Persistence**: Filters persist in URL for bookmarking/sharing
2. **Real-time Updates**: Filters apply immediately on change
3. **Server-side Processing**: Efficient database queries
4. **Active Filter Tracking**: Visual indicators for applied filters
5. **Clear All**: One-click filter reset

### ✅ **Responsive Design**
- **Mobile**: Single column filter layout
- **Tablet**: 2-3 column layout
- **Desktop**: Up to 5 column layout
- **Collapsible**: Filters can be hidden to save space

### ✅ **User Experience**
- **Progressive Disclosure**: Filters hidden by default
- **Visual Feedback**: Active filter count and clear indicators
- **Results Summary**: Shows filtered result count
- **Intuitive Controls**: Standard form inputs with clear labels

## Filter Logic

### ✅ **Date Filtering**
- Filters by sheet date (not creation date)
- Supports date ranges with from/to dates
- Prevents future date selection

### ✅ **Status Filtering**
- **Pending**: Sheets with only day OR night shift
- **Completed**: Sheets with both day AND night shifts
- Based on sheet status field

### ✅ **Employee Filtering**
- Shows sheets where the selected employee has at least one shift
- Checks both day and night shift assignments
- Applied after database query due to complex relationship

### ✅ **Location Filtering**
- Filters by area and dredger location
- Uses direct foreign key relationships
- Efficient database-level filtering

## Use Cases

### **Common Filtering Scenarios**

1. **Date Range Analysis**
   - Filter sheets from last week
   - View sheets for specific date range
   - Analyze monthly performance

2. **Status-Based Views**
   - Show only pending sheets (incomplete)
   - View completed sheets only
   - Track completion rates

3. **Location-Based Filtering**
   - View sheets for specific areas
   - Analyze dredger location performance
   - Location-specific reporting

4. **Employee Performance**
   - View sheets by specific employee
   - Track individual contributions
   - Employee-specific analysis

5. **Combined Filtering**
   - Pending sheets from Area A last week
   - Specific employee's completed sheets
   - Location + date + status combinations

## Benefits

### ✅ **Operational Benefits**
1. **Faster Data Access**: Quick filtering vs manual searching
2. **Better Analysis**: Focus on specific data subsets
3. **Improved Productivity**: Less time finding relevant sheets
4. **Enhanced Reporting**: Filtered data for management reports

### ✅ **Technical Benefits**
1. **Performance**: Server-side filtering reduces data transfer
2. **Scalability**: Efficient database queries with proper indexing
3. **Maintainability**: Clean, modular filter implementation
4. **Extensibility**: Easy to add new filter criteria

## Performance Considerations

### ✅ **Database Optimization**
- Indexed columns for common filters (date, areaId, dredgerLocationId)
- Efficient WHERE clause construction
- Proper date range handling
- Complex employee filtering handled efficiently

### ✅ **UI Performance**
- Efficient re-renders with proper state management
- Minimal DOM updates
- Fast filter application

## Integration with Existing Features

### ✅ **Consistent with Reports Page**
- Similar filter UI and behavior
- Consistent URL parameter patterns
- Same responsive design principles
- Matching user experience

### ✅ **Permission Handling**
- Respects user auth levels
- Level 1 users see filtered results based on their sheets
- Admin users see all filtered results

## Future Enhancements

### **Potential Additions**
1. **Saved Filters**: Allow users to save common filter combinations
2. **Advanced Filters**: More complex filtering options
3. **Export Filtered Data**: Export only filtered results
4. **Filter Presets**: Quick access to common filter combinations
5. **Search**: Text search within sheet data

### **Advanced Features**
1. **Date Shortcuts**: \"Last 7 days\", \"This month\", etc.
2. **Multi-Select**: Select multiple areas or employees
3. **Custom Date Ranges**: More flexible date selection
4. **Filter History**: Remember recent filter combinations

The filter feature significantly improves the usability of the Report Sheets page, making it easier for users to find and analyze specific sheet data based on multiple criteria."