diff --git a/backend/api/routes/file_upload.py b/backend/api/routes/file_upload.py index 491d4b78..8e047dfc 100644 --- a/backend/api/routes/file_upload.py +++ b/backend/api/routes/file_upload.py @@ -56,6 +56,52 @@ def _is_youtube_url(url: str) -> bool: router = APIRouter(tags=["jobs"]) +def _apply_tenant_overrides( + dist: EffectiveDistributionSettings, + tenant_config, + effective_theme_id: str | None, + is_private: bool, + enable_youtube_upload: bool, +) -> tuple: + """ + Apply tenant-specific overrides to distribution settings and job options. + + For tenant jobs: + - Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults + (only when not already set in the request body / dist) + - Forces is_private = True + - Applies locked_theme as effective theme + - Disables YouTube upload + + Returns: + Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload) + """ + if not tenant_config: + return dist, effective_theme_id, is_private, enable_youtube_upload + + defaults = tenant_config.defaults + + # Overlay tenant distribution defaults (request-level values take precedence) + if defaults.brand_prefix and not dist.brand_prefix: + dist.brand_prefix = defaults.brand_prefix + if defaults.dropbox_path and not dist.dropbox_path: + dist.dropbox_path = defaults.dropbox_path + if defaults.gdrive_folder_id and not dist.gdrive_folder_id: + dist.gdrive_folder_id = defaults.gdrive_folder_id + + # Force private for all tenant jobs + is_private = True + + # Apply locked_theme (overrides any user selection) + if defaults.locked_theme: + effective_theme_id = defaults.locked_theme + + # Disable YouTube upload for tenants + enable_youtube_upload = False + + return dist, effective_theme_id, is_private, enable_youtube_upload + + # ============================================================================ # Pydantic models for signed URL upload flow # ============================================================================ @@ -510,7 +556,7 @@ async def upload_and_create_job( "auth_url": "/api/auth/status" } ) - + # Extract request metadata for tracking and filtering request_metadata = extract_request_metadata(request, created_from="upload") @@ -534,6 +580,14 @@ async def upload_and_create_job( if effective_theme_id: logger.info(f"Applying default theme: {effective_theme_id}") + # Apply tenant-specific overrides (brand, paths, privacy, theme) + dist, effective_theme_id, is_private, effective_enable_youtube_upload = _apply_tenant_overrides( + dist, tenant_config, effective_theme_id, is_private, effective_enable_youtube_upload, + ) + if tenant_config: + logger.info(f"Applied tenant overrides for '{tenant_config.id}': " + f"brand={dist.brand_prefix}, private={is_private}, theme={effective_theme_id}") + # Resolve CDG/TXT defaults based on theme resolved_cdg, resolved_txt = resolve_cdg_txt_defaults( effective_theme_id, enable_cdg, enable_txt @@ -1077,12 +1131,29 @@ async def create_job_with_upload_urls( settings = get_settings() effective_enable_youtube_upload = body.enable_youtube_upload if body.enable_youtube_upload is not None else settings.default_enable_youtube_upload + # Apply default theme if none specified + effective_theme_id = body.theme_id + if effective_theme_id is None: + theme_service = get_theme_service() + effective_theme_id = theme_service.get_default_theme_id() + if effective_theme_id: + logger.info(f"Applying default theme: {effective_theme_id}") + + # Apply tenant-specific overrides (brand, paths, privacy, theme) + effective_is_private = body.is_private + dist, effective_theme_id, effective_is_private, effective_enable_youtube_upload = _apply_tenant_overrides( + dist, tenant_config, effective_theme_id, effective_is_private, effective_enable_youtube_upload, + ) + if tenant_config: + logger.info(f"Applied tenant overrides for '{tenant_config.id}': " + f"brand={dist.brand_prefix}, private={effective_is_private}, theme={effective_theme_id}") + # Validate credentials for requested distribution services # Skip YouTube/GDrive checks for private jobs (they won't use those services) invalid_services = [] credential_manager = get_credential_manager() - if effective_enable_youtube_upload and not body.is_private: + if effective_enable_youtube_upload and not effective_is_private: result = credential_manager.check_youtube_credentials() if result.status != CredentialStatus.VALID: invalid_services.append(f"youtube ({result.message})") @@ -1092,7 +1163,7 @@ async def create_job_with_upload_urls( if result.status != CredentialStatus.VALID: invalid_services.append(f"dropbox ({result.message})") - if dist.gdrive_folder_id and not body.is_private: + if dist.gdrive_folder_id and not effective_is_private: result = credential_manager.check_gdrive_credentials() if result.status != CredentialStatus.VALID: invalid_services.append(f"gdrive ({result.message})") @@ -1114,15 +1185,6 @@ async def create_job_with_upload_urls( # Get original audio filename audio_file = audio_files[0] - # Apply default theme if none specified - # This ensures all karaoke videos use the Nomad theme by default - effective_theme_id = body.theme_id - if effective_theme_id is None: - theme_service = get_theme_service() - effective_theme_id = theme_service.get_default_theme_id() - if effective_theme_id: - logger.info(f"Applying default theme: {effective_theme_id}") - # Resolve CDG/TXT defaults based on theme resolved_cdg, resolved_txt = resolve_cdg_txt_defaults( effective_theme_id, body.enable_cdg, body.enable_txt @@ -1161,7 +1223,7 @@ async def create_job_with_upload_urls( other_stems_models=body.other_stems_models, request_metadata=request_metadata, non_interactive=body.non_interactive, - is_private=body.is_private, + is_private=effective_is_private, # Tenant scoping tenant_id=tenant_config.id if tenant_config else None, ) diff --git a/backend/models/tenant.py b/backend/models/tenant.py index 7f4d52b3..25f902fa 100644 --- a/backend/models/tenant.py +++ b/backend/models/tenant.py @@ -95,6 +95,12 @@ class TenantDefaults(BaseModel): brand_prefix: Optional[str] = Field( None, description="Prefix for output filenames (e.g., 'VSTAR')" ) + dropbox_path: Optional[str] = Field( + None, description="Tenant-specific Dropbox folder path (e.g., '/Karaoke/Vocal-Star')" + ) + gdrive_folder_id: Optional[str] = Field( + None, description="Tenant-specific Google Drive folder ID for output uploads" + ) youtube_description_template: Optional[str] = Field( None, description="Default YouTube description template" ) diff --git a/backend/services/job_defaults_service.py b/backend/services/job_defaults_service.py index 7af62e46..eb3ad694 100644 --- a/backend/services/job_defaults_service.py +++ b/backend/services/job_defaults_service.py @@ -80,6 +80,17 @@ def get_effective_distribution_for_job(job) -> EffectiveDistributionSettings: EffectiveDistributionSettings with private overrides applied if needed """ if getattr(job, 'is_private', False): + # Tenant jobs: use the job's own distribution fields (set at creation from tenant config) + # Non-tenant private jobs: override to NonPublished paths + if getattr(job, 'tenant_id', None): + return EffectiveDistributionSettings( + dropbox_path=getattr(job, 'dropbox_path', None), + brand_prefix=getattr(job, 'brand_prefix', None), + enable_youtube_upload=False, + gdrive_folder_id=getattr(job, 'gdrive_folder_id', None), + discord_webhook_url=getattr(job, 'discord_webhook_url', None), + youtube_description=None, + ) settings = get_settings() return EffectiveDistributionSettings( dropbox_path=settings.default_private_dropbox_path, diff --git a/backend/tests/test_private_tracks.py b/backend/tests/test_private_tracks.py index 8ea3486c..f1da2ff8 100644 --- a/backend/tests/test_private_tracks.py +++ b/backend/tests/test_private_tracks.py @@ -406,6 +406,7 @@ class TestOrchestratorConfigPrivate: job.gdrive_folder_id = "folder-123" job.keep_brand_code = None job.existing_instrumental_gcs_path = None + job.tenant_id = None # Non-tenant job config = create_orchestrator_config_from_job( job=job, diff --git a/backend/tests/test_tenant_job_defaults.py b/backend/tests/test_tenant_job_defaults.py new file mode 100644 index 00000000..e14dcaef --- /dev/null +++ b/backend/tests/test_tenant_job_defaults.py @@ -0,0 +1,259 @@ +""" +Unit tests for tenant-aware job defaults and distribution overrides. + +Tests that: +- Tenant config fields (brand_prefix, dropbox_path, gdrive_folder_id) are applied to jobs +- All tenant jobs are forced private +- Locked theme overrides user selection +- Private tenant jobs use tenant-specific paths (not NonPublished) +- Non-tenant private jobs still use NonPublished paths +""" + +import pytest +from unittest.mock import MagicMock, patch + +from backend.models.tenant import TenantConfig, TenantDefaults, TenantFeatures, TenantBranding, TenantAuth +from backend.services.job_defaults_service import ( + get_effective_distribution_settings, + get_effective_distribution_for_job, + EffectiveDistributionSettings, +) + + +def _make_tenant_config(**defaults_kwargs) -> TenantConfig: + """Create a TenantConfig with custom defaults for testing.""" + return TenantConfig( + id="vocalstar", + name="Vocal Star", + subdomain="vocalstar.nomadkaraoke.com", + defaults=TenantDefaults( + locked_theme="vocalstar", + distribution_mode="cloud_only", + brand_prefix="VSTAR", + dropbox_path="/Karaoke/Vocal-Star", + gdrive_folder_id="gdrive-folder-123", + **defaults_kwargs, + ), + ) + + +def _make_job_mock(**kwargs): + """Create a mock job object with the given attributes.""" + defaults = { + "is_private": False, + "tenant_id": None, + "dropbox_path": None, + "gdrive_folder_id": None, + "brand_prefix": None, + "enable_youtube_upload": False, + "discord_webhook_url": None, + "youtube_description_template": None, + } + defaults.update(kwargs) + job = MagicMock() + for key, value in defaults.items(): + setattr(job, key, value) + return job + + +class TestApplyTenantOverrides: + """Tests for _apply_tenant_overrides() in file_upload.py.""" + + def _get_apply_fn(self): + """Import the function under test.""" + from backend.api.routes.file_upload import _apply_tenant_overrides + return _apply_tenant_overrides + + def test_tenant_defaults_applied_to_distribution(self): + """Tenant brand_prefix, dropbox_path, gdrive_folder_id are applied to distribution settings.""" + apply_fn = self._get_apply_fn() + tenant_config = _make_tenant_config() + + dist = EffectiveDistributionSettings( + dropbox_path=None, + gdrive_folder_id=None, + discord_webhook_url=None, + brand_prefix=None, + enable_youtube_upload=True, + youtube_description=None, + ) + + new_dist, theme, is_private, yt_upload = apply_fn( + dist, tenant_config, "default", False, True + ) + + assert new_dist.brand_prefix == "VSTAR" + assert new_dist.dropbox_path == "/Karaoke/Vocal-Star" + assert new_dist.gdrive_folder_id == "gdrive-folder-123" + + def test_tenant_job_forced_private(self): + """All tenant jobs are forced to is_private=True.""" + apply_fn = self._get_apply_fn() + tenant_config = _make_tenant_config() + + dist = EffectiveDistributionSettings( + dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None, + brand_prefix=None, enable_youtube_upload=True, youtube_description=None, + ) + + _, _, is_private, _ = apply_fn(dist, tenant_config, "default", False, True) + assert is_private is True + + def test_tenant_locked_theme_applied(self): + """locked_theme overrides the user's theme selection.""" + apply_fn = self._get_apply_fn() + tenant_config = _make_tenant_config() + + dist = EffectiveDistributionSettings( + dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None, + brand_prefix=None, enable_youtube_upload=True, youtube_description=None, + ) + + _, theme, _, _ = apply_fn(dist, tenant_config, "user-selected-theme", False, True) + assert theme == "vocalstar" + + def test_tenant_youtube_upload_disabled(self): + """YouTube upload is disabled for tenant jobs.""" + apply_fn = self._get_apply_fn() + tenant_config = _make_tenant_config() + + dist = EffectiveDistributionSettings( + dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None, + brand_prefix=None, enable_youtube_upload=True, youtube_description=None, + ) + + _, _, _, yt_upload = apply_fn(dist, tenant_config, "default", False, True) + assert yt_upload is False + + def test_request_values_take_precedence(self): + """Explicit request-level values are not overridden by tenant defaults.""" + apply_fn = self._get_apply_fn() + tenant_config = _make_tenant_config() + + dist = EffectiveDistributionSettings( + dropbox_path="/Custom/Path", + gdrive_folder_id="custom-folder", + discord_webhook_url=None, + brand_prefix="CUSTOM", + enable_youtube_upload=True, + youtube_description=None, + ) + + new_dist, _, _, _ = apply_fn(dist, tenant_config, "default", False, True) + assert new_dist.brand_prefix == "CUSTOM" + assert new_dist.dropbox_path == "/Custom/Path" + assert new_dist.gdrive_folder_id == "custom-folder" + + def test_no_tenant_config_passthrough(self): + """When no tenant config, all values pass through unchanged.""" + apply_fn = self._get_apply_fn() + + dist = EffectiveDistributionSettings( + dropbox_path="/Some/Path", gdrive_folder_id=None, discord_webhook_url=None, + brand_prefix="NOMAD", enable_youtube_upload=True, youtube_description=None, + ) + + new_dist, theme, is_private, yt_upload = apply_fn( + dist, None, "nomad", False, True + ) + assert new_dist.brand_prefix == "NOMAD" + assert new_dist.dropbox_path == "/Some/Path" + assert theme == "nomad" + assert is_private is False + assert yt_upload is True + + def test_partial_tenant_defaults_only_overrides_set_fields(self): + """When tenant config has only some defaults, only those are applied.""" + apply_fn = self._get_apply_fn() + # Only brand_prefix set, no dropbox_path or gdrive_folder_id + tenant_config = TenantConfig( + id="partial", + name="Partial Tenant", + subdomain="partial.nomadkaraoke.com", + defaults=TenantDefaults( + brand_prefix="PART", + dropbox_path=None, + gdrive_folder_id=None, + locked_theme=None, + ), + ) + + dist = EffectiveDistributionSettings( + dropbox_path=None, gdrive_folder_id=None, discord_webhook_url=None, + brand_prefix=None, enable_youtube_upload=True, youtube_description=None, + ) + + new_dist, theme, is_private, yt_upload = apply_fn( + dist, tenant_config, "user-theme", False, True + ) + + # brand_prefix applied + assert new_dist.brand_prefix == "PART" + # dropbox/gdrive remain None since tenant has None + assert new_dist.dropbox_path is None + assert new_dist.gdrive_folder_id is None + # No locked_theme, so user theme preserved + assert theme == "user-theme" + # Still forced private and no YT + assert is_private is True + assert yt_upload is False + + +class TestTenantJobDistribution: + """Tests for get_effective_distribution_for_job() with tenant jobs.""" + + def test_private_tenant_job_uses_tenant_paths(self): + """Private tenant jobs use their own Dropbox/GDrive paths, not NonPublished.""" + job = _make_job_mock( + is_private=True, + tenant_id="vocalstar", + dropbox_path="/Karaoke/Vocal-Star", + gdrive_folder_id="gdrive-folder-123", + brand_prefix="VSTAR", + ) + + result = get_effective_distribution_for_job(job) + + assert result.dropbox_path == "/Karaoke/Vocal-Star" + assert result.gdrive_folder_id == "gdrive-folder-123" + assert result.brand_prefix == "VSTAR" + assert result.enable_youtube_upload is False + + @patch("backend.services.job_defaults_service.get_settings") + def test_non_tenant_private_job_still_uses_nonpublished(self, mock_settings): + """Non-tenant private jobs still get the NonPublished path override.""" + mock_settings.return_value = MagicMock( + default_private_dropbox_path="/Tracks-NonPublished", + default_private_brand_prefix="NOMADNP", + ) + + job = _make_job_mock( + is_private=True, + tenant_id=None, + dropbox_path="/Some/User/Path", + brand_prefix="SOMETHING", + ) + + result = get_effective_distribution_for_job(job) + + assert result.dropbox_path == "/Tracks-NonPublished" + assert result.brand_prefix == "NOMADNP" + assert result.enable_youtube_upload is False + assert result.gdrive_folder_id is None + + def test_non_private_job_uses_own_settings(self): + """Non-private jobs (tenant or not) use their own distribution settings.""" + job = _make_job_mock( + is_private=False, + tenant_id="vocalstar", + dropbox_path="/Karaoke/Vocal-Star", + gdrive_folder_id="gdrive-folder-123", + brand_prefix="VSTAR", + enable_youtube_upload=False, + ) + + result = get_effective_distribution_for_job(job) + + assert result.dropbox_path == "/Karaoke/Vocal-Star" + assert result.gdrive_folder_id == "gdrive-folder-123" + assert result.brand_prefix == "VSTAR" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index e7eb3a55..9e9710ff 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -453,10 +453,11 @@ if tenant_config and not tenant_config.features.audio_search: ### Active Tenants **Vocal Star** (`vocalstar.nomadkaraoke.com`) -- Features: File upload only (no audio search, no YouTube URL) -- Distribution: Download only (no YouTube/Dropbox/GDrive) +- Features: File upload only (no audio search, no YouTube URL), streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) +- Distribution: Cloud only (Dropbox + Google Drive to tenant-specific folders, no YouTube) - Theme: Locked to "vocalstar" theme (yellow/blue) - Auth: Restricted to `@vocal-star.com` and `@vocalstarmusic.com` emails +- All jobs automatically private with VSTAR brand prefix - Setup: `python scripts/setup-vocalstar-tenant.py` **Singa** (`singa.nomadkaraoke.com`) diff --git a/docs/README.md b/docs/README.md index e797ead0..b958ed63 100644 --- a/docs/README.md +++ b/docs/README.md @@ -45,6 +45,8 @@ ## Recent Changes +- **Tenant Portal UI Rework** (2026-03-04): Replaced the multi-step consumer wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for B2B tenant portals. Vocal Star's portal now uses the new `TenantJobFlow` component instead of `GuidedJobFlow`. All tenant jobs are automatically private with tenant-specific distribution: Dropbox delivery to `/MediaUnsynced/Karaoke/Tracks-VocalStar`, Google Drive upload to tenant folder, VSTAR brand prefix. Backend adds `_apply_tenant_overrides()` helper that forces private, applies locked theme, and overlays tenant distribution settings. Private tenant jobs now use their own Dropbox/GDrive paths instead of the NonPublished override. Frontend conditionally renders `TenantJobFlow` vs `GuidedJobFlow` based on tenant detection. See [archive/2026-03-04-tenant-portal-ui-rework.md](archive/2026-03-04-tenant-portal-ui-rework.md). + - **Custom Video Styling for Private Jobs** (2026-03-04): Users who select "Private (no YouTube upload)" can now customize their karaoke video styling. New options in the guided flow's customize step: upload a custom **karaoke background image** (replaces the starfield behind lyrics), upload a custom **title card background image**, and change **artist/title text colors** via color pickers. Both backgrounds show accurate canvas-based live previews. Style assets are uploaded to GCS via signed URLs after job creation (non-blocking — job falls back to default theme on upload failure). Backend: 2 new endpoints (`style-upload-urls`, `style-uploads-complete`) that validate ownership, cutoff status, and merge custom assets into the theme's `style_params.json`. See [API.md](API.md#get-style-upload-urls). - **Tenant Portal Frontend Separation** (2026-03-03): B2B tenants now served from a dedicated Cloudflare Pages project (`karaoke-gen-tenant`) built with `NEXT_PUBLIC_TENANT_PORTAL=true` to tree-shake consumer content. A Cloudflare edge function injects `window.__TENANT_CONFIG__` and CSS variables into HTML at the edge, eliminating the initial API round-trip for tenant config. Magic link emails now use tenant-specific URLs (e.g., `vocalstar.nomadkaraoke.com/auth/verify`). Admins can preview any tenant's branding via `?preview_tenant=`. See [ARCHITECTURE.md](ARCHITECTURE.md#tenant-portal-frontend-b2b-deployment). diff --git a/docs/archive/2026-03-04-tenant-portal-ui-rework.md b/docs/archive/2026-03-04-tenant-portal-ui-rework.md new file mode 100644 index 00000000..18cf6a65 --- /dev/null +++ b/docs/archive/2026-03-04-tenant-portal-ui-rework.md @@ -0,0 +1,158 @@ +# Tenant Portal UI Rework + +**Date**: 2026-03-04 +**Branch**: `feat/sess-20260304-0007-tenant-ui-rework` +**Worktree**: `karaoke-gen-tenant-ui-rework` +**Status**: Implementation + Config Complete — Ready for PR + +## Context + +The tenant portal at `vocalstar.nomadkaraoke.com` shows the same 3-step consumer wizard (song search -> audio source -> customize) designed for end users. B2B white-label customers like Vocal Star always provide their own mixed audio AND instrumental files. They don't need audio search, YouTube URL input, theme selection, privacy toggles, or customization options. + +**Goal**: Replace the multi-step wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for tenant portals. All tracks are automatically private, delivered to tenant-specific Dropbox/Google Drive folders, with tenant brand codes and styling. + +## Implementation Plan + +### Phase 1: Backend — Tenant Distribution Defaults + +| Step | File | Change | Status | +|------|------|--------|--------| +| 1.1 | `backend/models/tenant.py` | Add `dropbox_path`, `gdrive_folder_id` to TenantDefaults | Done | +| 1.2 | `backend/api/routes/file_upload.py` | Create `_apply_tenant_overrides()`, call in 2 endpoints | Done | +| 1.3 | `backend/services/job_defaults_service.py` | Tenant-aware private job handling (skip NonPublished override) | Done | +| 1.4 | `frontend/lib/api.ts` | Add `existing_instrumental` flag to createJobWithUploadUrls | Done | +| 1.5 | `backend/tests/test_tenant_job_defaults.py` | 9 unit tests for tenant override logic | Done | + +**1.1 Details**: Two new Optional fields on TenantDefaults: +- `dropbox_path: Optional[str]` — e.g., `/Karaoke/Vocal-Star` +- `gdrive_folder_id: Optional[str]` — tenant GDrive folder ID + +Already excluded from TenantPublicConfig (line 194 only copies theme_id, locked_theme, distribution_mode). + +**1.2 Details**: `_apply_tenant_overrides(dist, tenant_config, body)` helper that: +1. Overlays tenant `brand_prefix`, `dropbox_path`, `gdrive_folder_id` onto EffectiveDistributionSettings +2. Forces `is_private = True` for all tenant jobs +3. Applies `locked_theme` as effective theme +4. Disables YouTube upload + +Called in: `create_job_with_upload_urls` (line 971) and `upload_and_create_job` (line 324). + +**1.3 Details**: In `get_effective_distribution_for_job` (line 64), if `job.tenant_id` is set AND `is_private=True`, skip the NonPublished path override. Use job's own distribution fields (which contain tenant defaults from creation). Still disable YouTube. + +**1.4 Details**: The backend `CreateJobWithUploadUrlsRequest` already has `existing_instrumental: bool` (line 170). Frontend `api.ts` `createJobWithUploadUrls()` just needs to pass it through in the request body. + +**1.5 Tests**: +- `test_tenant_defaults_applied_to_distribution` — brand_prefix, dropbox_path, gdrive_folder_id applied +- `test_tenant_job_forced_private` — is_private always True for tenant jobs +- `test_tenant_locked_theme_applied` — locked_theme overrides user theme +- `test_private_tenant_job_uses_tenant_paths` — uses tenant Dropbox/GDrive, NOT NonPublished +- `test_non_tenant_private_job_still_uses_nonpublished` — existing behavior preserved + +### Phase 2: Frontend — TenantJobFlow Component + +| Step | File | Change | Status | +|------|------|--------|--------| +| 2.1 | `frontend/components/job/TenantJobFlow.tsx` | **Create** single-page 4-field form | Done | +| 2.2 | `frontend/app/app/page.tsx` | TenantLogo in header, conditional form rendering | Done | +| 2.3 | `frontend/__tests__/tenant-job-flow.test.tsx` | Component tests (4 tests) | Done | + +**2.1 Details**: Single-page form (~250 lines) with: +- Artist text input, Title text input +- Mixed Audio file upload (drag-and-drop, accepts .mp3,.wav,.flac,.m4a,.ogg,.aac) +- Instrumental Audio file upload (same types) +- Submit button (disabled until all 4 fields filled) +- Submission: `createJobWithUploadUrls` -> `uploadToSignedUrl` x2 -> `completeJobUpload` +- Success view: simplified timeline (review lyrics -> video delivered), "Create Another" button +- Omits "audio processing" step since instrumental is provided + +**2.2 Details**: +- Replace hardcoded `` (line 196) with `` +- Tenant-aware title using `branding.site_title` +- Conditional: `` when `!isDefault`, else `` +- Card text: "Submit Track" / "Upload your mixed audio and instrumental" for tenants +- Hide feedback banner for non-default users + +### Phase 3: Config & Deployment + +| Step | Change | Status | +|------|--------|--------| +| 3.1 | Update Vocalstar tenant config in GCS | Done | +| 3.2 | Post-deploy setup tasks | Done — all verified | + +Config additions needed: +```json +{ + "defaults": { + "locked_theme": "vocalstar", + "distribution_mode": "cloud_only", + "brand_prefix": "VSTAR", + "dropbox_path": "", + "gdrive_folder_id": "" + }, + "features": { + "audio_search": false, + "file_upload": true, + "youtube_url": false, + "youtube_upload": false, + "theme_selection": false, + "color_overrides": false + } +} +``` + +### Phase 4: Production Verification + +| Step | File | Change | Status | +|------|------|--------|--------| +| 4.1 | `frontend/e2e/production/tenant-job-submission.spec.ts` | **Create** Playwright E2E test (3 tests) | Done | + +Full lifecycle: navigate tenant portal -> verify branding -> submit track -> wait for processing -> approve reviews -> verify outputs delivered to tenant paths. + +## Key Files + +| File | Action | +|------|--------| +| `backend/models/tenant.py` | Modify — add 2 fields to TenantDefaults | +| `backend/api/routes/file_upload.py` | Modify — add `_apply_tenant_overrides()`, call in 2 endpoints | +| `backend/services/job_defaults_service.py` | Modify — tenant-aware private job handling | +| `frontend/components/job/TenantJobFlow.tsx` | **Create** — new simplified 4-field form | +| `frontend/app/app/page.tsx` | Modify — TenantLogo in header, conditional form | +| `frontend/lib/api.ts` | Modify — add `existing_instrumental` flag | +| `backend/tests/test_tenant_job_defaults.py` | **Create** — backend tests | +| `frontend/__tests__/components/job/TenantJobFlow.test.tsx` | **Create** — component tests | +| `frontend/e2e/production/tenant-job-submission.spec.ts` | **Create** — E2E prod test | + +## Implementation Log + +### Phase 1 — Backend (Complete) +- Added `dropbox_path` and `gdrive_folder_id` to `TenantDefaults` model +- Created `_apply_tenant_overrides()` helper in `file_upload.py` — overlays tenant config, forces private, applies locked_theme, disables YouTube +- Wired into both `upload_and_create_job` and `create_job_with_upload_urls` endpoints +- Fixed `get_effective_distribution_for_job` to respect tenant paths for private jobs (skips NonPublished override when `tenant_id` is set) +- Added `existing_instrumental` option to frontend `api.createJobWithUploadUrls()` +- 9 unit tests in `test_tenant_job_defaults.py` — all pass + +### Phase 2 — Frontend (Complete) +- Created `TenantJobFlow.tsx` (~300 lines) — 4-field form with drag-and-drop, progress tracking, success timeline +- Updated `app/page.tsx`: + - `TenantLogo` component in header (replaces hardcoded Nomad logo for tenants) + - Tenant-aware title using `branding.site_title` + - Conditional rendering: `TenantJobFlow` for tenants, `GuidedJobFlow` for consumers + - Card titles/descriptions adapted per mode + - Feedback banner hidden for tenants +- 4 component tests in `tenant-job-flow.test.tsx` — all pass (520/520 total) + +### Phase 3 — Config (Complete) +- Updated `gs://karaoke-gen-storage-nomadkaraoke/tenants/vocalstar/config.json`: + - `distribution_mode`: "download_only" → "cloud_only" + - `dropbox_upload`/`gdrive_upload`: false → true + - Added `dropbox_path`: "/MediaUnsynced/Karaoke/Tracks-VocalStar" + - Added `gdrive_folder_id`: "15pKDJSh9uQSAJFbKlHsiiRLmFCUkYZPc" +- Verified: `vocalstar` theme exists with style_params.json + 6 assets (font, backgrounds) +- Verified: logo.jpg accessible via API asset endpoint (85KB, 200 OK) + +### Phase 4 — E2E (Complete) +- Created `tenant-job-submission.spec.ts` with 3 tests: + 1. Tenant portal shows simplified form (not consumer wizard) + 2. Full track submission flow + 3. Consumer portal still works normally diff --git a/frontend/__tests__/tenant-job-flow.test.tsx b/frontend/__tests__/tenant-job-flow.test.tsx new file mode 100644 index 00000000..a9a80b92 --- /dev/null +++ b/frontend/__tests__/tenant-job-flow.test.tsx @@ -0,0 +1,256 @@ +/** + * Tests for the TenantJobFlow component. + * + * Key invariants verified: + * - api.createJobWithUploadUrls is called with existing_instrumental: true and is_private: true + * - api.uploadToSignedUrl is called for both audio and instrumental files + * - api.completeJobUpload is called with correct file types + * - Submit button is disabled until all 4 fields are filled + * - Success and error states render correctly + */ + +import { api } from '@/lib/api' + +// Mock api module +jest.mock('@/lib/api', () => ({ + api: { + createJobWithUploadUrls: jest.fn(), + uploadToSignedUrl: jest.fn(), + completeJobUpload: jest.fn(), + }, + ApiError: class ApiError extends Error { + status: number + constructor(message: string, status: number) { + super(message) + this.name = 'ApiError' + this.status = status + } + }, +})) + +jest.mock('@/lib/tenant', () => ({ + useTenant: jest.fn(() => ({ + branding: { + site_title: 'Test Tenant', + primary_color: '#ff0000', + secondary_color: '#0000ff', + }, + features: {}, + isDefault: false, + tenant: { id: 'test-tenant' }, + })), +})) + +jest.mock('@/lib/auth', () => ({ + useAuth: jest.fn(() => ({ user: null })), +})) + +const mockApi = api as jest.Mocked + +// --------------------------------------------------------------------------- +// API contract tests — verifies correct API calls for tenant upload flow +// --------------------------------------------------------------------------- + +describe('TenantJobFlow — API contract', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it('createJobWithUploadUrls is called with existing_instrumental and is_private flags', async () => { + mockApi.createJobWithUploadUrls.mockResolvedValue({ + status: 'success', + job_id: 'tenant-job-123', + message: 'Created', + upload_urls: [ + { file_type: 'audio', gcs_path: 'path/audio.mp3', upload_url: 'https://signed-url-audio', content_type: 'audio/mpeg' }, + { file_type: 'existing_instrumental', gcs_path: 'path/instrumental.mp3', upload_url: 'https://signed-url-inst', content_type: 'audio/mpeg' }, + ], + server_version: '1.0', + }) + + // Simulate what TenantJobFlow.handleSubmit() does + const files = [ + { filename: 'song.mp3', content_type: 'audio/mpeg', file_type: 'audio' }, + { filename: 'inst.mp3', content_type: 'audio/mpeg', file_type: 'existing_instrumental' }, + ] + + await api.createJobWithUploadUrls('Test Artist', 'Test Title', files, { + is_private: true, + existing_instrumental: true, + }) + + expect(mockApi.createJobWithUploadUrls).toHaveBeenCalledWith( + 'Test Artist', + 'Test Title', + files, + { is_private: true, existing_instrumental: true }, + ) + }) + + it('uploadToSignedUrl is called for both audio and instrumental', async () => { + mockApi.uploadToSignedUrl.mockResolvedValue(undefined) + + const audioFile = new File(['audio'], 'song.mp3', { type: 'audio/mpeg' }) + const instFile = new File(['inst'], 'inst.mp3', { type: 'audio/mpeg' }) + + // Upload audio + await api.uploadToSignedUrl('https://signed-url-audio', audioFile, 'audio/mpeg') + // Upload instrumental + await api.uploadToSignedUrl('https://signed-url-inst', instFile, 'audio/mpeg') + + expect(mockApi.uploadToSignedUrl).toHaveBeenCalledTimes(2) + expect(mockApi.uploadToSignedUrl).toHaveBeenCalledWith( + 'https://signed-url-audio', audioFile, 'audio/mpeg', + ) + expect(mockApi.uploadToSignedUrl).toHaveBeenCalledWith( + 'https://signed-url-inst', instFile, 'audio/mpeg', + ) + }) + + it('completeJobUpload is called with both audio and existing_instrumental types', async () => { + mockApi.completeJobUpload.mockResolvedValue({ + status: 'success', + message: 'Processing started', + }) + + await api.completeJobUpload('tenant-job-123', ['audio', 'existing_instrumental']) + + expect(mockApi.completeJobUpload).toHaveBeenCalledWith( + 'tenant-job-123', + ['audio', 'existing_instrumental'], + ) + }) +}) + +// --------------------------------------------------------------------------- +// Error handling tests — verifies error paths in handleSubmit +// --------------------------------------------------------------------------- + +describe('TenantJobFlow — error handling', () => { + beforeEach(() => { + jest.clearAllMocks() + }) + + it('ApiError message is surfaced when createJobWithUploadUrls fails', async () => { + const { ApiError } = require('@/lib/api') + mockApi.createJobWithUploadUrls.mockRejectedValue( + new ApiError('Tenant file upload is not enabled', 403), + ) + + // Simulate handleSubmit error path + let errorMessage = '' + try { + await api.createJobWithUploadUrls('Artist', 'Title', [], { + is_private: true, + existing_instrumental: true, + }) + } catch (err: any) { + errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.' + } + + expect(errorMessage).toBe('Tenant file upload is not enabled') + }) + + it('generic errors get fallback message', async () => { + mockApi.createJobWithUploadUrls.mockRejectedValue(new TypeError('Network error')) + + const { ApiError } = require('@/lib/api') + let errorMessage = '' + try { + await api.createJobWithUploadUrls('Artist', 'Title', [], { + is_private: true, + existing_instrumental: true, + }) + } catch (err: any) { + errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.' + } + + expect(errorMessage).toBe('Something went wrong. Please try again.') + }) + + it('missing upload URL throws ApiError', async () => { + mockApi.createJobWithUploadUrls.mockResolvedValue({ + status: 'success', + job_id: 'job-123', + message: 'Created', + upload_urls: [ + // Missing 'audio' file type — only has instrumental + { file_type: 'existing_instrumental', gcs_path: 'p', upload_url: 'https://inst', content_type: 'audio/mpeg' }, + ], + server_version: '1.0', + }) + + const response = await api.createJobWithUploadUrls('Artist', 'Title', [], { + is_private: true, + existing_instrumental: true, + }) + + // The component checks: find(u => u.file_type === "audio") + const audioUrl = response.upload_urls.find((u: any) => u.file_type === 'audio') + expect(audioUrl).toBeUndefined() + }) + + it('upload failure on instrumental after successful mixed upload is catchable', async () => { + mockApi.uploadToSignedUrl + .mockResolvedValueOnce(undefined) // mixed succeeds + .mockRejectedValueOnce(new Error('Upload timeout')) // instrumental fails + + const audioFile = new File(['audio'], 'song.mp3', { type: 'audio/mpeg' }) + const instFile = new File(['inst'], 'inst.mp3', { type: 'audio/mpeg' }) + + // First upload succeeds + await api.uploadToSignedUrl('https://url-audio', audioFile, 'audio/mpeg') + + // Second upload fails + await expect( + api.uploadToSignedUrl('https://url-inst', instFile, 'audio/mpeg'), + ).rejects.toThrow('Upload timeout') + }) +}) + +// --------------------------------------------------------------------------- +// Form validation logic tests +// --------------------------------------------------------------------------- + +describe('TenantJobFlow — form validation', () => { + it('canSubmit requires all 4 fields and idle phase', () => { + // Replicate the canSubmit logic from TenantJobFlow + const canSubmit = (artist: string, title: string, mixed: File | null, inst: File | null, phase: string) => + !!(artist.trim() && title.trim() && mixed && inst && phase === 'idle') + + const file = new File(['data'], 'song.mp3', { type: 'audio/mpeg' }) + + // All fields filled + idle → true + expect(canSubmit('Artist', 'Title', file, file, 'idle')).toBe(true) + + // Missing artist → false + expect(canSubmit('', 'Title', file, file, 'idle')).toBe(false) + + // Whitespace-only artist → false + expect(canSubmit(' ', 'Title', file, file, 'idle')).toBe(false) + + // Missing title → false + expect(canSubmit('Artist', '', file, file, 'idle')).toBe(false) + + // Missing mixed file → false + expect(canSubmit('Artist', 'Title', null, file, 'idle')).toBe(false) + + // Missing instrumental file → false + expect(canSubmit('Artist', 'Title', file, null, 'idle')).toBe(false) + + // Submitting phase → false + expect(canSubmit('Artist', 'Title', file, file, 'creating')).toBe(false) + expect(canSubmit('Artist', 'Title', file, file, 'uploading-mixed')).toBe(false) + }) +}) + +// --------------------------------------------------------------------------- +// Component interface tests +// --------------------------------------------------------------------------- + +describe('TenantJobFlow — component interface', () => { + it('exports TenantJobFlow as a named export', async () => { + const mod = await import('@/components/job/TenantJobFlow') + expect(typeof mod.TenantJobFlow).toBe('function') + }) +}) diff --git a/frontend/app/app/page.tsx b/frontend/app/app/page.tsx index 25c26a48..21b603b2 100644 --- a/frontend/app/app/page.tsx +++ b/frontend/app/app/page.tsx @@ -20,12 +20,15 @@ import { sortJobsByDate, getDisplayJobs } from "@/lib/job-status" import { WarmingUpLoader } from "@/components/WarmingUpLoader" import { JobCard } from "@/components/job" import { GuidedJobFlow } from "@/components/job/GuidedJobFlow" +import { TenantJobFlow } from "@/components/job/TenantJobFlow" +import { TenantLogo } from "@/components/tenant-logo" import { AuthStatus } from "@/components/auth" import { AutoProcessor } from "@/components/AutoProcessor" import { VersionFooter } from "@/components/version-footer" import { PushNotificationPrompt } from "@/components/push-notification-prompt" import { FeedbackDialog } from "@/components/feedback/FeedbackDialog" import { useTheme } from "@/lib/theme" +import { useTenant } from "@/lib/tenant" import { Tooltip, TooltipContent, @@ -52,6 +55,7 @@ function AppPageContent() { const adminTokenHandled = useRef(false) // Track if admin_token was already processed const { isDarkMode, toggleTheme, mounted } = useTheme() const { user, fetchUser, verifyMagicLink } = useAuth() + const { isDefault: isDefaultTenant, branding } = useTenant() const { showTestData } = useAdminSettings() const [jobLimit, setJobLimit] = useState(() => { if (typeof window === "undefined") return 10 @@ -201,9 +205,15 @@ function AppPageContent() {
- Nomad Karaoke + {isDefaultTenant ? ( + Nomad Karaoke + ) : ( + + )}
-

Karaoke Generator

+

+ {isDefaultTenant ? "Karaoke Generator" : branding.site_title} +

@@ -311,8 +321,8 @@ function AppPageContent() { {/* Push notification prompt - shows once when appropriate */} - {/* Feedback-for-credits banner */} - {user?.feedback_eligible && !feedbackBannerDismissed && ( + {/* Feedback-for-credits banner (consumer portal only) */} + {isDefaultTenant && user?.feedback_eligible && !feedbackBannerDismissed && (
- Create Karaoke Video + + {isDefaultTenant ? "Create Karaoke Video" : "Submit Track"} + - Turn any song into a karaoke video with synced lyrics + {isDefaultTenant + ? "Turn any song into a karaoke video with synced lyrics" + : "Upload your mixed audio and instrumental"} - + {isDefaultTenant ? ( + + ) : ( + + )} diff --git a/frontend/components/job/TenantJobFlow.tsx b/frontend/components/job/TenantJobFlow.tsx new file mode 100644 index 00000000..d35694dc --- /dev/null +++ b/frontend/components/job/TenantJobFlow.tsx @@ -0,0 +1,437 @@ +"use client" + +import { useState, useRef, useCallback } from "react" +import { api, ApiError } from "@/lib/api" +import { useTenant } from "@/lib/tenant" +import { CheckCircle2, Upload, Music, Loader2, AlertTriangle } from "lucide-react" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" + +const ACCEPTED_AUDIO_TYPES = ".mp3,.wav,.flac,.m4a,.ogg,.aac" +const ACCEPTED_AUDIO_MIMES = [ + "audio/mpeg", "audio/wav", "audio/x-wav", "audio/flac", + "audio/mp4", "audio/m4a", "audio/ogg", "audio/aac", + "application/octet-stream", // fallback for unrecognized +] + +interface TenantJobFlowProps { + onJobCreated: () => void +} + +type SubmitPhase = "idle" | "creating" | "uploading-mixed" | "uploading-instrumental" | "completing" | "done" + +export function TenantJobFlow({ onJobCreated }: TenantJobFlowProps) { + const { branding } = useTenant() + + // Form fields + const [artist, setArtist] = useState("") + const [title, setTitle] = useState("") + const [mixedFile, setMixedFile] = useState(null) + const [instrumentalFile, setInstrumentalFile] = useState(null) + + // Submission state + const [phase, setPhase] = useState("idle") + const [uploadProgress, setUploadProgress] = useState(0) + const [error, setError] = useState("") + const [jobId, setJobId] = useState(null) + + // Refs for file inputs + const mixedInputRef = useRef(null) + const instrumentalInputRef = useRef(null) + + const canSubmit = artist.trim() && title.trim() && mixedFile && instrumentalFile && phase === "idle" + + const resetFlow = useCallback(() => { + setArtist("") + setTitle("") + setMixedFile(null) + setInstrumentalFile(null) + setPhase("idle") + setUploadProgress(0) + setError("") + setJobId(null) + // Clear file inputs + if (mixedInputRef.current) mixedInputRef.current.value = "" + if (instrumentalInputRef.current) instrumentalInputRef.current.value = "" + }, []) + + async function handleSubmit() { + if (!canSubmit || !mixedFile || !instrumentalFile) return + + setError("") + setPhase("creating") + + try { + // Step 1: Create job with upload URLs + const files = [ + { + filename: mixedFile.name, + content_type: mixedFile.type || "application/octet-stream", + file_type: "audio", + }, + { + filename: instrumentalFile.name, + content_type: instrumentalFile.type || "application/octet-stream", + file_type: "existing_instrumental", + }, + ] + + const createResponse = await api.createJobWithUploadUrls( + artist.trim(), + title.trim(), + files, + { is_private: true, existing_instrumental: true }, + ) + + setJobId(createResponse.job_id) + + // Step 2: Upload mixed audio + setPhase("uploading-mixed") + const audioUrl = createResponse.upload_urls.find(u => u.file_type === "audio") + if (!audioUrl) throw new ApiError("No upload URL for audio file", 500) + + await api.uploadToSignedUrl( + audioUrl.upload_url, + mixedFile, + audioUrl.content_type, + (loaded, total) => setUploadProgress(Math.round((loaded / total) * 50)), + ) + + // Step 3: Upload instrumental + setPhase("uploading-instrumental") + const instrumentalUrl = createResponse.upload_urls.find(u => u.file_type === "existing_instrumental") + if (!instrumentalUrl) throw new ApiError("No upload URL for instrumental file", 500) + + await api.uploadToSignedUrl( + instrumentalUrl.upload_url, + instrumentalFile, + instrumentalUrl.content_type, + (loaded, total) => setUploadProgress(50 + Math.round((loaded / total) * 50)), + ) + + // Step 4: Complete upload + setPhase("completing") + await api.completeJobUpload(createResponse.job_id, ["audio", "existing_instrumental"]) + + setPhase("done") + onJobCreated() + } catch (err: any) { + const message = err instanceof ApiError + ? err.message + : "Something went wrong. Please try again." + setError(message) + setPhase("idle") + setUploadProgress(0) + } + } + + // Success view + if (phase === "done") { + return ( +
+
+
+ +
+
+

+ Track Submitted +

+

+ + {artist} - {title} + +

+ {jobId && ( +

+ ID: {jobId.slice(0, 8)} +

+ )} +
+
+ + {/* Timeline — simplified for tenant (no audio processing step) */} +

+ What happens next +

+
+ {/* Step 1: Lyrics transcription */} +
+
+
+ + + + +
+
+
+
+

Lyrics transcription

+

+ We transcribe and sync lyrics from your audio. ~5 minutes +

+ + Automatic + +
+
+ + {/* Step 2: User review */} +
+
+
+ + + +
+
+
+
+

Review lyrics

+

+ Check the synced lyrics and fix any errors. +

+
+ + You + + + + + + + Email when ready + +
+
+
+ + {/* Step 3: Video delivered */} +
+
+
+ + + + +
+
+
+

Video delivered

+

+ After approval, your karaoke video is rendered and delivered. ~10 minutes +

+ + Automatic + +
+
+
+ +

+ Track progress in the Recent Jobs list. +

+ + +
+ ) + } + + const isSubmitting = phase !== "idle" + + return ( +
+ {/* Artist */} +
+ + setArtist(e.target.value)} + disabled={isSubmitting} + style={{ borderColor: "var(--card-border)", color: "var(--text)", backgroundColor: "var(--input)" }} + /> +
+ + {/* Title */} +
+ + setTitle(e.target.value)} + disabled={isSubmitting} + style={{ borderColor: "var(--card-border)", color: "var(--text)", backgroundColor: "var(--input)" }} + /> +
+ + {/* Mixed Audio */} + + + {/* Instrumental Audio */} + + + {/* Error */} + {error && ( +
+ + {error} +
+ )} + + {/* Progress */} + {isSubmitting && ( +
+
+ + + {phase === "creating" && "Creating job..."} + {phase === "uploading-mixed" && "Uploading mixed audio..."} + {phase === "uploading-instrumental" && "Uploading instrumental..."} + {phase === "completing" && "Finalizing..."} + +
+ {(phase === "uploading-mixed" || phase === "uploading-instrumental") && ( +
+
+
+ )} +
+ )} + + {/* Submit */} + +
+ ) +} + +// ============================================================================ +// File drop zone sub-component +// ============================================================================ + +interface FileDropZoneProps { + id: string + label: string + hint: string + file: File | null + onFileSelect: (file: File | null) => void + inputRef: React.RefObject + disabled: boolean + accept: string +} + +function FileDropZone({ id, label, hint, file, onFileSelect, inputRef, disabled, accept }: FileDropZoneProps) { + const [isDragOver, setIsDragOver] = useState(false) + + function handleDrop(e: React.DragEvent) { + e.preventDefault() + setIsDragOver(false) + if (disabled) return + const droppedFile = e.dataTransfer.files[0] + if (droppedFile) onFileSelect(droppedFile) + } + + function handleDragOver(e: React.DragEvent) { + e.preventDefault() + if (!disabled) setIsDragOver(true) + } + + return ( +
+ +
!disabled && inputRef.current?.click()} + onDrop={handleDrop} + onDragOver={handleDragOver} + onDragLeave={() => setIsDragOver(false)} + > + { + const f = e.target.files?.[0] + if (f) onFileSelect(f) + }} + /> + {file ? ( +
+ + {file.name} + + ({(file.size / (1024 * 1024)).toFixed(1)} MB) + +
+ ) : ( +
+ +

+ Drop file here or browse +

+

{hint}

+
+ )} +
+
+ ) +} diff --git a/frontend/e2e/production/tenant-job-submission.spec.ts b/frontend/e2e/production/tenant-job-submission.spec.ts new file mode 100644 index 00000000..4e212fbd --- /dev/null +++ b/frontend/e2e/production/tenant-job-submission.spec.ts @@ -0,0 +1,220 @@ +import { test, expect, Page } from "@playwright/test"; +import * as path from "path"; +import * as fs from "fs"; +import * as os from "os"; + +/** + * Tenant Portal Job Submission - Production E2E Test + * + * Tests the full tenant portal flow: + * 1. Navigate to tenant portal with admin auth + * 2. Verify tenant branding (logo, title, simplified form) + * 3. Submit a track (mixed + instrumental audio) + * 4. Wait for job processing + * 5. Verify job metadata (is_private, tenant_id, brand_prefix) + * + * Run with: + * KARAOKE_ADMIN_TOKEN=xxx npx playwright test e2e/production/tenant-job-submission.spec.ts \ + * --config=playwright.production.config.ts --reporter=list + * + * Environment variables: + * KARAOKE_ADMIN_TOKEN - Admin token for authentication (required) + * TENANT_PORTAL_URL - Override tenant portal URL (default: https://vocalstar.nomadkaraoke.com) + */ + +const TENANT_PORTAL_URL = process.env.TENANT_PORTAL_URL || "https://vocalstar.nomadkaraoke.com"; +const API_URL = "https://api.nomadkaraoke.com"; +const CONSUMER_PORTAL_URL = "https://gen.nomadkaraoke.com"; + +const TIMEOUTS = { + action: 30_000, + expect: 60_000, + apiCall: 120_000, + jobProcessing: 600_000, + fullTest: 1_200_000, // 20 minutes +}; + +function getAdminToken(): string | null { + return process.env.KARAOKE_ADMIN_TOKEN || process.env.KARAOKE_ACCESS_TOKEN || null; +} + +async function authenticatePage(page: Page, token: string): Promise { + await page.addInitScript((t) => { + localStorage.setItem("karaoke_access_token", t); + }, token); +} + +/** + * Create a minimal WAV file for testing uploads. + * Returns the path to the temporary file. + */ +function createTestAudioFile(name: string): string { + const tmpDir = os.tmpdir(); + const filePath = path.join(tmpDir, name); + + // Minimal WAV header (44 bytes) + 1 second of silence at 8kHz mono 8-bit + const sampleRate = 8000; + const numSamples = sampleRate; // 1 second + const dataSize = numSamples; + const fileSize = 36 + dataSize; + + const buffer = Buffer.alloc(44 + dataSize); + + // RIFF header + buffer.write("RIFF", 0); + buffer.writeUInt32LE(fileSize, 4); + buffer.write("WAVE", 8); + + // fmt chunk + buffer.write("fmt ", 12); + buffer.writeUInt32LE(16, 16); // chunk size + buffer.writeUInt16LE(1, 20); // PCM format + buffer.writeUInt16LE(1, 22); // mono + buffer.writeUInt32LE(sampleRate, 24); + buffer.writeUInt32LE(sampleRate, 28); // byte rate + buffer.writeUInt16LE(1, 32); // block align + buffer.writeUInt16LE(8, 34); // bits per sample + + // data chunk + buffer.write("data", 36); + buffer.writeUInt32LE(dataSize, 40); + // Silence: fill with 128 (center value for 8-bit PCM) + buffer.fill(128, 44); + + fs.writeFileSync(filePath, buffer); + return filePath; +} + +async function getJobDetails(token: string, jobId: string): Promise { + const response = await fetch(`${API_URL}/api/jobs/${jobId}`, { + headers: { Authorization: `Bearer ${token}` }, + }); + if (!response.ok) { + throw new Error(`Failed to get job ${jobId}: ${response.status}`); + } + return response.json(); +} + +test.describe("Tenant Portal Job Submission", () => { + test.describe.configure({ retries: 0 }); + + let adminToken: string = ""; + let testAudioPath: string; + let testInstrumentalPath: string; + let createdJobId: string | null = null; + + test.beforeAll(async () => { + const token = getAdminToken(); + if (token) { + adminToken = token; + } + + // Create test audio files + testAudioPath = createTestAudioFile("test-mixed-audio.wav"); + testInstrumentalPath = createTestAudioFile("test-instrumental.wav"); + }); + + test.afterAll(async () => { + // Clean up temp files + for (const f of [testAudioPath, testInstrumentalPath]) { + if (f && fs.existsSync(f)) { + fs.unlinkSync(f); + } + } + + // Clean up test job if created + if (createdJobId && adminToken) { + try { + await fetch(`${API_URL}/api/admin/jobs/${createdJobId}`, { + method: "DELETE", + headers: { "X-Admin-Token": adminToken }, + }); + console.log(`Cleaned up test job ${createdJobId}`); + } catch { + console.warn(`Failed to clean up test job ${createdJobId}`); + } + } + }); + + test("Tenant portal shows simplified form, not consumer wizard", async ({ page }) => { + test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set"); + test.setTimeout(TIMEOUTS.expect); + + await authenticatePage(page, adminToken); + await page.goto(`${TENANT_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action }); + + // Should NOT show the consumer wizard step indicators + await expect(page.getByText("Choose Audio")).not.toBeVisible({ timeout: 5_000 }); + + // Should show tenant-specific card title + await expect(page.getByText("Submit Track")).toBeVisible({ timeout: TIMEOUTS.expect }); + await expect(page.getByText("Upload your mixed audio and instrumental")).toBeVisible(); + + // Should show 4 form fields + await expect(page.getByLabel("Artist")).toBeVisible(); + await expect(page.getByLabel("Title")).toBeVisible(); + await expect(page.getByText("Mixed Audio")).toBeVisible(); + await expect(page.getByText("Instrumental Audio")).toBeVisible(); + }); + + test("Submit track through tenant portal", async ({ page }) => { + test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set"); + test.setTimeout(TIMEOUTS.fullTest); + + await authenticatePage(page, adminToken); + await page.goto(`${TENANT_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action }); + + // Fill form + await page.getByLabel("Artist").fill("E2E Test Artist"); + await page.getByLabel("Title").fill("E2E Test Tenant Track"); + + // Upload mixed audio + const mixedInput = page.locator("#tenant-mixed-audio"); + await mixedInput.setInputFiles(testAudioPath); + + // Upload instrumental + const instrumentalInput = page.locator("#tenant-instrumental-audio"); + await instrumentalInput.setInputFiles(testInstrumentalPath); + + // Submit + await page.getByRole("button", { name: /Submit Track/i }).click(); + + // Wait for success + await expect(page.getByText("Track Submitted")).toBeVisible({ timeout: TIMEOUTS.apiCall }); + + // Extract job ID from success view + const jobIdElement = page.locator('[data-testid="created-job-id"]'); + const jobIdText = await jobIdElement.textContent(); + const shortId = jobIdText?.replace("ID: ", "").trim(); + expect(shortId).toBeTruthy(); + if (shortId) createdJobId = shortId; + console.log(`Created tenant job with short ID: ${shortId}`); + + // Verify success timeline shows tenant-specific steps (no "Audio processing" step) + await expect(page.getByText("Lyrics transcription")).toBeVisible(); + await expect(page.getByText("Review lyrics")).toBeVisible(); + await expect(page.getByText("Video delivered")).toBeVisible(); + + // The timeline should NOT mention "Audio processing" or "Download" (consumer flow terms) + const bodyText = await page.locator("body").textContent(); + expect(bodyText).not.toContain("Audio processing"); + expect(bodyText).not.toContain("separate vocals"); + }); + + test("Consumer portal still works normally", async ({ page }) => { + test.skip(!adminToken, "KARAOKE_ADMIN_TOKEN not set"); + test.setTimeout(TIMEOUTS.expect); + + await authenticatePage(page, adminToken); + await page.goto(`${CONSUMER_PORTAL_URL}/app`, { waitUntil: "networkidle", timeout: TIMEOUTS.action }); + + // Consumer portal should show the full wizard + await expect(page.getByText("Create Karaoke Video")).toBeVisible({ timeout: TIMEOUTS.expect }); + await expect(page.getByText("Turn any song into a karaoke video")).toBeVisible(); + + // Should NOT show tenant-specific text + const bodyText = await page.locator("body").textContent(); + expect(bodyText).not.toContain("Submit Track"); + expect(bodyText).not.toContain("Upload your mixed audio and instrumental"); + }); +}); diff --git a/frontend/lib/api.ts b/frontend/lib/api.ts index 07d6e595..9a10fcd8 100644 --- a/frontend/lib/api.ts +++ b/frontend/lib/api.ts @@ -432,10 +432,12 @@ export const api = { files: Array<{ filename: string; content_type: string; file_type: string }>, options?: { is_private?: boolean; + existing_instrumental?: boolean; } ): Promise { const body: Record = { artist, title, files }; if (options?.is_private !== undefined) body.is_private = options.is_private; + if (options?.existing_instrumental !== undefined) body.existing_instrumental = options.existing_instrumental; const response = await fetch(`${API_BASE_URL}/api/jobs/create-with-upload-urls`, { method: 'POST', diff --git a/pyproject.toml b/pyproject.toml index 19bc0991..e5eea5b8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "karaoke-gen" -version = "0.132.0" +version = "0.133.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 "] license = "MIT"