# Shot Table Enhanced Specification - 2024 Update

## Overview

This specification documents the comprehensive shot table implementation with all recent enhancements and improvements. The shot table provides a powerful, feature-rich interface for managing shots with task status tracking, advanced filtering, sorting, and bulk operations.

## Current Implementation Status

### ✅ Completed Features

1. **TanStack Table Integration** - Modern, performant table implementation
2. **Directional Sort Icons** - Visual feedback for sort direction (up/down arrows)
3. **Column Visibility Control** - Unified popover pattern matching task page
4. **Task Status Filtering** - Advanced multi-select popover with search
5. **Toolbar Restructuring** - Consistent layout matching task page structure
6. **Full Width Layout** - Optimized screen space utilization
7. **Cascade Deletion** - Safe shot deletion with task confirmation
8. **Custom Status Support** - Integration with project-specific task statuses
9. **Enhanced UI Components** - Consistent heights and icon-only buttons
10. **Independent Frames Column** - Separate frame count display

## User Stories

### User Story 1: Enhanced Shot Table Display
**As a** coordinator  
**I want** to view shots in a comprehensive table with advanced features  
**So that** I can efficiently manage shot production with full visibility

**Acceptance Criteria:**
1. ✅ WHEN viewing shots, THE system SHALL display a table with sortable columns showing directional sort icons
2. ✅ WHEN sorting columns, THE system SHALL show up arrow for ascending, down arrow for descending, and up-down arrow for no sort
3. ✅ WHEN displaying frame information, THE system SHALL show both frame range (1001-1120) and frame count (120) in separate columns
4. ✅ WHEN viewing task statuses, THE system SHALL display custom project statuses with correct names and colors
5. ✅ WHEN the table loads, THE system SHALL use full screen width for optimal space utilization

### User Story 2: Advanced Filtering and Search
**As a** user  
**I want** sophisticated filtering options with visual feedback  
**So that** I can quickly find relevant shots

**Acceptance Criteria:**
1. ✅ WHEN using task status filter, THE system SHALL provide a popover with multi-select checkboxes
2. ✅ WHEN filtering by status, THE system SHALL show search functionality within the filter
3. ✅ WHEN filters are active, THE system SHALL display a badge counter showing number of active filters
4. ✅ WHEN using search, THE system SHALL position the search field on the right side of the toolbar
5. ✅ WHEN episode filtering, THE system SHALL provide a popover dropdown in the toolbar

### User Story 3: Consistent UI and Layout
**As a** user  
**I want** consistent interface elements across all pages  
**So that** I have a familiar and predictable experience

**Acceptance Criteria:**
1. ✅ WHEN viewing the toolbar, THE system SHALL ensure all components have consistent 32px height
2. ✅ WHEN using action buttons, THE system SHALL display icons only without text labels
3. ✅ WHEN accessing filters, THE system SHALL use the same popover + command pattern as task page
4. ✅ WHEN viewing the toolbar structure, THE system SHALL match the task page layout exactly
5. ✅ WHEN using column visibility, THE system SHALL provide the same interface as other data tables

### User Story 4: Safe Deletion with Cascade Confirmation
**As a** coordinator  
**I want** comprehensive deletion confirmation with task details  
**So that** I can safely delete shots while understanding the impact

**Acceptance Criteria:**
1. ✅ WHEN deleting a shot, THE system SHALL show a confirmation dialog with all associated tasks
2. ✅ WHEN viewing task details in deletion dialog, THE system SHALL display task status using TaskStatusBadge component
3. ✅ WHEN confirming deletion, THE system SHALL require typing the shot name for confirmation
4. ✅ WHEN deletion is confirmed, THE system SHALL cascade delete all associated tasks
5. ✅ WHEN deletion completes, THE system SHALL show success message with count of deleted tasks

### User Story 5: Custom Status Integration
**As a** project manager  
**I want** custom task statuses to display correctly throughout the interface  
**So that** project-specific workflows are properly supported

**Acceptance Criteria:**
1. ✅ WHEN viewing task statuses, THE system SHALL fetch and display custom project statuses
2. ✅ WHEN showing status badges, THE system SHALL use correct custom status names and colors
3. ✅ WHEN filtering by status, THE system SHALL include both system and custom statuses
4. ✅ WHEN displaying status in dialogs, THE system SHALL use the enhanced TaskStatusBadge component
5. ✅ WHEN status data is unavailable, THE system SHALL gracefully fall back to string display

## Technical Implementation

### Component Architecture

```
ShotBrowser.vue (Main Container)
├── ShotTableToolbar.vue (Sticky Toolbar)
│   ├── Episode Filter (Popover)
│   ├── Task Status Filter (Popover + Command)
│   ├── Column Visibility (Popover + Command)
│   ├── Search Input (Right-aligned)
│   └── Action Buttons (Icon-only)
├── ShotsDataTable.vue (TanStack Table)
│   └── columns.ts (Column Definitions)
└── ShotDeleteConfirmDialog.vue (Enhanced Deletion)
    └── TaskStatusBadge.vue (Status Display)
```

### Key Technical Features

#### 1. TanStack Table Integration
- **Type Safety**: Full TypeScript support with proper column definitions
- **Performance**: Optimized rendering for large datasets
- **Sorting**: Built-in sorting with directional icons
- **Column Management**: Robust show/hide functionality
- **State Management**: Proper sorting and visibility state handling

#### 2. Enhanced Column Definitions
```typescript
// Directional sort icons
const getSortIcon = (sortDirection: false | 'asc' | 'desc') => {
  if (sortDirection === 'asc') return h(ArrowUp, { class: 'ml-2 h-4 w-4' })
  if (sortDirection === 'desc') return h(ArrowDown, { class: 'ml-2 h-4 w-4' })
  return h(ArrowUpDown, { class: 'ml-2 h-4 w-4' })
}

// Independent frames column
{
  accessorKey: 'frame_end',
  id: 'frames',
  header: ({ column }) => h(Button, {
    variant: 'ghost',
    onClick: () => column.toggleSorting(column.getIsSorted() === 'asc'),
  }, () => ['Frames', getSortIcon(column.getIsSorted())]),
  cell: ({ row }) => {
    const frameCount = row.original.frame_end - row.original.frame_start + 1
    return h('span', { class: 'text-sm font-medium' }, frameCount.toString())
  },
}
```

#### 3. Advanced Filtering System
```vue
<!-- Task Status Filter with Multi-select -->
<Popover v-model:open="isOpen">
  <PopoverTrigger asChild>
    <Button variant="outline" size="sm" class="h-8">
      <Filter class="h-4 w-4 mr-2" />
      Task Status
      <Badge v-if="selectedCount > 0" class="ml-2">{{ selectedCount }}</Badge>
    </Button>
  </PopoverTrigger>
  <PopoverContent class="w-64 p-0">
    <Command>
      <CommandInput placeholder="Search statuses..." />
      <CommandList>
        <!-- Status options with checkboxes -->
      </CommandList>
    </Command>
  </PopoverContent>
</Popover>
```

#### 4. Custom Status Integration
```typescript
// Status mapping for proper display
const statusMap = computed(() => {
  if (!allTaskStatuses.value) return new Map()
  
  const map = new Map()
  
  // Add system statuses
  allTaskStatuses.value.system_statuses.forEach(status => {
    map.set(status.id, {
      id: status.id,
      name: status.name,
      color: status.color,
      is_system: status.is_system
    })
  })
  
  // Add custom statuses
  allTaskStatuses.value.statuses.forEach(status => {
    map.set(status.id, {
      id: status.id,
      name: status.name,
      color: status.color,
      is_system: false
    })
  })
  
  return map
})
```

#### 5. Enhanced Deletion Dialog
```vue
<!-- Task information with status badges -->
<div v-for="task in tasks" :key="task.id" class="flex items-center justify-between p-3">
  <div class="flex-1">
    <div class="font-medium">{{ task.name }}</div>
    <div class="flex items-center gap-2 mt-1">
      <span class="text-sm text-muted-foreground">{{ task.task_type }}</span>
      <TaskStatusBadge :status="getStatusForTask(task.status)" compact />
    </div>
  </div>
  <div v-if="task.assigned_user" class="text-sm text-muted-foreground">
    Assigned to: {{ task.assigned_user.name || task.assigned_user.email }}
  </div>
</div>
```

## Design Patterns

### 1. Consistent Component Heights
All toolbar components use `h-8` class (32px height) for visual consistency:
- Filter buttons: `h-8`
- Search input: `h-8`
- Action buttons: `h-8 w-8` (square)
- Dropdown triggers: `h-8`

### 2. Icon-Only Action Buttons
Action buttons display only icons for clean, compact design:
```vue
<Button variant="outline" size="sm" class="h-8 w-8 p-0">
  <Plus class="h-4 w-4" />
</Button>
```

### 3. Unified Filter Pattern
All filters use the same Popover + Command pattern:
- Consistent trigger button styling
- Same popover content structure
- Unified search functionality
- Badge counters for active filters

### 4. Full Width Layout
Optimized screen space utilization:
- Removed container padding restrictions
- Full width toolbar and table
- Proper spacing only where needed
- Responsive design maintained

## Backend Integration

### Enhanced Shot Deletion
```python
@router.get("/{shot_id}/deletion-info")
async def get_shot_deletion_info(shot_id: int, db: Session = Depends(get_db)):
    """Get information about what will be deleted with the shot"""
    # Returns task count, task details, and user assignments

@router.delete("/{shot_id}")
async def delete_shot(shot_id: int, force: bool = False, db: Session = Depends(get_db)):
    """Delete shot with optional cascade deletion of tasks"""
    # When force=true, deletes all associated tasks
```

### Custom Status Support
Integration with custom task status service:
- Fetches project-specific statuses
- Maps status IDs to display objects
- Handles both system and custom statuses
- Graceful fallback for missing statuses

## Performance Optimizations

### 1. Efficient State Management
- Session storage for column visibility
- Optimized re-renders with computed properties
- Proper Vue reactivity patterns

### 2. TanStack Table Benefits
- Virtual scrolling capability
- Optimized sorting algorithms
- Efficient column management
- Minimal re-renders

### 3. Smart Data Loading
- Fetch custom statuses only when needed
- Cache status mappings
- Efficient task status queries

## Testing Strategy

### Completed Testing
1. ✅ Sort direction icons display correctly
2. ✅ Column visibility persists across sessions
3. ✅ Task status filtering works with custom statuses
4. ✅ Deletion dialog shows correct task information
5. ✅ Toolbar layout matches task page structure
6. ✅ Full width layout works on all screen sizes
7. ✅ Custom status colors display properly
8. ✅ Cascade deletion removes all associated tasks

### Integration Points
- Shot table integrates with project shots view
- Detail panel opens correctly from table rows
- Episode filtering works across all view modes
- Search functionality works with all filters
- Bulk operations maintain selection state

## Future Enhancements

### Planned Improvements
1. **Bulk Shot Operations** - Multi-select with bulk actions
2. **Advanced Search** - Search across multiple fields
3. **Export Functionality** - CSV/Excel export
4. **Column Reordering** - Drag and drop columns
5. **Saved Views** - Save custom table configurations
6. **Real-time Updates** - WebSocket integration
7. **Performance Monitoring** - Track table performance metrics

### Technical Debt
1. Consider extracting common filter patterns into reusable composables
2. Optimize custom status fetching with caching
3. Add comprehensive error handling for edge cases
4. Implement loading states for better UX

## Success Metrics

### Achieved Goals
1. ✅ **Usability**: Consistent 32px component heights improve visual harmony
2. ✅ **Functionality**: Directional sort icons provide clear user feedback
3. ✅ **Safety**: Enhanced deletion dialog prevents accidental data loss
4. ✅ **Flexibility**: Column visibility and filtering support diverse workflows
5. ✅ **Performance**: TanStack Table handles large datasets efficiently
6. ✅ **Consistency**: UI patterns match across all data tables
7. ✅ **Customization**: Custom status support enables project-specific workflows

### User Feedback Integration
- Toolbar restructuring based on task page consistency request
- Search field positioning based on user preference
- Icon-only buttons for cleaner interface
- Full width layout for better space utilization
- Enhanced deletion confirmation for safety

## Conclusion

The shot table implementation represents a comprehensive, production-ready solution that addresses all user requirements while maintaining high code quality and performance standards. The implementation follows modern Vue.js and TypeScript best practices, integrates seamlessly with the existing application architecture, and provides a solid foundation for future enhancements.

The specification captures the current state of implementation and serves as a reference for maintenance, testing, and future development efforts.
