LinkDesk/.kiro/specs/vfx-project-management/design.md

1821 lines
70 KiB
Markdown

# Design Document
## Overview
The VFX Project Management System is a web-based application designed to streamline animation and VFX production workflows. The system follows a modern three-tier architecture with a FastAPI backend, SQLite database, and Vue.js frontend using shadcn-vue components.
The system supports role-based access control with four functional user roles (director, coordinator, artist, developer) plus an independent admin permission that can be granted to users of any role, along with department-based specialization. It manages the complete production pipeline from asset creation through shot completion, including review and approval workflows.
## Architecture
### System Architecture
```mermaid
graph TB
subgraph "Frontend Layer"
A[Vue.js Application]
B[shadcn-vue Components]
C[Sidebar07 Layout]
end
subgraph "Backend Layer"
D[FastAPI Application]
E[Authentication Middleware]
F[Role-based Authorization]
G[File Upload Handler]
end
subgraph "Data Layer"
H[SQLite Database]
I[File Storage System]
end
A --> D
B --> A
C --> A
D --> E
E --> F
D --> G
D --> H
G --> I
```
### Technology Stack
- **Frontend**: Vue.js 3 with Composition API, TypeScript
- **UI Components**: shadcn-vue component library
- **Layout**: Sidebar07 layout pattern
- **Backend**: FastAPI with Python 3.9+
- **Database**: SQLite with SQLAlchemy ORM
- **Authentication**: JWT tokens with refresh mechanism
- **File Storage**: Local file system with organized directory structure
- **API**: RESTful endpoints with OpenAPI documentation
## Design Decisions and Rationale
### Developer Role Design Decision
The developer role was introduced to support external integrations and automation tools while maintaining security boundaries. Key design decisions:
- **Read-Only by Default**: Developers can view all project data but cannot modify production data unless explicitly granted additional permissions. This prevents accidental data corruption while enabling comprehensive automation.
- **API Key Management**: Developers can create and manage their own API keys, reducing administrative overhead while maintaining security through scoped permissions.
- **Separate Interface**: Developer-specific UI components provide tools for integration management without cluttering the production interface.
### API Key Authentication Design Decision
API key authentication was implemented as an alternative to JWT tokens specifically for external application integration:
- **Scoped Permissions**: API keys support fine-grained scopes to limit access to specific operations, following the principle of least privilege.
- **User Association**: API keys inherit the permissions of the user who created them, ensuring consistent authorization across authentication methods.
- **Usage Tracking**: Comprehensive logging enables security auditing and usage analytics for integration monitoring.
- **Flexible Expiration**: Configurable expiration dates balance security with operational convenience for long-running integrations.
### Four-Role System with Independent Admin Permission Rationale
The system supports four distinct functional roles plus independent admin permission to match typical VFX production hierarchies:
**Functional Roles:**
- **Director**: Creative approval and review workflows
- **Coordinator**: Production management and scheduling
- **Artist**: Task execution and work submission
- **Developer**: Integration development and automation
**Admin Permission:**
- **Independent Permission**: Can be granted to users of any functional role
- **System Administration**: User management, role assignment, and system configuration
- **Flexible Administration**: Allows coordinators or directors to have admin privileges without changing their primary functional role
This structure aligns with industry standards where administrative responsibilities may be distributed among different functional roles, providing clear separation of concerns while maintaining flexible permission boundaries.
## Components and Interfaces
### Frontend Components
#### Core Layout Components
- **AppLayout**: Implements Sidebar07 layout with role-based navigation
- **Sidebar**: Dynamic navigation based on user role and permissions with integrated ProjectSwitcher
- **Header**: User profile, notifications, episode dropdown, and global actions
- **MainContent**: Route-based content area
- **ProjectSwitcher**: Dropdown component in sidebar for switching between projects with automatic loading
- **ProjectTabs**: Tab navigation component for project pages (Overview | Shots | Assets)
- **EpisodeDropdown**: Dropdown component for episode navigation within the Shots tab only
#### Feature Components
- **ProjectDashboard**: Overview of all projects with progress indicators (ftrack-style project cards)
- **TaskList**: Artist task view with filtering and sorting (ftrack My Tasks interface)
- **ReviewInterface**: Media player with approval/retake controls (ftrack Review interface)
- **UserManagement**: Admin interface for user and role management with comprehensive CRUD operations
- **AdminUserTable**: Data table component displaying all users with sortable columns and filters
- **UserCreateDialog**: Modal dialog for creating new user accounts with all required fields
- **UserEditDialog**: Modal dialog for editing existing user information including password reset
- **UserDeleteConfirmation**: Confirmation dialog with warnings for users with project associations
- **AssetBrowser**: Categorized asset management interface (ftrack Asset Manager)
- **AssetTable**: Enhanced table view with task status columns, thumbnails, sorting, and filtering
- **ColumnVisibilityControl**: Dropdown menu component for controlling individual column visibility
- **ThumbnailToggle**: Switch component for showing/hiding thumbnail column
- **TaskStatusBadge**: Visual status indicator component with consistent width for proper alignment
- **EpisodeManager**: Episode creation and management interface with dropdown navigation
- **ProjectTabs**: Tab navigation system for project pages with Overview, Shots, and Assets tabs
- **ShotTracker**: Shot-based task and progress tracking (ftrack Shot Manager)
- **ShotCreator**: Bulk shot creation with default task templates
- **ShotDetailPanel**: Comprehensive shot information panel with tabbed interface (Notes | Tasks | Assets | References | Design)
- **SpreadsheetView**: Tabular data view for bulk operations (ftrack spreadsheet interface)
- **TimelineView**: Gantt-style timeline for project scheduling
- **ActivityFeed**: Real-time updates and notifications stream
#### Shared Components
- **MediaPlayer**: Video/image viewer with annotation support
- **FileUpload**: Drag-and-drop file upload with progress
- **TaskCard**: Reusable task display component
- **StatusBadge**: Visual status indicators
- **DatePicker**: Deadline and scheduling interface
- **TaskDetailPanel**: Right-side panel for selected task information
- **NotesSection**: Threaded notes with rich text editing
- **AttachmentGallery**: File attachment viewer with thumbnails
- **ReferenceViewer**: Reference image/video display with comparison tools
#### Developer-Specific Components
- **APIKeyManager**: Interface for creating, viewing, and revoking API keys
- **IntegrationDashboard**: Overview of external application integrations
- **UsageAnalytics**: API usage statistics and logging interface
- **ScopeSelector**: Component for defining API key permissions and scopes
- **DeveloperConsole**: Read-only access to all project data for automation purposes
#### Technical Specifications Components
- **ProjectTechnicalSpecs**: Form component for editing project technical specifications
- **TechnicalSpecsDisplay**: Read-only display of project technical specifications for artists
- **FrameRateSelector**: Dropdown component with common frame rate presets
- **ResolutionSelector**: Dropdown component with standard delivery resolutions
- **PathSelector**: File path input component with validation
- **DeliveryMovieSpecsEditor**: Component for configuring delivery movie specifications per department
- **MovieFormatSelector**: Dropdown component with standard movie formats and codecs
- **DepartmentSpecsPanel**: Component showing department-specific delivery requirements
- **TechnicalSpecsPanel**: Collapsible panel showing technical specs in project views
#### Global Settings Components
- **GlobalUploadLimitEditor**: Admin interface for setting site-wide upload size limit for movie files
- **UploadLimitDisplay**: Component showing current upload limit to artists during file submission
- **GlobalSettingsPanel**: Admin panel for managing all global system settings
#### Shot Detail Panel Design
The **ShotDetailPanel** component provides a comprehensive view of shot information organized into five tabs:
**Layout Structure:**
1. **Header Section**: Shot name, frame range, status badge, and action menu (edit/delete)
2. **Shot Information**: Description, creation date, and last updated date
3. **Progress Overview**: Visual progress bar and task status summary (always visible above tabs)
4. **Tabbed Content Area**: Five tabs for different information categories
**Tab Specifications:**
1. **Notes Tab**
- Purpose: Production notes and comments about the shot
- Content: Threaded notes with timestamps and user avatars
- Actions: "Add Note" button (coordinators/admins only)
- Empty State: Helpful message encouraging note creation
- Icon: MessageSquare
2. **Tasks Tab** (Default)
- Purpose: List and manage all tasks for the shot
- Content: Task cards with status badges, assignment info, and deadlines
- Actions: "Add Task" button (coordinators/admins only)
- Features: Click task to open detail panel, loading states
- Empty State: Message about creating tasks
- Icon: ListTodo
3. **Assets Tab**
- Purpose: Display and manage assets linked to the shot
- Content: Asset cards with thumbnails and status information
- Actions: "Link Asset" button (coordinators/admins only)
- Empty State: Message about linking assets
- Icon: Package
4. **References Tab**
- Purpose: Reference files for the shot
- Content: Gallery of reference images, videos, and documents
- Actions: "Upload Reference" button (all users)
- Features: File preview, download, and delete
- Empty State: Message about uploading references
- Icon: Image
5. **Design Tab**
- Purpose: Design specifications and notes
- Content: Camera notes, lighting notes, animation notes
- Actions: "Edit Design" button (coordinators/admins only)
- Empty State: Placeholder text for each note type
- Icon: Edit
**Permission Model:**
- Add Note: Coordinators & Admins
- Add Task: Coordinators & Admins
- Link Asset: Coordinators & Admins
- Upload Reference: All Users
- Edit Design: Coordinators & Admins
**User Experience:**
- Default tab is "Tasks" for immediate access to work items
- Progress overview remains visible when switching tabs
- Smooth tab transitions with proper loading states
- Empty states guide users on next actions
- Role-based action buttons prevent unauthorized operations
#### Asset Detail Panel Design
The **AssetDetailPanel** component provides a comprehensive view of asset information organized into four tabs, similar to the Shot Detail Panel:
**Layout Structure:**
1. **Header Section**: Asset name, category badge, status badge, and action menu (edit/delete)
2. **Asset Information**: Description, creation date, and last updated date
3. **Progress Overview**: Visual progress bar and task status summary (always visible above tabs)
4. **Tabbed Content Area**: Four tabs for different information categories
**Tab Specifications:**
1. **Tasks Tab** (Default)
- Purpose: List and manage all tasks for the asset
- Content: Task cards with status badges, assignment info, and deadlines
- Actions: "Add Task" button (coordinators/admins only)
- Features: Click task to open task detail panel, loading states
- Empty State: Message about creating tasks
- Icon: ListTodo
- Integration: Uses existing TaskList component with asset_id filter
2. **Notes Tab**
- Purpose: Production notes and comments about the asset
- Content: Threaded notes with timestamps and user avatars
- Actions: "Add Note" button (coordinators/admins only)
- Empty State: Helpful message encouraging note creation
- Icon: MessageSquare
3. **References Tab**
- Purpose: Reference files for the asset (concept art, reference images, etc.)
- Content: Gallery of reference images, videos, and documents
- Actions: "Upload Reference" button (all users)
- Features: File preview, download, and delete
- Empty State: Message about uploading references
- Icon: Image
4. **Versions Tab**
- Purpose: Track asset version history and published files
- Content: List of asset versions with timestamps and user info
- Actions: "Publish Version" button (artists/coordinators/admins)
- Features: Version comparison, download previous versions
- Empty State: Message about publishing first version
- Icon: History
**Permission Model:**
- Add Task: Coordinators & Admins
- Add Note: Coordinators & Admins
- Upload Reference: All Users
- Publish Version: Artists, Coordinators & Admins
- Edit Asset: Coordinators & Admins
- Delete Asset: Coordinators & Admins
**User Experience:**
- Default tab is "Tasks" for immediate access to work items
- Progress overview remains visible when switching tabs
- Smooth tab transitions with proper loading states
- Empty states guide users on next actions
- Role-based action buttons prevent unauthorized operations
- Panel slides in from the right side of the screen
- Clicking outside or close button returns to asset browser
- Asset browser state is maintained when panel opens/closes
**Integration with Asset Browser:**
- Clicking an asset card in AssetBrowser opens AssetDetailPanel
- Panel overlays the asset browser (similar to ShotDetailPanel)
- URL updates to include asset ID for direct linking
- Browser back button closes the panel
### Backend API Structure
#### Authentication Endpoints
```
POST /auth/register - User registration
POST /auth/login - User authentication
POST /auth/refresh - Token refresh
POST /auth/logout - User logout
POST /auth/api-keys - Generate API key (developer/admin only)
GET /auth/api-keys - List user's API keys
DELETE /auth/api-keys/{key_id} - Revoke API key
```
#### User Management Endpoints
```
GET /users - List all users (admin permission required)
POST /users/{user_id}/approve - Approve user registration (admin permission required)
PUT /users/{user_id}/role - Update user role (admin permission required)
PUT /users/{user_id}/admin - Grant/revoke admin permission (admin permission required)
GET /users/me - Get current user profile
PUT /users/me - Update current user profile
```
#### Project Management Endpoints
```
GET /projects - List projects
POST /projects - Create new project with technical specifications
GET /projects/{project_id} - Get project details including technical specs
PUT /projects/{project_id} - Update project and technical specifications
DELETE /projects/{project_id} - Delete project
GET /projects/{project_id}/technical-specs - Get project technical specifications
PUT /projects/{project_id}/technical-specs - Update project technical specifications
GET /projects/{project_id}/settings - Get project-specific settings
PUT /projects/{project_id}/settings - Update project settings (upload location, default tasks)
```
#### Episode Management Endpoints
```
GET /projects/{project_id}/episodes - List project episodes
POST /projects/{project_id}/episodes - Create new episode
GET /episodes/{episode_id} - Get episode details
PUT /episodes/{episode_id} - Update episode
DELETE /episodes/{episode_id} - Delete episode
```
#### Asset Management Endpoints
```
GET /projects/{project_id}/assets - List project assets with task status details
POST /projects/{project_id}/assets - Create new asset with default tasks
GET /assets/{asset_id} - Get asset details
PUT /assets/{asset_id} - Update asset
GET /assets/categories - List asset categories
GET /assets/default-tasks/{category} - Get default tasks for asset category
GET /assets/{asset_id}/task-status - Get detailed task status for asset
POST /assets/{asset_id}/references - Upload reference files
GET /assets/{asset_id}/references - Get asset reference files
DELETE /assets/{asset_id}/references/{file_id} - Delete reference file
```
#### Shot Management Endpoints
```
GET /episodes/{episode_id}/shots - List episode shots
POST /episodes/{episode_id}/shots - Create new shot with default tasks
GET /shots/{shot_id} - Get shot details
PUT /shots/{shot_id} - Update shot
DELETE /shots/{shot_id} - Delete shot
POST /episodes/{episode_id}/shots/bulk - Create multiple shots with default tasks
POST /shots/{shot_id}/references - Upload reference files
GET /shots/{shot_id}/references - Get shot reference files
DELETE /shots/{shot_id}/references/{file_id} - Delete reference file
```
#### Task Management Endpoints
```
GET /tasks - List tasks (filtered by user role)
POST /tasks - Create new task
GET /tasks/{task_id} - Get task details
PUT /tasks/{task_id}/status - Update task status
POST /tasks/{task_id}/submit - Submit work for review
GET /tasks/{task_id}/notes - Get task notes
POST /tasks/{task_id}/notes - Add note to task
PUT /tasks/{task_id}/notes/{note_id} - Update task note
DELETE /tasks/{task_id}/notes/{note_id} - Delete task note
GET /tasks/{task_id}/attachments - Get task attachments
POST /tasks/{task_id}/attachments - Upload task attachment
DELETE /tasks/{task_id}/attachments/{attachment_id} - Delete attachment
POST /tasks/{task_id}/references - Upload reference files
GET /tasks/{task_id}/references - Get task reference files
DELETE /tasks/{task_id}/references/{file_id} - Delete reference file
```
#### Review Endpoints
```
GET /reviews/pending - List pending reviews
POST /reviews/{task_id}/approve - Approve submission
POST /reviews/{task_id}/retake - Request retake with notes
```
#### Developer Integration Endpoints
```
GET /developer/projects - List all projects (developer role only)
GET /developer/tasks - List all tasks across projects (developer role only)
GET /developer/submissions - List all submissions (developer role only)
GET /developer/api-keys - Manage API keys
POST /developer/api-keys - Create scoped API key
PUT /developer/api-keys/{key_id} - Update API key scopes
GET /developer/usage-logs - View API usage logs
```
#### Global Settings Endpoints
```
GET /settings/upload-limit - Get global upload size limit for movie files
PUT /settings/upload-limit - Update global upload size limit (admin permission required)
GET /settings - Get all global settings (admin permission required)
PUT /settings/{setting_key} - Update specific global setting (admin permission required)
```
## Data Models
### Database Schema
```mermaid
erDiagram
User ||--o{ ProjectMember : "belongs to"
User ||--o{ Task : "assigned to"
User ||--o{ Submission : "creates"
User ||--o{ Review : "creates"
User ||--o{ APIKey : "owns"
Project ||--o{ ProjectMember : "has"
Project ||--o{ Episode : "contains"
Project ||--o{ Asset : "contains"
Episode ||--o{ Shot : "contains"
Shot ||--o{ Task : "has"
Asset ||--o{ Task : "has"
Asset ||--o{ ReferenceFile : "has"
Shot ||--o{ ReferenceFile : "has"
Task ||--o{ ReferenceFile : "has"
Task ||--o{ Submission : "has"
Task ||--o{ ProductionNote : "has"
Task ||--o{ TaskAttachment : "has"
Submission ||--o{ Review : "has"
User {
int id PK
string email UK
string password_hash
string first_name
string last_name
enum role
boolean is_admin
boolean is_approved
datetime created_at
datetime updated_at
}
APIKey {
int id PK
int user_id FK
string key_hash
string name
string scopes
boolean is_active
datetime expires_at
datetime last_used_at
datetime created_at
}
Project {
int id PK
string name
string code_name
string client_name
enum project_type
string description
enum status
date start_date
date end_date
float frame_rate
string data_drive_path
string publish_storage_path
string delivery_image_resolution
json delivery_movie_specs_by_department
string upload_data_location
json asset_task_templates
json shot_task_templates
json enabled_asset_tasks
json enabled_shot_tasks
datetime created_at
datetime updated_at
}
ProjectMember {
int id PK
int user_id FK
int project_id FK
enum department_role
datetime joined_at
datetime updated_at
}
Asset {
int id PK
int project_id FK
string name
enum category
string description
enum status
datetime created_at
datetime updated_at
}
AssetTaskStatus {
int asset_id FK
enum task_type
enum task_status
int task_id FK
datetime updated_at
}
ReferenceFile {
int id PK
int asset_id FK
int shot_id FK
int task_id FK
string file_name
string file_path
string file_type
enum reference_type
string description
string caption
int file_size
datetime uploaded_at
}
Episode {
int id PK
int project_id FK
string name
string description
int episode_number
enum status
datetime created_at
datetime updated_at
}
Shot {
int id PK
int episode_id FK
string name
string description
int frame_start
int frame_end
enum status
datetime created_at
datetime updated_at
}
Task {
int id PK
int project_id FK
int episode_id FK
int shot_id FK
int asset_id FK
int assigned_user_id FK
enum task_type
string name
string description
enum status
date deadline
datetime created_at
datetime updated_at
}
Submission {
int id PK
int task_id FK
int user_id FK
string file_path
string file_name
int version_number
string notes
datetime submitted_at
}
Review {
int id PK
int submission_id FK
int reviewer_id FK
enum decision
string feedback
datetime reviewed_at
}
ProductionNote {
int id PK
int task_id FK
int user_id FK
string content
int parent_note_id FK
datetime created_at
datetime updated_at
}
TaskAttachment {
int id PK
int task_id FK
int user_id FK
string file_name
string file_path
string file_type
int file_size
enum attachment_type
string description
datetime uploaded_at
}
GlobalSettings {
int id PK
string setting_key UK
string setting_value
string description
datetime created_at
datetime updated_at
}
```
### Technical Specifications Data Structure
```python
# Project Technical Specifications
class ProjectTechnicalSpecs(BaseModel):
frame_rate: float = Field(..., ge=1.0, le=120.0, description="Frames per second (1-120 fps)")
data_drive_path: str = Field(..., description="Physical path for project data storage")
publish_storage_path: str = Field(..., description="Path for approved work delivery")
delivery_image_resolution: str = Field(..., description="Required image resolution (e.g., '1920x1080', '4096x2160')")
delivery_movie_specs_by_department: Dict[str, DeliveryMovieSpec] = Field(
default_factory=dict,
description="Delivery movie resolution and format specifications per department"
)
# Delivery Movie Specifications per Department
class DeliveryMovieSpec(BaseModel):
resolution: str = Field(..., description="Movie resolution (e.g., '1920x1080', '2048x1080')")
format: str = Field(..., description="Movie format (e.g., 'mov', 'mp4', 'exr')")
codec: Optional[str] = Field(None, description="Video codec (e.g., 'h264', 'prores', 'dnxhd')")
quality: Optional[str] = Field(None, description="Quality setting (e.g., 'high', 'medium', 'low')")
# Default global upload size limit (in MB) - Site-wide configuration
DEFAULT_GLOBAL_UPLOAD_LIMIT_MB = 1000 # 1GB default limit for movie files
# Default delivery movie specifications per department
DEFAULT_DELIVERY_MOVIE_SPECS = {
"layout": {
"resolution": "1920x1080",
"format": "mov",
"codec": "h264",
"quality": "medium"
},
"animation": {
"resolution": "1920x1080",
"format": "mov",
"codec": "h264",
"quality": "high"
},
"lighting": {
"resolution": "2048x1080",
"format": "exr",
"codec": None,
"quality": "high"
},
"composite": {
"resolution": "2048x1080",
"format": "mov",
"codec": "prores",
"quality": "high"
}
}
# Default asset tasks by category
DEFAULT_ASSET_TASKS = {
"characters": ["modeling", "surfacing", "rigging"],
"props": ["modeling", "surfacing"],
"sets": ["modeling", "surfacing"],
"vehicles": ["modeling", "surfacing", "rigging"]
}
# Default shot tasks by type
DEFAULT_SHOT_TASKS = ["layout", "animation", "simulation", "lighting", "compositing"]
# Project-specific settings structure
class ProjectSettings(BaseModel):
upload_data_location: str = Field(..., description="Custom upload storage path for project files")
asset_task_templates: Dict[str, List[str]] = Field(
default_factory=lambda: DEFAULT_ASSET_TASKS.copy(),
description="Custom default tasks per asset category"
)
shot_task_templates: List[str] = Field(
default_factory=lambda: DEFAULT_SHOT_TASKS.copy(),
description="Custom default tasks for shots"
)
enabled_asset_tasks: Dict[str, List[str]] = Field(
default_factory=dict,
description="Enabled/disabled status for asset tasks per category"
)
enabled_shot_tasks: List[str] = Field(
default_factory=lambda: DEFAULT_SHOT_TASKS.copy(),
description="Enabled/disabled status for shot tasks"
)
# Common frame rates for VFX projects
COMMON_FRAME_RATES = [23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0]
# Standard delivery resolutions
STANDARD_RESOLUTIONS = [
"1920x1080", # HD
"2048x1080", # 2K DCI
"3840x2160", # 4K UHD
"4096x2160", # 4K DCI
"1280x720", # HD 720p
"2560x1440", # QHD
]
# Standard movie formats for VFX delivery
STANDARD_MOVIE_FORMATS = ["mov", "mp4", "exr", "dpx", "tiff"]
# Standard video codecs
STANDARD_VIDEO_CODECS = ["h264", "h265", "prores", "dnxhd", "dnxhr", "uncompressed"]
# Quality settings
QUALITY_SETTINGS = ["low", "medium", "high", "lossless"]
```
### Enums and Constants
```python
# User Roles (Functional Roles)
class UserRole(str, Enum):
DIRECTOR = "director"
COORDINATOR = "coordinator"
ARTIST = "artist"
DEVELOPER = "developer"
# Department Roles
class DepartmentRole(str, Enum):
LAYOUT = "layout"
ANIMATION = "animation"
LIGHTING = "lighting"
COMPOSITE = "composite"
MODELING = "modeling"
RIGGING = "rigging"
SURFACING = "surfacing"
# Asset Categories
class AssetCategory(str, Enum):
CHARACTERS = "characters"
PROPS = "props"
SETS = "sets"
VEHICLES = "vehicles"
# Task Types
class TaskType(str, Enum):
# Shot tasks
LAYOUT = "layout"
ANIMATION = "animation"
SIMULATION = "simulation"
LIGHTING = "lighting"
COMPOSITING = "compositing"
# Asset tasks
MODELING = "modeling"
SURFACING = "surfacing"
RIGGING = "rigging"
# Status Types
class TaskStatus(str, Enum):
NOT_STARTED = "not_started"
IN_PROGRESS = "in_progress"
SUBMITTED = "submitted"
APPROVED = "approved"
RETAKE = "retake"
class ReviewDecision(str, Enum):
APPROVED = "approved"
RETAKE = "retake"
# Attachment Types
class AttachmentType(str, Enum):
REFERENCE = "reference"
WORK_FILE = "work_file"
PREVIEW = "preview"
DOCUMENTATION = "documentation"
# Reference File Types
class ReferenceFileType(str, Enum):
IMAGE = "image"
DOCUMENT = "document"
VIDEO = "video"
AUDIO = "audio"
# API Key Scopes
class APIKeyScope(str, Enum):
READ_PROJECTS = "read:projects"
READ_TASKS = "read:tasks"
READ_SUBMISSIONS = "read:submissions"
READ_USERS = "read:users"
WRITE_TASKS = "write:tasks"
WRITE_SUBMISSIONS = "write:submissions"
ADMIN_USERS = "admin:users"
FULL_ACCESS = "full:access"
```
## Error Handling
### Authentication Flow Design
#### JWT Token Authentication (Web Interface)
1. User submits login credentials
2. Backend validates credentials and generates JWT access/refresh token pair
3. Frontend stores tokens securely and includes access token in API requests
4. Backend validates JWT token and extracts user permissions
5. Automatic token refresh when access token expires
#### API Key Authentication (External Integrations)
1. Developer/Admin creates API key through web interface
2. API key is generated with specified scopes and expiration
3. External application includes API key in request headers
4. Backend validates API key hash and checks scopes
5. Request is authorized based on key creator's permissions and key scopes
6. Usage is logged for security auditing
### Frontend Error Handling
- **Network Errors**: Retry mechanism with exponential backoff
- **Authentication Errors**: Automatic token refresh and redirect to login for JWT; clear error messages for API key failures
- **Validation Errors**: Form-level error display with field highlighting
- **File Upload Errors**: Progress indication with error recovery options
- **Permission Errors**: Graceful degradation with appropriate messaging
- **API Key Errors**: Specific error codes for expired, revoked, or insufficient scope scenarios
### Backend Error Handling
- **HTTP Status Codes**: Consistent use of appropriate status codes
- **Error Response Format**: Standardized JSON error responses
- **Validation Errors**: Detailed field-level error information
- **Database Errors**: Transaction rollback with user-friendly messages
- **File System Errors**: Graceful handling of storage issues
### Error Response Schema
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": {
"field_name": ["Field-specific error message"]
}
}
}
```
## Testing Strategy
### Frontend Testing
- **Unit Tests**: Vue component testing with Vue Test Utils
- **Integration Tests**: API integration testing with mock backend
- **E2E Tests**: Critical user flows with Playwright
- **Visual Regression**: Component visual testing with Chromatic
### Backend Testing
- **Unit Tests**: FastAPI endpoint testing with pytest
- **Integration Tests**: Database integration with test fixtures
- **API Tests**: OpenAPI schema validation
- **Performance Tests**: Load testing for file upload endpoints
### Test Coverage Goals
- **Backend**: Minimum 80% code coverage
- **Frontend**: Minimum 70% component coverage
- **Critical Paths**: 100% coverage for authentication and review workflows
### Testing Environment
- **Database**: In-memory SQLite for fast test execution
- **File Storage**: Temporary directories for upload testing
- **Authentication**: Mock JWT tokens for test scenarios
- **External Dependencies**: Mock services for isolated testing
## Security Considerations
### Authentication & Authorization
- **JWT Tokens**: Short-lived access tokens with refresh mechanism
- **API Key Authentication**: Alternative authentication method for external integrations
- **Role-based Access**: Endpoint-level permission checking with five distinct roles
- **Password Security**: Bcrypt hashing with salt
- **Session Management**: Secure token storage and invalidation
- **API Key Management**: Scoped API keys with usage logging and revocation capabilities
### Data Protection
- **Input Validation**: Comprehensive validation on all endpoints
- **SQL Injection**: SQLAlchemy ORM with parameterized queries
- **File Upload Security**: File type validation and size limits
- **CORS Configuration**: Restricted cross-origin access
### File Security
- **Upload Validation**: MIME type and extension checking
- **Storage Isolation**: User-specific directory structure
- **Access Control**: File access through authenticated endpoints only
- **Virus Scanning**: Integration point for file scanning services
### API Key Security
- **Key Generation**: Cryptographically secure random key generation
- **Key Hashing**: API keys stored as hashed values in database
- **Scope Limitation**: Fine-grained permission scopes for API keys
- **Usage Logging**: Comprehensive logging of API key usage for security auditing
- **Expiration Management**: Configurable expiration dates for API keys
- **Revocation**: Immediate key revocation capabilities for compromised keys
## UI/UX Workflow Design
### ftrack-Inspired Interface Patterns
#### Navigation Structure
- **Left Sidebar**: Project-based navigation with collapsible sections
- **Project Switcher**: Dropdown in sidebar header showing all available projects with automatic loading on login
- **Project Navigation**: Context-sensitive navigation items based on selected project
- **Top Bar**: Breadcrumb navigation and global search (similar to ftrack's navigation)
- **Project Tab System**: Tabbed interface within project pages (Overview | Shots | Assets)
- **Episode Dropdown**: Appears specifically in the Shots tab for episode-based shot filtering
- **Quick Episode Switching**: Users can switch between episodes within the Shots tab context
- **Right Detail Panel**: Context-sensitive task/asset information panel (ftrack-style)
- **Tab System**: Multi-tab interface for managing different views simultaneously
- **Three-Panel Layout**: Left navigation, center content, right details (ftrack layout)
#### Dashboard Layout (ftrack Projects Page)
- **Project Cards**: Visual project overview with progress bars and key metrics
- **Quick Actions**: Prominent buttons for common tasks (Create Shot, Assign Task)
- **Activity Stream**: Recent activity feed with user avatars and timestamps
- **Status Indicators**: Color-coded status badges throughout the interface
#### Task Management Interface (ftrack My Tasks)
- **Task List View**: Sortable/filterable list with priority indicators
- **Card View**: Visual task cards with thumbnails and status
- **Calendar View**: Timeline view for deadline management
- **Bulk Operations**: Multi-select with batch actions toolbar
- **Right Detail Panel**: Task-specific information panel (ftrack-style)
- **Department Filtering**: Task assignment interface filters available artists by matching department roles
- **Role-Based Assignment**: Visual indicators showing artist department specializations during task assignment
#### Task Detail Panel (ftrack Right Panel)
- **Task Information**: Name, description, status, deadline, assigned artist
- **Notes Section**: Threaded discussion with rich text formatting
- **Attachments Gallery**: Reference images, work files, and documentation
- **Version History**: Previous submissions with comparison tools
- **Activity Timeline**: Chronological activity feed for the task
- **Quick Actions**: Status updates, file uploads, and assignment changes
#### Review Interface (ftrack Review)
- **Media Player**: Central video/image player with frame controls
- **Annotation Tools**: Drawing tools for frame-specific feedback
- **Version Comparison**: Side-by-side version comparison
- **Comment Thread**: Threaded comments with timestamp markers
- **Approval Controls**: Clear approve/retake buttons with required feedback
#### Asset/Episode/Shot Browser (ftrack Asset Manager)
- **Hierarchical Tree**: Expandable tree structure (Project > Episode > Shot) for organization
- **Grid View**: Thumbnail grid with metadata overlay
- **Table View**: Detailed table view with task status columns and sorting capabilities
- **Detail Panel**: Right panel showing selected item details
- **Search/Filter**: Advanced filtering with saved filter presets
- **Bulk Operations**: Multi-select for batch shot creation and task assignment
#### Asset Table with Task Status Display and Thumbnails
- **Task Status Columns**: Individual columns for each task type (modeling, surfacing, rigging) showing status badges
- **Status Indicators**: Color-coded badges with consistent width (130px) for proper alignment and professional appearance
- **Column Visibility Control**: Comprehensive dropdown menu for showing/hiding individual columns (Name, Category, Status, Thumbnails, Task Status, Description, Updated)
- **Thumbnail Column**: Visual preview column displaying asset thumbnails with placeholder icons when no image is available
- **Thumbnail Toggle**: Separate toggle switch specifically for showing/hiding the thumbnail column
- **Status Sorting**: Sortable columns for each task type to identify assets by task progress
- **Category-Aware Display**: Task columns adapt based on asset category (characters show rigging, props don't)
- **Real-time Updates**: Task status changes reflect immediately in the table view
- **Status Filtering**: Filter assets by specific task status combinations
- **Session Persistence**: User preferences for column visibility and thumbnail display saved per session
- **Removed Task Count**: Task count column removed to focus on individual task status rather than aggregate counts
- **Progress Overview**: Quick visual assessment of production progress across all assets
#### Shot Table with Task Status Display
- **Task Status Columns**: Individual columns for each shot task type (layout, animation, simulation, lighting, compositing) showing status badges
- **Status Indicators**: Color-coded badges with consistent width (130px) matching asset table design
- **Column Visibility Control**: Dropdown menu for showing/hiding columns (Shot Name, Episode, Frame Range, Status, Task Status, Description)
- **Status Sorting**: Sortable columns for each task type to identify shots by task progress
- **Episode Display**: Shows episode name for each shot with clear visual grouping
- **Frame Range Display**: Shows start-end frame range with total frame count
- **Real-time Updates**: Task status changes reflect immediately in the table view
- **Status Filtering**: Filter shots by specific task status to identify shots needing attention
- **Session Persistence**: User preferences for column visibility saved per session
- **Progress Overview**: Quick visual assessment of shot production progress across episodes
- **Custom Task Types**: Dynamically displays custom shot task types alongside standard types
#### Project Switcher Component
- **Sidebar Integration**: Positioned at the top of the left sidebar as a prominent dropdown
- **Project Loading**: Automatically fetches and displays all available projects on application initialization
- **Visual Indicators**: Shows project status, type icons, and member count
- **Quick Access**: Keyboard shortcuts (⌘1, ⌘2, etc.) for switching between recent projects
- **Create Project**: Direct access to project creation for users with appropriate permissions
- **Project Context**: Updates entire application context when project is switched
#### Project Tab Navigation
- **Tab Layout**: Horizontal tab bar with Overview, Shots, and Assets tabs
- **Tab Persistence**: Active tab state maintained during project navigation
- **Tab-Specific Content**: Each tab displays relevant project information and tools
- **Responsive Design**: Tabs adapt to mobile/tablet layouts with appropriate spacing
#### Episode Navigation Component (Shots Tab Only)
- **Conditional Display**: Appears only when the Shots tab is active within a project
- **Top Bar Integration**: Positioned in the content area header within the Shots tab
- **Dropdown Menu**: Compact dropdown showing all episodes for the current project
- **Episode Filtering**: Automatically filters displayed shots based on selected episode
- **Episode Status**: Visual indicators for episode progress and status
- **Episode Creation**: Quick access to create new episodes for coordinators
- **All Episodes View**: Option to view shots from all episodes when no specific episode is selected
#### Project Page Tab System
- **Overview Tab**: Project summary, progress indicators, team members, and recent activity
- **Shots Tab**: Shot management with episode dropdown for filtering and organization
- **Episode Dropdown**: Contextual episode selection for shot filtering
- **Shot Grid/List**: Episode-filtered shot display with creation and management tools
- **Episode Context**: URL and state management for selected episode
- **Assets Tab**: Asset browser and management without episode context
- **Asset Categories**: Organized by asset type (characters, props, sets, vehicles)
- **Asset Grid/List**: Category-filtered asset display with creation tools
#### Asset Creation Workflow
- **Category-Based Task Generation**: Automatic task creation based on asset category
- **Default Task Templates**: Standard tasks created for each asset type (modeling, surfacing, rigging)
- **Customizable Task Creation**: Coordinators can modify which default tasks are created
- **Unassigned Tasks**: Default tasks created without artist assignment for later coordination
- **Standard Naming**: Consistent task naming conventions across all assets
#### Shot Creation Workflow
- **Episode-First**: Create episodes before shots for better organization
- **Tab-Based Access**: Shot creation accessed through the Shots tab
- **Episode Context**: Shot creation respects currently selected episode
- **Default Task Templates**: Automatic task creation based on shot type
- **Bulk Shot Creation**: Create multiple shots with naming conventions
- **Task Assignment**: Auto-assign tasks based on department roles and availability
#### Spreadsheet View (ftrack Spreadsheet)
- **Editable Grid**: In-line editing for bulk data management
- **Column Customization**: Show/hide columns based on user preferences
- **Sorting/Grouping**: Multi-level sorting and grouping options
- **Export Functions**: CSV/Excel export capabilities
### User Experience Patterns
#### Role-Based Interface Adaptation
- **Artist View**: Simplified interface focused on assigned tasks and submissions
- **Coordinator View**: Project overview with team management and scheduling tools
- **Director View**: Review-focused interface with approval workflows
- **Developer View**: API management interface with integration tools and read-only access to all project data
- **Admin Permission Features**: Additional system management controls available to users with admin permission regardless of their functional role
#### Admin User Management Interface
- **User Management Page**: Comprehensive admin interface for managing all user accounts
- **User Table View**: Data table displaying all users with columns for name, email, role, admin status, approval status, and actions
- **Search and Filter**: Real-time search by name or email, filter by role, approval status, or admin permission
- **Sortable Columns**: Click column headers to sort by any field (name, email, role, created date)
- **Add User Button**: Prominent button in page header to create new user accounts
- **User Actions Menu**: Dropdown menu for each user with Edit, Reset Password, and Delete options
- **Bulk Actions**: Select multiple users for batch operations (approve, delete, export)
**User Creation Dialog:**
- **Form Fields**: First name, last name, email, password, confirm password, role dropdown, approval checkbox, admin permission checkbox
- **Validation**: Real-time validation for email format, password strength, and duplicate email detection
- **Role Selection**: Dropdown with all four roles (artist, coordinator, director, developer)
- **Permission Toggles**: Checkboxes for "Approved" and "Admin Permission" with clear labels
- **Auto-Approval Option**: Allow admins to create pre-approved accounts
- **Password Requirements**: Display password requirements (minimum length, complexity)
**User Edit Dialog:**
- **Editable Fields**: First name, last name, email, role, approval status, admin permission
- **Password Reset Section**: Separate section with "Reset Password" button that opens password reset dialog
- **Current Values**: Pre-populate form with current user data
- **Change Tracking**: Highlight fields that have been modified
- **Validation**: Prevent duplicate emails and validate all fields before saving
- **Self-Protection**: Prevent admins from removing their own admin permission
**Password Reset Dialog:**
- **New Password Field**: Input for new password with strength indicator
- **Confirm Password Field**: Confirmation input with real-time matching validation
- **Generate Password Button**: Option to auto-generate secure password
- **Copy to Clipboard**: Button to copy generated password for sharing with user
- **Security Notice**: Warning that user will need to use new password on next login
**User Delete Confirmation:**
- **Warning Message**: Clear warning about permanent deletion
- **Association Check**: Display warning if user has project memberships or task assignments
- **Cascade Options**: Option to reassign tasks before deletion (if applicable)
- **Confirmation Input**: Require typing user email to confirm deletion
- **Cancel Button**: Prominent cancel option to prevent accidental deletion
**User Status Indicators:**
- **Approval Badge**: Green "Approved" or gray "Pending" badge
- **Admin Badge**: Red "Admin" badge for users with admin permission
- **Role Badge**: Color-coded badge for user role (artist, coordinator, director, developer)
- **Last Login**: Display last login timestamp for activity monitoring
#### User Profile Management Interface
- **Profile Page**: Personal profile page accessible to all registered users for managing account settings
- **Profile Header**: Large avatar display with user name, email, role badge, and account status
- **Profile Information Section**: Editable fields for first name and last name
- **Avatar Management Section**: Upload, preview, and remove profile avatar functionality
- **Password Change Section**: Secure password update form with current password verification
- **Account Information**: Read-only display of account creation date, last update, user ID, and account status
**Avatar Upload Component:**
- **Upload Area**: Drag-and-drop zone or click-to-browse file selector
- **Image Preview**: Real-time preview of selected image before upload
- **Crop Tool**: Built-in image cropping interface to select avatar area
- **Size Validation**: Client-side validation for 5MB maximum file size
- **Format Validation**: Accept only jpg, jpeg, png, gif, and webp formats
- **Upload Progress**: Progress bar showing upload status
- **Current Avatar Display**: Show existing avatar with option to remove
- **Default Placeholder**: Fallback to initials-based avatar when no image is uploaded
- **Remove Button**: Option to delete current avatar and revert to default
**Password Change Form:**
- **Current Password Field**: Required field to verify user identity
- **New Password Field**: Input for new password with show/hide toggle
- **Confirm Password Field**: Confirmation input with real-time matching validation
- **Password Requirements**: Display list of requirements (minimum 8 characters, uppercase, lowercase, number, special character)
- **Password Strength Indicator**: Visual meter showing password strength (weak, medium, strong)
- **Validation Messages**: Real-time feedback for password requirements and matching
- **Submit Button**: Disabled until all validations pass
- **Success Message**: Confirmation toast after successful password change
- **Error Handling**: Clear error messages for incorrect current password or validation failures
**Profile Update Features:**
- **Auto-Save Indicator**: Show when changes are being saved
- **Unsaved Changes Warning**: Prompt user before navigating away with unsaved changes
- **Success Notifications**: Toast messages for successful updates
- **Error Recovery**: Clear error messages with retry options
- **Form Validation**: Real-time validation for all editable fields
- **Optimistic Updates**: Update UI immediately while saving in background
#### Responsive Design Patterns
- **Mobile-First**: Touch-friendly interface for tablet/mobile access
- **Progressive Enhancement**: Desktop features that enhance mobile base
- **Adaptive Layout**: Interface adapts to screen size and orientation
- **Gesture Support**: Swipe gestures for navigation and actions
#### Notification System
- **Toast Notifications**: Non-intrusive status updates
- **Badge Indicators**: Unread count badges on navigation items
- **Email Integration**: Configurable email notifications for key events
- **Real-time Updates**: WebSocket-based live updates for collaborative work
- **Review Notifications**: Immediate notifications to artists when directors make review decisions
- **Submission Notifications**: Automatic notifications to directors when new submissions are available
- **Deadline Alerts**: Visual indicators and notifications for approaching task deadlines
#### Workflow Optimization
- **Quick Actions**: Context menus and keyboard shortcuts
- **Batch Operations**: Multi-select actions for efficiency
- **Smart Defaults**: Intelligent form pre-filling based on context
- **Undo/Redo**: Action history with rollback capabilities
#### Reporting and Analytics Interface
- **Production Dashboard**: Project completion percentages with visual progress indicators
- **Overdue Task Tracking**: Clear visual indicators for tasks past their deadlines
- **Workload Distribution**: Visual representation of task assignments across all artists
- **Performance Reports**: Task completion rates by artist and task type
- **Timeline Visualization**: Gantt-style charts for project scheduling and milestone tracking
### Visual Design System
#### Color Scheme (ftrack-inspired)
- **Primary**: Deep blue (#1a365d) for main actions and navigation
- **Secondary**: Orange (#ed8936) for highlights and warnings
- **Success**: Green (#38a169) for approved/completed states
- **Warning**: Yellow (#d69e2e) for pending/review states
- **Error**: Red (#e53e3e) for retakes and errors
- **Neutral**: Gray scale for text and backgrounds
#### Dark Theme Support
- **Theme Toggle**: Persistent theme preference stored in localStorage with system preference detection
- **CSS Variables**: Dynamic color scheme switching using CSS custom properties defined in shadcn-vue
- **Component Integration**: Built-in dark mode support with automatic shadcn-vue component adaptation
- **Color Accessibility**: WCAG AA compliant contrast ratios for both light and dark themes
- **Media Query Support**: Automatic theme detection based on user's system preference on first visit
- **Smooth Transitions**: Animated theme switching with CSS transitions for better user experience
- **Theme Store**: Pinia store for theme state management across components
- **Header Integration**: Theme toggle button in the application header for easy access
#### Typography
- **Font Family**: Inter font-face for all text elements
- **Headers**: Bold Inter with clear hierarchy for section organization
- **Body Text**: Inter Regular with appropriate line spacing for readability
- **Monospace**: Inter Mono or fallback monospace for code/technical information
- **Icon Font**: Consistent iconography throughout interface (Lucide icons recommended)
#### Component Styling
- **Cards**: Subtle shadows with rounded corners
- **Buttons**: Clear primary/secondary button hierarchy
- **Forms**: Consistent input styling with validation states
- **Tables**: Zebra striping with hover states
- **Progress Bars**: Animated progress indicators
## Performance Considerations
### Database Optimization
- **Indexing Strategy**: Indexes on foreign keys and frequently queried fields
- **Query Optimization**: Eager loading for related data
- **Connection Pooling**: SQLAlchemy connection pool configuration
- **Pagination**: Cursor-based pagination for large datasets
### File Handling
- **Streaming Uploads**: Chunked file upload for large media files
- **Supported Formats**: Common VFX media formats (mov, mp4, exr, jpg, png) with MIME type validation
- **Compression**: Automatic compression for supported file types
- **CDN Integration**: Ready for CDN integration for file delivery
- **Thumbnail Generation**: Automatic thumbnail creation for images
- **Version Control**: Automatic versioning system for all submissions with history tracking
### Frontend Performance
- **Code Splitting**: Route-based code splitting
- **Lazy Loading**: Component lazy loading for better initial load
- **Caching Strategy**: HTTP caching for static assets
- **Bundle Optimization**: Tree shaking and minification
##
Custom Task Type Management
### Overview
The system allows coordinators to define custom task types beyond the standard predefined types (modeling, surfacing, rigging for assets; layout, animation, simulation, lighting, compositing for shots). This enables projects to adapt the production pipeline to unique workflows, specialized departments, or client-specific requirements.
### Data Model
#### Custom Task Types Storage
Custom task types are stored per project in JSON format:
```json
{
"custom_asset_task_types": [
"grooming",
"lookdev",
"fx_setup"
],
"custom_shot_task_types": [
"previz",
"matchmove",
"rotoscoping",
"paint"
]
}
```
#### Database Schema
```sql
-- Add to projects table
ALTER TABLE projects ADD COLUMN custom_asset_task_types TEXT; -- JSON array
ALTER TABLE projects ADD COLUMN custom_shot_task_types TEXT; -- JSON array
```
### API Endpoints
#### Get Custom Task Types
```
GET /projects/{project_id}/custom-task-types
```
**Response:**
```json
{
"asset_task_types": ["modeling", "surfacing", "rigging", "grooming", "lookdev"],
"shot_task_types": ["layout", "animation", "simulation", "lighting", "compositing", "previz"]
}
```
#### Add Custom Task Type
```
POST /projects/{project_id}/custom-task-types
```
**Request Body:**
```json
{
"task_type": "grooming",
"category": "asset" // or "shot"
}
```
#### Update Custom Task Type
```
PUT /projects/{project_id}/custom-task-types/{task_type}
```
**Request Body:**
```json
{
"old_name": "grooming",
"new_name": "hair_grooming",
"category": "asset"
}
```
#### Delete Custom Task Type
```
DELETE /projects/{project_id}/custom-task-types/{task_type}?category=asset
```
**Validation:**
- Returns 400 if task type is currently in use
- Returns 404 if task type doesn't exist
### User Interface Components
#### Custom Task Type Manager
**Location:** Project Settings > Tasks Tab
**Features:**
- Separate sections for Asset Task Types and Shot Task Types
- List of all task types (standard + custom) with visual distinction
- Add button to create new custom task types
- Edit button (pencil icon) for custom task types only
- Delete button (trash icon) for custom task types only
- Standard task types are read-only and cannot be deleted
**Add Task Type Dialog:**
- Input field for task type name
- Validation: no duplicates, alphanumeric with underscores
- Category selection (Asset or Shot)
- Save/Cancel buttons
**Edit Task Type Dialog:**
- Input field pre-filled with current name
- Validation: no duplicates, alphanumeric with underscores
- Warning if task type is in use
- Save/Cancel buttons
**Delete Confirmation:**
- Warning message if task type has active tasks
- Confirmation dialog for deletion
- List of affected tasks (if any)
#### Task Template Editor Integration
The existing task template editor (table view) dynamically includes custom task types:
**Asset Task Templates Table:**
- Rows: Standard tasks (modeling, surfacing, rigging) + Custom tasks
- Custom task rows have an edit/delete icon
- New row appears when custom task is added
**Shot Task Templates Table:**
- Rows: Standard tasks (layout, animation, etc.) + Custom tasks
- Custom task rows have an edit/delete icon
- New row appears when custom task is added
### Business Logic
#### Task Type Validation
```python
def validate_task_type_name(name: str) -> bool:
"""Validate task type name format"""
# Must be alphanumeric with underscores
# Must be 3-50 characters
# Must not match existing task types
pattern = r'^[a-z0-9_]{3,50}$'
return bool(re.match(pattern, name))
```
#### Task Type Usage Check
```python
def is_task_type_in_use(project_id: int, task_type: str, category: str) -> bool:
"""Check if task type has active tasks"""
if category == "asset":
return db.query(Task).join(Asset).filter(
Asset.project_id == project_id,
Task.task_type == task_type
).count() > 0
else: # shot
return db.query(Task).join(Shot).filter(
Shot.project_id == project_id,
Task.task_type == task_type
).count() > 0
```
#### Cascading Updates
When a task type name is updated:
1. Update all task records using that task type
2. Update task templates that reference the task type
3. Notify affected users of the change
### Security & Permissions
- Only coordinators and admins can manage custom task types
- Artists and directors can view but not modify
- API endpoints require coordinator or admin role
- Task type deletion requires confirmation
### Error Handling
**Common Errors:**
- `400 Bad Request`: Invalid task type name format
- `409 Conflict`: Task type name already exists
- `422 Unprocessable Entity`: Task type is in use and cannot be deleted
- `403 Forbidden`: User lacks permission to manage task types
- `404 Not Found`: Task type doesn't exist
### Migration Strategy
For existing projects:
1. Custom task types start as empty arrays
2. Existing tasks continue to work with standard types
3. Coordinators can gradually add custom types as needed
4. No breaking changes to existing workflows
### Future Enhancements
1. **Task Type Templates**: Save and share task type sets across projects
2. **Task Type Metadata**: Add descriptions, icons, and colors to task types
3. **Department Mapping**: Associate task types with specific departments
4. **Task Type Dependencies**: Define which tasks must complete before others
5. **Import/Export**: Share custom task type configurations between projects
## Avatar Display System
### Overview
The avatar display system provides consistent visual identification of users throughout the application using uploaded avatars, generated avatars, or initials fallback.
### Components
#### Avatar Display Strategy
1. **Primary**: User's uploaded avatar image
2. **Secondary**: Dicebear API generated avatar based on user's full name
3. **Tertiary**: Initials fallback using Avatar component
#### Implementation Locations
- UserManagementTable - User rows
- UserApprovalCard - Approval cards
- UserEditDialog - Dialog headers
- UserDeleteConfirmDialog - Confirmation dialogs
- ProjectMemberManagement - Team member lists
- TaskList - Assigned users and assignment dialogs
- TaskDetailPanel - Assigned users and member selection
- SubmissionCard - Submitters
- NoteItem - Note authors
- AttachmentCard - Uploaders
- ActivityFeed - Activity items
#### Avatar Sizing
- h-4 w-4: Tiny (attachment cards)
- h-5 w-5: Small (task list)
- h-6 w-6: Medium (task detail)
- h-8 w-8: Standard (tables, feeds, dialogs)
- h-10 w-10: Large (dialog headers)
- h-12 w-12: Extra large (approval cards)
#### Helper Functions
```typescript
function getAvatarUrl(url: string | null | undefined): string {
if (!url) return ''
if (url.startsWith('http')) return url
const cleanUrl = url.replace(/^backend[\/\\]/, '').replace(/\\/g, '/')
return `http://localhost:8000/${cleanUrl}`
}
function getUserInitials(firstName: string, lastName: string): string {
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase()
}
```
## Shot Detail Panel Enhancement
### Overview
Enhanced shot detail panel with tabbed interface providing comprehensive shot information and task management.
### Panel Structure
#### Header Section
- Shot name and icon
- Frame range display (start-end with count)
- Status badge with color coding
- Action menu (Edit, Delete)
#### Progress Overview
- Completion percentage bar
- Task count (completed/total)
- Status breakdown by task status type
#### Tabbed Content
**Tasks Tab**
- List of all tasks for the shot
- Task name, type, status badges
- Assigned user display
- Deadline information
- Click to view task details
- Add Task button (for coordinators/admins)
**Notes Tab**
- Task update history
- Department-specific notes
- User avatars with timestamps
- Add note functionality
- Threaded conversations
**References Tab**
- Reference materials
- Attachments
- Design documents
**Design Tab**
- Design specifications
- Technical requirements
### Data Loading
- Shot details loaded on panel open
- Tasks fetched using shot_id filter
- Real-time updates for task status changes
- Progress calculations based on task statuses
## Task Filtering Enhancement
### Backend API Updates
#### GET /tasks Endpoint
Added query parameters:
- `shot_id`: Filter tasks by shot ID
- `asset_id`: Filter tasks by asset ID
#### Implementation
```python
@router.get("/", response_model=List[TaskListResponse])
async def get_tasks(
project_id: Optional[int] = Query(None),
shot_id: Optional[int] = Query(None), # NEW
asset_id: Optional[int] = Query(None), # NEW
assigned_user_id: Optional[int] = Query(None),
status: Optional[str] = Query(None),
task_type: Optional[str] = Query(None),
...
):
query = db.query(Task)
if shot_id:
query = query.filter(Task.shot_id == shot_id)
if asset_id:
query = query.filter(Task.asset_id == asset_id)
# ... other filters
```
### Frontend Service Updates
#### TaskFilters Interface
```typescript
export interface TaskFilters {
projectId?: number
shotId?: number // NEW
assetId?: number // NEW
assignedUserId?: number
status?: string
taskType?: string
departmentRole?: string
}
```
#### Usage in ShotDetailPanel
```typescript
const loadTasks = async () => {
const taskList = await taskService.getTasks({
shotId: props.shotId
})
tasks.value = taskList
}
```
## File Handler Path Resolution
### Issue
File handler was using relative paths that failed when backend was run from different working directories.
### Solution
Use absolute path resolution based on file location:
```python
def __init__(self, base_upload_dir: str = "uploads"):
current_file = Path(__file__).resolve()
backend_dir = current_file.parent.parent # Go up from utils/ to backend/
self.base_upload_dir = backend_dir / base_upload_dir
self.base_upload_dir.mkdir(parents=True, exist_ok=True)
```
This ensures uploads directory is always created at `backend/uploads` regardless of working directory.
### Project Tasks Tab Design
#### Overview
The Tasks tab provides a unified view of all project tasks (both shot and asset tasks) in a comprehensive data table with advanced filtering and sorting capabilities.
#### Component Structure
```
ProjectTasksView
├── TasksDataTable
│ ├── TaskTableToolbar (filters, search, column visibility)
│ ├── TaskTableHeader (sortable columns)
│ ├── TaskTableBody (task rows)
│ └── TaskTablePagination
└── TaskDetailPanel (slide-in panel)
```
#### Data Table Columns
1. **Task Name**: Clickable link to open task detail panel
2. **Type**: Task type badge (layout, animation, lighting, etc.)
3. **Status**: Color-coded status badge (not started, in progress, submitted, approved, retake)
4. **Context**: Shows "Shot" or "Asset" with icon
5. **Shot/Asset Name**: Name of the associated shot or asset
6. **Episode**: Episode name (for shot tasks only)
7. **Assignee**: Avatar and name of assigned artist
8. **Deadline**: Date with urgency indicator
9. **Created**: Creation date
#### Filtering Options
- **Status Filter**: Multi-select dropdown for task statuses
- **Type Filter**: Multi-select dropdown for task types (standard + custom)
- **Episode Filter**: Dropdown to filter by episode (shot tasks only)
- **Assignee Filter**: Multi-select dropdown for artists
- **Search**: Text search across task names and descriptions
- **Context Filter**: Toggle between All/Shots Only/Assets Only
#### Sorting
- All columns sortable (ascending/descending)
- Default sort: Created date (newest first)
- Multi-column sorting support
#### Column Visibility
- Toggle visibility for each column
- Persist preferences in session storage
- Minimum required columns: Task Name, Status, Context
#### Bulk Operations (Coordinators Only)
- Row selection with checkboxes
- Bulk status update
- Bulk reassignment
- Bulk deadline modification
#### Export Functionality
- Export filtered results to CSV
- Export filtered results to Excel
- Include all visible columns in export
#### Task Detail Panel
- Slides in from right side
- Shows complete task information
- Includes tabs: Details, Notes, Attachments, Submissions, Activity
- Allows inline editing for coordinators
- Close button and overlay click to dismiss
#### Performance Considerations
- Virtual scrolling for large task lists (1000+ tasks)
- Debounced search input (300ms)
- Lazy loading of task details
- Cached filter options
#### Responsive Design
- Desktop: Full data table with all columns
- Tablet: Hide less critical columns (Created, Episode)
- Mobile: Card-based layout instead of table
#### Integration Points
- Uses existing `/tasks/` API endpoint with project_id filter
- Leverages task store for state management
- Shares TaskDetailPanel component with other views
- Integrates with notification system for task updates
## Project Thumbnail Management
### Overview
Project thumbnails provide visual identification for projects on the projects list page. Coordinators and administrators can upload custom thumbnail images through the project settings page, enhancing project recognition and visual organization.
### Architecture
#### Backend Components
**Database Schema Extension**
- Add `thumbnail_path` field to Project model (nullable string)
- Add `thumbnail_url` field to Project model (nullable string, computed property)
- Store original uploaded file and generate optimized thumbnail version
**File Storage**
- Store thumbnails in `uploads/projects/{project_id}/` directory
- Generate thumbnail filename: `thumbnail_{timestamp}.{ext}`
- Create resized version for optimal display (e.g., 400x300px maintaining aspect ratio)
**API Endpoints**
```
POST /projects/{project_id}/thumbnail - Upload project thumbnail
DELETE /projects/{project_id}/thumbnail - Remove project thumbnail
GET /files/projects/{project_id}/thumbnail - Serve thumbnail with authentication
```
#### Frontend Components
**ProjectThumbnailUpload Component**
- Drag-and-drop upload interface
- Image preview before upload
- Current thumbnail display with replace/remove options
- Upload progress indicator
- File validation (type, size)
**Project Card Enhancement**
- Display thumbnail image on project cards
- Fallback to default placeholder or project initials when no thumbnail exists
- Maintain consistent aspect ratio across all cards
- Hover effects for better UX
### Data Models
#### Project Model Extension (Backend)
```python
class Project(Base):
# ... existing fields ...
thumbnail_path = Column(String, nullable=True)
@property
def thumbnail_url(self):
if self.thumbnail_path:
return f"/files/projects/{self.id}/thumbnail"
return None
```
#### Project Interface Extension (Frontend)
```typescript
interface Project {
// ... existing fields ...
thumbnail_url?: string | null
}
```
### Components and Interfaces
#### ProjectThumbnailUpload Component
**Props:**
- `projectId: number` - The project ID
- `currentThumbnail?: string | null` - Current thumbnail URL
**Events:**
- `@thumbnail-updated` - Emitted when thumbnail is uploaded or removed
**Features:**
- Drag-and-drop zone for image upload
- Click to browse file selection
- Image preview with crop/resize preview
- Remove thumbnail button
- Upload progress indicator
- Error handling and validation messages
#### Project Card Component Updates
**Enhancements:**
- Add thumbnail image display area at top of card
- Use `object-cover` CSS for consistent sizing
- Implement lazy loading for thumbnails
- Add loading skeleton while thumbnail loads
- Fallback to gradient background with project initials
### Error Handling
**Upload Errors:**
- File too large (> 10MB)
- Invalid file type (not an image)
- Network errors during upload
- Server processing errors
**Display Errors:**
- Missing thumbnail file on server
- Failed to load thumbnail (404, 403)
- Corrupted image files
**Error Messages:**
- Clear, user-friendly error descriptions
- Actionable suggestions for resolution
- Toast notifications for upload status
### Testing Strategy
**Backend Tests:**
- Test thumbnail upload with valid images
- Test file size validation
- Test file type validation
- Test thumbnail deletion
- Test authenticated access to thumbnail files
- Test thumbnail URL generation
**Frontend Tests:**
- Test thumbnail upload component rendering
- Test drag-and-drop functionality
- Test file selection via click
- Test thumbnail preview display
- Test remove thumbnail functionality
- Test project card thumbnail display
- Test fallback to default placeholder
**Integration Tests:**
- Test end-to-end thumbnail upload flow
- Test thumbnail display on projects page
- Test thumbnail persistence across page reloads
- Test thumbnail access control (authentication required)
### Implementation Notes
1. **Image Processing**: Use Pillow (Python) for server-side image resizing and optimization
2. **File Validation**: Validate file type and size on both client and server
3. **Authentication**: Thumbnail files require authentication to access
4. **Caching**: Implement browser caching for thumbnail images
5. **Optimization**: Generate multiple sizes if needed for different display contexts
6. **Cleanup**: Remove old thumbnail files when new ones are uploaded
7. **Default Placeholder**: Use project name initials with gradient background as fallback