feat: streamlined tenant portal with 4-field upload form (#481)

@coderabbitai ignore

## Summary

- Replace the multi-step consumer wizard with a streamlined 4-field form
(Artist, Title, Mixed Audio, Instrumental Audio) for B2B tenant portals
- All tenant jobs automatically private with tenant-specific
Dropbox/GDrive delivery, locked theme, and brand prefix
- Backend: `_apply_tenant_overrides()` helper forces private, applies
locked theme, overlays tenant distribution settings; private tenant jobs
use their own paths instead of NonPublished override
- Frontend: New `TenantJobFlow` component with drag-and-drop file
uploads; conditional rendering based on tenant detection

## Test plan

- [x] 10 backend unit tests (tenant override logic, distribution
routing, partial config edge cases)
- [x] 9 frontend unit tests (API contract, error handling, form
validation)
- [x] 3 E2E production tests (simplified form verification, track
submission, consumer portal isolation)
- [x] All existing tests pass (2307 backend + 520 frontend Jest + 181
Playwright regression)
- [ ] Run production E2E test after deploy: `KARAOKE_ADMIN_TOKEN=xxx npx
playwright test e2e/production/tenant-job-submission.spec.ts
--config=playwright.production.config.ts`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Andrew Beveridge ☄️andClaude Opus 4.6 authored and GitHub committed 2026-03-04 21:04:36 -05:00
1 parent f017ba7d77
commit ca9f3bd5ba
14 files changed
+1456 -23

No files matched your search

+75 -13
View File
@@ -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,
)
+6
View File
@@ -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"
)
+11
View File
@@ -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,
+1
View File
@@ -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,
+259
View File
@@ -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"
+3 -2
View File
@@ -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`)
+2
View File
@@ -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=<id>`. See [ARCHITECTURE.md](ARCHITECTURE.md#tenant-portal-frontend-b2b-deployment).
@@ -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 `<img src="/nomad-karaoke-logo.svg">` (line 196) with `<TenantLogo size="sm" />`
- Tenant-aware title using `branding.site_title`
- Conditional: `<TenantJobFlow>` when `!isDefault`, else `<GuidedJobFlow>`
- 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": "<user-to-provide>",
"gdrive_folder_id": "<user-to-provide>"
},
"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
+256
View File
@@ -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<typeof api>
// ---------------------------------------------------------------------------
// 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')
})
})
+25 -7
View File
@@ -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<number>(() => {
if (typeof window === "undefined") return 10
@@ -201,9 +205,15 @@ function AppPageContent() {
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
<div className="px-3 sm:px-4 py-2 sm:py-3 flex items-center justify-between gap-2">
<div className="flex items-center gap-2 sm:gap-3 min-w-0">
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
{isDefaultTenant ? (
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 sm:h-10 shrink-0" />
) : (
<TenantLogo size="sm" />
)}
<div className="min-w-0">
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>Karaoke Generator</h1>
<h1 className="text-base sm:text-xl font-bold truncate" style={{ color: 'var(--text)' }}>
{isDefaultTenant ? "Karaoke Generator" : branding.site_title}
</h1>
</div>
</div>
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
@@ -311,8 +321,8 @@ function AppPageContent() {
{/* Push notification prompt - shows once when appropriate */}
<PushNotificationPrompt />
{/* Feedback-for-credits banner */}
{user?.feedback_eligible && !feedbackBannerDismissed && (
{/* Feedback-for-credits banner (consumer portal only) */}
{isDefaultTenant && user?.feedback_eligible && !feedbackBannerDismissed && (
<div className="flex items-center justify-between gap-3 rounded-lg border px-4 py-3"
style={{
borderColor: 'var(--accent)',
@@ -352,13 +362,21 @@ function AppPageContent() {
{/* Submit Job Card */}
<Card className="backdrop-blur min-w-0" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--card)' }}>
<CardHeader>
<CardTitle style={{ color: 'var(--text)' }}>Create Karaoke Video</CardTitle>
<CardTitle style={{ color: 'var(--text)' }}>
{isDefaultTenant ? "Create Karaoke Video" : "Submit Track"}
</CardTitle>
<CardDescription style={{ color: 'var(--text-muted)' }}>
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"}
</CardDescription>
</CardHeader>
<CardContent>
<GuidedJobFlow onJobCreated={loadJobs} />
{isDefaultTenant ? (
<GuidedJobFlow onJobCreated={loadJobs} />
) : (
<TenantJobFlow onJobCreated={loadJobs} />
)}
</CardContent>
</Card>
+437
View File
@@ -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<File | null>(null)
const [instrumentalFile, setInstrumentalFile] = useState<File | null>(null)
// Submission state
const [phase, setPhase] = useState<SubmitPhase>("idle")
const [uploadProgress, setUploadProgress] = useState(0)
const [error, setError] = useState("")
const [jobId, setJobId] = useState<string | null>(null)
// Refs for file inputs
const mixedInputRef = useRef<HTMLInputElement>(null)
const instrumentalInputRef = useRef<HTMLInputElement>(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 (
<div className="space-y-5">
<div className="flex flex-col items-center text-center py-5 space-y-3">
<div
className="w-12 h-12 rounded-full flex items-center justify-center"
style={{ backgroundColor: "rgba(34, 197, 94, 0.15)" }}
>
<CheckCircle2 className="w-7 h-7 text-green-500" />
</div>
<div>
<h2 className="text-lg font-semibold" style={{ color: "var(--text)" }}>
Track Submitted
</h2>
<p className="text-sm mt-1" style={{ color: "var(--text-muted)" }}>
<span className="font-medium" style={{ color: "var(--text)" }}>
{artist} - {title}
</span>
</p>
{jobId && (
<p className="text-xs mt-0.5 font-mono" style={{ color: "var(--text-muted)" }} data-testid="created-job-id">
ID: {jobId.slice(0, 8)}
</p>
)}
</div>
</div>
{/* Timeline — simplified for tenant (no audio processing step) */}
<p className="text-xs font-semibold uppercase tracking-wider" style={{ color: "var(--text-muted)" }}>
What happens next
</p>
<div className="space-y-0 mt-3">
{/* Step 1: Lyrics transcription */}
<div className="flex gap-3">
<div className="flex flex-col items-center">
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-blue-500/15">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-blue-400">
<path d="M8 1.5a1.25 1.25 0 0 1 1.177.825l.573 1.608 1.608.573a1.25 1.25 0 0 1 0 2.354l-1.608.573-.573 1.608a1.25 1.25 0 0 1-2.354 0l-.573-1.608-1.608-.573a1.25 1.25 0 0 1 0-2.354l1.608-.573.573-1.608A1.25 1.25 0 0 1 8 1.5Z" fill="currentColor" opacity="0.85"/>
<path d="M12 9a1 1 0 0 1 .94.66l.36 1.02 1.02.36a1 1 0 0 1 0 1.884l-1.02.36-.36 1.02a1 1 0 0 1-1.88 0l-.36-1.02-1.02-.36a1 1 0 0 1 0-1.884l1.02-.36.36-1.02A1 1 0 0 1 12 9Z" fill="currentColor" opacity="0.55"/>
</svg>
</div>
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: "var(--card-border)" }} />
</div>
<div className="pb-4 pt-1">
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Lyrics transcription</p>
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
We transcribe and sync lyrics from your audio. <span className="font-medium" style={{ color: "var(--text)" }}>~5 minutes</span>
</p>
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-blue-500/15 text-blue-400">
Automatic
</span>
</div>
</div>
{/* Step 2: User review */}
<div className="flex gap-3">
<div className="flex flex-col items-center">
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: "rgba(255, 122, 204, 0.15)" }}>
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" style={{ color: "var(--brand-pink)" }}>
<path d="M8 2a3 3 0 1 0 0 6 3 3 0 0 0 0-6ZM3.5 13.5c0-2.485 2.015-4.5 4.5-4.5s4.5 2.015 4.5 4.5a.5.5 0 0 1-.5.5h-8a.5.5 0 0 1-.5-.5Z" fill="currentColor" opacity="0.85"/>
</svg>
</div>
<div className="w-px flex-1 min-h-[20px]" style={{ backgroundColor: "var(--card-border)" }} />
</div>
<div className="pb-4 pt-1">
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Review lyrics</p>
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
Check the synced lyrics and fix any errors.
</p>
<div className="flex items-center gap-2 mt-1.5 flex-wrap">
<span className="inline-block text-[10px] px-1.5 py-0.5 rounded-full font-medium" style={{ backgroundColor: "rgba(255, 122, 204, 0.15)", color: "var(--brand-pink)" }}>
You
</span>
<span className="flex items-center gap-1 text-[10px]" style={{ color: "var(--text-muted)" }}>
<svg width="12" height="12" viewBox="0 0 16 16" fill="none">
<path d="M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v.401a1 1 0 0 1-.373.78L8.707 8.79a1 1 0 0 1-1.414 0L2.373 4.68A1 1 0 0 1 2 3.9V3.5Z" fill="currentColor" opacity="0.7"/>
<path d="M2 6.12l4.586 3.59a2 2 0 0 0 2.828 0L14 6.12V12.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5V6.12Z" fill="currentColor" opacity="0.5"/>
</svg>
Email when ready
</span>
</div>
</div>
</div>
{/* Step 3: Video delivered */}
<div className="flex gap-3">
<div className="flex flex-col items-center">
<div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0 bg-green-500/15">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" className="text-green-400">
<path d="M3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v11a.5.5 0 0 1-.765.424L8 11.28l-4.235 2.644A.5.5 0 0 1 3 13.5v-11Z" fill="currentColor" opacity="0.5"/>
<path d="M6.354 7.854 7.5 9l2.146-2.146a.5.5 0 0 0-.708-.708L7.5 7.586l-.646-.647a.5.5 0 1 0-.708.708l.208.207Z" fill="currentColor"/>
</svg>
</div>
</div>
<div className="pt-1">
<p className="text-sm font-medium" style={{ color: "var(--text)" }}>Video delivered</p>
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>
After approval, your karaoke video is rendered and delivered. <span className="font-medium" style={{ color: "var(--text)" }}>~10 minutes</span>
</p>
<span className="inline-block mt-1.5 text-[10px] px-1.5 py-0.5 rounded-full font-medium bg-green-500/15 text-green-400">
Automatic
</span>
</div>
</div>
</div>
<p className="text-[10px] text-center" style={{ color: "var(--text-muted)" }}>
Track progress in the <span className="font-medium" style={{ color: "var(--text)" }}>Recent Jobs</span> list.
</p>
<Button
onClick={resetFlow}
variant="outline"
className="w-full"
style={{ borderColor: "var(--card-border)", color: "var(--text)" }}
>
<Music className="w-4 h-4 mr-2" />
Submit Another Track
</Button>
</div>
)
}
const isSubmitting = phase !== "idle"
return (
<div className="space-y-4">
{/* Artist */}
<div className="space-y-1.5">
<Label htmlFor="tenant-artist" style={{ color: "var(--text)" }}>Artist</Label>
<Input
id="tenant-artist"
placeholder="e.g. Adele"
value={artist}
onChange={e => setArtist(e.target.value)}
disabled={isSubmitting}
style={{ borderColor: "var(--card-border)", color: "var(--text)", backgroundColor: "var(--input)" }}
/>
</div>
{/* Title */}
<div className="space-y-1.5">
<Label htmlFor="tenant-title" style={{ color: "var(--text)" }}>Title</Label>
<Input
id="tenant-title"
placeholder="e.g. Someone Like You"
value={title}
onChange={e => setTitle(e.target.value)}
disabled={isSubmitting}
style={{ borderColor: "var(--card-border)", color: "var(--text)", backgroundColor: "var(--input)" }}
/>
</div>
{/* Mixed Audio */}
<FileDropZone
id="tenant-mixed-audio"
label="Mixed Audio"
hint="The full song with vocals"
file={mixedFile}
onFileSelect={setMixedFile}
inputRef={mixedInputRef}
disabled={isSubmitting}
accept={ACCEPTED_AUDIO_TYPES}
/>
{/* Instrumental Audio */}
<FileDropZone
id="tenant-instrumental-audio"
label="Instrumental Audio"
hint="The instrumental (backing track)"
file={instrumentalFile}
onFileSelect={setInstrumentalFile}
inputRef={instrumentalInputRef}
disabled={isSubmitting}
accept={ACCEPTED_AUDIO_TYPES}
/>
{/* Error */}
{error && (
<div className="flex items-start gap-2 text-sm p-3 rounded-lg" style={{ backgroundColor: "rgba(239, 68, 68, 0.1)", color: "#ef4444" }}>
<AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
<span>{error}</span>
</div>
)}
{/* Progress */}
{isSubmitting && (
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm" style={{ color: "var(--text-muted)" }}>
<Loader2 className="w-4 h-4 animate-spin" />
<span>
{phase === "creating" && "Creating job..."}
{phase === "uploading-mixed" && "Uploading mixed audio..."}
{phase === "uploading-instrumental" && "Uploading instrumental..."}
{phase === "completing" && "Finalizing..."}
</span>
</div>
{(phase === "uploading-mixed" || phase === "uploading-instrumental") && (
<div className="w-full h-1.5 rounded-full overflow-hidden" style={{ backgroundColor: "var(--card-border)" }}>
<div
className="h-full rounded-full transition-all duration-300"
style={{
width: `${uploadProgress}%`,
backgroundColor: "var(--tenant-primary, var(--brand-pink))",
}}
/>
</div>
)}
</div>
)}
{/* Submit */}
<Button
onClick={handleSubmit}
disabled={!canSubmit}
className="w-full"
style={{
backgroundColor: canSubmit ? "var(--tenant-primary, var(--brand-pink))" : undefined,
color: canSubmit ? "white" : undefined,
}}
>
<Upload className="w-4 h-4 mr-2" />
Submit Track
</Button>
</div>
)
}
// ============================================================================
// File drop zone sub-component
// ============================================================================
interface FileDropZoneProps {
id: string
label: string
hint: string
file: File | null
onFileSelect: (file: File | null) => void
inputRef: React.RefObject<HTMLInputElement | null>
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 (
<div className="space-y-1.5">
<Label htmlFor={id} style={{ color: "var(--text)" }}>{label}</Label>
<div
className={`relative border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors ${
disabled ? "opacity-50 cursor-not-allowed" : "hover:border-white/30"
}`}
style={{
borderColor: isDragOver ? "var(--tenant-primary, var(--brand-pink))" : "var(--card-border)",
backgroundColor: isDragOver ? "rgba(255, 255, 255, 0.03)" : "transparent",
}}
onClick={() => !disabled && inputRef.current?.click()}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragLeave={() => setIsDragOver(false)}
>
<input
ref={inputRef}
id={id}
type="file"
accept={accept}
className="hidden"
disabled={disabled}
onChange={e => {
const f = e.target.files?.[0]
if (f) onFileSelect(f)
}}
/>
{file ? (
<div className="flex items-center justify-center gap-2">
<Music className="w-4 h-4 shrink-0" style={{ color: "var(--tenant-primary, var(--brand-pink))" }} />
<span className="text-sm truncate" style={{ color: "var(--text)" }}>{file.name}</span>
<span className="text-xs shrink-0" style={{ color: "var(--text-muted)" }}>
({(file.size / (1024 * 1024)).toFixed(1)} MB)
</span>
</div>
) : (
<div>
<Upload className="w-5 h-5 mx-auto mb-1" style={{ color: "var(--text-muted)" }} />
<p className="text-sm" style={{ color: "var(--text-muted)" }}>
Drop file here or <span style={{ color: "var(--tenant-primary, var(--brand-pink))" }}>browse</span>
</p>
<p className="text-xs mt-0.5" style={{ color: "var(--text-muted)" }}>{hint}</p>
</div>
)}
</div>
</div>
)
}
@@ -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<void> {
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<any> {
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");
});
});
+2
View File
@@ -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<CreateJobWithUploadUrlsResponse> {
const body: Record<string, any> = { 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',
+1 -1
View File
@@ -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 <andrew@beveridge.uk>"]
license = "MIT"