mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
feat(admin): Enhanced admin job detail page with files, edit, and reset (#261)
## Summary
- Add comprehensive job management features to admin job detail view
- Enable file downloads with signed GCS URLs grouped by category
- Add inline editing of job fields (artist, title, theme, etc.)
- Add job reset actions to re-process from workflow checkpoints
## Changes
### Backend (39 new tests)
- `GET /api/admin/jobs/{job_id}/files` - Get all job files with signed
URLs (2-hour expiry)
- `PATCH /api/admin/jobs/{job_id}` - Update editable job fields with
whitelist validation
- `POST /api/admin/jobs/{job_id}/reset` - Reset job to specific workflow
checkpoint
### Frontend (13 E2E tests)
- **Files accordion** - Download job files grouped by category (input,
stems, lyrics, outputs)
- **Configuration section** - Inline editing for artist, title,
theme_id, brand_prefix, customer_email
- **Admin Actions section** - Reset buttons for pending, audio
selection, review, instrumental selection
- **Enhanced timeline** - Color-coded stages (green=complete,
blue=processing, orange=waiting, red=failed)
### Documentation
- Updated `docs/API.md` with new endpoint documentation
- Updated `docs/README.md` with feature summary
- Added lesson learned about AuthResult tuple unpacking gotcha
## Test Plan
- [x] Backend tests pass (39 new tests for files, update, reset
endpoints)
- [x] Frontend E2E tests pass (13 tests for admin job detail page)
- [x] Frontend unit tests pass (150 tests)
- [x] Frontend builds successfully
- [x] CodeRabbit review passed (2 cycles, all issues fixed)
## Screenshots
See updated admin job detail page at `/admin/jobs?id={job_id}`
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
49158f99ac
commit
7cfac407e3
13 files changed
+3585
-436
No files matched your search
@@ -0,0 +1,393 @@
|
||||
# Plan: Admin Job Details Page
|
||||
|
||||
**Created:** 2026-01-09
|
||||
**Branch:** feat/sess-20260109-1738-admin-job-details
|
||||
**Status:** In Progress (Phase 1 Complete)
|
||||
|
||||
## Overview
|
||||
|
||||
The admin jobs list page links to `/admin/jobs/{job_id}` but that route doesn't exist - the detail page is at `/admin/jobs/detail` expecting `?id=` query params. This causes a 404 when clicking jobs.
|
||||
|
||||
We'll fix the routing and enhance the job detail page with comprehensive admin features: full job metadata display, file downloads with signed URLs, editable fields, and job stage reset capabilities.
|
||||
|
||||
**Note:** Due to Next.js static export constraints (the frontend deploys to Cloudflare Pages), we cannot use dynamic routes like `/admin/jobs/[jobId]`. Instead, we use query parameters: `/admin/jobs?id={job_id}`. The single page component handles both list and detail views based on the presence of the `id` query param.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Must Have
|
||||
- [x] Fix 404 - use query param routing at `/admin/jobs?id={job_id}` (dynamic routes not compatible with static export)
|
||||
- [ ] Display all job metadata (source, user info, request_metadata, timeline)
|
||||
- [ ] Stage-by-stage breakdown with timestamps and duration calculations
|
||||
- [ ] Download links for all existing files (generate signed URLs)
|
||||
- [ ] View worker logs with filtering by level/worker
|
||||
- [ ] Restart job from beginning (reset to PENDING)
|
||||
- [ ] Edit key job fields inline (artist, title, user_email, theme_id, etc.)
|
||||
|
||||
### Should Have
|
||||
- [ ] Reset job to specific intermediate stages (audio selection, lyrics review)
|
||||
- [ ] View/edit raw JSON fields (state_data, file_urls)
|
||||
- [ ] Quick actions: send completion email, clear cache, impersonate user
|
||||
|
||||
### Nice to Have
|
||||
- [ ] Job timeline visualization (Gantt-style or vertical timeline)
|
||||
- [ ] Diff view when editing fields
|
||||
- [ ] Audit log of admin changes
|
||||
|
||||
## Technical Approach
|
||||
|
||||
### Routing Fix (COMPLETED)
|
||||
~~Create `/admin/jobs/[jobId]/page.tsx` as a dynamic route.~~ **UPDATE:** Dynamic routes are incompatible with Next.js `output: 'export'` (static site generation for Cloudflare Pages) without `generateStaticParams()`, which doesn't work for client components.
|
||||
|
||||
**Actual approach:** Enhanced `/admin/jobs/page.tsx` to handle both list and detail views:
|
||||
- Uses `useSearchParams()` to detect `?id=` parameter
|
||||
- Shows detail view when `selectedJobId` is present, list view otherwise
|
||||
- Navigation uses `router.push(\`/admin/jobs?id=${job.job_id}\`)`
|
||||
- Deleted old `/admin/jobs/detail/` directory
|
||||
|
||||
### Backend Enhancements
|
||||
1. **New endpoint**: `GET /api/admin/jobs/{job_id}/files` - returns all files with signed download URLs
|
||||
2. **New endpoint**: `PATCH /api/admin/jobs/{job_id}` - update editable fields (admin only)
|
||||
3. **New endpoint**: `POST /api/admin/jobs/{job_id}/reset` - reset job to specific state
|
||||
|
||||
### Frontend Structure
|
||||
The page will have collapsible sections:
|
||||
1. **Header**: Job ID, status badge, artist/title, quick actions
|
||||
2. **Overview Cards**: User, dates, progress, source info
|
||||
3. **Stage Timeline**: Visual breakdown of each stage with times
|
||||
4. **Files**: Downloadable links for all GCS files
|
||||
5. **Logs**: Filterable worker logs
|
||||
6. **Configuration**: Editable job settings
|
||||
7. **Raw Data**: JSON views of state_data, file_urls, full job
|
||||
|
||||
### Job Reset Logic
|
||||
Reset to specific states requires:
|
||||
- Clearing downstream state_data keys
|
||||
- Resetting status
|
||||
- Optionally clearing associated files
|
||||
- Adding timeline event for the reset
|
||||
|
||||
Valid reset targets:
|
||||
| Target State | Clears | Use Case |
|
||||
|--------------|--------|----------|
|
||||
| PENDING | Everything except input | Full restart |
|
||||
| AWAITING_AUDIO_SELECTION | Audio search results | Re-search for audio |
|
||||
| AWAITING_REVIEW | Review data, screens, videos | Re-do lyrics review |
|
||||
| AWAITING_INSTRUMENTAL_SELECTION | Instrumental selection, finals | Re-choose instrumental |
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
Testing is integrated into each phase (following TDD/"write tests immediately after" guidance).
|
||||
|
||||
### Phase 1: Fix Routing (COMPLETED)
|
||||
1. [x] ~~Create `/frontend/app/admin/jobs/[jobId]/page.tsx`~~ Enhanced `/admin/jobs/page.tsx` with query param routing
|
||||
2. [x] Combined list and detail views in single component
|
||||
3. [x] Use `useSearchParams()` to detect `?id=` parameter
|
||||
4. [x] Delete `/frontend/app/admin/jobs/detail/` directory
|
||||
5. [x] **E2E Test**: Added `admin-job-detail.spec.ts` with 9 tests (navigation, metadata, timeline, logs, error states, delete dialog, refresh)
|
||||
6. [x] Verified: All 9 E2E tests pass, build succeeds
|
||||
|
||||
### Phase 2: Backend - File Downloads with Signed URLs
|
||||
7. [ ] **Write tests first**: Add test file `backend/tests/test_admin_job_detail.py`
|
||||
8. [ ] Add tests for `GET /api/admin/jobs/{job_id}/files` (see Testing Strategy)
|
||||
9. [ ] Add `GET /api/admin/jobs/{job_id}/files` endpoint
|
||||
10. [ ] Traverse job.file_urls recursively
|
||||
11. [ ] Generate signed URLs for each GCS path
|
||||
12. [ ] Return structured response with file metadata
|
||||
13. [ ] Verify: `poetry run pytest backend/tests/test_admin_job_detail.py -v` passes
|
||||
14. [ ] Add frontend API method `adminApi.getJobFiles(jobId)`
|
||||
|
||||
### Phase 3: Frontend - Enhanced File Display
|
||||
15. [ ] Create "Files" accordion section with grouped downloads
|
||||
16. [ ] Group by category (input, stems, lyrics, screens, videos, finals, packages)
|
||||
17. [ ] Show file name, type, download button
|
||||
18. [ ] Handle missing/unavailable files gracefully
|
||||
19. [ ] **E2E Test**: Add files section test to `admin-job-detail.spec.ts`
|
||||
20. [ ] Verify: `npm run test:e2e` passes
|
||||
|
||||
### Phase 4: Backend - Job Update Endpoint
|
||||
21. [ ] **Write tests first**: Add tests for `PATCH /api/admin/jobs/{job_id}`
|
||||
22. [ ] Add `PATCH /api/admin/jobs/{job_id}` endpoint
|
||||
23. [ ] Define editable fields whitelist
|
||||
24. [ ] Validate field values (e.g., status must be valid enum)
|
||||
25. [ ] Log admin changes for audit trail
|
||||
26. [ ] Verify: Backend tests pass
|
||||
27. [ ] Add frontend API method `adminApi.updateJob(jobId, updates)`
|
||||
|
||||
### Phase 5: Frontend - Editable Fields
|
||||
28. [ ] Create "Configuration" section with editable fields
|
||||
29. [ ] Use inline edit pattern (click to edit, enter to save)
|
||||
30. [ ] Fields: artist, title, user_email, theme_id, enable_cdg, enable_txt, enable_youtube_upload
|
||||
31. [ ] Show validation errors inline
|
||||
32. [ ] **E2E Test**: Add inline edit test to `admin-job-detail.spec.ts`
|
||||
33. [ ] Verify: `npm run test:e2e` passes
|
||||
|
||||
### Phase 6: Backend - Job Reset Endpoint
|
||||
34. [ ] **Write tests first**: Add tests for `POST /api/admin/jobs/{job_id}/reset`
|
||||
35. [ ] Add `POST /api/admin/jobs/{job_id}/reset` endpoint
|
||||
36. [ ] Accept `target_state` parameter
|
||||
37. [ ] Implement reset logic for each target state
|
||||
38. [ ] Clear appropriate state_data keys
|
||||
39. [ ] Optionally trigger workers after reset
|
||||
40. [ ] Verify: Backend tests pass
|
||||
41. [ ] Add frontend API method `adminApi.resetJob(jobId, targetState)`
|
||||
|
||||
### Phase 7: Frontend - Reset Actions
|
||||
42. [ ] Add "Reset Job" dropdown/menu in header
|
||||
43. [ ] Show available reset targets based on current state
|
||||
44. [ ] Confirm dialog explaining what will be cleared
|
||||
45. [ ] Show success/error toast after reset
|
||||
46. [ ] **E2E Test**: Add reset confirmation dialog test
|
||||
47. [ ] Verify: `npm run test:e2e` passes
|
||||
|
||||
### Phase 8: Enhanced Stage Timeline
|
||||
48. [ ] Parse timeline events to calculate stage durations
|
||||
49. [ ] Display stages as cards or timeline items
|
||||
50. [ ] Show duration for each stage
|
||||
51. [ ] Highlight current/blocking stages
|
||||
52. [ ] **E2E Test**: Add timeline display test
|
||||
|
||||
### Phase 9: Final Verification
|
||||
53. [ ] Run full backend test suite: `make test-backend`
|
||||
54. [ ] Run full frontend test suite: `cd frontend && npm run test:all`
|
||||
55. [ ] Manual production testing checklist (see Testing Strategy)
|
||||
56. [ ] Verify CI passes on PR
|
||||
|
||||
## Files to Create/Modify
|
||||
|
||||
| File | Action | Description |
|
||||
|------|--------|-------------|
|
||||
| `frontend/app/admin/jobs/[jobId]/page.tsx` | Create | Dynamic route for job detail |
|
||||
| `frontend/app/admin/jobs/detail/` | Delete | Remove old query-param based route |
|
||||
| `backend/api/routes/admin.py` | Modify | Add files, update, reset endpoints |
|
||||
| `frontend/lib/api.ts` | Modify | Add adminApi methods for new endpoints |
|
||||
| `backend/tests/test_admin_job_detail.py` | Create | Backend unit tests for new endpoints |
|
||||
| `frontend/e2e/regression/admin-job-detail.spec.ts` | Create | Frontend E2E regression tests |
|
||||
| `frontend/e2e/fixtures/test-helper.ts` | Modify | Add admin auth helper if needed |
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
Based on `docs/TESTING.md` guidelines, this feature requires:
|
||||
|
||||
### Test Types Required
|
||||
|
||||
| Type | Location | Purpose |
|
||||
|------|----------|---------|
|
||||
| Backend Unit Tests | `backend/tests/test_admin_job_detail.py` | Test new API endpoints |
|
||||
| Frontend E2E Regression | `frontend/e2e/regression/admin-job-detail.spec.ts` | Test UI flows with mocked API |
|
||||
| Manual Production E2E | N/A | Final validation on staging/prod |
|
||||
|
||||
### Backend Unit Tests (`backend/tests/test_admin_job_detail.py`)
|
||||
|
||||
**Mocking approach:** Mock Firestore and GCS (following existing patterns in `backend/tests/conftest.py`). Do NOT mock our own code - test the real `JobManager` and `StorageService` logic.
|
||||
|
||||
**Test cases for `GET /api/admin/jobs/{job_id}/files`:**
|
||||
```python
|
||||
def test_get_job_files_returns_signed_urls_for_all_files():
|
||||
"""Test that all files in file_urls get signed URLs."""
|
||||
|
||||
def test_get_job_files_handles_nested_file_urls():
|
||||
"""Test recursive traversal of stems.instrumental_clean, etc."""
|
||||
|
||||
def test_get_job_files_handles_missing_files_gracefully():
|
||||
"""Test files that don't exist in GCS are omitted or marked."""
|
||||
|
||||
def test_get_job_files_requires_admin():
|
||||
"""Test non-admin gets 403."""
|
||||
|
||||
def test_get_job_files_returns_404_for_missing_job():
|
||||
"""Test invalid job_id returns 404."""
|
||||
```
|
||||
|
||||
**Test cases for `PATCH /api/admin/jobs/{job_id}`:**
|
||||
```python
|
||||
def test_update_job_allows_editable_fields():
|
||||
"""Test artist, title, user_email, theme_id can be updated."""
|
||||
|
||||
def test_update_job_rejects_non_editable_fields():
|
||||
"""Test job_id, created_at, etc. cannot be updated."""
|
||||
|
||||
def test_update_job_validates_status_enum():
|
||||
"""Test invalid status value returns 422."""
|
||||
|
||||
def test_update_job_validates_theme_id_exists():
|
||||
"""Test non-existent theme_id returns 422."""
|
||||
|
||||
def test_update_job_requires_admin():
|
||||
"""Test non-admin gets 403."""
|
||||
|
||||
def test_update_job_returns_updated_job():
|
||||
"""Test response includes updated job data."""
|
||||
```
|
||||
|
||||
**Test cases for `POST /api/admin/jobs/{job_id}/reset`:**
|
||||
```python
|
||||
def test_reset_to_pending_clears_all_state_data():
|
||||
"""Test full reset clears everything except input."""
|
||||
|
||||
def test_reset_to_audio_selection_clears_search_results():
|
||||
"""Test audio selection reset clears audio_search_results."""
|
||||
|
||||
def test_reset_to_awaiting_review_clears_review_data():
|
||||
"""Test review reset clears screens, videos, review data."""
|
||||
|
||||
def test_reset_to_instrumental_selection_clears_finals():
|
||||
"""Test instrumental reset clears encoding results."""
|
||||
|
||||
def test_reset_adds_timeline_event():
|
||||
"""Test reset adds admin action to timeline."""
|
||||
|
||||
def test_reset_invalid_target_returns_422():
|
||||
"""Test invalid target_state returns validation error."""
|
||||
|
||||
def test_reset_requires_admin():
|
||||
"""Test non-admin gets 403."""
|
||||
|
||||
def test_reset_from_complete_to_pending_works():
|
||||
"""Test can reset completed job back to start."""
|
||||
```
|
||||
|
||||
### Frontend E2E Regression Tests (`frontend/e2e/regression/admin-job-detail.spec.ts`)
|
||||
|
||||
**Mocking approach:** Use Playwright route interception to mock API responses (following patterns in `frontend/e2e/fixtures/test-helper.ts`).
|
||||
|
||||
```typescript
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { setupApiFixtures, setAdminAuthToken } from '../fixtures/test-helper';
|
||||
|
||||
test.describe('Admin Job Detail Page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await setAdminAuthToken(page);
|
||||
});
|
||||
|
||||
test('navigates from jobs list to detail page', async ({ page }) => {
|
||||
// Mock jobs list and single job endpoints
|
||||
await page.route('**/api/admin/jobs', route => route.fulfill({
|
||||
json: [{ job_id: 'test123', status: 'complete', artist: 'Test', title: 'Song' }]
|
||||
}));
|
||||
await page.route('**/api/jobs/test123', route => route.fulfill({
|
||||
json: { job_id: 'test123', status: 'complete', artist: 'Test', title: 'Song' }
|
||||
}));
|
||||
|
||||
await page.goto('/admin/jobs');
|
||||
await page.click('text=test123');
|
||||
await expect(page).toHaveURL('/admin/jobs/test123');
|
||||
await expect(page.getByText('Job test123')).toBeVisible();
|
||||
});
|
||||
|
||||
test('displays all job metadata sections', async ({ page }) => {
|
||||
// Test overview cards, timeline, logs accordion, etc.
|
||||
});
|
||||
|
||||
test('files section shows downloadable links', async ({ page }) => {
|
||||
// Mock files endpoint, verify download buttons appear
|
||||
});
|
||||
|
||||
test('edit field inline and save', async ({ page }) => {
|
||||
// Click edit, change value, press Enter, verify PATCH called
|
||||
});
|
||||
|
||||
test('reset job shows confirmation dialog', async ({ page }) => {
|
||||
// Click reset, verify dialog, confirm, verify POST called
|
||||
});
|
||||
|
||||
test('handles API errors gracefully', async ({ page }) => {
|
||||
// Mock 500 response, verify error toast shown
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Test File Organization
|
||||
|
||||
```
|
||||
backend/tests/
|
||||
├── test_admin_job_detail.py # NEW - all backend tests for this feature
|
||||
├── test_admin_api.py # Existing admin tests (keep separate)
|
||||
└── conftest.py # Shared fixtures
|
||||
|
||||
frontend/e2e/
|
||||
├── fixtures/
|
||||
│ ├── test-helper.ts # Add setAdminAuthToken helper
|
||||
│ └── mock-responses.ts # Add admin job detail mocks
|
||||
└── regression/
|
||||
└── admin-job-detail.spec.ts # NEW - E2E regression tests
|
||||
```
|
||||
|
||||
### Mocking Guidelines
|
||||
|
||||
**Backend - What to mock:**
|
||||
- `StorageService.generate_signed_url()` - return predictable test URLs
|
||||
- `StorageService.file_exists()` - control which files "exist"
|
||||
- Firestore operations via existing `mock_firestore` fixture
|
||||
|
||||
**Backend - What NOT to mock:**
|
||||
- `JobManager` logic - test the real reset/update logic
|
||||
- Validation logic - test real Pydantic validation
|
||||
- Authorization checks - test real `require_admin` dependency
|
||||
|
||||
**Frontend - What to mock:**
|
||||
- All API responses via Playwright route interception
|
||||
- Time (if testing token expiry)
|
||||
|
||||
**Frontend - What NOT to mock:**
|
||||
- React component behavior
|
||||
- User interactions (click, type, etc.)
|
||||
|
||||
### CI Requirements
|
||||
|
||||
This feature will be validated by existing CI checks:
|
||||
- `backend-unit-tests` - Must pass (includes new `test_admin_job_detail.py`)
|
||||
- `frontend-e2e-smoke` - Must pass (includes new `admin-job-detail.spec.ts`)
|
||||
- `frontend-build` - Must pass (verifies new page compiles)
|
||||
|
||||
### Running Tests Locally
|
||||
|
||||
```bash
|
||||
# Backend tests only (for this feature)
|
||||
poetry run pytest backend/tests/test_admin_job_detail.py -v
|
||||
|
||||
# All backend tests
|
||||
make test-backend
|
||||
|
||||
# Frontend E2E regression (includes new tests)
|
||||
cd frontend && npm run test:e2e
|
||||
|
||||
# Single E2E test file
|
||||
cd frontend && npx playwright test e2e/regression/admin-job-detail.spec.ts
|
||||
|
||||
# With browser visible for debugging
|
||||
cd frontend && npx playwright test e2e/regression/admin-job-detail.spec.ts --headed
|
||||
```
|
||||
|
||||
### Manual Production Testing Checklist
|
||||
|
||||
After deployment, manually verify on production:
|
||||
- [ ] Navigate `/admin/jobs` → click job → lands on `/admin/jobs/{id}` (not 404)
|
||||
- [ ] All file download links work (valid signed URLs)
|
||||
- [ ] Edit artist/title → refresh → changes persisted
|
||||
- [ ] Reset job to pending → job status shows "pending"
|
||||
- [ ] Logs section loads and filters work
|
||||
- [ ] Error states handled (invalid job ID shows friendly error)
|
||||
|
||||
## Open Questions
|
||||
|
||||
1. [ ] Should we keep the old `/admin/jobs/detail?id=` route for backwards compatibility, or delete it entirely?
|
||||
- **Recommendation**: Delete it. No external links depend on it.
|
||||
|
||||
2. [ ] Should job reset delete GCS files or just clear state_data references?
|
||||
- **Recommendation**: Clear state_data only. Files can be useful for debugging. Add a separate "Delete Files" action if needed.
|
||||
|
||||
3. [ ] Should edits be immediately saved or require explicit "Save" button?
|
||||
- **Recommendation**: Inline edit with Enter to save, Escape to cancel. Show loading indicator during save.
|
||||
|
||||
## Rollback Plan
|
||||
|
||||
If issues arise:
|
||||
1. Routing: Can revert to query-param routing by restoring `detail/page.tsx` and updating navigation
|
||||
2. Backend: New endpoints are additive, won't affect existing functionality
|
||||
3. Reset feature: Admin-only, can be disabled by removing endpoint if problematic
|
||||
|
||||
## Notes
|
||||
|
||||
- The existing detail page has good foundational code - we're enhancing rather than replacing
|
||||
- Signed URLs expire (default 60-120 min) - consider caching or refresh mechanism for long sessions
|
||||
- Job reset is powerful - consider adding confirmation dialogs and logging
|
||||
+438
-1
@@ -15,10 +15,11 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.services.auth_service import UserType, AuthResult
|
||||
from backend.services.user_service import get_user_service, UserService, USERS_COLLECTION
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchServiceError
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.models.job import JobStatus
|
||||
from backend.utils.test_data import is_test_email
|
||||
from karaoke_gen.utils import sanitize_filename
|
||||
@@ -56,6 +57,74 @@ class AdminStatsOverview(BaseModel):
|
||||
total_beta_testers: int
|
||||
|
||||
|
||||
class FileInfo(BaseModel):
|
||||
"""Information about a single file with signed download URL."""
|
||||
name: str
|
||||
path: str # GCS path (gs://bucket/...)
|
||||
download_url: str # Signed URL for download
|
||||
category: str # e.g., "stems", "lyrics", "finals"
|
||||
file_key: str # e.g., "instrumental_clean", "lrc"
|
||||
|
||||
|
||||
class JobFilesResponse(BaseModel):
|
||||
"""Response containing all files for a job with signed download URLs."""
|
||||
job_id: str
|
||||
artist: Optional[str]
|
||||
title: Optional[str]
|
||||
files: List[FileInfo]
|
||||
total_files: int
|
||||
|
||||
|
||||
class JobUpdateRequest(BaseModel):
|
||||
"""Request model for updating job fields."""
|
||||
# Editable text fields
|
||||
artist: Optional[str] = None
|
||||
title: Optional[str] = None
|
||||
user_email: Optional[str] = None
|
||||
theme_id: Optional[str] = None
|
||||
brand_prefix: Optional[str] = None
|
||||
discord_webhook_url: Optional[str] = None
|
||||
youtube_description: Optional[str] = None
|
||||
youtube_description_template: Optional[str] = None
|
||||
customer_email: Optional[str] = None
|
||||
customer_notes: Optional[str] = None
|
||||
|
||||
# Editable boolean fields
|
||||
enable_cdg: Optional[bool] = None
|
||||
enable_txt: Optional[bool] = None
|
||||
enable_youtube_upload: Optional[bool] = None
|
||||
non_interactive: Optional[bool] = None
|
||||
prep_only: Optional[bool] = None
|
||||
|
||||
|
||||
class JobUpdateResponse(BaseModel):
|
||||
"""Response from job update endpoint."""
|
||||
status: str
|
||||
job_id: str
|
||||
updated_fields: List[str]
|
||||
message: str
|
||||
|
||||
|
||||
# Fields that are allowed to be updated via PATCH endpoint
|
||||
EDITABLE_JOB_FIELDS = {
|
||||
"artist",
|
||||
"title",
|
||||
"user_email",
|
||||
"theme_id",
|
||||
"brand_prefix",
|
||||
"discord_webhook_url",
|
||||
"youtube_description",
|
||||
"youtube_description_template",
|
||||
"customer_email",
|
||||
"customer_notes",
|
||||
"enable_cdg",
|
||||
"enable_txt",
|
||||
"enable_youtube_upload",
|
||||
"non_interactive",
|
||||
"prep_only",
|
||||
}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Admin Stats Endpoints
|
||||
# =============================================================================
|
||||
@@ -702,6 +771,374 @@ class SendCompletionEmailResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Job Files Endpoint
|
||||
# =============================================================================
|
||||
|
||||
def _extract_files_recursive(
|
||||
file_urls: Dict[str, Any],
|
||||
storage: StorageService,
|
||||
category: str = "",
|
||||
expiration_minutes: int = 120,
|
||||
) -> List[FileInfo]:
|
||||
"""
|
||||
Recursively extract files from nested file_urls structure.
|
||||
|
||||
Only includes entries that are GCS paths (gs://...).
|
||||
Skips non-GCS entries like YouTube URLs.
|
||||
|
||||
Args:
|
||||
file_urls: Dictionary of file URLs (may be nested)
|
||||
storage: StorageService instance for generating signed URLs
|
||||
category: Current category name (for nested calls)
|
||||
expiration_minutes: How long signed URLs should be valid
|
||||
|
||||
Returns:
|
||||
List of FileInfo objects with signed download URLs
|
||||
"""
|
||||
files = []
|
||||
|
||||
for key, value in file_urls.items():
|
||||
if isinstance(value, dict):
|
||||
# Nested structure - recurse with key as category
|
||||
nested_files = _extract_files_recursive(
|
||||
value,
|
||||
storage,
|
||||
category=key if not category else f"{category}.{key}",
|
||||
expiration_minutes=expiration_minutes,
|
||||
)
|
||||
files.extend(nested_files)
|
||||
elif isinstance(value, str) and value.startswith("gs://"):
|
||||
# GCS path - generate signed URL
|
||||
try:
|
||||
signed_url = storage.generate_signed_url(value, expiration_minutes=expiration_minutes)
|
||||
# Extract filename from path
|
||||
name = value.split("/")[-1] if "/" in value else value
|
||||
files.append(FileInfo(
|
||||
name=name,
|
||||
path=value,
|
||||
download_url=signed_url,
|
||||
category=category,
|
||||
file_key=key,
|
||||
))
|
||||
except Exception as e:
|
||||
# Log but don't fail - file might not exist
|
||||
logger.warning(f"Failed to generate signed URL for {value}: {e}")
|
||||
# Skip non-GCS values (e.g., youtube URLs, video IDs)
|
||||
|
||||
return files
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/files", response_model=JobFilesResponse)
|
||||
async def get_job_files(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Get all files for a job with signed download URLs.
|
||||
|
||||
Returns a list of all files associated with the job, including:
|
||||
- Input audio file
|
||||
- Stem separation results (vocals, instrumentals, etc.)
|
||||
- Lyrics files (LRC, ASS, corrections JSON)
|
||||
- Screen files (title, end screens)
|
||||
- Video files (with/without vocals)
|
||||
- Final output files (various formats)
|
||||
- Package files (CDG, TXT zips)
|
||||
|
||||
Each file includes a signed URL that's valid for 2 hours.
|
||||
Non-GCS entries (like YouTube URLs) are excluded.
|
||||
|
||||
Requires admin authentication.
|
||||
"""
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Extract all files with signed URLs
|
||||
storage = StorageService()
|
||||
file_urls = job.file_urls or {}
|
||||
|
||||
files = _extract_files_recursive(file_urls, storage)
|
||||
|
||||
return JobFilesResponse(
|
||||
job_id=job.job_id,
|
||||
artist=job.artist,
|
||||
title=job.title,
|
||||
files=files,
|
||||
total_files=len(files),
|
||||
)
|
||||
|
||||
|
||||
@router.patch("/jobs/{job_id}", response_model=JobUpdateResponse)
|
||||
async def update_job(
|
||||
job_id: str,
|
||||
request: Dict[str, Any],
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
):
|
||||
"""
|
||||
Update editable fields of a job (admin only).
|
||||
|
||||
This endpoint allows admins to update certain job fields without
|
||||
affecting the job's processing state. It's useful for:
|
||||
- Correcting artist/title typos
|
||||
- Changing user assignment
|
||||
- Updating delivery settings (email, theme, etc.)
|
||||
|
||||
Editable fields:
|
||||
- artist, title: Track metadata
|
||||
- user_email: Job owner
|
||||
- theme_id: Visual theme
|
||||
- enable_cdg, enable_txt, enable_youtube_upload: Output options
|
||||
- customer_email, customer_notes: Made-for-you order info
|
||||
- brand_prefix: Brand code prefix
|
||||
- non_interactive, prep_only: Workflow options
|
||||
- discord_webhook_url: Notification URL
|
||||
- youtube_description, youtube_description_template: YouTube settings
|
||||
|
||||
Non-editable fields (will return 400 error):
|
||||
- job_id, status, progress: System-managed
|
||||
- created_at, updated_at: Timestamps
|
||||
- state_data, file_urls, timeline: Processing state
|
||||
- worker_logs, worker_ids: Audit/tracking data
|
||||
|
||||
For status changes, use the reset endpoint instead.
|
||||
"""
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
|
||||
# Check for non-editable fields in request
|
||||
non_editable_fields = set(request.keys()) - EDITABLE_JOB_FIELDS
|
||||
if non_editable_fields:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"The following fields are not editable: {', '.join(sorted(non_editable_fields))}. "
|
||||
f"Editable fields are: {', '.join(sorted(EDITABLE_JOB_FIELDS))}"
|
||||
)
|
||||
|
||||
# Filter to only include provided fields (non-None values)
|
||||
updates = {k: v for k, v in request.items() if v is not None}
|
||||
|
||||
if not updates:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="No valid fields provided for update. "
|
||||
f"Editable fields are: {', '.join(sorted(EDITABLE_JOB_FIELDS))}"
|
||||
)
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
# Perform the update
|
||||
success = job_manager.update_job(job_id, updates)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to update job. Please try again."
|
||||
)
|
||||
|
||||
# Log the admin action
|
||||
logger.info(
|
||||
f"Admin {admin_email} updated job {job_id}. "
|
||||
f"Updated fields: {list(updates.keys())}"
|
||||
)
|
||||
|
||||
return JobUpdateResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
updated_fields=list(updates.keys()),
|
||||
message=f"Successfully updated {len(updates)} field(s)",
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Job Reset Endpoint
|
||||
# =============================================================================
|
||||
|
||||
class JobResetRequest(BaseModel):
|
||||
"""Request model for resetting a job to a specific state."""
|
||||
target_state: str
|
||||
|
||||
|
||||
class JobResetResponse(BaseModel):
|
||||
"""Response from job reset endpoint."""
|
||||
status: str
|
||||
job_id: str
|
||||
previous_status: str
|
||||
new_status: str
|
||||
message: str
|
||||
cleared_data: List[str]
|
||||
|
||||
|
||||
# States that are allowed as reset targets
|
||||
ALLOWED_RESET_STATES = {
|
||||
"pending",
|
||||
"awaiting_audio_selection",
|
||||
"awaiting_review",
|
||||
"awaiting_instrumental_selection",
|
||||
}
|
||||
|
||||
# State data keys to clear for each reset target
|
||||
# Keys not in this mapping are preserved
|
||||
STATE_DATA_CLEAR_KEYS = {
|
||||
"pending": [
|
||||
"audio_search_results",
|
||||
"audio_search_count",
|
||||
"remote_search_id",
|
||||
"audio_selection",
|
||||
"review_complete",
|
||||
"corrected_lyrics",
|
||||
"instrumental_selection",
|
||||
"video_progress",
|
||||
"render_progress",
|
||||
"screens_progress",
|
||||
],
|
||||
"awaiting_audio_selection": [
|
||||
"audio_selection",
|
||||
"review_complete",
|
||||
"corrected_lyrics",
|
||||
"instrumental_selection",
|
||||
"video_progress",
|
||||
"render_progress",
|
||||
"screens_progress",
|
||||
],
|
||||
"awaiting_review": [
|
||||
"review_complete",
|
||||
"corrected_lyrics",
|
||||
"instrumental_selection",
|
||||
"video_progress",
|
||||
"render_progress",
|
||||
"screens_progress",
|
||||
],
|
||||
"awaiting_instrumental_selection": [
|
||||
"instrumental_selection",
|
||||
"video_progress",
|
||||
"render_progress",
|
||||
"screens_progress",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/reset", response_model=JobResetResponse)
|
||||
async def reset_job(
|
||||
job_id: str,
|
||||
request: JobResetRequest,
|
||||
auth_data: AuthResult = Depends(require_admin),
|
||||
user_service: UserService = Depends(get_user_service),
|
||||
):
|
||||
"""
|
||||
Reset a job to a specific state for re-processing (admin only).
|
||||
|
||||
This endpoint allows admins to reset a job back to specific workflow
|
||||
checkpoints to re-do parts of the processing. This is useful for:
|
||||
- Re-running audio search after flacfetch updates
|
||||
- Re-reviewing lyrics after corrections
|
||||
- Re-selecting instrumental after hearing the result
|
||||
- Restarting a failed job from the beginning
|
||||
|
||||
Allowed target states:
|
||||
- pending: Restart from the beginning (clears all processing data)
|
||||
- awaiting_audio_selection: Re-select audio source
|
||||
- awaiting_review: Re-review lyrics (preserves audio stems)
|
||||
- awaiting_instrumental_selection: Re-select instrumental (preserves review)
|
||||
|
||||
State data is cleared based on the target state to ensure a clean
|
||||
re-processing from that point forward.
|
||||
"""
|
||||
admin_email = auth_data.user_email or "unknown"
|
||||
target_state = request.target_state.lower()
|
||||
|
||||
# Validate target state
|
||||
if target_state not in ALLOWED_RESET_STATES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid target state '{target_state}'. "
|
||||
f"Allowed states are: {', '.join(sorted(ALLOWED_RESET_STATES))}"
|
||||
)
|
||||
|
||||
job_manager = JobManager()
|
||||
job = job_manager.get_job(job_id)
|
||||
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
|
||||
|
||||
previous_status = job.status
|
||||
|
||||
# Build update payload
|
||||
updates = {
|
||||
"status": target_state,
|
||||
"progress": 0,
|
||||
"message": f"Job reset to {target_state} by admin",
|
||||
"updated_at": datetime.utcnow().isoformat(),
|
||||
}
|
||||
|
||||
# Clear state data keys based on target state
|
||||
keys_to_clear = STATE_DATA_CLEAR_KEYS.get(target_state, [])
|
||||
cleared_keys = []
|
||||
current_state_data = job.state_data or {}
|
||||
|
||||
for key in keys_to_clear:
|
||||
if key in current_state_data:
|
||||
cleared_keys.append(key)
|
||||
|
||||
# Add timeline event
|
||||
timeline_event = {
|
||||
"status": target_state,
|
||||
"timestamp": datetime.utcnow().isoformat(),
|
||||
"message": f"Admin reset from {previous_status} to {target_state}",
|
||||
}
|
||||
|
||||
# Perform the update with state_data clearing
|
||||
# We need to set the cleared keys to DELETE_FIELD
|
||||
success = job_manager.update_job(job_id, updates)
|
||||
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="Failed to reset job. Please try again."
|
||||
)
|
||||
|
||||
# Clear the state data keys separately using direct Firestore update
|
||||
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
|
||||
|
||||
job_ref = user_service.db.collection("jobs").document(job_id)
|
||||
|
||||
if cleared_keys:
|
||||
clear_updates = {}
|
||||
for key in cleared_keys:
|
||||
clear_updates[f"state_data.{key}"] = DELETE_FIELD
|
||||
|
||||
# Add timeline event
|
||||
clear_updates["timeline"] = ArrayUnion([timeline_event])
|
||||
|
||||
job_ref.update(clear_updates)
|
||||
else:
|
||||
# Just add timeline event
|
||||
job_ref.update({
|
||||
"timeline": ArrayUnion([timeline_event])
|
||||
})
|
||||
|
||||
# Log the admin action
|
||||
logger.info(
|
||||
f"Admin {admin_email} reset job {job_id} from {previous_status} to {target_state}. "
|
||||
f"Cleared state_data keys: {cleared_keys}"
|
||||
)
|
||||
|
||||
return JobResetResponse(
|
||||
status="success",
|
||||
job_id=job_id,
|
||||
previous_status=previous_status,
|
||||
new_status=target_state,
|
||||
message=f"Job reset from {previous_status} to {target_state}",
|
||||
cleared_data=cleared_keys,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/jobs/{job_id}/completion-message", response_model=CompletionMessageResponse)
|
||||
async def get_job_completion_message(
|
||||
job_id: str,
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
"""
|
||||
Unit tests for admin job files endpoint.
|
||||
|
||||
Tests the GET /api/admin/jobs/{job_id}/files endpoint that returns
|
||||
all files for a job with signed download URLs.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# Create a test app with the admin router
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
# Override the require_admin dependency
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Create a test client."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_with_files():
|
||||
"""Create a mock job with comprehensive file_urls."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-123"
|
||||
job.user_email = "user@example.com"
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Song"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.file_urls = {
|
||||
"input": "gs://bucket/jobs/test-job-123/input.flac",
|
||||
"stems": {
|
||||
"instrumental_clean": "gs://bucket/jobs/test-job-123/stems/instrumental_clean.flac",
|
||||
"vocals": "gs://bucket/jobs/test-job-123/stems/vocals.flac",
|
||||
},
|
||||
"lyrics": {
|
||||
"corrections": "gs://bucket/jobs/test-job-123/lyrics/corrections.json",
|
||||
"lrc": "gs://bucket/jobs/test-job-123/lyrics/output.lrc",
|
||||
},
|
||||
"finals": {
|
||||
"lossy_720p_mp4": "gs://bucket/jobs/test-job-123/finals/video_720p.mp4",
|
||||
},
|
||||
"youtube": {
|
||||
"url": "https://youtube.com/watch?v=xyz789",
|
||||
"video_id": "xyz789",
|
||||
},
|
||||
}
|
||||
return job
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_no_files():
|
||||
"""Create a mock job with empty file_urls."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-empty"
|
||||
job.user_email = "user@example.com"
|
||||
job.artist = "Empty Artist"
|
||||
job.title = "Empty Song"
|
||||
job.status = JobStatus.PENDING
|
||||
job.file_urls = {}
|
||||
return job
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job_partial_files():
|
||||
"""Create a mock job with only some files (partial processing)."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-partial"
|
||||
job.user_email = "user@example.com"
|
||||
job.artist = "Partial Artist"
|
||||
job.title = "Partial Song"
|
||||
job.status = JobStatus.SEPARATING_STAGE1
|
||||
job.file_urls = {
|
||||
"input": "gs://bucket/jobs/test-job-partial/input.flac",
|
||||
"stems": {
|
||||
"instrumental_clean": "gs://bucket/jobs/test-job-partial/stems/instrumental_clean.flac",
|
||||
},
|
||||
}
|
||||
return job
|
||||
|
||||
|
||||
class TestGetJobFiles:
|
||||
"""Tests for GET /api/admin/jobs/{job_id}/files endpoint."""
|
||||
|
||||
def test_returns_files_with_signed_urls(self, client, mock_job_with_files):
|
||||
"""Test that endpoint returns all files with signed URLs."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.StorageService') as mock_storage_class:
|
||||
|
||||
# Setup JobManager mock
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_with_files
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
# Setup StorageService mock to return predictable signed URLs
|
||||
mock_storage = Mock()
|
||||
mock_storage.generate_signed_url.side_effect = lambda path, **kwargs: f"https://signed.url/{path}"
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
response = client.get(
|
||||
"/api/admin/jobs/test-job-123/files",
|
||||
headers={"Authorization": "Bearer admin-token"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["job_id"] == "test-job-123"
|
||||
assert data["artist"] == "Test Artist"
|
||||
assert data["title"] == "Test Song"
|
||||
assert "files" in data
|
||||
assert data["total_files"] > 0
|
||||
|
||||
def test_returns_correct_file_count(self, client, mock_job_with_files):
|
||||
"""Test that file count matches actual GCS files (excluding non-GCS entries)."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.StorageService') as mock_storage_class:
|
||||
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_with_files
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.generate_signed_url.side_effect = lambda path, **kwargs: f"https://signed.url/{path}"
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
response = client.get("/api/admin/jobs/test-job-123/files")
|
||||
|
||||
data = response.json()
|
||||
# Should have: input, stems.instrumental_clean, stems.vocals,
|
||||
# lyrics.corrections, lyrics.lrc, finals.lossy_720p_mp4
|
||||
# NOT youtube.url or youtube.video_id (not GCS paths)
|
||||
assert data["total_files"] == 6
|
||||
|
||||
def test_handles_nested_file_structure(self, client, mock_job_with_files):
|
||||
"""Test that nested file_urls structure is properly traversed."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.StorageService') as mock_storage_class:
|
||||
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_with_files
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.generate_signed_url.side_effect = lambda path, **kwargs: f"https://signed.url/{path}"
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
response = client.get("/api/admin/jobs/test-job-123/files")
|
||||
|
||||
data = response.json()
|
||||
files = data["files"]
|
||||
|
||||
# Check that files from different categories are present
|
||||
categories = {f["category"] for f in files}
|
||||
assert "input" in categories or any(f["category"] == "" and f["file_key"] == "input" for f in files)
|
||||
assert "stems" in categories
|
||||
assert "lyrics" in categories
|
||||
assert "finals" in categories
|
||||
|
||||
def test_file_info_structure(self, client, mock_job_with_files):
|
||||
"""Test that each file has correct info structure."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.StorageService') as mock_storage_class:
|
||||
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_with_files
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.generate_signed_url.side_effect = lambda path, **kwargs: f"https://signed.url/{path}"
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
response = client.get("/api/admin/jobs/test-job-123/files")
|
||||
|
||||
data = response.json()
|
||||
files = data["files"]
|
||||
|
||||
# Every file should have these fields
|
||||
for file_info in files:
|
||||
assert "name" in file_info
|
||||
assert "path" in file_info
|
||||
assert "download_url" in file_info
|
||||
assert "category" in file_info
|
||||
assert "file_key" in file_info
|
||||
# download_url should be a signed URL
|
||||
assert file_info["download_url"].startswith("https://signed.url/")
|
||||
|
||||
def test_returns_404_when_job_not_found(self, client):
|
||||
"""Test 404 when job doesn't exist."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.get(
|
||||
"/api/admin/jobs/nonexistent-job/files",
|
||||
headers={"Authorization": "Bearer admin-token"}
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "not found" in response.json()["detail"].lower()
|
||||
|
||||
def test_returns_empty_files_for_new_job(self, client, mock_job_no_files):
|
||||
"""Test that new jobs with no files return empty list."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.StorageService') as mock_storage_class:
|
||||
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_no_files
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
response = client.get("/api/admin/jobs/test-job-empty/files")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["job_id"] == "test-job-empty"
|
||||
assert data["files"] == []
|
||||
assert data["total_files"] == 0
|
||||
|
||||
def test_handles_partial_processing(self, client, mock_job_partial_files):
|
||||
"""Test job with only some files processed."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.StorageService') as mock_storage_class:
|
||||
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_partial_files
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.generate_signed_url.side_effect = lambda path, **kwargs: f"https://signed.url/{path}"
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
response = client.get("/api/admin/jobs/test-job-partial/files")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Should have input + stems.instrumental_clean = 2 files
|
||||
assert data["total_files"] == 2
|
||||
|
||||
def test_skips_non_gcs_urls(self, client, mock_job_with_files):
|
||||
"""Test that non-GCS URLs (like youtube URLs) are skipped."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.StorageService') as mock_storage_class:
|
||||
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_with_files
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.generate_signed_url.side_effect = lambda path, **kwargs: f"https://signed.url/{path}"
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
response = client.get("/api/admin/jobs/test-job-123/files")
|
||||
|
||||
data = response.json()
|
||||
files = data["files"]
|
||||
|
||||
# Ensure no youtube URLs or video IDs are in the files
|
||||
for file_info in files:
|
||||
assert "youtube.com" not in file_info["path"]
|
||||
assert file_info["path"].startswith("gs://")
|
||||
|
||||
def test_signed_url_expiration(self, client, mock_job_with_files):
|
||||
"""Test that signed URLs are generated with appropriate expiration."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.StorageService') as mock_storage_class:
|
||||
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job_with_files
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.generate_signed_url.return_value = "https://signed.url/test"
|
||||
mock_storage_class.return_value = mock_storage
|
||||
|
||||
client.get("/api/admin/jobs/test-job-123/files")
|
||||
|
||||
# Verify signed URLs were requested with expiration (default 120 minutes)
|
||||
assert mock_storage.generate_signed_url.called
|
||||
# Check that expiration_minutes was passed (could be any reasonable value)
|
||||
call_kwargs = mock_storage.generate_signed_url.call_args_list[0][1]
|
||||
if "expiration_minutes" in call_kwargs:
|
||||
assert call_kwargs["expiration_minutes"] >= 60
|
||||
|
||||
|
||||
class TestGetJobFilesAuthorization:
|
||||
"""Tests for authorization on the files endpoint."""
|
||||
|
||||
def test_requires_admin_access(self, client, mock_job_with_files):
|
||||
"""Test that non-admin users cannot access the endpoint."""
|
||||
# Reset the dependency override to test auth
|
||||
original_override = app.dependency_overrides.get(require_admin)
|
||||
|
||||
def get_non_admin():
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
|
||||
app.dependency_overrides[require_admin] = get_non_admin
|
||||
|
||||
try:
|
||||
response = client.get(
|
||||
"/api/admin/jobs/test-job-123/files",
|
||||
headers={"Authorization": "Bearer user-token"}
|
||||
)
|
||||
assert response.status_code == 403
|
||||
finally:
|
||||
# Restore the original override
|
||||
if original_override:
|
||||
app.dependency_overrides[require_admin] = original_override
|
||||
else:
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
@@ -0,0 +1,384 @@
|
||||
"""
|
||||
Unit tests for admin job reset endpoint.
|
||||
|
||||
Tests the POST /api/admin/jobs/{job_id}/reset endpoint that allows admins
|
||||
to reset a job to a specific state for re-processing.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
from datetime import datetime
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# Create a test app with the admin router
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
# Override the require_admin dependency
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Create a test client."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job():
|
||||
"""Create a mock job in COMPLETE status for testing."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-123"
|
||||
job.user_email = "user@example.com"
|
||||
job.artist = "Test Artist"
|
||||
job.title = "Test Title"
|
||||
job.status = JobStatus.COMPLETE
|
||||
job.theme_id = "nomad"
|
||||
job.file_urls = {
|
||||
"input": "gs://bucket/input.flac",
|
||||
"stems": {
|
||||
"instrumental_clean": "gs://bucket/stems/clean.flac",
|
||||
},
|
||||
"lyrics": {
|
||||
"corrections": "gs://bucket/lyrics/corrections.json",
|
||||
},
|
||||
}
|
||||
job.state_data = {
|
||||
"audio_search_results": [{"provider": "test"}],
|
||||
"audio_selection": {"index": 0},
|
||||
"review_complete": True,
|
||||
"corrected_lyrics": {"lines": []},
|
||||
"instrumental_selection": "clean",
|
||||
"brand_code": "NOMAD-1234",
|
||||
}
|
||||
job.timeline = []
|
||||
job.created_at = datetime(2026, 1, 9, 10, 0, 0)
|
||||
job.updated_at = datetime(2026, 1, 9, 12, 0, 0)
|
||||
return job
|
||||
|
||||
|
||||
class TestResetJobToPending:
|
||||
"""Tests for resetting job to PENDING state."""
|
||||
|
||||
def test_reset_to_pending_success(self, client, mock_job):
|
||||
"""Test resetting a job to PENDING state."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["job_id"] == "test-job-123"
|
||||
assert data["new_status"] == "pending"
|
||||
assert "pending" in data["message"].lower()
|
||||
|
||||
def test_reset_to_pending_clears_state_data(self, client, mock_job):
|
||||
"""Test that resetting to PENDING clears appropriate state_data keys."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Verify update_job was called with cleared state_data keys
|
||||
call_args = mock_jm.update_job.call_args
|
||||
update_data = call_args[0][1]
|
||||
# Verify status was set
|
||||
assert update_data["status"] == "pending"
|
||||
|
||||
|
||||
class TestResetJobToAwaitingAudioSelection:
|
||||
"""Tests for resetting job to AWAITING_AUDIO_SELECTION state."""
|
||||
|
||||
def test_reset_to_awaiting_audio_selection(self, client, mock_job):
|
||||
"""Test resetting a job to AWAITING_AUDIO_SELECTION state."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_audio_selection"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["new_status"] == "awaiting_audio_selection"
|
||||
|
||||
|
||||
class TestResetJobToAwaitingReview:
|
||||
"""Tests for resetting job to AWAITING_REVIEW state."""
|
||||
|
||||
def test_reset_to_awaiting_review(self, client, mock_job):
|
||||
"""Test resetting a job to AWAITING_REVIEW state."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_review"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["new_status"] == "awaiting_review"
|
||||
|
||||
|
||||
class TestResetJobToAwaitingInstrumentalSelection:
|
||||
"""Tests for resetting job to AWAITING_INSTRUMENTAL_SELECTION state."""
|
||||
|
||||
def test_reset_to_awaiting_instrumental_selection(self, client, mock_job):
|
||||
"""Test resetting a job to AWAITING_INSTRUMENTAL_SELECTION state."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_instrumental_selection"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["new_status"] == "awaiting_instrumental_selection"
|
||||
|
||||
|
||||
class TestResetJobValidation:
|
||||
"""Tests for reset endpoint validation."""
|
||||
|
||||
def test_rejects_invalid_target_state(self, client, mock_job):
|
||||
"""Test that invalid target states are rejected."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "encoding"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "invalid" in response.json()["detail"].lower() or "not allowed" in response.json()["detail"].lower()
|
||||
|
||||
def test_rejects_complete_as_target(self, client, mock_job):
|
||||
"""Test that COMPLETE is not a valid reset target."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "complete"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_rejects_failed_as_target(self, client, mock_job):
|
||||
"""Test that FAILED is not a valid reset target."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "failed"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
def test_returns_404_when_job_not_found(self, client):
|
||||
"""Test 404 when job doesn't exist."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/nonexistent-job/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "not found" in response.json()["detail"].lower()
|
||||
|
||||
def test_rejects_missing_target_state(self, client, mock_job):
|
||||
"""Test that target_state is required."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={},
|
||||
)
|
||||
|
||||
assert response.status_code == 422 # Validation error
|
||||
|
||||
|
||||
class TestResetJobLogging:
|
||||
"""Tests for logging on the reset endpoint."""
|
||||
|
||||
def test_logs_admin_reset_action(self, client, mock_job):
|
||||
"""Test that admin reset actions are logged."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.logger') as mock_logger:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Verify logging was called
|
||||
mock_logger.info.assert_called()
|
||||
log_message = mock_logger.info.call_args[0][0]
|
||||
assert "admin" in log_message.lower() or "reset" in log_message.lower()
|
||||
|
||||
|
||||
class TestResetJobTimeline:
|
||||
"""Tests for timeline event on reset."""
|
||||
|
||||
def test_adds_timeline_event_on_reset(self, client, mock_job):
|
||||
"""Test that a timeline event is added when job is reset."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_review"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Timeline event should be included in response
|
||||
assert "timeline_event" in data or data.get("message")
|
||||
|
||||
|
||||
class TestResetJobAuthorization:
|
||||
"""Tests for authorization on the reset endpoint."""
|
||||
|
||||
def test_requires_admin_access(self, client, mock_job):
|
||||
"""Test that non-admin users cannot access the endpoint."""
|
||||
original_override = app.dependency_overrides.get(require_admin)
|
||||
|
||||
def get_non_admin():
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
|
||||
app.dependency_overrides[require_admin] = get_non_admin
|
||||
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "pending"},
|
||||
headers={"Authorization": "Bearer user-token"}
|
||||
)
|
||||
assert response.status_code == 403
|
||||
finally:
|
||||
if original_override:
|
||||
app.dependency_overrides[require_admin] = original_override
|
||||
else:
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
class TestResetJobClearsStateData:
|
||||
"""Tests for state_data clearing based on target state."""
|
||||
|
||||
def test_reset_to_pending_clears_all_processing_data(self, client, mock_job):
|
||||
"""Test that resetting to PENDING clears audio search results."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "pending"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# The cleared_data field should list what was cleared
|
||||
data = response.json()
|
||||
assert "cleared_data" in data or "state_data" in str(data)
|
||||
|
||||
def test_reset_to_awaiting_review_preserves_audio_data(self, client, mock_job):
|
||||
"""Test that resetting to AWAITING_REVIEW preserves audio stems."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_review"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
|
||||
def test_reset_to_instrumental_preserves_review_data(self, client, mock_job):
|
||||
"""Test that resetting to AWAITING_INSTRUMENTAL_SELECTION preserves review data."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.post(
|
||||
"/api/admin/jobs/test-job-123/reset",
|
||||
json={"target_state": "awaiting_instrumental_selection"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
@@ -0,0 +1,326 @@
|
||||
"""
|
||||
Unit tests for admin job update endpoint.
|
||||
|
||||
Tests the PATCH /api/admin/jobs/{job_id} endpoint that allows admins
|
||||
to update editable job fields.
|
||||
"""
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from fastapi.testclient import TestClient
|
||||
from fastapi import FastAPI
|
||||
|
||||
from backend.api.routes.admin import router
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
# Create a test app with the admin router
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def get_mock_admin():
|
||||
"""Override for require_admin dependency."""
|
||||
from backend.api.dependencies import AuthResult, UserType
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
# Override the require_admin dependency
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""Create a test client."""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_job():
|
||||
"""Create a mock job for testing."""
|
||||
job = Mock(spec=Job)
|
||||
job.job_id = "test-job-123"
|
||||
job.user_email = "user@example.com"
|
||||
job.artist = "Original Artist"
|
||||
job.title = "Original Title"
|
||||
job.status = JobStatus.AWAITING_REVIEW
|
||||
job.theme_id = "nomad"
|
||||
job.enable_cdg = False
|
||||
job.enable_txt = False
|
||||
job.enable_youtube_upload = True
|
||||
job.customer_email = None
|
||||
job.customer_notes = None
|
||||
job.brand_prefix = None
|
||||
job.non_interactive = False
|
||||
job.prep_only = False
|
||||
job.discord_webhook_url = None
|
||||
job.youtube_description = None
|
||||
job.youtube_description_template = None
|
||||
job.file_urls = {}
|
||||
job.state_data = {}
|
||||
job.created_at = "2026-01-09T10:00:00Z"
|
||||
job.updated_at = "2026-01-09T10:30:00Z"
|
||||
return job
|
||||
|
||||
|
||||
class TestUpdateJob:
|
||||
"""Tests for PATCH /api/admin/jobs/{job_id} endpoint."""
|
||||
|
||||
def test_update_artist_field(self, client, mock_job):
|
||||
"""Test updating the artist field."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"artist": "New Artist"},
|
||||
headers={"Authorization": "Bearer admin-token"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "success"
|
||||
assert data["job_id"] == "test-job-123"
|
||||
assert "artist" in data["updated_fields"]
|
||||
|
||||
# Verify update_job was called with correct args
|
||||
mock_jm.update_job.assert_called_once()
|
||||
call_args = mock_jm.update_job.call_args
|
||||
assert call_args[0][0] == "test-job-123"
|
||||
assert call_args[0][1]["artist"] == "New Artist"
|
||||
|
||||
def test_update_multiple_fields(self, client, mock_job):
|
||||
"""Test updating multiple fields at once."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={
|
||||
"artist": "New Artist",
|
||||
"title": "New Title",
|
||||
"theme_id": "default",
|
||||
"enable_cdg": True,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert len(data["updated_fields"]) == 4
|
||||
assert "artist" in data["updated_fields"]
|
||||
assert "title" in data["updated_fields"]
|
||||
assert "theme_id" in data["updated_fields"]
|
||||
assert "enable_cdg" in data["updated_fields"]
|
||||
|
||||
def test_update_user_email(self, client, mock_job):
|
||||
"""Test updating user_email field."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"user_email": "newuser@example.com"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
call_args = mock_jm.update_job.call_args
|
||||
assert call_args[0][1]["user_email"] == "newuser@example.com"
|
||||
|
||||
def test_update_boolean_fields(self, client, mock_job):
|
||||
"""Test updating boolean fields."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={
|
||||
"enable_cdg": True,
|
||||
"enable_txt": True,
|
||||
"enable_youtube_upload": False,
|
||||
"non_interactive": True,
|
||||
"prep_only": True,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
call_args = mock_jm.update_job.call_args
|
||||
assert call_args[0][1]["enable_cdg"] is True
|
||||
assert call_args[0][1]["enable_txt"] is True
|
||||
assert call_args[0][1]["enable_youtube_upload"] is False
|
||||
|
||||
def test_rejects_non_editable_job_id(self, client, mock_job):
|
||||
"""Test that job_id cannot be updated."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"job_id": "new-job-id"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "not editable" in response.json()["detail"].lower()
|
||||
|
||||
def test_rejects_non_editable_created_at(self, client, mock_job):
|
||||
"""Test that created_at cannot be updated."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"created_at": "2025-01-01T00:00:00Z"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "not editable" in response.json()["detail"].lower()
|
||||
|
||||
def test_rejects_status_update(self, client, mock_job):
|
||||
"""Test that status cannot be updated via PATCH (use reset endpoint)."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"status": "complete"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "not editable" in response.json()["detail"].lower()
|
||||
|
||||
def test_rejects_state_data_update(self, client, mock_job):
|
||||
"""Test that state_data cannot be updated directly."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"state_data": {"foo": "bar"}},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "not editable" in response.json()["detail"].lower()
|
||||
|
||||
def test_returns_404_when_job_not_found(self, client):
|
||||
"""Test 404 when job doesn't exist."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = None
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/nonexistent-job",
|
||||
json={"artist": "New Artist"},
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "not found" in response.json()["detail"].lower()
|
||||
|
||||
def test_returns_400_for_empty_update(self, client, mock_job):
|
||||
"""Test 400 when no valid fields are provided."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "no valid" in response.json()["detail"].lower()
|
||||
|
||||
def test_logs_admin_changes(self, client, mock_job):
|
||||
"""Test that admin changes are logged."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
|
||||
patch('backend.api.routes.admin.logger') as mock_logger:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"artist": "New Artist"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# Verify logging was called
|
||||
mock_logger.info.assert_called()
|
||||
log_message = mock_logger.info.call_args[0][0]
|
||||
assert "admin@example.com" in log_message.lower() or "admin" in log_message.lower()
|
||||
|
||||
def test_update_customer_fields(self, client, mock_job):
|
||||
"""Test updating made-for-you customer fields."""
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={
|
||||
"customer_email": "customer@example.com",
|
||||
"customer_notes": "Special request: add extra countdown",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
call_args = mock_jm.update_job.call_args
|
||||
assert call_args[0][1]["customer_email"] == "customer@example.com"
|
||||
assert call_args[0][1]["customer_notes"] == "Special request: add extra countdown"
|
||||
|
||||
|
||||
class TestUpdateJobAuthorization:
|
||||
"""Tests for authorization on the update endpoint."""
|
||||
|
||||
def test_requires_admin_access(self, client, mock_job):
|
||||
"""Test that non-admin users cannot access the endpoint."""
|
||||
original_override = app.dependency_overrides.get(require_admin)
|
||||
|
||||
def get_non_admin():
|
||||
from fastapi import HTTPException
|
||||
raise HTTPException(status_code=403, detail="Admin access required")
|
||||
|
||||
app.dependency_overrides[require_admin] = get_non_admin
|
||||
|
||||
try:
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"artist": "New Artist"},
|
||||
headers={"Authorization": "Bearer user-token"}
|
||||
)
|
||||
assert response.status_code == 403
|
||||
finally:
|
||||
if original_override:
|
||||
app.dependency_overrides[require_admin] = original_override
|
||||
else:
|
||||
app.dependency_overrides[require_admin] = get_mock_admin
|
||||
+93
@@ -769,6 +769,99 @@ Response:
|
||||
}
|
||||
```
|
||||
|
||||
### Job Files (Admin)
|
||||
|
||||
#### Get Job Files
|
||||
|
||||
```http
|
||||
GET /api/admin/jobs/{job_id}/files
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Returns all files associated with a job with signed download URLs (2-hour expiry).
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"job_id": "abc123",
|
||||
"artist": "Artist Name",
|
||||
"title": "Song Title",
|
||||
"files": [
|
||||
{
|
||||
"name": "input.flac",
|
||||
"path": "jobs/abc123/input.flac",
|
||||
"download_url": "https://storage.googleapis.com/signed-url...",
|
||||
"category": "input",
|
||||
"file_key": "input"
|
||||
}
|
||||
],
|
||||
"total_files": 1
|
||||
}
|
||||
```
|
||||
|
||||
Categories: `input`, `stems`, `lyrics`, `screens`, `videos`, `finals`, `packages`
|
||||
|
||||
### Job Updates (Admin)
|
||||
|
||||
#### Update Job Fields
|
||||
|
||||
```http
|
||||
PATCH /api/admin/jobs/{job_id}
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"artist": "New Artist",
|
||||
"title": "New Title"
|
||||
}
|
||||
```
|
||||
|
||||
Updates editable job fields. Allowed fields: `artist`, `title`, `user_email`, `theme_id`, `brand_prefix`, `discord_webhook_url`, `youtube_description`, `youtube_description_template`, `customer_email`, `customer_notes`, `enable_cdg`, `enable_txt`, `enable_youtube_upload`, `non_interactive`, `prep_only`.
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"job_id": "abc123",
|
||||
"updated_fields": ["artist", "title"],
|
||||
"message": "Successfully updated 2 field(s)"
|
||||
}
|
||||
```
|
||||
|
||||
Non-editable fields (job_id, status, created_at, file_urls, state_data) return 400.
|
||||
|
||||
#### Reset Job State
|
||||
|
||||
```http
|
||||
POST /api/admin/jobs/{job_id}/reset
|
||||
Authorization: Bearer ADMIN_TOKEN
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"target_state": "awaiting_review"
|
||||
}
|
||||
```
|
||||
|
||||
Resets a job to a specific workflow checkpoint for re-processing.
|
||||
|
||||
Allowed target states:
|
||||
- `pending` - Restart from beginning (clears all processing data)
|
||||
- `awaiting_audio_selection` - Re-select audio source
|
||||
- `awaiting_review` - Re-review lyrics (preserves audio stems)
|
||||
- `awaiting_instrumental_selection` - Re-select instrumental (preserves review)
|
||||
|
||||
Response:
|
||||
```json
|
||||
{
|
||||
"status": "success",
|
||||
"job_id": "abc123",
|
||||
"previous_status": "complete",
|
||||
"new_status": "awaiting_review",
|
||||
"message": "Job reset from complete to awaiting_review",
|
||||
"cleared_data": ["review_complete", "corrected_lyrics", "instrumental_selection"]
|
||||
}
|
||||
```
|
||||
|
||||
### Internal Email Endpoints
|
||||
|
||||
These endpoints are used by Cloud Tasks for automated notifications.
|
||||
|
||||
@@ -71,6 +71,26 @@ Base Docker images have no fonts. Install `fonts-noto-core`, `fonts-noto-cjk` fo
|
||||
|
||||
---
|
||||
|
||||
### AuthResult Has Tuple Unpacking But Not Subscripting
|
||||
|
||||
**Problem**: The `AuthResult` class returned by `require_admin` supports tuple unpacking via `__iter__` but NOT subscript access via `__getitem__`. Using `auth_data[0]` raises `TypeError: 'AuthResult' object is not subscriptable`.
|
||||
|
||||
**Misleading code**: Existing admin.py endpoints had incorrect type hints:
|
||||
```python
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin) # WRONG type hint
|
||||
admin_email = auth_data[0] # Would get is_valid (bool), NOT email!
|
||||
```
|
||||
|
||||
**Correct approach**: Access attributes directly:
|
||||
```python
|
||||
auth_data: AuthResult = Depends(require_admin) # Correct type hint
|
||||
admin_email = auth_data.user_email or "unknown" # Use attribute access
|
||||
```
|
||||
|
||||
**Why `auth_data[0]` appeared to work**: The `__iter__` method returns `(is_valid, user_type, remaining_uses, message)` - NOT email. Code using `auth_data[0]` was silently getting a boolean, not the admin email. This likely never caused visible failures because the value was only used in logs.
|
||||
|
||||
**Key insight**: When a class has `__iter__` for backward-compatible tuple unpacking but not `__getitem__`, prefer attribute access over index access. Type hints can be misleading if the codebase hasn't been updated consistently.
|
||||
|
||||
## Testing Insights
|
||||
|
||||
### Test Webhook Handlers with Unit Tests
|
||||
|
||||
@@ -79,6 +79,8 @@
|
||||
|
||||
- **Worker Logs Subcollection** (2026-01-04): Moved `worker_logs` from embedded array in job documents to Firestore subcollection (`jobs/{job_id}/logs`). Fixes job failures when logs exceed 1MB (job 501258e1 had 1.26MB of logs). New logs stored with 30-day TTL via Firestore TTL policy. Feature flag `USE_LOG_SUBCOLLECTION=true` (default). See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#firestore-document-1mb-limit-with-embedded-arrays).
|
||||
|
||||
- **Admin Job Detail Enhancements** (2026-01-09): Enhanced admin job detail page with comprehensive job management features. Added: file downloads with signed GCS URLs grouped by category (stems, lyrics, outputs), inline editing of job fields (artist, title, theme, etc.), job reset actions to re-process from specific workflow checkpoints (pending, audio selection, review, instrumental selection), visual timeline with color-coded stages. New endpoints: `GET /api/admin/jobs/{job_id}/files`, `PATCH /api/admin/jobs/{job_id}`, `POST /api/admin/jobs/{job_id}/reset`. See [API.md](API.md#job-files-admin).
|
||||
|
||||
- **GCE Encoding Response Fixes** (2026-01-04): Fixed multiple response format mismatches with GCE encoding worker. The worker returns `output_files` as a list of paths, not a dict with format keys - added conversion logic. Also added defensive type checking for status responses that could be lists. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#external-service-response-format-mismatches).
|
||||
|
||||
- **Video Worker Orchestrator** (2026-01-04): Major refactor to unify video generation pipeline. Created VideoWorkerOrchestrator that coordinates all stages (packaging, encoding, distribution, notifications) regardless of encoding backend (GCE or local). Fixes issue where GCE encoding path bypassed YouTube upload, Discord notifications, and CDG/TXT packaging. Feature flag `USE_NEW_ORCHESTRATOR` (default: true) enables rollback. 139 new tests across 6 new service modules. See [ARCHITECTURE.md](ARCHITECTURE.md#video-worker-orchestrator) and [archive/2026-01-04-video-worker-orchestrator-refactor.md](archive/2026-01-04-video-worker-orchestrator-refactor.md).
|
||||
|
||||
@@ -1,428 +0,0 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useSearchParams, useRouter } from "next/navigation"
|
||||
import { api, adminApi, Job } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import {
|
||||
Accordion,
|
||||
AccordionContent,
|
||||
AccordionItem,
|
||||
AccordionTrigger,
|
||||
} from "@/components/ui/accordion"
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import {
|
||||
ArrowLeft,
|
||||
RefreshCw,
|
||||
Loader2,
|
||||
Trash2,
|
||||
User,
|
||||
Clock,
|
||||
FileText,
|
||||
XCircle,
|
||||
} from "lucide-react"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
|
||||
export default function AdminJobDetailPage() {
|
||||
const searchParams = useSearchParams()
|
||||
const router = useRouter()
|
||||
const { toast } = useToast()
|
||||
const jobId = searchParams.get("id") || ""
|
||||
|
||||
const [job, setJob] = useState<Job | null>(null)
|
||||
const [logs, setLogs] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [logsLoading, setLogsLoading] = useState(false)
|
||||
|
||||
// Delete dialog
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
|
||||
const loadJob = async () => {
|
||||
if (!jobId) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
try {
|
||||
setLoading(true)
|
||||
const data = await api.getJob(jobId)
|
||||
setJob(data)
|
||||
} catch (err: any) {
|
||||
console.error("Failed to load job:", err)
|
||||
toast({
|
||||
title: "Error",
|
||||
description: err.message || "Failed to load job",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadLogs = async () => {
|
||||
if (!jobId) return
|
||||
try {
|
||||
setLogsLoading(true)
|
||||
const data = await api.getJobLogs(jobId, 200)
|
||||
setLogs(data)
|
||||
} catch (err: any) {
|
||||
console.error("Failed to load logs:", err)
|
||||
} finally {
|
||||
setLogsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadJob()
|
||||
loadLogs()
|
||||
}, [jobId])
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
setDeleting(true)
|
||||
await adminApi.deleteJob(jobId)
|
||||
toast({
|
||||
title: "Job Deleted",
|
||||
description: `Job ${jobId} has been deleted`,
|
||||
})
|
||||
router.push("/admin/jobs")
|
||||
} catch (err: any) {
|
||||
toast({
|
||||
title: "Error",
|
||||
description: err.message || "Failed to delete job",
|
||||
variant: "destructive",
|
||||
})
|
||||
} finally {
|
||||
setDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const getStatusVariant = (status: string) => {
|
||||
if (status === "complete" || status === "prep_complete") return "default"
|
||||
if (status === "failed") return "destructive"
|
||||
if (status === "cancelled") return "outline"
|
||||
if (status.includes("awaiting")) return "secondary"
|
||||
return "secondary"
|
||||
}
|
||||
|
||||
const getLogLevelColor = (level: string) => {
|
||||
switch (level?.toUpperCase()) {
|
||||
case "ERROR":
|
||||
return "text-red-500"
|
||||
case "WARNING":
|
||||
return "text-yellow-500"
|
||||
case "INFO":
|
||||
return "text-blue-500"
|
||||
case "DEBUG":
|
||||
return "text-muted-foreground"
|
||||
default:
|
||||
return "text-foreground"
|
||||
}
|
||||
}
|
||||
|
||||
const formatDate = (dateStr?: string) => {
|
||||
if (!dateStr) return "—"
|
||||
return new Date(dateStr).toLocaleString()
|
||||
}
|
||||
|
||||
if (!jobId) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-muted-foreground">No job ID provided</p>
|
||||
<Button variant="outline" className="mt-4" onClick={() => router.push("/admin/jobs")}>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Jobs
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!job) {
|
||||
return (
|
||||
<div className="text-center py-12">
|
||||
<p className="text-muted-foreground">Job not found</p>
|
||||
<Button variant="outline" className="mt-4" onClick={() => router.push("/admin/jobs")}>
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back to Jobs
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Button variant="ghost" size="icon" onClick={() => router.push("/admin/jobs")}>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight flex items-center gap-2">
|
||||
Job {job.job_id}
|
||||
<Badge variant={getStatusVariant(job.status)}>
|
||||
{job.status.replace(/_/g, " ")}
|
||||
</Badge>
|
||||
</h1>
|
||||
{job.artist && job.title && (
|
||||
<p className="text-muted-foreground">{job.artist} - {job.title}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" size="sm" onClick={() => { loadJob(); loadLogs(); }} disabled={loading}>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => setDeleteDialogOpen(true)}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-2" />
|
||||
Delete
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Overview Cards */}
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium flex items-center gap-2">
|
||||
<User className="w-4 h-4" />
|
||||
User
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm truncate">
|
||||
{job.user_email || "Unknown"}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium flex items-center gap-2">
|
||||
<Clock className="w-4 h-4" />
|
||||
Created
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm">{formatDate(job.created_at)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium flex items-center gap-2">
|
||||
<Clock className="w-4 h-4" />
|
||||
Updated
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm">{formatDate(job.updated_at)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium flex items-center gap-2">
|
||||
Progress
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-primary transition-all"
|
||||
style={{ width: `${job.progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-sm font-medium">{job.progress}%</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{job.error_message && (
|
||||
<Card className="border-destructive">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-destructive flex items-center gap-2">
|
||||
<XCircle className="w-5 h-5" />
|
||||
Error
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm">{job.error_message}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Accordion Sections */}
|
||||
<Accordion type="multiple" className="w-full" defaultValue={["timeline", "logs"]}>
|
||||
{/* Timeline */}
|
||||
<AccordionItem value="timeline">
|
||||
<AccordionTrigger>
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="w-4 h-4" />
|
||||
Timeline ({job.timeline?.length || 0} events)
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-2 max-h-[400px] overflow-y-auto">
|
||||
{job.timeline && job.timeline.length > 0 ? (
|
||||
job.timeline.map((event, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex items-start gap-3 text-sm border-l-2 border-muted pl-4 py-1"
|
||||
>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{event.status}
|
||||
</Badge>
|
||||
{event.progress !== undefined && (
|
||||
<span className="text-muted-foreground">
|
||||
{event.progress}%
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{event.message && (
|
||||
<p className="text-muted-foreground mt-1">{event.message}</p>
|
||||
)}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{formatDate(event.timestamp)}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<p className="text-muted-foreground text-sm">No timeline events</p>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* Worker Logs */}
|
||||
<AccordionItem value="logs">
|
||||
<AccordionTrigger>
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="w-4 h-4" />
|
||||
Worker Logs ({logs.length} entries)
|
||||
{logsLoading && <Loader2 className="w-4 h-4 animate-spin ml-2" />}
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<div className="space-y-1 max-h-[500px] overflow-y-auto font-mono text-xs">
|
||||
{logs.length > 0 ? (
|
||||
logs.map((log, i) => (
|
||||
<div key={i} className="flex gap-2 py-0.5 border-b border-muted/50">
|
||||
<span className="text-muted-foreground whitespace-nowrap">
|
||||
{log.timestamp ? new Date(log.timestamp).toLocaleTimeString() : "—"}
|
||||
</span>
|
||||
<span className={`w-16 ${getLogLevelColor(log.level)}`}>
|
||||
[{log.level}]
|
||||
</span>
|
||||
<span className="text-muted-foreground w-20">
|
||||
{log.worker || "—"}
|
||||
</span>
|
||||
<span className="flex-1 break-all">{log.message}</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<p className="text-muted-foreground">No logs available</p>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* State Data */}
|
||||
<AccordionItem value="state">
|
||||
<AccordionTrigger>
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="w-4 h-4" />
|
||||
State Data
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<pre className="text-xs bg-muted p-4 rounded-md overflow-x-auto max-h-[400px]">
|
||||
{JSON.stringify(job.state_data || {}, null, 2)}
|
||||
</pre>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* File URLs */}
|
||||
<AccordionItem value="files">
|
||||
<AccordionTrigger>
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="w-4 h-4" />
|
||||
File URLs
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<pre className="text-xs bg-muted p-4 rounded-md overflow-x-auto max-h-[400px]">
|
||||
{JSON.stringify(job.file_urls || {}, null, 2)}
|
||||
</pre>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
{/* Raw Job Data */}
|
||||
<AccordionItem value="raw">
|
||||
<AccordionTrigger>
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="w-4 h-4" />
|
||||
Raw Job Data
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<pre className="text-xs bg-muted p-4 rounded-md overflow-x-auto max-h-[500px]">
|
||||
{JSON.stringify(job, null, 2)}
|
||||
</pre>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Job</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete job {jobId}? This action cannot be
|
||||
undone and will also delete all associated files.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
disabled={deleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,447 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { setupApiFixtures, setAuthToken, clearAuthToken } from '../fixtures/test-helper';
|
||||
|
||||
/**
|
||||
* Admin Job Detail Page Tests
|
||||
*
|
||||
* Tests the admin job detail page functionality with mocked API responses.
|
||||
* These tests run as part of the regression suite on every PR.
|
||||
*/
|
||||
|
||||
// Mock data for tests
|
||||
const mockAdminUser = {
|
||||
user: {
|
||||
email: 'admin@nomadkaraoke.com',
|
||||
role: 'admin',
|
||||
credits: 100,
|
||||
is_active: true,
|
||||
},
|
||||
};
|
||||
|
||||
const mockJob = {
|
||||
job_id: 'test-job-123',
|
||||
status: 'complete',
|
||||
progress: 100,
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
user_email: 'user@example.com',
|
||||
created_at: '2026-01-09T10:00:00Z',
|
||||
updated_at: '2026-01-09T10:30:00Z',
|
||||
url: 'https://youtube.com/watch?v=abc123',
|
||||
theme_id: 'nomad',
|
||||
enable_cdg: false,
|
||||
enable_txt: false,
|
||||
enable_youtube_upload: true,
|
||||
timeline: [
|
||||
{ status: 'pending', timestamp: '2026-01-09T10:00:00Z', progress: 0 },
|
||||
{ status: 'downloading', timestamp: '2026-01-09T10:01:00Z', progress: 10 },
|
||||
{ status: 'separating_stage1', timestamp: '2026-01-09T10:05:00Z', progress: 30 },
|
||||
{ status: 'complete', timestamp: '2026-01-09T10:30:00Z', progress: 100 },
|
||||
],
|
||||
state_data: {
|
||||
youtube_url: 'https://youtube.com/watch?v=xyz789',
|
||||
dropbox_link: 'https://dropbox.com/s/abc123',
|
||||
},
|
||||
file_urls: {
|
||||
input: 'gs://bucket/jobs/test-job-123/input.flac',
|
||||
stems: {
|
||||
instrumental_clean: 'gs://bucket/jobs/test-job-123/stems/clean.flac',
|
||||
},
|
||||
},
|
||||
request_metadata: {
|
||||
environment: 'production',
|
||||
client_ip: '192.168.1.1',
|
||||
user_agent: 'Mozilla/5.0',
|
||||
server_version: '0.72.0',
|
||||
},
|
||||
};
|
||||
|
||||
const mockJobsList = [mockJob];
|
||||
|
||||
// Note: API returns { logs: [...] }, not just the array
|
||||
const mockLogs = {
|
||||
logs: [
|
||||
{ timestamp: '2026-01-09T10:01:00Z', level: 'INFO', worker: 'audio', message: 'Starting audio download' },
|
||||
{ timestamp: '2026-01-09T10:05:00Z', level: 'INFO', worker: 'audio', message: 'Audio download complete' },
|
||||
{ timestamp: '2026-01-09T10:10:00Z', level: 'WARNING', worker: 'lyrics', message: 'Retrying transcription' },
|
||||
{ timestamp: '2026-01-09T10:30:00Z', level: 'INFO', worker: 'video', message: 'Video encoding complete' },
|
||||
],
|
||||
};
|
||||
|
||||
// Mock files response with signed URLs
|
||||
const mockFiles = {
|
||||
job_id: 'test-job-123',
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
files: [
|
||||
{
|
||||
name: 'input.flac',
|
||||
path: 'gs://bucket/jobs/test-job-123/input.flac',
|
||||
download_url: 'https://storage.googleapis.com/signed/input.flac',
|
||||
category: '',
|
||||
file_key: 'input',
|
||||
},
|
||||
{
|
||||
name: 'instrumental_clean.flac',
|
||||
path: 'gs://bucket/jobs/test-job-123/stems/instrumental_clean.flac',
|
||||
download_url: 'https://storage.googleapis.com/signed/instrumental_clean.flac',
|
||||
category: 'stems',
|
||||
file_key: 'instrumental_clean',
|
||||
},
|
||||
{
|
||||
name: 'vocals.flac',
|
||||
path: 'gs://bucket/jobs/test-job-123/stems/vocals.flac',
|
||||
download_url: 'https://storage.googleapis.com/signed/vocals.flac',
|
||||
category: 'stems',
|
||||
file_key: 'vocals',
|
||||
},
|
||||
{
|
||||
name: 'output.lrc',
|
||||
path: 'gs://bucket/jobs/test-job-123/lyrics/output.lrc',
|
||||
download_url: 'https://storage.googleapis.com/signed/output.lrc',
|
||||
category: 'lyrics',
|
||||
file_key: 'lrc',
|
||||
},
|
||||
{
|
||||
name: 'video_720p.mp4',
|
||||
path: 'gs://bucket/jobs/test-job-123/finals/video_720p.mp4',
|
||||
download_url: 'https://storage.googleapis.com/signed/video_720p.mp4',
|
||||
category: 'finals',
|
||||
file_key: 'lossy_720p_mp4',
|
||||
},
|
||||
],
|
||||
total_files: 5,
|
||||
};
|
||||
|
||||
test.describe('Admin Job Detail Page', () => {
|
||||
test.beforeEach(async ({ page }) => {
|
||||
// Set admin auth token
|
||||
await setAuthToken(page, 'mock-admin-token');
|
||||
});
|
||||
|
||||
test('navigates from jobs list to detail page', async ({ page }) => {
|
||||
// Set up API mocks
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: mockJobsList } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
// Go to jobs list
|
||||
await page.goto('/admin/jobs');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Click on the job row (the job ID text)
|
||||
await page.click('text=test-job-123');
|
||||
|
||||
// Should navigate to detail page (using query param)
|
||||
// Note: Next.js may add trailing slash depending on config
|
||||
await expect(page).toHaveURL(/\/admin\/jobs\/?\?id=test-job-123/);
|
||||
|
||||
// Job header should be visible
|
||||
await expect(page.getByText('Job test-job-123')).toBeVisible();
|
||||
await expect(page.getByText('Test Artist - Test Song')).toBeVisible();
|
||||
});
|
||||
|
||||
test('displays job metadata sections', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } }, // List endpoint is called on page load
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Overview cards should show
|
||||
await expect(page.getByText('user@example.com')).toBeVisible();
|
||||
await expect(page.getByText('YouTube URL')).toBeVisible();
|
||||
await expect(page.getByText('100%')).toBeVisible();
|
||||
|
||||
// Timeline section should be visible (expanded by default)
|
||||
await expect(page.getByText('Timeline (4 events)')).toBeVisible();
|
||||
// Check for specific timeline entries - use first() to avoid strict mode violations
|
||||
await expect(page.getByText('pending').first()).toBeVisible();
|
||||
// 'complete' appears in multiple places (status badge, timeline, logs), check timeline header exists
|
||||
await expect(page.locator('[data-slot="badge"]').filter({ hasText: 'complete' }).first()).toBeVisible();
|
||||
|
||||
// Worker logs section should be visible
|
||||
await expect(page.getByText('Worker Logs (4 entries)')).toBeVisible();
|
||||
});
|
||||
|
||||
test('displays timeline with stage durations', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Timeline should show durations
|
||||
// pending -> downloading took 1 minute
|
||||
await expect(page.getByText(/1m 0s/)).toBeVisible();
|
||||
});
|
||||
|
||||
test('displays request metadata when available', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Click to expand Request Metadata section
|
||||
await page.click('text=Request Metadata');
|
||||
|
||||
// Should show metadata values
|
||||
await expect(page.getByText('production')).toBeVisible();
|
||||
await expect(page.getByText('192.168.1.1')).toBeVisible();
|
||||
});
|
||||
|
||||
test('shows error message for failed jobs', async ({ page }) => {
|
||||
const failedJob = {
|
||||
...mockJob,
|
||||
status: 'failed',
|
||||
progress: 45,
|
||||
error_message: 'Audio separation timed out after 10 minutes',
|
||||
error_details: { worker: 'audio', timeout_seconds: 600 },
|
||||
};
|
||||
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: failedJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Error card should be visible
|
||||
await expect(page.getByText('Error')).toBeVisible();
|
||||
await expect(page.getByText('Audio separation timed out after 10 minutes')).toBeVisible();
|
||||
});
|
||||
|
||||
test('back button returns to jobs list', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: mockJobsList } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Click back button (ghost button with ArrowLeft icon)
|
||||
await page.locator('button:has(svg.lucide-arrow-left)').click();
|
||||
|
||||
// Should navigate to jobs list (no query param)
|
||||
// Note: Next.js may add trailing slash depending on config
|
||||
await expect(page).toHaveURL(/\/admin\/jobs\/?$/);
|
||||
});
|
||||
|
||||
test('handles job not found gracefully', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/nonexistent', response: { status: 404, body: { detail: 'Job not found' } } },
|
||||
{ method: 'GET', path: '/api/jobs/nonexistent/logs', response: { body: { logs: [] } } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=nonexistent');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Should show not found message
|
||||
await expect(page.getByText('Job not found')).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: /Back to Jobs/i })).toBeVisible();
|
||||
});
|
||||
|
||||
test('delete job shows confirmation dialog', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Click delete button
|
||||
await page.click('button:has-text("Delete")');
|
||||
|
||||
// Confirmation dialog should appear
|
||||
await expect(page.getByRole('alertdialog')).toBeVisible();
|
||||
// The dialog text includes "job test-job-123" (not the exact string from before)
|
||||
await expect(page.getByText(/delete job test-job-123/i)).toBeVisible();
|
||||
|
||||
// Cancel button should close dialog
|
||||
await page.click('button:has-text("Cancel")');
|
||||
await expect(page.getByRole('alertdialog')).not.toBeVisible();
|
||||
});
|
||||
|
||||
test('refresh button reloads job data', async ({ page }) => {
|
||||
// Set up API mocks
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Verify initial page loaded correctly
|
||||
await expect(page.getByText('Job test-job-123')).toBeVisible();
|
||||
|
||||
// Click refresh button
|
||||
await page.click('button:has-text("Refresh")');
|
||||
|
||||
// Wait for refresh to complete - the button shows a spinner while loading
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Verify the job data is still visible (refresh completed successfully)
|
||||
await expect(page.getByText('Job test-job-123')).toBeVisible();
|
||||
await expect(page.getByText('Test Artist - Test Song')).toBeVisible();
|
||||
});
|
||||
|
||||
test('files section shows downloadable files grouped by category', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
{ method: 'GET', path: '/api/admin/jobs/test-job-123/files', response: { body: mockFiles } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Expand the Files accordion
|
||||
await page.click('text=Files (5 downloadable)');
|
||||
|
||||
// Should show category groups (use heading role to be specific, avoid matching log entries)
|
||||
await expect(page.getByRole('heading', { name: 'Audio Stems' })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Lyrics' })).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Final Outputs' })).toBeVisible();
|
||||
|
||||
// Should show individual files
|
||||
await expect(page.getByText('input.flac')).toBeVisible();
|
||||
await expect(page.getByText('instrumental_clean.flac')).toBeVisible();
|
||||
await expect(page.getByText('output.lrc')).toBeVisible();
|
||||
|
||||
// Should show download buttons with correct links
|
||||
const downloadLinks = page.locator('a[href*="storage.googleapis.com/signed"]');
|
||||
await expect(downloadLinks).toHaveCount(5);
|
||||
});
|
||||
|
||||
test('files section handles empty files gracefully', async ({ page }) => {
|
||||
const emptyFiles = {
|
||||
job_id: 'test-job-123',
|
||||
artist: 'Test Artist',
|
||||
title: 'Test Song',
|
||||
files: [],
|
||||
total_files: 0,
|
||||
};
|
||||
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
{ method: 'GET', path: '/api/admin/jobs/test-job-123/files', response: { body: emptyFiles } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Expand the Files accordion
|
||||
await page.click('text=Files (0 downloadable)');
|
||||
|
||||
// Should show "no files" message
|
||||
await expect(page.getByText('No files available')).toBeVisible();
|
||||
});
|
||||
|
||||
test('admin actions section shows reset options', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Expand the Admin Actions accordion
|
||||
await page.click('text=Admin Actions');
|
||||
|
||||
// Should show reset options
|
||||
await expect(page.getByText('Reset Job State')).toBeVisible();
|
||||
// Check the reset buttons are visible - use .first() to handle multiple matches
|
||||
await expect(page.locator('button:has-text("Pending")').first()).toBeVisible();
|
||||
await expect(page.locator('button:has-text("Audio Selection")').first()).toBeVisible();
|
||||
await expect(page.locator('button:has-text("Lyrics Review")').first()).toBeVisible();
|
||||
await expect(page.locator('button:has-text("Instrumental Selection")').first()).toBeVisible();
|
||||
});
|
||||
|
||||
test('clicking reset button shows confirmation dialog', async ({ page }) => {
|
||||
await setupApiFixtures(page, {
|
||||
mocks: [
|
||||
{ method: 'GET', path: '/api/users/me', response: { body: mockAdminUser } },
|
||||
{ method: 'GET', path: '/api/jobs', response: { body: [] } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123', response: { body: mockJob } },
|
||||
{ method: 'GET', path: '/api/jobs/test-job-123/logs', response: { body: mockLogs } },
|
||||
],
|
||||
});
|
||||
|
||||
await page.goto('/admin/jobs?id=test-job-123');
|
||||
await page.waitForLoadState('networkidle');
|
||||
|
||||
// Expand the Admin Actions accordion
|
||||
await page.click('text=Admin Actions');
|
||||
|
||||
// Click a reset button (Pending)
|
||||
await page.locator('button:has-text("Pending")').click();
|
||||
|
||||
// Should show confirmation dialog
|
||||
await expect(page.getByRole('alertdialog')).toBeVisible();
|
||||
await expect(page.getByRole('heading', { name: 'Reset Job' })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Cancel' })).toBeVisible();
|
||||
await expect(page.getByRole('button', { name: 'Reset' })).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -1113,6 +1113,53 @@ export const adminApi = {
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all files for a job with signed download URLs
|
||||
*/
|
||||
async getJobFiles(jobId: string): Promise<JobFilesResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/jobs/${jobId}/files`,
|
||||
{ headers: getAuthHeaders() }
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
/**
|
||||
* Update editable fields of a job (admin only)
|
||||
*/
|
||||
async updateJob(jobId: string, updates: JobUpdateRequest): Promise<JobUpdateResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/jobs/${jobId}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify(updates),
|
||||
}
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
/**
|
||||
* Reset a job to a specific state for re-processing (admin only)
|
||||
*/
|
||||
async resetJob(jobId: string, targetState: string): Promise<JobResetResponse> {
|
||||
const response = await fetch(
|
||||
`${API_BASE_URL}/api/admin/jobs/${jobId}/reset`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify({ target_state: targetState }),
|
||||
}
|
||||
);
|
||||
return handleResponse(response);
|
||||
},
|
||||
};
|
||||
|
||||
// Types for admin completion message API
|
||||
@@ -1131,5 +1178,56 @@ export interface SendCompletionEmailResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Types for admin job files API
|
||||
export interface FileInfo {
|
||||
name: string;
|
||||
path: string;
|
||||
download_url: string;
|
||||
category: string;
|
||||
file_key: string;
|
||||
}
|
||||
|
||||
export interface JobFilesResponse {
|
||||
job_id: string;
|
||||
artist?: string;
|
||||
title?: string;
|
||||
files: FileInfo[];
|
||||
total_files: number;
|
||||
}
|
||||
|
||||
export interface JobUpdateRequest {
|
||||
artist?: string;
|
||||
title?: string;
|
||||
user_email?: string;
|
||||
theme_id?: string;
|
||||
brand_prefix?: string;
|
||||
discord_webhook_url?: string;
|
||||
youtube_description?: string;
|
||||
youtube_description_template?: string;
|
||||
customer_email?: string;
|
||||
customer_notes?: string;
|
||||
enable_cdg?: boolean;
|
||||
enable_txt?: boolean;
|
||||
enable_youtube_upload?: boolean;
|
||||
non_interactive?: boolean;
|
||||
prep_only?: boolean;
|
||||
}
|
||||
|
||||
export interface JobUpdateResponse {
|
||||
status: string;
|
||||
job_id: string;
|
||||
updated_fields: string[];
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface JobResetResponse {
|
||||
status: string;
|
||||
job_id: string;
|
||||
previous_status: string;
|
||||
new_status: string;
|
||||
message: string;
|
||||
cleared_data: string[];
|
||||
}
|
||||
|
||||
export { ApiError };
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.99.9"
|
||||
version = "0.100.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
Reference in new issue
Block a user