mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 09:28:25 +09:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
517dac00c8 |
No files matched your search
@@ -1,37 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Auto-translate when English translation files change.
|
||||
# Uses GCS cache so this is near-instant for small changes.
|
||||
# Skip with: git commit --no-verify
|
||||
|
||||
set -e
|
||||
|
||||
STAGED_EN=$(git diff --cached --name-only --diff-filter=ACM | grep -E '(messages|translations)/en\.json$' || true)
|
||||
|
||||
if [ -z "$STAGED_EN" ]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "i18n: English translations changed — running translation pipeline..."
|
||||
|
||||
for en_file in $STAGED_EN; do
|
||||
dir=$(dirname "$en_file")
|
||||
|
||||
if [[ "$dir" == frontend/messages ]]; then
|
||||
script="frontend/scripts/translate.py"
|
||||
elif [[ "$dir" == backend/translations ]]; then
|
||||
script="frontend/scripts/translate.py"
|
||||
else
|
||||
echo " Warning: Unknown messages dir $dir, skipping"
|
||||
continue
|
||||
fi
|
||||
|
||||
echo " Translating $dir..."
|
||||
if python "$script" --messages-dir "$dir" --target all --skip-review 2>&1 | tail -5; then
|
||||
git add "$dir"/*.json
|
||||
echo " Done: $dir"
|
||||
else
|
||||
echo " Warning: Translation failed for $dir (GCP auth may be missing). CI will catch this."
|
||||
fi
|
||||
done
|
||||
|
||||
echo "i18n: Translation complete."
|
||||
@@ -90,26 +90,6 @@ jobs:
|
||||
working-directory: frontend
|
||||
run: npm run lint
|
||||
|
||||
translation-check:
|
||||
name: "Translation Validation"
|
||||
runs-on: ubuntu-latest
|
||||
needs: changes
|
||||
if: github.ref != 'refs/heads/main' && needs.changes.outputs.frontend == 'true'
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Validate frontend translations (key parity)
|
||||
run: |
|
||||
python frontend/scripts/validate-translations.py --messages-dir frontend/messages --keys-only || echo "::warning::Frontend translation validation failed — run translate.py to fix"
|
||||
|
||||
- name: Validate backend translations (key parity)
|
||||
run: python frontend/scripts/validate-translations.py --messages-dir backend/translations --keys-only
|
||||
|
||||
frontend-unit-tests:
|
||||
name: "Frontend - Unit Tests"
|
||||
runs-on: ubuntu-latest
|
||||
@@ -714,7 +694,7 @@ jobs:
|
||||
# frontend-lint IS required - catches React hooks violations that cause runtime crashes
|
||||
# frontend-e2e-happy-path is required ONLY when 'e2e-happy-path' label is present
|
||||
# frontend-e2e-full is optional (requires 'e2e' label) so not enforced here
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path, translation-check]
|
||||
needs: [frontend-lint, frontend-unit-tests, frontend-e2e-smoke, frontend-build, package-unit-tests, package-integration-tests, backend-unit-tests, backend-emulator-tests, backend-lint, frontend-e2e-happy-path]
|
||||
if: github.ref != 'refs/heads/main' && always()
|
||||
steps:
|
||||
- name: Check results
|
||||
@@ -738,14 +718,6 @@ jobs:
|
||||
fi
|
||||
done
|
||||
|
||||
# Translation check: warn but don't block (pre-existing placeholder issues)
|
||||
translation_result="${{ needs.translation-check.result }}"
|
||||
if [[ "$translation_result" == "failure" ]]; then
|
||||
echo "⚠️ Translation validation failed — run translate.py to fix"
|
||||
elif [[ "$translation_result" == "success" ]]; then
|
||||
echo "✅ Translation validation passed"
|
||||
fi
|
||||
|
||||
# E2E Happy Path: enforced when 'e2e-happy-path' label is on the PR
|
||||
e2e_result="${{ needs.frontend-e2e-happy-path.result }}"
|
||||
has_label="${{ contains(github.event.pull_request.labels.*.name, 'e2e-happy-path') }}"
|
||||
|
||||
@@ -1,337 +0,0 @@
|
||||
name: E2E Daily Test (Payment + Happy Path)
|
||||
|
||||
# Full production E2E: buy credits via real Stripe, then use them for karaoke generation.
|
||||
# Replaces the previous e2e-happy-path.yml with an additional payment stage.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 6 * * *'
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
debug_mode:
|
||||
description: 'Enable debug mode (slower, more screenshots)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
browser:
|
||||
description: 'Browser to test with'
|
||||
required: false
|
||||
default: 'chromium'
|
||||
type: choice
|
||||
options:
|
||||
- chromium
|
||||
- firefox
|
||||
- webkit
|
||||
skip_payment:
|
||||
description: 'Skip Stage 1 (payment) — use admin-granted credits for happy path only'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
use_test_token:
|
||||
description: 'Skip signup entirely — use E2E_TEST_TOKEN (for quick iterations)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# =========================================================================
|
||||
# Stage 1: Purchase credits via real Stripe Checkout
|
||||
# =========================================================================
|
||||
e2e-credit-purchase:
|
||||
name: "Stage 1: Credit Purchase"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
|
||||
|
||||
outputs:
|
||||
session_token: ${{ steps.extract_token.outputs.token }}
|
||||
result: ${{ steps.test_result.outputs.result }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps ${{ inputs.browser || 'chromium' }}
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Run Credit Purchase Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_STRIPE_CARD_NUMBER: ${{ secrets.E2E_STRIPE_CARD_NUMBER }}
|
||||
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
|
||||
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
|
||||
E2E_STRIPE_CARDHOLDER_NAME: ${{ secrets.E2E_STRIPE_CARDHOLDER_NAME }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
|
||||
echo "Time: $(date)"
|
||||
npx playwright test credit-purchase-real.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=${{ inputs.browser || 'chromium' }} \
|
||||
--reporter=list \
|
||||
--timeout=600000 \
|
||||
2>&1 | tee test-output-payment.log
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if grep -q "CREDIT PURCHASE TEST PASSED" test-output-payment.log; then
|
||||
echo "result=success" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "result=failure" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Extract session token
|
||||
id: extract_token
|
||||
if: steps.test_result.outputs.result == 'success'
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if [ -f test-results/e2e-session-token.txt ]; then
|
||||
TOKEN=$(cat test-results/e2e-session-token.txt)
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
echo "Session token extracted for Stage 2"
|
||||
else
|
||||
echo "No session token file found"
|
||||
echo "token=" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Upload artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-payment-results-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/test-output-payment.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase\", \"description\": \"Payment flow is broken. Customers may not be receiving credits.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
|
||||
# =========================================================================
|
||||
# Stage 2: Happy Path (uses credit from Stage 1)
|
||||
# =========================================================================
|
||||
e2e-happy-path:
|
||||
name: "Stage 2: Happy Path"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
needs: e2e-credit-purchase
|
||||
if: |
|
||||
always() && (
|
||||
needs.e2e-credit-purchase.result == 'success' ||
|
||||
github.event.inputs.skip_payment == 'true' ||
|
||||
github.event.inputs.use_test_token == 'true'
|
||||
)
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps ${{ inputs.browser || 'chromium' }}
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: github.event.inputs.use_test_token == 'true'
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Happy Path Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || needs.e2e-credit-purchase.outputs.session_token || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "=== Stage 2: Happy Path ==="
|
||||
echo "Time: $(date)"
|
||||
TOKEN_SOURCE="none"
|
||||
if [ -n "${{ steps.refresh_token.outputs.token }}" ]; then
|
||||
TOKEN_SOURCE="use_test_token (impersonation)"
|
||||
elif [ -n "${{ needs.e2e-credit-purchase.outputs.session_token }}" ]; then
|
||||
TOKEN_SOURCE="Stage 1 (credit purchase)"
|
||||
fi
|
||||
echo "Token source: $TOKEN_SOURCE"
|
||||
|
||||
npx playwright test happy-path-real-user.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=${{ inputs.browser || 'chromium' }} \
|
||||
--reporter=list \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output-happy-path.log
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if grep -q "passed" test-output-happy-path.log && ! grep -q "failed" test-output-happy-path.log; then
|
||||
echo "result=success" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "result=failure" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Upload test artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-results-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/test-output-happy-path.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload video recordings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-videos-${{ github.run_number }}
|
||||
path: frontend/test-results/**/*.webm
|
||||
retention-days: 30
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Create summary
|
||||
if: always()
|
||||
run: |
|
||||
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
|
||||
STAGE2="${{ steps.test_result.outputs.result || 'unknown' }}"
|
||||
echo "## E2E Daily Test Results" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage | Result |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage 1: Credit Purchase | ${STAGE1} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage 2: Happy Path | ${STAGE2} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Run | #${{ github.run_number }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Trigger | ${{ github.event_name }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Browser | ${{ inputs.browser || 'chromium' }} |" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 2: Happy Path\", \"description\": \"Karaoke generation flow is broken.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
|
||||
# =========================================================================
|
||||
# Final: Send notifications
|
||||
# =========================================================================
|
||||
notify:
|
||||
name: "Notify"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [e2e-credit-purchase, e2e-happy-path]
|
||||
if: always()
|
||||
|
||||
steps:
|
||||
- name: Discord notification (success)
|
||||
if: needs.e2e-happy-path.result == 'success'
|
||||
run: |
|
||||
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"✅ E2E Daily Test PASSED\", \"description\": \"Payment: ${STAGE1} | Happy Path: success\n\n**Run:** #${{ github.run_number }}\", \"color\": 3066993}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Send email notification
|
||||
if: github.event_name == 'schedule'
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.sendgrid.net
|
||||
server_port: 587
|
||||
username: apikey
|
||||
password: ${{ secrets.SENDGRID_API_KEY }}
|
||||
subject: "E2E Daily Test ${{ needs.e2e-happy-path.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
E2E Daily Test Results
|
||||
======================
|
||||
|
||||
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
|
||||
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
|
||||
|
||||
Run: #${{ github.run_number }}
|
||||
Trigger: ${{ github.event_name }}
|
||||
|
||||
View details: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
@@ -0,0 +1,196 @@
|
||||
name: E2E Happy Path Test
|
||||
|
||||
# Comprehensive end-to-end test that validates the full karaoke generation journey
|
||||
# using ONLY browser interactions (no API shortcuts)
|
||||
#
|
||||
# See docs/E2E-HAPPY-PATH-TEST-SPEC.md for full requirements
|
||||
|
||||
on:
|
||||
# Daily run at 6 AM UTC
|
||||
schedule:
|
||||
- cron: '0 6 * * *'
|
||||
|
||||
# Manual trigger with optional parameters
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
debug_mode:
|
||||
description: 'Enable debug mode (slower, more screenshots)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
browser:
|
||||
description: 'Browser to test with'
|
||||
required: false
|
||||
default: 'chromium'
|
||||
type: choice
|
||||
options:
|
||||
- chromium
|
||||
- firefox
|
||||
- webkit
|
||||
use_test_token:
|
||||
description: 'Skip signup and use E2E_TEST_TOKEN (for iterations)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
e2e-happy-path:
|
||||
name: "Full Happy Path (Real User)"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90 # 1.5 hours max (test itself is 60 min)
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: |
|
||||
BROWSER=${{ inputs.browser || 'chromium' }}
|
||||
npx playwright install --with-deps $BROWSER
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
# testmail.app is used for E2E testing but gets flagged as disposable
|
||||
# by external APIs. Ensure it's in the allowlist before the test runs.
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: failed to allowlist domain (may already exist)"
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: inputs.use_test_token == true
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run E2E Happy Path Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "Starting E2E Happy Path Test"
|
||||
echo "Browser: ${{ inputs.browser || 'chromium' }}"
|
||||
echo "Debug mode: ${{ inputs.debug_mode || 'false' }}"
|
||||
echo "Use test token: ${{ inputs.use_test_token || 'false' }}"
|
||||
echo "Time: $(date)"
|
||||
echo ""
|
||||
|
||||
# Run the real user happy path test
|
||||
npx playwright test happy-path-real-user.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=${{ inputs.browser || 'chromium' }} \
|
||||
--reporter=list \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output.log
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if grep -q "passed" test-output.log && ! grep -q "failed" test-output.log; then
|
||||
echo "result=success" >> $GITHUB_OUTPUT
|
||||
echo "Test PASSED"
|
||||
else
|
||||
echo "result=failure" >> $GITHUB_OUTPUT
|
||||
echo "Test FAILED - see artifacts for details"
|
||||
fi
|
||||
|
||||
- name: Upload test artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-results-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/test-output.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload video recordings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-videos-${{ github.run_number }}
|
||||
path: frontend/test-results/**/*.webm
|
||||
retention-days: 30
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Create summary
|
||||
if: always()
|
||||
run: |
|
||||
echo "## E2E Happy Path Test Results" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Run | #${{ github.run_number }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Trigger | ${{ github.event_name }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Browser | ${{ inputs.browser || 'chromium' }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Result | ${{ steps.test_result.outputs.result || 'unknown' }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
if [ -f frontend/test-output.log ]; then
|
||||
echo "### Test Output (last 100 lines)" >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
tail -100 frontend/test-output.log >> $GITHUB_STEP_SUMMARY
|
||||
echo "\`\`\`" >> $GITHUB_STEP_SUMMARY
|
||||
fi
|
||||
|
||||
- name: Send email notification
|
||||
if: always() && github.event_name == 'schedule'
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.sendgrid.net
|
||||
server_port: 587
|
||||
username: apikey
|
||||
password: ${{ secrets.SENDGRID_API_KEY }}
|
||||
subject: "E2E Happy Path Test ${{ steps.test_result.outputs.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
E2E Happy Path Test Results
|
||||
===========================
|
||||
|
||||
Status: ${{ steps.test_result.outputs.result == 'success' && 'PASSED ✅' || 'FAILED ❌' }}
|
||||
Run: #${{ github.run_number }}
|
||||
Trigger: ${{ github.event_name }}
|
||||
Time: ${{ github.event.repository.updated_at }}
|
||||
|
||||
View details: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
|
||||
This is an automated notification from the daily E2E happy path test.
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
@@ -97,20 +97,6 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
|
||||
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
|
||||
- Stop and notify user on auth issues
|
||||
|
||||
### Internationalization (i18n)
|
||||
|
||||
- All user-facing strings live in `frontend/messages/{locale}.json` (33 locales), NOT in components
|
||||
- Backend strings live in `backend/translations/{locale}.json` (currently 3 locales: en, es, de)
|
||||
- Components use `useTranslations('namespace')` from next-intl
|
||||
- Pages are under `frontend/src/app/[locale]/` — locale-aware routing
|
||||
- Admin pages (under `/admin/`, `/app/`) use DefaultIntlProvider (English-only, excluded from i18n)
|
||||
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
|
||||
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
|
||||
- Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
|
||||
- CI validates all locale files have matching keys — **PR will fail if translations are missing**
|
||||
- Pre-commit hook auto-translates when en.json changes (enable: `git config core.hooksPath .githooks`)
|
||||
- Don't hardcode user-facing strings — add to `messages/en.json` and use `t('key')`
|
||||
|
||||
## API Authentication (for Agents)
|
||||
|
||||
When you need to call backend APIs programmatically:
|
||||
|
||||
@@ -23,7 +23,6 @@ RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
curl \
|
||||
xz-utils \
|
||||
chromium \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install comprehensive font support for international lyrics and symbols
|
||||
|
||||
@@ -11,8 +11,6 @@ import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from backend.api.dependencies import require_auth, require_admin
|
||||
from backend.models.referral import (
|
||||
@@ -20,7 +18,6 @@ from backend.models.referral import (
|
||||
UpdateReferralLinkRequest,
|
||||
ReferralInterstitialResponse,
|
||||
)
|
||||
from backend.services.flyer_service import get_flyer_service, FlyerError
|
||||
from backend.services.referral_service import get_referral_service
|
||||
|
||||
|
||||
@@ -29,22 +26,17 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/referrals", tags=["referrals"])
|
||||
|
||||
|
||||
class GenerateFlyerRequest(BaseModel):
|
||||
theme: str = Field(..., pattern="^(light|dark)$")
|
||||
qr_data_url: str = Field(..., max_length=500_000)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Public endpoints
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@router.get("/r/{code}", response_model=ReferralInterstitialResponse)
|
||||
async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
async def get_referral_interstitial(code: str):
|
||||
"""
|
||||
Public endpoint: get interstitial data for a referral link.
|
||||
|
||||
Increments click count unless no_track=true. Returns valid=False if code not found.
|
||||
Increments click count. Returns valid=False if code not found.
|
||||
"""
|
||||
service = get_referral_service()
|
||||
link = service.get_link_by_code(code)
|
||||
@@ -52,12 +44,11 @@ async def get_referral_interstitial(code: str, no_track: bool = False):
|
||||
if not link:
|
||||
return ReferralInterstitialResponse(valid=False)
|
||||
|
||||
# Track the click (skip when fetching for display purposes)
|
||||
if not no_track:
|
||||
try:
|
||||
service.increment_clicks(code)
|
||||
except Exception:
|
||||
logger.warning("Failed to increment clicks for code %s", code, exc_info=True)
|
||||
# Track the click
|
||||
try:
|
||||
service.increment_clicks(code)
|
||||
except Exception:
|
||||
logger.warning("Failed to increment clicks for code %s", code, exc_info=True)
|
||||
|
||||
return ReferralInterstitialResponse(
|
||||
valid=True,
|
||||
@@ -127,105 +118,6 @@ async def start_stripe_connect(auth=Depends(require_auth)):
|
||||
return {"account_id": account_id, "onboarding_url": onboarding_url}
|
||||
|
||||
|
||||
@router.post("/me/connect/dashboard-link")
|
||||
async def get_connect_dashboard_link(auth=Depends(require_auth)):
|
||||
"""Get a login link to the Stripe Express dashboard for managing payout settings."""
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(auth.user_email)
|
||||
if not user or not user.stripe_connect_account_id:
|
||||
raise HTTPException(status_code=400, detail="No Stripe Connect account configured")
|
||||
|
||||
service = get_referral_service()
|
||||
url = service.create_connect_login_link(user.stripe_connect_account_id)
|
||||
if not url:
|
||||
raise HTTPException(status_code=500, detail="Failed to create dashboard link")
|
||||
|
||||
return {"url": url}
|
||||
|
||||
|
||||
@router.post("/me/connect/update-link")
|
||||
async def get_connect_update_link(auth=Depends(require_auth)):
|
||||
"""Get a link to update Stripe Connect account info (re-onboarding)."""
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(auth.user_email)
|
||||
if not user or not user.stripe_connect_account_id:
|
||||
raise HTTPException(status_code=400, detail="No Stripe Connect account configured")
|
||||
|
||||
service = get_referral_service()
|
||||
url = service.create_connect_update_link(user.stripe_connect_account_id)
|
||||
if not url:
|
||||
raise HTTPException(status_code=500, detail="Failed to create update link")
|
||||
|
||||
return {"url": url}
|
||||
|
||||
|
||||
class VanityRequest(BaseModel):
|
||||
desired_code: str = Field(..., min_length=2, max_length=30, pattern="^[a-z0-9-]+$")
|
||||
|
||||
|
||||
@router.post("/me/vanity-request")
|
||||
async def request_vanity_url(
|
||||
request: VanityRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
"""Request a custom vanity referral URL. Sends email to admin for review."""
|
||||
from backend.services.email_service import get_email_service
|
||||
|
||||
service = get_referral_service()
|
||||
link = service.get_or_create_link(auth.user_email)
|
||||
|
||||
# Check if code is already taken
|
||||
existing = service.get_link_by_code(request.desired_code)
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="That code is already taken. Please try another.")
|
||||
|
||||
email_service = get_email_service()
|
||||
email_service.provider.send_email(
|
||||
to_email="andrew@nomadkaraoke.com",
|
||||
subject=f"Vanity referral URL request: {request.desired_code}",
|
||||
html_content=f"""
|
||||
<h2>Vanity Referral URL Request</h2>
|
||||
<p><strong>User:</strong> {auth.user_email}</p>
|
||||
<p><strong>Current code:</strong> {link.code}</p>
|
||||
<p><strong>Desired vanity code:</strong> {request.desired_code}</p>
|
||||
<p>To approve, create the vanity link in the <a href="https://gen.nomadkaraoke.com/admin/referrals">admin dashboard</a>.</p>
|
||||
""",
|
||||
text_content=f"Vanity URL request from {auth.user_email}: {request.desired_code} (current: {link.code})",
|
||||
)
|
||||
|
||||
logger.info("Vanity URL request from %s: %s", auth.user_email, request.desired_code)
|
||||
return {"ok": True, "message": "Request sent"}
|
||||
|
||||
|
||||
@router.post("/me/flyer")
|
||||
async def generate_flyer(
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
"""Generate a personalized referral flyer PDF."""
|
||||
service = get_referral_service()
|
||||
link = service.get_or_create_link(auth.user_email)
|
||||
|
||||
try:
|
||||
flyer_service = get_flyer_service()
|
||||
pdf_bytes = flyer_service.generate_pdf(
|
||||
theme=request.theme,
|
||||
referral_code=link.code,
|
||||
discount_percent=link.discount_percent,
|
||||
qr_data_url=request.qr_data_url,
|
||||
)
|
||||
except FlyerError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": 'attachment; filename="nomad-karaoke-referral-flyer.pdf"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Admin endpoints
|
||||
# ============================================================================
|
||||
@@ -339,36 +231,3 @@ async def update_link(
|
||||
raise HTTPException(status_code=404, detail=message)
|
||||
|
||||
return {"ok": True, "message": message}
|
||||
|
||||
|
||||
@router.post("/admin/links/{code}/flyer")
|
||||
async def admin_generate_flyer(
|
||||
code: str,
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_admin),
|
||||
):
|
||||
"""Admin: generate a personalized referral flyer PDF for any code."""
|
||||
service = get_referral_service()
|
||||
link = service.get_link_by_code(code)
|
||||
|
||||
if not link:
|
||||
raise HTTPException(status_code=404, detail=f"Referral link '{code}' not found")
|
||||
|
||||
try:
|
||||
flyer_service = get_flyer_service()
|
||||
pdf_bytes = flyer_service.generate_pdf(
|
||||
theme=request.theme,
|
||||
referral_code=link.code,
|
||||
discount_percent=link.discount_percent,
|
||||
qr_data_url=request.qr_data_url,
|
||||
)
|
||||
except FlyerError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="nomad-karaoke-flyer-{link.code}.pdf"',
|
||||
},
|
||||
)
|
||||
@@ -1 +0,0 @@
|
||||
"""Production error monitoring service for Nomad Karaoke."""
|
||||
@@ -1,177 +0,0 @@
|
||||
"""Configuration for the production error monitoring service.
|
||||
|
||||
All constants, service lists, and environment-driven configuration
|
||||
functions used across the error monitor modules.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GCP project settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
GCP_PROJECT: str = os.environ.get("GCP_PROJECT", "nomadkaraoke")
|
||||
GCP_REGION: str = os.environ.get("GCP_REGION", "us-central1")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Log querying settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: How far back to look for errors on each run (minutes).
|
||||
LOOKBACK_MINUTES: int = 15
|
||||
|
||||
#: Maximum number of log entries to fetch per service per run.
|
||||
MAX_LOG_ENTRIES: int = 500
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Monitored services
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
MONITORED_CLOUD_RUN_SERVICES: list[str] = [
|
||||
"karaoke-backend",
|
||||
"karaoke-decide",
|
||||
"audio-separator",
|
||||
# Gen2 Cloud Functions appear as Cloud Run services in logs
|
||||
"gdrive-validator",
|
||||
"github-runner-manager",
|
||||
"backup-to-aws",
|
||||
"divebar-mirror",
|
||||
"kn-data-sync",
|
||||
"divebar-lookup",
|
||||
"encoding-worker-idle-shutdown",
|
||||
]
|
||||
|
||||
MONITORED_CLOUD_RUN_JOBS: list[str] = [
|
||||
"video-encoding-job",
|
||||
"lyrics-transcription-job",
|
||||
"audio-separation-job",
|
||||
"audio-download-job",
|
||||
]
|
||||
|
||||
# Gen2 Cloud Functions log as cloud_run_revision, not cloud_function.
|
||||
# Their names are in MONITORED_CLOUD_RUN_SERVICES above.
|
||||
MONITORED_CLOUD_FUNCTIONS: list[str] = []
|
||||
|
||||
MONITORED_GCE_INSTANCES: list[str] = [
|
||||
"encoding-worker-a",
|
||||
"encoding-worker-b",
|
||||
"flacfetch-vm",
|
||||
"divebar-sync-vm",
|
||||
]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Service dependency map
|
||||
# Human-readable description of which services depend on which workers.
|
||||
# Used as LLM context when generating root-cause analysis.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SERVICE_DEPENDENCY_MAP: str = """\
|
||||
karaoke-backend (main API)
|
||||
→ video-encoding-job (Cloud Run Job, triggered per order)
|
||||
→ lyrics-transcription-job (Cloud Run Job, triggered after audio-sep)
|
||||
→ audio-separation-job (Cloud Run Job, runs on Cloud Run GPU)
|
||||
→ audio-download-job (Cloud Run Job, uses flacfetch-vm)
|
||||
→ gdrive-validator (Cloud Function, validates output files)
|
||||
→ encoding-worker-a/b (GCE VMs, long-running encoding workers)
|
||||
|
||||
karaoke-decide (catalog / discovery API)
|
||||
→ kn_data_sync (Cloud Function, syncs KaraokeNerds catalog)
|
||||
→ divebar_mirror (Cloud Function, mirrors Divebar catalog)
|
||||
→ divebar_lookup (Cloud Function, single-song lookup)
|
||||
|
||||
audio-separator (Cloud Run service, GPU stem separation)
|
||||
→ audio-separation-job (Cloud Run Job, launched by audio-separator)
|
||||
|
||||
flacfetch-vm (GCE VM)
|
||||
→ audio-download-job (initiated by karaoke-backend)
|
||||
|
||||
divebar-sync-vm (GCE VM)
|
||||
→ divebar_mirror (Cloud Function, reads from this VM)
|
||||
|
||||
Shared infrastructure:
|
||||
→ runner_manager (Cloud Function, manages encoding worker lifecycle)
|
||||
→ encoding_worker_idle (Cloud Function, shuts down idle encoding workers)
|
||||
→ backup_to_aws (Cloud Function, daily GCS → S3 backup)
|
||||
"""
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM analysis settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
LLM_ANALYSIS_MODEL: str = os.environ.get("LLM_ANALYSIS_MODEL", "gemini-2.0-flash-001")
|
||||
LLM_VERTEX_LOCATION: str = os.environ.get("LLM_VERTEX_LOCATION", "us-central1")
|
||||
|
||||
#: Minimum number of active error patterns required before triggering LLM analysis.
|
||||
MIN_PATTERNS_FOR_ANALYSIS: int = 3
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Spike detection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: An error count is a spike if it exceeds SPIKE_MULTIPLIER × baseline average.
|
||||
SPIKE_MULTIPLIER: float = 5.0
|
||||
|
||||
#: Minimum absolute error count before spike detection fires (avoids noise).
|
||||
SPIKE_MIN_COUNT: int = 5
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Auto-resolution settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Multiply LOOKBACK_MINUTES by this to get auto-resolve window in minutes.
|
||||
AUTO_RESOLVE_MULTIPLIER: int = 8
|
||||
|
||||
#: Minimum hours before a pattern can be auto-resolved.
|
||||
AUTO_RESOLVE_MIN_HOURS: int = 6
|
||||
|
||||
#: Maximum hours before a pattern is force-resolved even if still active.
|
||||
AUTO_RESOLVE_MAX_HOURS: int = 168 # 1 week
|
||||
|
||||
#: Fallback resolve window (hours) if baseline data is unavailable.
|
||||
AUTO_RESOLVE_FALLBACK_HOURS: int = 48
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Discord settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Maximum Discord messages to send per monitor run (rate-limit guard).
|
||||
MAX_DISCORD_MESSAGES_PER_RUN: int = 10
|
||||
|
||||
#: Discord API hard limit on message length.
|
||||
DISCORD_MAX_MESSAGE_LENGTH: int = 2000
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pattern tracking settings
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Maximum number of active error patterns to track in Firestore.
|
||||
MAX_ACTIVE_PATTERNS: int = 500
|
||||
|
||||
#: Rolling window used when computing error baselines.
|
||||
ROLLING_WINDOW_DAYS: int = 7
|
||||
|
||||
#: Maximum length of a normalized error message stored in Firestore.
|
||||
MAX_NORMALIZED_MESSAGE_LENGTH: int = 200
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helper functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_llm_enabled() -> bool:
|
||||
"""Return True if LLM analysis is enabled via the LLM_ANALYSIS_ENABLED env var."""
|
||||
return os.environ.get("LLM_ANALYSIS_ENABLED", "false").strip().lower() == "true"
|
||||
|
||||
|
||||
def get_discord_webhook_secret_name() -> str:
|
||||
"""Return the Secret Manager secret name for the Discord webhook URL."""
|
||||
return os.environ.get("DISCORD_WEBHOOK_SECRET_NAME", "error-monitor-discord-webhook")
|
||||
|
||||
|
||||
def get_digest_mode() -> bool:
|
||||
"""Return True if the monitor should run in digest mode (batch alerts instead of immediate).
|
||||
|
||||
In digest mode all alerts are bundled into a single Discord message sent at
|
||||
the end of the run, rather than sending one message per error pattern.
|
||||
"""
|
||||
return os.environ.get("DIGEST_MODE", "false").strip().lower() == "true"
|
||||
@@ -1,323 +0,0 @@
|
||||
"""Discord alert client for the production error monitoring service.
|
||||
|
||||
Provides formatting functions for each alert type, and an ErrorMonitorDiscord
|
||||
webhook client that rate-limits outbound messages to MAX_DISCORD_MESSAGES_PER_RUN
|
||||
per monitor run.
|
||||
|
||||
Usage:
|
||||
from backend.services.error_monitor.discord import (
|
||||
ErrorMonitorDiscord,
|
||||
format_new_pattern_alert,
|
||||
format_incident_alert,
|
||||
format_auto_resolved_alert,
|
||||
format_spike_alert,
|
||||
format_daily_digest,
|
||||
)
|
||||
|
||||
discord = ErrorMonitorDiscord(webhook_url="https://discord.com/api/webhooks/...")
|
||||
msg = format_new_pattern_alert(...)
|
||||
discord.send_message(msg)
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import requests
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
DISCORD_MAX_MESSAGE_LENGTH,
|
||||
MAX_DISCORD_MESSAGES_PER_RUN,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
SEVERITY_EMOJI: dict[str, str] = {
|
||||
"P0": "🚨",
|
||||
"P1": "🔴",
|
||||
"P2": "⚠️",
|
||||
"P3": "🟡",
|
||||
}
|
||||
|
||||
_EASTERN = ZoneInfo("America/New_York")
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Private helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _now_eastern() -> str:
|
||||
"""Return the current Eastern time as 'HH:MM AM/PM ET' (DST-aware)."""
|
||||
now = datetime.now(tz=_EASTERN)
|
||||
return now.strftime("%I:%M %p ET").lstrip("0")
|
||||
|
||||
|
||||
def _truncate(msg: str) -> str:
|
||||
"""Truncate *msg* to DISCORD_MAX_MESSAGE_LENGTH characters."""
|
||||
if len(msg) <= DISCORD_MAX_MESSAGE_LENGTH:
|
||||
return msg
|
||||
suffix = "…"
|
||||
return msg[: DISCORD_MAX_MESSAGE_LENGTH - len(suffix)] + suffix
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Formatting functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def format_new_pattern_alert(
|
||||
service: str,
|
||||
resource_type: str,
|
||||
normalized_message: str,
|
||||
sample_message: str,
|
||||
count: int,
|
||||
first_seen: str,
|
||||
) -> str:
|
||||
"""Format a Discord alert for a newly-detected error pattern.
|
||||
|
||||
Args:
|
||||
service: Name of the service emitting the error.
|
||||
resource_type: GCP resource type (e.g. 'cloud_run_service', 'gce_instance').
|
||||
normalized_message: Normalised error pattern string.
|
||||
sample_message: A representative raw log message.
|
||||
count: Number of occurrences seen so far.
|
||||
first_seen: ISO 8601 timestamp when the pattern was first seen.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"🔴 **New Error Pattern Detected**",
|
||||
f"",
|
||||
f"**Service:** {service}",
|
||||
f"**Resource type:** {resource_type}",
|
||||
f"**Pattern:** {normalized_message}",
|
||||
f"**Sample:** {sample_message}",
|
||||
f"**Count:** {count}",
|
||||
f"**First seen:** {first_seen}",
|
||||
f"**Alerted at:** {_now_eastern()}",
|
||||
f"",
|
||||
f"To investigate: `/prod-investigate {service} \"{normalized_message}\"`",
|
||||
]
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_incident_alert(
|
||||
title: str,
|
||||
severity: str,
|
||||
root_cause: str,
|
||||
suggested_fix: str,
|
||||
primary_service: str,
|
||||
patterns: list[dict],
|
||||
) -> str:
|
||||
"""Format a Discord alert for an analysed incident (LLM-generated).
|
||||
|
||||
Args:
|
||||
title: Short incident title.
|
||||
severity: Severity level — one of P0, P1, P2, P3.
|
||||
root_cause: Human-readable root-cause analysis.
|
||||
suggested_fix: Recommended remediation steps.
|
||||
primary_service: The main service involved in the incident.
|
||||
patterns: List of dicts, each with keys: service, normalized_message, count.
|
||||
Only the first 5 are shown; normalized_message is truncated to 80 chars.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
emoji = SEVERITY_EMOJI.get(severity, "⚠️")
|
||||
lines = [
|
||||
f"{emoji} **[{severity}] {title}**",
|
||||
f"",
|
||||
f"**Primary service:** {primary_service}",
|
||||
f"**Root cause:** {root_cause}",
|
||||
f"**Suggested fix:** {suggested_fix}",
|
||||
]
|
||||
|
||||
shown_patterns = patterns[:5]
|
||||
if shown_patterns:
|
||||
lines.append("")
|
||||
lines.append(f"**Patterns ({len(shown_patterns)} of {len(patterns)}):**")
|
||||
for p in shown_patterns:
|
||||
svc = p.get("service", "unknown")
|
||||
msg = p.get("normalized_message", "")[:80]
|
||||
cnt = p.get("count", 0)
|
||||
lines.append(f" • `{svc}` — {msg} ({cnt}x)")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Alerted at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_auto_resolved_alert(resolved_patterns: list[dict]) -> str:
|
||||
"""Format a consolidated auto-resolved alert.
|
||||
|
||||
Args:
|
||||
resolved_patterns: List of dicts, each with keys: service, message, hours_silent.
|
||||
Only the first 8 are shown; message is truncated to 60 chars.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"✅ **Patterns Auto-Resolved**",
|
||||
f"",
|
||||
]
|
||||
|
||||
shown = resolved_patterns[:8]
|
||||
if shown:
|
||||
for p in shown:
|
||||
svc = p.get("service", "unknown")
|
||||
msg = p.get("message", "")[:60]
|
||||
hours = p.get("hours_silent", 0)
|
||||
lines.append(f" • `{svc}` — {msg} (silent {hours}h)")
|
||||
else:
|
||||
lines.append(" *(no patterns)*")
|
||||
|
||||
if len(resolved_patterns) > 8:
|
||||
lines.append(f" … and {len(resolved_patterns) - 8} more")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Resolved at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_spike_alert(
|
||||
service: str,
|
||||
normalized_message: str,
|
||||
current_count: int,
|
||||
rolling_average: float,
|
||||
) -> str:
|
||||
"""Format a Discord alert for an error rate spike.
|
||||
|
||||
Args:
|
||||
service: Name of the service.
|
||||
normalized_message: Normalised error pattern string.
|
||||
current_count: Error count in the current window.
|
||||
rolling_average: Baseline rolling average count.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
if rolling_average > 0:
|
||||
multiplier = current_count / rolling_average
|
||||
multiplier_str = f"{multiplier:.1f}x"
|
||||
else:
|
||||
multiplier_str = "∞x"
|
||||
|
||||
lines = [
|
||||
f"⚠️ **Error Rate Spike Detected**",
|
||||
f"",
|
||||
f"**Service:** {service}",
|
||||
f"**Pattern:** {normalized_message}",
|
||||
f"**Current count:** {current_count}",
|
||||
f"**Normal (rolling avg):** {rolling_average}",
|
||||
f"**Multiplier:** {multiplier_str} above normal",
|
||||
f"",
|
||||
f"**Alerted at:** {_now_eastern()}",
|
||||
]
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
def format_daily_digest(
|
||||
total_errors: int,
|
||||
new_patterns: int,
|
||||
resolved_patterns: int,
|
||||
active_patterns: int,
|
||||
per_service_counts: dict,
|
||||
) -> str:
|
||||
"""Format the daily 24h error digest.
|
||||
|
||||
Args:
|
||||
total_errors: Total error count in the last 24 hours.
|
||||
new_patterns: Number of new error patterns detected.
|
||||
resolved_patterns: Number of patterns auto-resolved.
|
||||
active_patterns: Total number of currently active patterns.
|
||||
per_service_counts: Mapping of service name → error count.
|
||||
Displayed sorted by count descending.
|
||||
|
||||
Returns:
|
||||
Formatted Discord message string, truncated to 2000 chars.
|
||||
"""
|
||||
lines = [
|
||||
f"📊 **Daily Error Digest (24h)**",
|
||||
f"",
|
||||
f"**Total errors:** {total_errors}",
|
||||
f"**New patterns:** {new_patterns}",
|
||||
f"**Resolved patterns:** {resolved_patterns}",
|
||||
f"**Active patterns:** {active_patterns}",
|
||||
]
|
||||
|
||||
if per_service_counts:
|
||||
lines.append("")
|
||||
lines.append("**Per-service breakdown:**")
|
||||
sorted_services = sorted(per_service_counts.items(), key=lambda kv: kv[1], reverse=True)
|
||||
for svc, cnt in sorted_services:
|
||||
lines.append(f" • `{svc}`: {cnt}")
|
||||
|
||||
lines.append("")
|
||||
lines.append(f"**Generated at:** {_now_eastern()}")
|
||||
|
||||
return _truncate("\n".join(lines))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Discord webhook client
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ErrorMonitorDiscord:
|
||||
"""Webhook client for sending error monitor alerts to Discord.
|
||||
|
||||
Enforces a per-run rate limit of MAX_DISCORD_MESSAGES_PER_RUN to avoid
|
||||
flooding the channel during high-volume incident windows.
|
||||
|
||||
Attributes:
|
||||
webhook_url: The Discord incoming webhook URL.
|
||||
messages_sent: Counter of messages attempted this run (success or failure).
|
||||
"""
|
||||
|
||||
def __init__(self, webhook_url: str) -> None:
|
||||
self.webhook_url = webhook_url
|
||||
self.messages_sent: int = 0
|
||||
|
||||
def send_message(self, content: str) -> bool:
|
||||
"""Send a message to the configured Discord webhook.
|
||||
|
||||
Rate-limits: if messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN, the
|
||||
message is silently skipped and False is returned without incrementing
|
||||
the counter.
|
||||
|
||||
Args:
|
||||
content: The message text to send (should be pre-formatted and
|
||||
pre-truncated to ≤2000 chars).
|
||||
|
||||
Returns:
|
||||
True if the message was sent successfully, False otherwise.
|
||||
"""
|
||||
if self.messages_sent >= MAX_DISCORD_MESSAGES_PER_RUN:
|
||||
logger.warning(
|
||||
"Discord rate limit reached (%d messages sent this run); skipping message.",
|
||||
self.messages_sent,
|
||||
)
|
||||
return False
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
self.webhook_url,
|
||||
json={"content": content},
|
||||
timeout=30,
|
||||
)
|
||||
response.raise_for_status()
|
||||
logger.debug("Discord message sent successfully.")
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.error("Failed to send Discord message: %s", exc)
|
||||
return False
|
||||
finally:
|
||||
self.messages_sent += 1
|
||||
@@ -1,489 +0,0 @@
|
||||
"""Firestore adapter for the production error monitoring service.
|
||||
|
||||
Handles all CRUD for three Firestore collections:
|
||||
- error_patterns: normalized error patterns (pattern_id as doc ID)
|
||||
- error_incidents: groups of related patterns (incident_id as doc ID)
|
||||
- discord_alerts: audit trail for Discord messages (alert_id as doc ID)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
AUTO_RESOLVE_FALLBACK_HOURS,
|
||||
AUTO_RESOLVE_MAX_HOURS,
|
||||
AUTO_RESOLVE_MIN_HOURS,
|
||||
AUTO_RESOLVE_MULTIPLIER,
|
||||
ROLLING_WINDOW_DAYS,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data classes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class PatternData:
|
||||
"""Input data for creating or updating an error pattern."""
|
||||
|
||||
pattern_id: str
|
||||
service: str
|
||||
resource_type: str
|
||||
normalized_message: str
|
||||
sample_message: str
|
||||
count: int
|
||||
timestamp: datetime
|
||||
|
||||
|
||||
@dataclass
|
||||
class UpsertResult:
|
||||
"""Result of an upsert_pattern operation."""
|
||||
|
||||
pattern_id: str
|
||||
is_new: bool
|
||||
previous_status: str | None = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Collection names
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_COL_PATTERNS = "error_patterns"
|
||||
_COL_INCIDENTS = "error_incidents"
|
||||
_COL_ALERTS = "discord_alerts"
|
||||
|
||||
# Statuses that can be queried as "active"
|
||||
_ACTIVE_STATUSES = ["new", "acknowledged", "known"]
|
||||
|
||||
# Statuses from which a pattern is reactivated when the error recurs
|
||||
_REACTIVATION_STATUSES = {"auto_resolved", "fixed"}
|
||||
|
||||
# Statuses eligible for auto-resolve checking
|
||||
_AUTO_RESOLVE_ELIGIBLE = {"new", "acknowledged"}
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
"""Return current UTC datetime."""
|
||||
return datetime.now(tz=timezone.utc)
|
||||
|
||||
|
||||
def _iso(dt: datetime) -> str:
|
||||
"""Serialise a datetime to ISO-8601 string."""
|
||||
return dt.isoformat()
|
||||
|
||||
|
||||
def _generate_id(prefix: str, fmt: str) -> str:
|
||||
"""Generate a time-stamped ID with 8 hex random suffix.
|
||||
|
||||
Args:
|
||||
prefix: e.g. "inc" or "alert"
|
||||
fmt: strftime format string applied to utcnow(), e.g. "%Y%m%d_%H%M"
|
||||
"""
|
||||
ts = _utcnow().strftime(fmt)
|
||||
suffix = secrets.token_hex(4) # 8 hex chars
|
||||
return f"{prefix}_{ts}_{suffix}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Adapter
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ErrorPatternsAdapter:
|
||||
"""Firestore CRUD adapter for error monitoring collections.
|
||||
|
||||
Args:
|
||||
db: Optional Firestore client. If omitted, a default client for the
|
||||
``nomadkaraoke`` GCP project is constructed on first use.
|
||||
"""
|
||||
|
||||
def __init__(self, db=None) -> None:
|
||||
if db is None:
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
self._db = db
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — read
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_pattern(self, pattern_id: str) -> dict | None:
|
||||
"""Return the pattern document as a dict, or None if it doesn't exist.
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID in the ``error_patterns`` collection.
|
||||
"""
|
||||
snap = self._db.collection(_COL_PATTERNS).document(pattern_id).get()
|
||||
if not snap.exists:
|
||||
return None
|
||||
return snap.to_dict()
|
||||
|
||||
def get_active_patterns(self) -> list[dict]:
|
||||
"""Return all patterns with status in [new, acknowledged, known]."""
|
||||
query = self._db.collection(_COL_PATTERNS).where(
|
||||
"status", "in", _ACTIVE_STATUSES
|
||||
)
|
||||
return [snap.to_dict() for snap in query.stream()]
|
||||
|
||||
def get_patterns_for_auto_resolve(self) -> list[dict]:
|
||||
"""Return active patterns eligible for auto-resolution (new or acknowledged)."""
|
||||
query = self._db.collection(_COL_PATTERNS).where(
|
||||
"status", "in", list(_AUTO_RESOLVE_ELIGIBLE)
|
||||
)
|
||||
return [snap.to_dict() for snap in query.stream()]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — upsert
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def upsert_pattern(self, data: PatternData) -> UpsertResult:
|
||||
"""Create a new pattern or update an existing one.
|
||||
|
||||
New pattern:
|
||||
- status="new", severity="P3"
|
||||
- Initialize ``rolling_counts`` with one entry for this run.
|
||||
|
||||
Existing pattern:
|
||||
- Increment ``total_count`` and append to ``rolling_counts``.
|
||||
- If status was ``auto_resolved`` or ``fixed`` → reactivate (set status="new").
|
||||
- Prune ``rolling_counts`` entries older than ROLLING_WINDOW_DAYS.
|
||||
|
||||
Returns:
|
||||
UpsertResult with ``is_new=True`` for brand-new patterns *and* for
|
||||
reactivated patterns (auto_resolved → new, fixed → new).
|
||||
"""
|
||||
doc_ref = self._db.collection(_COL_PATTERNS).document(data.pattern_id)
|
||||
snap = doc_ref.get()
|
||||
ts_iso = _iso(data.timestamp)
|
||||
|
||||
new_rolling_entry = {"ts": ts_iso, "count": data.count}
|
||||
|
||||
if not snap.exists:
|
||||
# ── brand new pattern ──────────────────────────────────────────
|
||||
doc_ref.set(
|
||||
{
|
||||
"pattern_id": data.pattern_id,
|
||||
"service": data.service,
|
||||
"resource_type": data.resource_type,
|
||||
"normalized_message": data.normalized_message,
|
||||
"sample_message": data.sample_message,
|
||||
"status": "new",
|
||||
"severity": "P3",
|
||||
"total_count": data.count,
|
||||
"rolling_counts": [new_rolling_entry],
|
||||
"first_seen": ts_iso,
|
||||
"last_seen": ts_iso,
|
||||
"alerted_at": None,
|
||||
"created_at": ts_iso,
|
||||
"updated_at": ts_iso,
|
||||
}
|
||||
)
|
||||
return UpsertResult(pattern_id=data.pattern_id, is_new=True)
|
||||
|
||||
# ── existing pattern ───────────────────────────────────────────────
|
||||
existing = snap.to_dict()
|
||||
prev_status = existing.get("status", "new")
|
||||
|
||||
rolling_counts: list[dict] = list(existing.get("rolling_counts") or [])
|
||||
rolling_counts.append(new_rolling_entry)
|
||||
rolling_counts = self._prune_rolling_counts(rolling_counts)
|
||||
|
||||
update: dict[str, Any] = {
|
||||
"total_count": existing.get("total_count", 0) + data.count,
|
||||
"rolling_counts": rolling_counts,
|
||||
"last_seen": ts_iso,
|
||||
"sample_message": data.sample_message,
|
||||
"updated_at": ts_iso,
|
||||
}
|
||||
|
||||
# Reactivation: pattern was considered resolved/fixed but error recurred
|
||||
is_new = False
|
||||
if prev_status in _REACTIVATION_STATUSES:
|
||||
update["status"] = "new"
|
||||
update["alerted_at"] = None
|
||||
is_new = True
|
||||
|
||||
doc_ref.update(update)
|
||||
return UpsertResult(
|
||||
pattern_id=data.pattern_id,
|
||||
is_new=is_new,
|
||||
previous_status=prev_status,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Patterns — status changes
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def auto_resolve_pattern(self, pattern_id: str, hours_silent: float) -> None:
|
||||
"""Mark a pattern as auto-resolved.
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID.
|
||||
hours_silent: How many hours the pattern has been silent.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"status": "auto_resolved",
|
||||
"auto_resolve_hours_silent": hours_silent,
|
||||
"auto_resolved_at": _iso(_utcnow()),
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
def resolve_pattern(
|
||||
self,
|
||||
pattern_id: str,
|
||||
pr_url: str | None = None,
|
||||
note: str = "",
|
||||
) -> None:
|
||||
"""Mark a pattern as fixed (human-resolved).
|
||||
|
||||
Args:
|
||||
pattern_id: Firestore document ID.
|
||||
pr_url: Optional URL of the PR that fixed this pattern.
|
||||
note: Optional human-readable note about the fix.
|
||||
"""
|
||||
now_iso = _iso(_utcnow())
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"status": "fixed",
|
||||
"fixed_by": {
|
||||
"pr_url": pr_url,
|
||||
"note": note,
|
||||
"fixed_at": now_iso,
|
||||
},
|
||||
"updated_at": now_iso,
|
||||
}
|
||||
)
|
||||
|
||||
def update_pattern_alerted(self, pattern_id: str) -> None:
|
||||
"""Set the ``alerted_at`` timestamp on a pattern.
|
||||
|
||||
Called after a Discord alert has been successfully sent for the pattern.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"alerted_at": _iso(_utcnow()),
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
def merge_pattern(self, source_id: str, target_id: str, reason: str) -> None:
|
||||
"""Merge *source* into *target* by muting the source pattern.
|
||||
|
||||
Args:
|
||||
source_id: Pattern to mute.
|
||||
target_id: Pattern that the source is being merged into.
|
||||
reason: Human-readable rationale for the merge.
|
||||
"""
|
||||
self._db.collection(_COL_PATTERNS).document(source_id).update(
|
||||
{
|
||||
"status": "muted",
|
||||
"merged_into": target_id,
|
||||
"merge_reason": reason,
|
||||
"updated_at": _iso(_utcnow()),
|
||||
}
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Auto-resolve logic
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def check_auto_resolve(self, pattern: dict) -> float | None:
|
||||
"""Determine whether *pattern* should be auto-resolved.
|
||||
|
||||
Computes the frequency-aware silence threshold and compares it against
|
||||
how long the pattern has been silent.
|
||||
|
||||
Args:
|
||||
pattern: A pattern document dict (as returned by get_pattern).
|
||||
|
||||
Returns:
|
||||
The number of hours the pattern has been silent if the threshold is
|
||||
exceeded, or ``None`` if the pattern should not yet be resolved.
|
||||
"""
|
||||
status = pattern.get("status", "")
|
||||
if status not in _AUTO_RESOLVE_ELIGIBLE:
|
||||
return None
|
||||
|
||||
last_seen_str = pattern.get("last_seen")
|
||||
if not last_seen_str:
|
||||
return None
|
||||
|
||||
last_seen = datetime.fromisoformat(last_seen_str)
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
|
||||
# Ensure both datetimes are tz-aware for subtraction
|
||||
if last_seen.tzinfo is None:
|
||||
last_seen = last_seen.replace(tzinfo=timezone.utc)
|
||||
|
||||
hours_silent = (now - last_seen).total_seconds() / 3600.0
|
||||
|
||||
rolling_counts = pattern.get("rolling_counts") or []
|
||||
threshold = self._compute_resolve_threshold(rolling_counts)
|
||||
|
||||
if hours_silent >= threshold:
|
||||
return hours_silent
|
||||
return None
|
||||
|
||||
def _compute_resolve_threshold(self, rolling_counts: list[dict]) -> float:
|
||||
"""Compute the frequency-aware auto-resolve threshold in hours.
|
||||
|
||||
Algorithm:
|
||||
1. If fewer than 3 data points → return AUTO_RESOLVE_FALLBACK_HOURS (48).
|
||||
2. Compute mean interval between consecutive timestamps.
|
||||
3. threshold = mean_interval_hours * AUTO_RESOLVE_MULTIPLIER.
|
||||
4. Clamp result to [AUTO_RESOLVE_MIN_HOURS, AUTO_RESOLVE_MAX_HOURS].
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"ts": ISO-string, "count": int}`` dicts.
|
||||
|
||||
Returns:
|
||||
Threshold in hours (float).
|
||||
"""
|
||||
if len(rolling_counts) < 3:
|
||||
return float(AUTO_RESOLVE_FALLBACK_HOURS)
|
||||
|
||||
# Parse timestamps and sort ascending
|
||||
timestamps: list[datetime] = []
|
||||
for entry in rolling_counts:
|
||||
ts = datetime.fromisoformat(entry["ts"])
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
timestamps.append(ts)
|
||||
timestamps.sort()
|
||||
|
||||
# Compute pairwise intervals
|
||||
intervals_hours: list[float] = []
|
||||
for i in range(1, len(timestamps)):
|
||||
delta = (timestamps[i] - timestamps[i - 1]).total_seconds() / 3600.0
|
||||
intervals_hours.append(delta)
|
||||
|
||||
if not intervals_hours:
|
||||
return float(AUTO_RESOLVE_FALLBACK_HOURS)
|
||||
|
||||
mean_interval = sum(intervals_hours) / len(intervals_hours)
|
||||
threshold = mean_interval * AUTO_RESOLVE_MULTIPLIER
|
||||
|
||||
# Clamp to configured bounds
|
||||
threshold = max(float(AUTO_RESOLVE_MIN_HOURS), threshold)
|
||||
threshold = min(float(AUTO_RESOLVE_MAX_HOURS), threshold)
|
||||
return threshold
|
||||
|
||||
def _prune_rolling_counts(self, rolling_counts: list[dict]) -> list[dict]:
|
||||
"""Remove rolling_count entries older than ROLLING_WINDOW_DAYS.
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"ts": ISO-string, "count": int}`` dicts.
|
||||
|
||||
Returns:
|
||||
Filtered list with only recent entries.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return []
|
||||
|
||||
cutoff = _utcnow() - timedelta(days=ROLLING_WINDOW_DAYS)
|
||||
result = []
|
||||
for entry in rolling_counts:
|
||||
ts = datetime.fromisoformat(entry["ts"])
|
||||
if ts.tzinfo is None:
|
||||
ts = ts.replace(tzinfo=timezone.utc)
|
||||
if ts >= cutoff:
|
||||
result.append(entry)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Incidents
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def create_incident(
|
||||
self,
|
||||
title: str,
|
||||
root_cause: str,
|
||||
severity: str,
|
||||
suggested_fix: str,
|
||||
primary_service: str,
|
||||
pattern_ids: list[str],
|
||||
used_llm: bool,
|
||||
) -> str:
|
||||
"""Create a new incident document and link associated patterns.
|
||||
|
||||
Args:
|
||||
title: Short human-readable title.
|
||||
root_cause: LLM-generated or manual root-cause description.
|
||||
severity: Severity string (e.g. "P1", "P2", "P3").
|
||||
suggested_fix: Suggested remediation steps.
|
||||
primary_service: The primary affected service.
|
||||
pattern_ids: List of pattern_ids that belong to this incident.
|
||||
used_llm: Whether LLM analysis was used to generate this incident.
|
||||
|
||||
Returns:
|
||||
The generated incident_id string.
|
||||
"""
|
||||
incident_id = _generate_id("inc", "%Y%m%d_%H%M")
|
||||
now_iso = _iso(_utcnow())
|
||||
|
||||
self._db.collection(_COL_INCIDENTS).document(incident_id).set(
|
||||
{
|
||||
"incident_id": incident_id,
|
||||
"title": title,
|
||||
"root_cause": root_cause,
|
||||
"severity": severity,
|
||||
"suggested_fix": suggested_fix,
|
||||
"primary_service": primary_service,
|
||||
"pattern_ids": pattern_ids,
|
||||
"used_llm": used_llm,
|
||||
"created_at": now_iso,
|
||||
"updated_at": now_iso,
|
||||
"status": "open",
|
||||
}
|
||||
)
|
||||
|
||||
# Link each pattern back to this incident
|
||||
for pattern_id in pattern_ids:
|
||||
self._db.collection(_COL_PATTERNS).document(pattern_id).update(
|
||||
{
|
||||
"incident_id": incident_id,
|
||||
"updated_at": now_iso,
|
||||
}
|
||||
)
|
||||
|
||||
return incident_id
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Discord audit trail
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def log_discord_alert(
|
||||
self,
|
||||
alert_type: str,
|
||||
content: str,
|
||||
success: bool,
|
||||
metadata: dict | None = None,
|
||||
) -> None:
|
||||
"""Write an audit record to the ``discord_alerts`` collection.
|
||||
|
||||
Args:
|
||||
alert_type: Category of alert (e.g. "new_pattern", "digest").
|
||||
content: The message body that was (or would have been) sent.
|
||||
success: Whether the Discord webhook call succeeded.
|
||||
metadata: Optional additional data (pattern_ids, incident_id, etc.).
|
||||
"""
|
||||
alert_id = _generate_id("alert", "%Y%m%d_%H%M%S")
|
||||
now_iso = _iso(_utcnow())
|
||||
|
||||
self._db.collection(_COL_ALERTS).document(alert_id).set(
|
||||
{
|
||||
"alert_id": alert_id,
|
||||
"alert_type": alert_type,
|
||||
"content": content,
|
||||
"success": success,
|
||||
"metadata": metadata or {},
|
||||
"created_at": now_iso,
|
||||
}
|
||||
)
|
||||
@@ -1,106 +0,0 @@
|
||||
"""Known infrastructure noise patterns for the production error monitoring service.
|
||||
|
||||
Filters out transient, expected log messages so the error monitor is not flooded
|
||||
with Cloud Run cold-start probes, deploy events, spot VM preemptions, and similar
|
||||
operational noise.
|
||||
|
||||
Usage:
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
|
||||
reason = should_ignore(service, message)
|
||||
if reason:
|
||||
# skip this log entry — it's known infrastructure noise
|
||||
...
|
||||
"""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass
|
||||
class IgnoreReason:
|
||||
"""Describes why a log entry should be suppressed.
|
||||
|
||||
Attributes:
|
||||
pattern_name: Machine-readable name of the matching ignore pattern.
|
||||
reason: Human-readable explanation of why this is infrastructure noise.
|
||||
"""
|
||||
|
||||
pattern_name: str
|
||||
reason: str
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compiled ignore patterns (applied in order)
|
||||
# All patterns use re.IGNORECASE for case-insensitive matching.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_IGNORE_PATTERNS: list[tuple[str, re.Pattern, str]] = [
|
||||
(
|
||||
"startup_probe",
|
||||
re.compile(r"startup probe failed", re.IGNORECASE),
|
||||
"Cloud Run cold start — startup probe failure is transient and expected",
|
||||
),
|
||||
(
|
||||
"ready_condition",
|
||||
re.compile(r"ready condition status changed", re.IGNORECASE),
|
||||
"Cloud Run deploy event — readiness condition change is expected on deploy",
|
||||
),
|
||||
(
|
||||
"spot_preemption",
|
||||
re.compile(r"instance was preempted", re.IGNORECASE),
|
||||
"Spot/preemptible VM preemption — expected behaviour for spot instances",
|
||||
),
|
||||
(
|
||||
"idle_shutdown",
|
||||
re.compile(r"stopping idle encoding worker", re.IGNORECASE),
|
||||
"Encoding worker idle shutdown — expected behaviour when no jobs are queued",
|
||||
),
|
||||
(
|
||||
"health_check_404",
|
||||
re.compile(
|
||||
r"(?:GET|HEAD)\b[^\n]*?/health[^\n]*?\b(?:404|not found)\b",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
"Load balancer health check returning 404 — transient during cold start",
|
||||
),
|
||||
(
|
||||
"scheduler_retry",
|
||||
re.compile(r"cloud scheduler.*retry", re.IGNORECASE),
|
||||
"Cloud Scheduler transient retry — expected on intermittent job failures",
|
||||
),
|
||||
(
|
||||
"runner_startup",
|
||||
re.compile(r"github\.runner\..*(?:starting|stopping|idle)", re.IGNORECASE),
|
||||
"GitHub Actions runner lifecycle event — expected during runner start/stop",
|
||||
),
|
||||
(
|
||||
"container_shutdown",
|
||||
re.compile(r"container called exit\(0\)", re.IGNORECASE),
|
||||
"Container clean exit — exit code 0 indicates a graceful, expected shutdown",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def should_ignore(service: str, message: str) -> IgnoreReason | None:
|
||||
"""Check whether a log entry matches a known infrastructure noise pattern.
|
||||
|
||||
The check is purely message-based; ``service`` is accepted for API symmetry
|
||||
and future service-specific overrides but does not gate any pattern today.
|
||||
|
||||
Args:
|
||||
service: The originating service name (e.g. ``"karaoke-backend"``).
|
||||
message: The raw log message string to evaluate.
|
||||
|
||||
Returns:
|
||||
An :class:`IgnoreReason` if the message matches a known noise pattern,
|
||||
or ``None`` if the message should be processed normally.
|
||||
"""
|
||||
if not message:
|
||||
return None
|
||||
|
||||
for pattern_name, pattern, reason in _IGNORE_PATTERNS:
|
||||
if pattern.search(message):
|
||||
return IgnoreReason(pattern_name=pattern_name, reason=reason)
|
||||
|
||||
return None
|
||||
@@ -1,429 +0,0 @@
|
||||
"""LLM-powered incident analysis and duplicate detection for the error monitor.
|
||||
|
||||
Uses Gemini Flash via the google-generativeai library to:
|
||||
1. Group related error patterns into incidents with root-cause analysis.
|
||||
2. Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
Both functions fall back gracefully when the LLM is unavailable or returns
|
||||
unparseable output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from google import genai
|
||||
from google.genai import types as genai_types
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LLM_ANALYSIS_MODEL,
|
||||
LLM_VERTEX_LOCATION,
|
||||
MIN_PATTERNS_FOR_ANALYSIS,
|
||||
SERVICE_DEPENDENCY_MAP,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dataclasses
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class Incident:
|
||||
"""A grouped incident produced by LLM analysis or the fallback grouper."""
|
||||
|
||||
title: str
|
||||
root_cause: str | None
|
||||
severity: str # P0 / P1 / P2 / P3
|
||||
suggested_fix: str | None
|
||||
primary_service: str
|
||||
pattern_indices: list[int]
|
||||
|
||||
|
||||
@dataclass
|
||||
class IncidentAnalysis:
|
||||
"""The result of an incident grouping pass."""
|
||||
|
||||
incidents: list[Incident]
|
||||
used_llm: bool = True
|
||||
|
||||
|
||||
@dataclass
|
||||
class DuplicateGroup:
|
||||
"""A canonical pattern plus the new patterns that duplicate it."""
|
||||
|
||||
canonical_index: int
|
||||
duplicate_indices: list[int]
|
||||
reason: str
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM call helper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_RETRY_ATTEMPTS = 3
|
||||
_RETRY_BASE_DELAY = 2.0 # seconds
|
||||
|
||||
|
||||
def _call_llm(
|
||||
system_prompt: str,
|
||||
user_prompt: str,
|
||||
temperature: float = 0.2,
|
||||
) -> str:
|
||||
"""Call Gemini and return the response text.
|
||||
|
||||
Retries up to _RETRY_ATTEMPTS times with exponential back-off on failure.
|
||||
|
||||
Args:
|
||||
system_prompt: System instruction for the model.
|
||||
user_prompt: User-facing prompt content.
|
||||
temperature: Sampling temperature (lower = more deterministic).
|
||||
|
||||
Returns:
|
||||
The model's response text.
|
||||
|
||||
Raises:
|
||||
Exception: Re-raises the last exception after all retries are exhausted.
|
||||
"""
|
||||
last_exc: Exception | None = None
|
||||
|
||||
for attempt in range(_RETRY_ATTEMPTS):
|
||||
try:
|
||||
client = genai.Client(
|
||||
vertexai=True,
|
||||
project=GCP_PROJECT,
|
||||
location=LLM_VERTEX_LOCATION,
|
||||
)
|
||||
response = client.models.generate_content(
|
||||
model=LLM_ANALYSIS_MODEL,
|
||||
contents=user_prompt,
|
||||
config=genai_types.GenerateContentConfig(
|
||||
system_instruction=system_prompt,
|
||||
temperature=temperature,
|
||||
),
|
||||
)
|
||||
return response.text
|
||||
except Exception as exc: # noqa: BLE001
|
||||
last_exc = exc
|
||||
delay = _RETRY_BASE_DELAY * (2**attempt)
|
||||
logger.warning(
|
||||
"LLM call failed (attempt %d/%d): %s — retrying in %.1fs",
|
||||
attempt + 1,
|
||||
_RETRY_ATTEMPTS,
|
||||
exc,
|
||||
delay,
|
||||
)
|
||||
time.sleep(delay)
|
||||
|
||||
raise last_exc # type: ignore[misc]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Response parsing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_MD_CODE_BLOCK_RE = re.compile(r"```(?:json)?\s*([\s\S]*?)```", re.IGNORECASE)
|
||||
|
||||
|
||||
def _strip_markdown_code_block(text: str) -> str:
|
||||
"""Remove surrounding ```json ... ``` or ``` ... ``` fences if present."""
|
||||
match = _MD_CODE_BLOCK_RE.search(text)
|
||||
if match:
|
||||
return match.group(1).strip()
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _parse_llm_response(text: str) -> IncidentAnalysis | None:
|
||||
"""Parse the LLM response text into an IncidentAnalysis.
|
||||
|
||||
Args:
|
||||
text: Raw LLM output, possibly wrapped in a markdown code block.
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis on success, None on any parse failure.
|
||||
"""
|
||||
if not text:
|
||||
return None
|
||||
|
||||
cleaned = _strip_markdown_code_block(text)
|
||||
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("LLM returned non-JSON response (first 200 chars): %.200s", text)
|
||||
return None
|
||||
|
||||
if "incidents" not in data:
|
||||
logger.warning("LLM response missing 'incidents' key: %s", list(data.keys()))
|
||||
return None
|
||||
|
||||
incidents: list[Incident] = []
|
||||
for raw in data["incidents"]:
|
||||
try:
|
||||
incidents.append(
|
||||
Incident(
|
||||
title=raw.get("title", "Unknown incident"),
|
||||
root_cause=raw.get("root_cause"),
|
||||
severity=raw.get("severity", "P2"),
|
||||
suggested_fix=raw.get("suggested_fix"),
|
||||
primary_service=raw.get("primary_service", "unknown"),
|
||||
pattern_indices=raw.get("pattern_indices", []),
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Skipping malformed incident entry: %s — %s", raw, exc)
|
||||
|
||||
return IncidentAnalysis(incidents=incidents, used_llm=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fallback grouper
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _fallback_group_by_service(patterns: list[dict]) -> IncidentAnalysis:
|
||||
"""Group patterns by service name when the LLM is unavailable.
|
||||
|
||||
Each unique service becomes one P2 incident containing all of that
|
||||
service's pattern indices.
|
||||
|
||||
Args:
|
||||
patterns: List of error pattern dicts (must include 'service' key).
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis with used_llm=False.
|
||||
"""
|
||||
service_to_indices: dict[str, list[int]] = defaultdict(list)
|
||||
for idx, pattern in enumerate(patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
service_to_indices[service].append(idx)
|
||||
|
||||
incidents = [
|
||||
Incident(
|
||||
title=f"Errors in {service}",
|
||||
root_cause=None,
|
||||
severity="P2",
|
||||
suggested_fix=None,
|
||||
primary_service=service,
|
||||
pattern_indices=indices,
|
||||
)
|
||||
for service, indices in service_to_indices.items()
|
||||
]
|
||||
|
||||
return IncidentAnalysis(incidents=incidents, used_llm=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Main analysis functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_ANALYZE_SYSTEM_PROMPT = f"""\
|
||||
You are an expert site-reliability engineer for Nomad Karaoke, a karaoke video
|
||||
generation platform running on Google Cloud Platform.
|
||||
|
||||
Your task is to analyse a list of active error patterns detected across
|
||||
production services, group them into meaningful incidents, and identify root
|
||||
causes.
|
||||
|
||||
## Service dependency map
|
||||
|
||||
{SERVICE_DEPENDENCY_MAP}
|
||||
|
||||
## Severity definitions
|
||||
|
||||
- P0: Service is completely down / total outage
|
||||
- P1: Major pipeline broken — orders cannot complete
|
||||
- P2: Degraded performance — some orders affected
|
||||
- P3: Minor / cosmetic issue with no direct user impact
|
||||
|
||||
## Output format
|
||||
|
||||
Respond with a single JSON object (no markdown fencing) with this schema:
|
||||
|
||||
{{
|
||||
"incidents": [
|
||||
{{
|
||||
"title": "<short human-readable title>",
|
||||
"root_cause": "<root cause or null>",
|
||||
"severity": "P0|P1|P2|P3",
|
||||
"suggested_fix": "<actionable suggestion or null>",
|
||||
"primary_service": "<service name>",
|
||||
"pattern_indices": [<list of 0-based indices from the input list>]
|
||||
}}
|
||||
]
|
||||
}}
|
||||
|
||||
Group related patterns together into a single incident where they share a
|
||||
common root cause (e.g., a downstream dependency failure). Unrelated patterns
|
||||
should be in separate incidents. Every input pattern must appear in exactly
|
||||
one incident.
|
||||
"""
|
||||
|
||||
_DEDUP_SYSTEM_PROMPT = """\
|
||||
You are an expert at identifying near-duplicate error patterns in production
|
||||
monitoring systems.
|
||||
|
||||
Your task is to compare a list of NEW error patterns against a list of
|
||||
EXISTING (canonical) patterns and identify which new patterns are essentially
|
||||
duplicates of existing ones — i.e., they describe the same underlying error
|
||||
but with slightly different wording due to variation in log messages.
|
||||
|
||||
## Output format
|
||||
|
||||
Respond with a single JSON object (no markdown fencing) with this schema:
|
||||
|
||||
{
|
||||
"duplicates": [
|
||||
{
|
||||
"canonical_index": <0-based index into the EXISTING patterns list>,
|
||||
"duplicate_indices": [<0-based indices into the NEW patterns list>],
|
||||
"reason": "<brief explanation>"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
If no duplicates are found, return {"duplicates": []}.
|
||||
"""
|
||||
|
||||
|
||||
def analyze_patterns(patterns: list[dict]) -> IncidentAnalysis | None:
|
||||
"""Group error patterns into incidents using Gemini LLM analysis.
|
||||
|
||||
Returns None if there are fewer than MIN_PATTERNS_FOR_ANALYSIS patterns.
|
||||
Falls back to service-based grouping when the LLM fails or returns an
|
||||
unparseable response.
|
||||
|
||||
Args:
|
||||
patterns: List of error pattern dicts to analyse.
|
||||
|
||||
Returns:
|
||||
IncidentAnalysis, or None if insufficient patterns.
|
||||
"""
|
||||
if len(patterns) < MIN_PATTERNS_FOR_ANALYSIS:
|
||||
return None
|
||||
|
||||
user_prompt = _build_analyze_user_prompt(patterns)
|
||||
|
||||
try:
|
||||
raw_response = _call_llm(_ANALYZE_SYSTEM_PROMPT, user_prompt, temperature=0.2)
|
||||
result = _parse_llm_response(raw_response)
|
||||
if result is not None:
|
||||
return result
|
||||
|
||||
logger.warning("LLM returned unparseable response; falling back to service grouping")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("LLM analysis failed: %s — falling back to service grouping", exc)
|
||||
|
||||
return _fallback_group_by_service(patterns)
|
||||
|
||||
|
||||
def find_duplicate_patterns(
|
||||
new_patterns: list[dict],
|
||||
existing_patterns: list[dict],
|
||||
) -> list[DuplicateGroup]:
|
||||
"""Identify near-duplicate patterns that the regex normalizer missed.
|
||||
|
||||
Returns an empty list if either input list is empty, or if the LLM call
|
||||
fails for any reason.
|
||||
|
||||
Args:
|
||||
new_patterns: Newly detected error patterns to check.
|
||||
existing_patterns: Currently tracked (canonical) error patterns.
|
||||
|
||||
Returns:
|
||||
List of DuplicateGroup objects (may be empty).
|
||||
"""
|
||||
if not new_patterns or not existing_patterns:
|
||||
return []
|
||||
|
||||
user_prompt = _build_dedup_user_prompt(new_patterns, existing_patterns)
|
||||
|
||||
try:
|
||||
raw_response = _call_llm(_DEDUP_SYSTEM_PROMPT, user_prompt, temperature=0.1)
|
||||
return _parse_duplicate_response(raw_response)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Duplicate detection LLM call failed: %s", exc)
|
||||
return []
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prompt builders
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _build_analyze_user_prompt(patterns: list[dict]) -> str:
|
||||
"""Build the user prompt listing patterns for incident grouping."""
|
||||
lines = ["Error patterns to analyse:\n"]
|
||||
for idx, pattern in enumerate(patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
count = pattern.get("count", 0)
|
||||
lines.append(f"[{idx}] service={service!r} count={count} message={message!r}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _build_dedup_user_prompt(
|
||||
new_patterns: list[dict],
|
||||
existing_patterns: list[dict],
|
||||
) -> str:
|
||||
"""Build the user prompt listing existing and new patterns for dedup."""
|
||||
lines = ["EXISTING (canonical) patterns:\n"]
|
||||
for idx, pattern in enumerate(existing_patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
lines.append(f"[{idx}] service={service!r} message={message!r}")
|
||||
|
||||
lines.append("\nNEW patterns to check:\n")
|
||||
for idx, pattern in enumerate(new_patterns):
|
||||
service = pattern.get("service", "unknown")
|
||||
message = pattern.get("normalized_message", "")
|
||||
lines.append(f"[{idx}] service={service!r} message={message!r}")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _parse_duplicate_response(text: str) -> list[DuplicateGroup]:
|
||||
"""Parse the LLM response for duplicate detection.
|
||||
|
||||
Args:
|
||||
text: Raw LLM output.
|
||||
|
||||
Returns:
|
||||
List of DuplicateGroup objects, or [] on any failure.
|
||||
"""
|
||||
if not text:
|
||||
return []
|
||||
|
||||
cleaned = _strip_markdown_code_block(text)
|
||||
|
||||
try:
|
||||
data = json.loads(cleaned)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Dedup LLM returned non-JSON: %.200s", text)
|
||||
return []
|
||||
|
||||
if "duplicates" not in data:
|
||||
logger.warning("Dedup LLM response missing 'duplicates' key")
|
||||
return []
|
||||
|
||||
groups: list[DuplicateGroup] = []
|
||||
for raw in data["duplicates"]:
|
||||
try:
|
||||
groups.append(
|
||||
DuplicateGroup(
|
||||
canonical_index=int(raw["canonical_index"]),
|
||||
duplicate_indices=list(raw.get("duplicate_indices", [])),
|
||||
reason=raw.get("reason", ""),
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Skipping malformed duplicate entry: %s — %s", raw, exc)
|
||||
|
||||
return groups
|
||||
@@ -1,641 +0,0 @@
|
||||
"""Monitor orchestrator for the production error monitoring service.
|
||||
|
||||
This is the main entry point. Run as::
|
||||
|
||||
python -m backend.services.error_monitor.monitor
|
||||
|
||||
The ``ErrorMonitor.run()`` method executes the full pipeline:
|
||||
|
||||
* Monitor cycle (default) — query Cloud Logging, detect new patterns, send
|
||||
Discord alerts, check auto-resolution.
|
||||
* Daily digest mode (``DIGEST_MODE=true``) — bundle 24h stats into one message.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any
|
||||
|
||||
from google.cloud import logging as cloud_logging
|
||||
from google.cloud import secretmanager
|
||||
|
||||
from backend.services.error_monitor.config import (
|
||||
GCP_PROJECT,
|
||||
LOOKBACK_MINUTES,
|
||||
MAX_LOG_ENTRIES,
|
||||
MONITORED_CLOUD_FUNCTIONS,
|
||||
MONITORED_CLOUD_RUN_JOBS,
|
||||
MONITORED_CLOUD_RUN_SERVICES,
|
||||
MONITORED_GCE_INSTANCES,
|
||||
SPIKE_MIN_COUNT,
|
||||
SPIKE_MULTIPLIER,
|
||||
get_digest_mode,
|
||||
get_discord_webhook_secret_name,
|
||||
get_llm_enabled,
|
||||
)
|
||||
from backend.services.error_monitor.discord import (
|
||||
ErrorMonitorDiscord,
|
||||
format_auto_resolved_alert,
|
||||
format_daily_digest,
|
||||
format_incident_alert,
|
||||
format_new_pattern_alert,
|
||||
format_spike_alert,
|
||||
)
|
||||
from backend.services.error_monitor.firestore_adapter import (
|
||||
ErrorPatternsAdapter,
|
||||
PatternData,
|
||||
UpsertResult,
|
||||
)
|
||||
from backend.services.error_monitor.known_issues import should_ignore
|
||||
from backend.services.error_monitor.llm_analysis import analyze_patterns, find_duplicate_patterns
|
||||
from backend.services.error_monitor.normalizer import compute_pattern_hash, normalize_message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Module-level constants
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: Maps log resource type → (label_key, service_name_list)
|
||||
RESOURCE_TYPE_FILTERS: dict[str, tuple[str, list[str]]] = {
|
||||
"cloud_run_revision": ("resource.labels.service_name", MONITORED_CLOUD_RUN_SERVICES),
|
||||
"cloud_run_job": ("resource.labels.job_name", MONITORED_CLOUD_RUN_JOBS),
|
||||
"cloud_function": ("resource.labels.function_name", MONITORED_CLOUD_FUNCTIONS),
|
||||
"gce_instance": ('labels."compute.googleapis.com/resource_name"', MONITORED_GCE_INSTANCES),
|
||||
}
|
||||
|
||||
#: Maps log resource type → canonical resource_type string stored in Firestore.
|
||||
RESOURCE_TYPE_MAP: dict[str, str] = {
|
||||
"cloud_run_revision": "cloud_run_service",
|
||||
"cloud_run_job": "cloud_run_job",
|
||||
"cloud_function": "cloud_function",
|
||||
"gce_instance": "gce_instance",
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Free functions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _build_log_filter(
|
||||
resource_type: str,
|
||||
resource_names: list[str],
|
||||
lookback_minutes: int,
|
||||
) -> str:
|
||||
"""Build a Cloud Logging filter string.
|
||||
|
||||
Args:
|
||||
resource_type: GCP resource type (e.g. ``"cloud_run_revision"``).
|
||||
resource_names: List of service/job/function/instance names to include.
|
||||
lookback_minutes: How many minutes back to query.
|
||||
|
||||
Returns:
|
||||
A filter string suitable for ``logging_client.list_entries(filter_=...)``.
|
||||
"""
|
||||
label_key = RESOURCE_TYPE_FILTERS[resource_type][0]
|
||||
cutoff = datetime.now(tz=timezone.utc) - timedelta(minutes=lookback_minutes)
|
||||
cutoff_iso = cutoff.strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
name_clause = " OR ".join(f'{label_key}="{name}"' for name in resource_names)
|
||||
if len(resource_names) > 1:
|
||||
name_clause = f"({name_clause})"
|
||||
|
||||
return (
|
||||
f'resource.type="{resource_type}" '
|
||||
f"severity>=ERROR "
|
||||
f'timestamp>="{cutoff_iso}" '
|
||||
f"{name_clause}"
|
||||
)
|
||||
|
||||
|
||||
def _extract_message(entry: Any) -> str | None:
|
||||
"""Extract the log message text from a Cloud Logging entry.
|
||||
|
||||
Handles several payload shapes:
|
||||
|
||||
* ``str`` payload — returned directly.
|
||||
* ``dict`` payload — tries ``"message"``, ``"textPayload"``, ``"error"``,
|
||||
``"msg"`` keys in that order.
|
||||
* ``None`` payload — returns ``None``.
|
||||
|
||||
Args:
|
||||
entry: A Cloud Logging ``LogEntry`` object.
|
||||
|
||||
Returns:
|
||||
The message string, or ``None`` if not extractable.
|
||||
"""
|
||||
payload = entry.payload
|
||||
if payload is None:
|
||||
return None
|
||||
if isinstance(payload, str):
|
||||
return payload if payload else None
|
||||
if isinstance(payload, dict):
|
||||
for key in ("message", "textPayload", "error", "msg"):
|
||||
value = payload.get(key)
|
||||
if value:
|
||||
return str(value)
|
||||
return None
|
||||
# Fallback: convert to string representation
|
||||
text = str(payload)
|
||||
return text if text else None
|
||||
|
||||
|
||||
def _extract_service_name(entry: Any, resource_type: str) -> str:
|
||||
"""Extract the service/job/function/instance name from a log entry.
|
||||
|
||||
Args:
|
||||
entry: A Cloud Logging ``LogEntry`` object.
|
||||
resource_type: GCP log resource type string.
|
||||
|
||||
Returns:
|
||||
The service name string (falls back to ``"unknown"`` if not found).
|
||||
"""
|
||||
labels = getattr(entry.resource, "labels", {}) or {}
|
||||
entry_labels = getattr(entry, "labels", {}) or {}
|
||||
|
||||
if resource_type == "cloud_run_revision":
|
||||
return labels.get("service_name") or "unknown"
|
||||
if resource_type == "cloud_run_job":
|
||||
return labels.get("job_name") or "unknown"
|
||||
if resource_type == "cloud_function":
|
||||
return labels.get("function_name") or "unknown"
|
||||
if resource_type == "gce_instance":
|
||||
# Prefer the human-readable resource name label
|
||||
name = entry_labels.get("compute.googleapis.com/resource_name")
|
||||
if name:
|
||||
return name
|
||||
return labels.get("instance_id") or "unknown"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _classify_resource_type(log_resource_type: str) -> str:
|
||||
"""Map a Cloud Logging resource type to the canonical type stored in Firestore.
|
||||
|
||||
Args:
|
||||
log_resource_type: Raw GCP resource type (e.g. ``"cloud_run_revision"``).
|
||||
|
||||
Returns:
|
||||
Canonical resource type string (falls back to the input if not in map).
|
||||
"""
|
||||
return RESOURCE_TYPE_MAP.get(log_resource_type, log_resource_type)
|
||||
|
||||
|
||||
def _group_by_pattern(entries: list[dict]) -> dict[str, dict]:
|
||||
"""Group normalised log entries by their pattern hash.
|
||||
|
||||
Args:
|
||||
entries: List of dicts with ``service``, ``normalized``, and ``message`` keys.
|
||||
|
||||
Returns:
|
||||
Dict mapping ``pattern_id`` → group dict containing ``service``,
|
||||
``resource_type``, ``normalized``, ``sample_message``, ``count``.
|
||||
"""
|
||||
groups: dict[str, dict] = {}
|
||||
for entry in entries:
|
||||
service = entry["service"]
|
||||
normalized = entry["normalized"]
|
||||
pattern_id = compute_pattern_hash(service, normalized)
|
||||
|
||||
if pattern_id not in groups:
|
||||
groups[pattern_id] = {
|
||||
"pattern_id": pattern_id,
|
||||
"service": service,
|
||||
"resource_type": entry.get("resource_type", "unknown"),
|
||||
"normalized": normalized,
|
||||
"sample_message": entry["message"],
|
||||
"count": 0,
|
||||
}
|
||||
groups[pattern_id]["count"] += 1
|
||||
return groups
|
||||
|
||||
|
||||
def _rolling_average(rolling_counts: list[dict]) -> float:
|
||||
"""Compute the mean count from a list of rolling_count dicts.
|
||||
|
||||
Args:
|
||||
rolling_counts: List of ``{"count": int, ...}`` dicts.
|
||||
|
||||
Returns:
|
||||
The arithmetic mean as a float, or ``0.0`` for an empty list.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return 0.0
|
||||
total = sum(entry.get("count", 0) for entry in rolling_counts)
|
||||
return total / len(rolling_counts)
|
||||
|
||||
|
||||
def _is_spike(current_count: int, rolling_counts: list[dict]) -> bool:
|
||||
"""Determine whether ``current_count`` represents an error rate spike.
|
||||
|
||||
A spike is detected when:
|
||||
- ``current_count`` >= ``SPIKE_MIN_COUNT`` (avoids noise from rare errors), AND
|
||||
- ``current_count`` > ``rolling_average * SPIKE_MULTIPLIER``
|
||||
|
||||
Args:
|
||||
current_count: Error count in the current monitoring window.
|
||||
rolling_counts: Historical rolling counts from Firestore.
|
||||
|
||||
Returns:
|
||||
``True`` if a spike is detected, ``False`` otherwise.
|
||||
"""
|
||||
if not rolling_counts:
|
||||
return False
|
||||
if current_count < SPIKE_MIN_COUNT:
|
||||
return False
|
||||
avg = _rolling_average(rolling_counts)
|
||||
if avg == 0.0:
|
||||
return False
|
||||
return current_count > avg * SPIKE_MULTIPLIER
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ErrorMonitor class
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ErrorMonitor:
|
||||
"""Orchestrates the full production error monitoring pipeline.
|
||||
|
||||
On each run (typically every 15 minutes via Cloud Scheduler), it:
|
||||
|
||||
1. Queries Cloud Logging for recent errors across all monitored services.
|
||||
2. Groups errors into patterns using normalisation + hashing.
|
||||
3. Upserts patterns to Firestore, tracking new vs. recurrent.
|
||||
4. Optionally uses an LLM to deduplicate patterns and create incidents.
|
||||
5. Sends Discord alerts for new patterns, incidents, and spikes.
|
||||
6. Auto-resolves patterns that have been silent long enough.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.logging_client = cloud_logging.Client(project=GCP_PROJECT)
|
||||
self.firestore_adapter = ErrorPatternsAdapter()
|
||||
self.discord = ErrorMonitorDiscord(webhook_url=self._get_discord_webhook())
|
||||
|
||||
def _get_discord_webhook(self) -> str:
|
||||
"""Retrieve the Discord webhook URL.
|
||||
|
||||
Checks ``DISCORD_WEBHOOK_URL`` environment variable first; falls back
|
||||
to Secret Manager.
|
||||
|
||||
Returns:
|
||||
Discord webhook URL string.
|
||||
"""
|
||||
url = os.environ.get("DISCORD_WEBHOOK_URL")
|
||||
if url:
|
||||
return url
|
||||
|
||||
secret_name = get_discord_webhook_secret_name()
|
||||
client = secretmanager.SecretManagerServiceClient()
|
||||
secret_path = f"projects/{GCP_PROJECT}/secrets/{secret_name}/versions/latest"
|
||||
response = client.access_secret_version(name=secret_path)
|
||||
return response.payload.data.decode("utf-8").strip()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Main entry point
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def run(self) -> None:
|
||||
"""Execute the monitor pipeline (digest or cycle mode)."""
|
||||
if get_digest_mode():
|
||||
self._run_daily_digest()
|
||||
else:
|
||||
self._run_monitor_cycle()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Monitor cycle
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _run_monitor_cycle(self) -> None:
|
||||
"""Execute one monitor cycle: collect → group → upsert → alert → auto-resolve."""
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
now_iso = now.isoformat()
|
||||
|
||||
# ── Step 1: Collect log entries ────────────────────────────────────
|
||||
raw_entries: list[dict] = []
|
||||
for resource_type, (_, resource_names) in RESOURCE_TYPE_FILTERS.items():
|
||||
log_filter = _build_log_filter(resource_type, resource_names, LOOKBACK_MINUTES)
|
||||
logger.info("Querying %s with filter: %s", resource_type, log_filter)
|
||||
try:
|
||||
entries = self.logging_client.list_entries(
|
||||
filter_=log_filter,
|
||||
max_results=MAX_LOG_ENTRIES,
|
||||
)
|
||||
for entry in entries:
|
||||
message = _extract_message(entry)
|
||||
if not message:
|
||||
continue
|
||||
service = _extract_service_name(entry, resource_type)
|
||||
ignore_reason = should_ignore(service, message)
|
||||
if ignore_reason:
|
||||
logger.debug(
|
||||
"Ignoring entry from %s (%s): %s",
|
||||
service,
|
||||
ignore_reason.pattern_name,
|
||||
ignore_reason.reason,
|
||||
)
|
||||
continue
|
||||
normalized = normalize_message(message)
|
||||
if not normalized:
|
||||
continue
|
||||
raw_entries.append(
|
||||
{
|
||||
"service": service,
|
||||
"resource_type": _classify_resource_type(resource_type),
|
||||
"normalized": normalized,
|
||||
"message": message,
|
||||
}
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("Failed to query %s logs: %s", resource_type, exc)
|
||||
|
||||
logger.info("Collected %d log entries after filtering", len(raw_entries))
|
||||
|
||||
# ── Step 2: Group by pattern ───────────────────────────────────────
|
||||
groups = _group_by_pattern(raw_entries)
|
||||
logger.info("Grouped into %d distinct patterns", len(groups))
|
||||
|
||||
if not groups:
|
||||
logger.info("No new error entries found this cycle; checking auto-resolve.")
|
||||
self._check_auto_resolve()
|
||||
return
|
||||
|
||||
# ── Step 3: Upsert to Firestore ────────────────────────────────────
|
||||
new_pattern_ids: list[str] = []
|
||||
spike_patterns: list[dict] = []
|
||||
|
||||
for pattern_id, group in groups.items():
|
||||
data = PatternData(
|
||||
pattern_id=pattern_id,
|
||||
service=group["service"],
|
||||
resource_type=group["resource_type"],
|
||||
normalized_message=group["normalized"],
|
||||
sample_message=group["sample_message"],
|
||||
count=group["count"],
|
||||
timestamp=now,
|
||||
)
|
||||
result: UpsertResult = self.firestore_adapter.upsert_pattern(data)
|
||||
if result.is_new:
|
||||
new_pattern_ids.append(pattern_id)
|
||||
logger.info("New pattern detected: %s (%s)", pattern_id, group["service"])
|
||||
|
||||
# Check for spike on existing patterns
|
||||
existing = self.firestore_adapter.get_pattern(pattern_id)
|
||||
if existing and not result.is_new:
|
||||
rolling = existing.get("rolling_counts") or []
|
||||
if _is_spike(group["count"], rolling):
|
||||
spike_patterns.append(
|
||||
{
|
||||
"service": group["service"],
|
||||
"normalized_message": group["normalized"],
|
||||
"current_count": group["count"],
|
||||
"rolling_average": _rolling_average(rolling),
|
||||
}
|
||||
)
|
||||
logger.info("Spike detected for pattern %s", pattern_id)
|
||||
|
||||
# ── Step 4: LLM dedup ─────────────────────────────────────────────
|
||||
if new_pattern_ids and get_llm_enabled():
|
||||
new_patterns_data = [
|
||||
{
|
||||
"service": groups[pid]["service"],
|
||||
"normalized_message": groups[pid]["normalized"],
|
||||
"count": groups[pid]["count"],
|
||||
}
|
||||
for pid in new_pattern_ids
|
||||
]
|
||||
existing_patterns = self.firestore_adapter.get_active_patterns()
|
||||
# Exclude newly added patterns from the canonical list
|
||||
canonical = [p for p in existing_patterns if p.get("pattern_id") not in new_pattern_ids]
|
||||
|
||||
if canonical:
|
||||
duplicate_groups = find_duplicate_patterns(new_patterns_data, canonical)
|
||||
for dup_group in duplicate_groups:
|
||||
# Merge each duplicate new pattern into the canonical
|
||||
canonical_pattern = canonical[dup_group.canonical_index]
|
||||
canonical_id = canonical_pattern.get("pattern_id", "")
|
||||
for dup_idx in dup_group.duplicate_indices:
|
||||
if dup_idx < len(new_pattern_ids):
|
||||
dup_id = new_pattern_ids[dup_idx]
|
||||
logger.info(
|
||||
"Merging duplicate pattern %s into %s: %s",
|
||||
dup_id,
|
||||
canonical_id,
|
||||
dup_group.reason,
|
||||
)
|
||||
self.firestore_adapter.merge_pattern(dup_id, canonical_id, dup_group.reason)
|
||||
# Remove from new_pattern_ids since it was merged
|
||||
new_pattern_ids = [pid for pid in new_pattern_ids if pid != dup_id]
|
||||
|
||||
# ── Step 5: LLM incident analysis ─────────────────────────────────
|
||||
incident_pattern_ids: set[str] = set()
|
||||
|
||||
if len(new_pattern_ids) >= 2 and get_llm_enabled():
|
||||
patterns_for_analysis = [
|
||||
{
|
||||
"service": groups[pid]["service"],
|
||||
"normalized_message": groups[pid]["normalized"],
|
||||
"count": groups[pid]["count"],
|
||||
}
|
||||
for pid in new_pattern_ids
|
||||
if pid in groups
|
||||
]
|
||||
analysis = analyze_patterns(patterns_for_analysis)
|
||||
|
||||
if analysis and analysis.incidents:
|
||||
for incident in analysis.incidents:
|
||||
incident_pids = [
|
||||
new_pattern_ids[idx]
|
||||
for idx in incident.pattern_indices
|
||||
if idx < len(new_pattern_ids)
|
||||
]
|
||||
if not incident_pids:
|
||||
continue
|
||||
|
||||
incident_id = self.firestore_adapter.create_incident(
|
||||
title=incident.title,
|
||||
root_cause=incident.root_cause or "",
|
||||
severity=incident.severity,
|
||||
suggested_fix=incident.suggested_fix or "",
|
||||
primary_service=incident.primary_service,
|
||||
pattern_ids=incident_pids,
|
||||
used_llm=analysis.used_llm,
|
||||
)
|
||||
logger.info(
|
||||
"Created incident %s (%s) with %d patterns",
|
||||
incident_id,
|
||||
incident.severity,
|
||||
len(incident_pids),
|
||||
)
|
||||
|
||||
# Build pattern list for the Discord alert
|
||||
pattern_dicts = [
|
||||
{
|
||||
"service": groups[pid]["service"],
|
||||
"normalized_message": groups[pid]["normalized"],
|
||||
"count": groups[pid]["count"],
|
||||
}
|
||||
for pid in incident_pids
|
||||
if pid in groups
|
||||
]
|
||||
msg = format_incident_alert(
|
||||
title=incident.title,
|
||||
severity=incident.severity,
|
||||
root_cause=incident.root_cause or "Unknown",
|
||||
suggested_fix=incident.suggested_fix or "Investigate logs",
|
||||
primary_service=incident.primary_service,
|
||||
patterns=pattern_dicts,
|
||||
)
|
||||
if self.discord.send_message(msg):
|
||||
for pid in incident_pids:
|
||||
try:
|
||||
self.firestore_adapter.update_pattern_alerted(pid)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Could not update alerted_at for %s: %s", pid, exc)
|
||||
|
||||
incident_pattern_ids.update(incident_pids)
|
||||
|
||||
# ── Step 6: Individual alerts for new patterns not in incidents ────
|
||||
for pattern_id in new_pattern_ids:
|
||||
if pattern_id in incident_pattern_ids:
|
||||
continue
|
||||
if pattern_id not in groups:
|
||||
continue
|
||||
group = groups[pattern_id]
|
||||
|
||||
# Fetch fresh copy to get first_seen timestamp
|
||||
existing = self.firestore_adapter.get_pattern(pattern_id)
|
||||
first_seen = existing.get("first_seen", now_iso) if existing else now_iso
|
||||
|
||||
msg = format_new_pattern_alert(
|
||||
service=group["service"],
|
||||
resource_type=group["resource_type"],
|
||||
normalized_message=group["normalized"],
|
||||
sample_message=group["sample_message"],
|
||||
count=group["count"],
|
||||
first_seen=first_seen,
|
||||
)
|
||||
if self.discord.send_message(msg):
|
||||
try:
|
||||
self.firestore_adapter.update_pattern_alerted(pattern_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Could not update alerted_at for %s: %s", pattern_id, exc)
|
||||
|
||||
# ── Step 7: Spike alerts ───────────────────────────────────────────
|
||||
for spike in spike_patterns:
|
||||
msg = format_spike_alert(
|
||||
service=spike["service"],
|
||||
normalized_message=spike["normalized_message"],
|
||||
current_count=spike["current_count"],
|
||||
rolling_average=spike["rolling_average"],
|
||||
)
|
||||
self.discord.send_message(msg)
|
||||
|
||||
# ── Step 8: Auto-resolve check ─────────────────────────────────────
|
||||
self._check_auto_resolve()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Auto-resolve helper
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _check_auto_resolve(self) -> None:
|
||||
"""Check all active patterns for auto-resolution and send a consolidated alert."""
|
||||
patterns = self.firestore_adapter.get_patterns_for_auto_resolve()
|
||||
resolved: list[dict] = []
|
||||
|
||||
for pattern in patterns:
|
||||
pattern_id = pattern.get("pattern_id", "")
|
||||
hours_silent = self.firestore_adapter.check_auto_resolve(pattern)
|
||||
if hours_silent is not None:
|
||||
logger.info(
|
||||
"Auto-resolving pattern %s (silent %.1f hours)", pattern_id, hours_silent
|
||||
)
|
||||
self.firestore_adapter.auto_resolve_pattern(pattern_id, round(hours_silent, 1))
|
||||
resolved.append(
|
||||
{
|
||||
"service": pattern.get("service", "unknown"),
|
||||
"message": pattern.get("normalized_message", ""),
|
||||
"hours_silent": round(hours_silent, 1),
|
||||
}
|
||||
)
|
||||
|
||||
if resolved:
|
||||
msg = format_auto_resolved_alert(resolved)
|
||||
self.discord.send_message(msg)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Daily digest
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _run_daily_digest(self) -> None:
|
||||
"""Gather 24h stats and send a daily digest to Discord."""
|
||||
# Optional dedup sweep (best-effort; LLM errors are non-fatal)
|
||||
if get_llm_enabled():
|
||||
try:
|
||||
active = self.firestore_adapter.get_active_patterns()
|
||||
if len(active) >= 2:
|
||||
mid = len(active) // 2
|
||||
duplicates = find_duplicate_patterns(active[:mid], active[mid:])
|
||||
for dup in duplicates:
|
||||
for idx in dup.duplicate_indices:
|
||||
target_half = active[mid:]
|
||||
source_half = active[:mid]
|
||||
if idx < len(target_half) and dup.canonical_index < len(source_half):
|
||||
self.firestore_adapter.merge_pattern(
|
||||
target_half[idx]["pattern_id"],
|
||||
source_half[dup.canonical_index]["pattern_id"],
|
||||
dup.reason,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("Digest dedup sweep failed (non-fatal): %s", exc)
|
||||
|
||||
# Gather stats from active patterns
|
||||
active_patterns = self.firestore_adapter.get_active_patterns()
|
||||
per_service_counts: dict[str, int] = {}
|
||||
new_count = 0
|
||||
total_errors = 0
|
||||
|
||||
for pattern in active_patterns:
|
||||
service = pattern.get("service", "unknown")
|
||||
count = pattern.get("total_count", 0)
|
||||
per_service_counts[service] = per_service_counts.get(service, 0) + count
|
||||
total_errors += count
|
||||
if pattern.get("status") == "new":
|
||||
new_count += 1
|
||||
|
||||
# Count recently auto-resolved patterns
|
||||
resolved_patterns = self.firestore_adapter.get_patterns_for_auto_resolve()
|
||||
resolved_count = sum(
|
||||
1
|
||||
for p in resolved_patterns
|
||||
if self.firestore_adapter.check_auto_resolve(p) is not None
|
||||
)
|
||||
|
||||
msg = format_daily_digest(
|
||||
total_errors=total_errors,
|
||||
new_patterns=new_count,
|
||||
resolved_patterns=resolved_count,
|
||||
active_patterns=len(active_patterns),
|
||||
per_service_counts=per_service_counts,
|
||||
)
|
||||
self.discord.send_message(msg)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Configure logging and run the error monitor."""
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
||||
)
|
||||
monitor = ErrorMonitor()
|
||||
monitor.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,137 +0,0 @@
|
||||
"""Message normalizer for the production error monitoring service.
|
||||
|
||||
Replaces variable parts of error messages (IDs, timestamps, paths, etc.)
|
||||
with stable placeholders so the same logical error always produces the same
|
||||
pattern hash, regardless of which specific resource or timestamp was involved.
|
||||
|
||||
Normalizer rules are applied in order — more specific patterns first.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
|
||||
from backend.services.error_monitor.config import MAX_NORMALIZED_MESSAGE_LENGTH
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compiled regex patterns (applied in order — more specific first)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_NORMALIZERS: list[tuple[re.Pattern, str]] = [
|
||||
# 1. GCS paths: gs://bucket/path/to/object → gs://<BUCKET>/<PATH>
|
||||
# Must come before Firestore and URL normalization.
|
||||
(
|
||||
re.compile(r"gs://([^/\s]+)/([^\s]+)"),
|
||||
r"gs://<BUCKET>/<PATH>",
|
||||
),
|
||||
# 1b. GCS bucket root (no object path): gs://bucket/ or gs://bucket
|
||||
# Uses a lookahead so the slash/end-of-string is not consumed, and uses
|
||||
# a character class that excludes '<' to avoid re-matching placeholders.
|
||||
(
|
||||
re.compile(r"gs://([^/<\s]+)(?=[/\s]|$)"),
|
||||
r"gs://<BUCKET>",
|
||||
),
|
||||
# 2. Firestore document paths (collection/doc/…/doc — at least 2 segments)
|
||||
# Negative lookbehind for '.' prevents matching inside domain names (URLs).
|
||||
# Negative lookbehind for '/' prevents matching inside already-replaced paths.
|
||||
(
|
||||
re.compile(
|
||||
r"(?<![./])\b([a-zA-Z_][a-zA-Z0-9_-]*/[a-zA-Z0-9_-]+(?:/[a-zA-Z0-9_-]+){1,})\b"
|
||||
),
|
||||
r"<DOC_PATH>",
|
||||
),
|
||||
# 3. UUIDs (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
|
||||
(
|
||||
re.compile(
|
||||
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"
|
||||
),
|
||||
"<ID>",
|
||||
),
|
||||
# 4. ISO 8601 timestamps (2024-01-15T10:30:45Z / …+05:30 / ….123Z)
|
||||
(
|
||||
re.compile(
|
||||
r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})"
|
||||
),
|
||||
"<TS>",
|
||||
),
|
||||
# 5. Epoch timestamps: 10+ digit number optionally followed by fractional seconds
|
||||
(
|
||||
re.compile(r"\b\d{10,}(?:\.\d+)?\b"),
|
||||
"<EPOCH>",
|
||||
),
|
||||
# 6. Email addresses
|
||||
(
|
||||
re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b"),
|
||||
"<EMAIL>",
|
||||
),
|
||||
# 7. IP addresses (IPv4) — must come before large-number replacement
|
||||
(
|
||||
re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"),
|
||||
"<IP>",
|
||||
),
|
||||
# 8. URLs — strip to domain only (https://host/path → https://host)
|
||||
# Handles http and https; preserves the scheme+domain for context.
|
||||
(
|
||||
re.compile(r"https?://([A-Za-z0-9.\-]+(:\d+)?)/[^\s]*"),
|
||||
r"https://\1",
|
||||
),
|
||||
# 9. Job IDs in paths (/jobs/<alphanumeric>)
|
||||
(
|
||||
re.compile(r"/jobs/[A-Za-z0-9]+"),
|
||||
"/jobs/<ID>",
|
||||
),
|
||||
# 10. Firebase UIDs (20–28 mixed-case alphanumeric characters)
|
||||
# Firebase Auth UIDs are typically 28 chars; allow 20-28 for flexibility.
|
||||
# Must contain both letters and digits (to avoid replacing plain words).
|
||||
(
|
||||
re.compile(r"\b(?=[A-Za-z0-9]{20,28}\b)(?=[A-Za-z0-9]*[A-Z])(?=[A-Za-z0-9]*[a-z])(?=[A-Za-z0-9]*\d)[A-Za-z0-9]{20,28}\b"),
|
||||
"<UID>",
|
||||
),
|
||||
# 11. Hex/alphanumeric IDs: 8+ chars containing both letters and digits
|
||||
# (e.g. git SHAs, Cloud Run revision IDs, job IDs)
|
||||
# Uses a lookahead to require at least one digit AND one letter.
|
||||
(
|
||||
re.compile(r"\b(?=[a-fA-F0-9]*[a-fA-F][a-fA-F0-9]*\d|[a-fA-F0-9]*\d[a-fA-F0-9]*[a-fA-F])[a-fA-F0-9]{8,}\b"),
|
||||
"<ID>",
|
||||
),
|
||||
# 12. Large numbers (4+ digits) — must come after epoch/IP/UUID replacements
|
||||
(
|
||||
re.compile(r"\b\d{4,}\b"),
|
||||
"<NUM>",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def normalize_message(message: str) -> str:
|
||||
"""Normalize a raw log message by replacing variable parts with placeholders.
|
||||
|
||||
Applies each normalizer rule in order (more specific patterns first) and
|
||||
truncates the result to MAX_NORMALIZED_MESSAGE_LENGTH characters.
|
||||
|
||||
Args:
|
||||
message: Raw log message string.
|
||||
|
||||
Returns:
|
||||
Normalized message string, at most MAX_NORMALIZED_MESSAGE_LENGTH chars.
|
||||
"""
|
||||
if not message:
|
||||
return ""
|
||||
|
||||
result = message
|
||||
for pattern, replacement in _NORMALIZERS:
|
||||
result = pattern.sub(replacement, result)
|
||||
|
||||
return result[:MAX_NORMALIZED_MESSAGE_LENGTH]
|
||||
|
||||
|
||||
def compute_pattern_hash(service: str, normalized_message: str) -> str:
|
||||
"""Compute a stable SHA-256 fingerprint for an error pattern.
|
||||
|
||||
Args:
|
||||
service: The originating service name (e.g. "karaoke-backend").
|
||||
normalized_message: The output of normalize_message().
|
||||
|
||||
Returns:
|
||||
64-character lowercase hex SHA-256 digest.
|
||||
"""
|
||||
payload = f"{service}:{normalized_message}"
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
||||
@@ -1,141 +0,0 @@
|
||||
"""Service for generating personalized referral flyer PDFs."""
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), "..", "templates", "printables")
|
||||
|
||||
CHROMIUM_PATHS = [
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
"/usr/bin/google-chrome",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
]
|
||||
|
||||
VALID_THEMES = {"light", "dark"}
|
||||
MAX_QR_DATA_URL_BYTES = 500_000
|
||||
|
||||
|
||||
class FlyerError(Exception):
|
||||
"""Error during flyer generation."""
|
||||
|
||||
|
||||
class FlyerService:
|
||||
"""Generates personalized referral flyer PDFs."""
|
||||
|
||||
def __init__(self):
|
||||
self._chromium_path: str | None = None
|
||||
|
||||
def _get_chromium(self) -> str:
|
||||
"""Lazily find Chromium binary. Only needed when generating PDFs."""
|
||||
if self._chromium_path:
|
||||
return self._chromium_path
|
||||
for path in CHROMIUM_PATHS:
|
||||
if os.path.exists(path):
|
||||
self._chromium_path = path
|
||||
return path
|
||||
for name in ["chromium", "chromium-browser", "google-chrome"]:
|
||||
found = shutil.which(name)
|
||||
if found:
|
||||
self._chromium_path = found
|
||||
return found
|
||||
raise FlyerError("Chromium not found. Install chromium to generate flyer PDFs.")
|
||||
|
||||
def _validate_qr_data_url(self, qr_data_url: str) -> None:
|
||||
if not qr_data_url.startswith("data:image/"):
|
||||
raise FlyerError("Invalid QR data URL: must be a data:image/ URL")
|
||||
if len(qr_data_url) > MAX_QR_DATA_URL_BYTES:
|
||||
raise FlyerError(f"QR data URL too large (>{MAX_QR_DATA_URL_BYTES} bytes)")
|
||||
|
||||
def _render_template(
|
||||
self,
|
||||
theme: str,
|
||||
referral_code: str,
|
||||
discount_percent: int,
|
||||
qr_data_url: str,
|
||||
) -> str:
|
||||
if theme not in VALID_THEMES:
|
||||
raise FlyerError(f"Invalid theme: {theme}. Must be one of: {VALID_THEMES}")
|
||||
|
||||
suffix = "-dark" if theme == "dark" else ""
|
||||
template_path = os.path.join(TEMPLATE_DIR, f"website-referral-flyer{suffix}.html")
|
||||
|
||||
with open(template_path) as f:
|
||||
html = f.read()
|
||||
|
||||
html = html.replace("{{REFERRAL_CODE}}", referral_code.upper())
|
||||
html = html.replace("{{REFERRAL_CODE_LOWER}}", referral_code.lower())
|
||||
html = html.replace("{{DISCOUNT_PERCENT}}", str(discount_percent))
|
||||
html = html.replace("{{QR_DATA_URL}}", qr_data_url)
|
||||
|
||||
return html
|
||||
|
||||
def generate_pdf(
|
||||
self,
|
||||
theme: str,
|
||||
referral_code: str,
|
||||
discount_percent: int,
|
||||
qr_data_url: str,
|
||||
) -> bytes:
|
||||
"""Generate a personalized flyer PDF. Returns raw PDF bytes."""
|
||||
self._validate_qr_data_url(qr_data_url)
|
||||
html = self._render_template(theme, referral_code, discount_percent, qr_data_url)
|
||||
|
||||
with tempfile.NamedTemporaryFile(
|
||||
suffix=".html", delete=False, mode="w", encoding="utf-8"
|
||||
) as tmp_html:
|
||||
tmp_html.write(html)
|
||||
tmp_html_path = tmp_html.name
|
||||
|
||||
tmp_pdf_path = tmp_html_path.replace(".html", ".pdf")
|
||||
|
||||
try:
|
||||
cmd = [
|
||||
self._get_chromium(),
|
||||
"--headless",
|
||||
f"--print-to-pdf={tmp_pdf_path}",
|
||||
"--no-margins",
|
||||
"--print-background",
|
||||
"--no-pdf-header-footer",
|
||||
"--virtual-time-budget=5000",
|
||||
"--paper-width=8.5",
|
||||
"--paper-height=11",
|
||||
"--disable-gpu",
|
||||
"--no-sandbox",
|
||||
tmp_html_path,
|
||||
]
|
||||
|
||||
result = subprocess.run(
|
||||
cmd, capture_output=True, text=True, timeout=30
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
logger.error("Chromium PDF generation failed: %s", result.stderr)
|
||||
raise FlyerError(f"PDF generation failed: {result.stderr[:200]}")
|
||||
|
||||
if not os.path.exists(tmp_pdf_path):
|
||||
raise FlyerError("PDF generation failed: no output file created")
|
||||
|
||||
with open(tmp_pdf_path, "rb") as f:
|
||||
return f.read()
|
||||
|
||||
finally:
|
||||
for path in [tmp_html_path, tmp_pdf_path]:
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
_flyer_service = None
|
||||
|
||||
|
||||
def get_flyer_service() -> FlyerService:
|
||||
global _flyer_service
|
||||
if _flyer_service is None:
|
||||
_flyer_service = FlyerService()
|
||||
return _flyer_service
|
||||
@@ -242,11 +242,7 @@ class ReferralService:
|
||||
if not expires_at:
|
||||
return False
|
||||
if isinstance(expires_at, datetime):
|
||||
now = datetime.utcnow()
|
||||
# Firestore returns timezone-aware datetimes; ensure comparison is compatible
|
||||
if expires_at.tzinfo is not None:
|
||||
now = now.replace(tzinfo=expires_at.tzinfo)
|
||||
return expires_at > now
|
||||
return expires_at > datetime.utcnow()
|
||||
return False
|
||||
|
||||
def get_discount_for_checkout(self, user_email: str) -> Optional[dict]:
|
||||
@@ -339,24 +335,6 @@ class ReferralService:
|
||||
return None, None
|
||||
return self.stripe_service.create_connect_account(email)
|
||||
|
||||
def get_connect_account_status(self, account_id: str) -> Optional[dict]:
|
||||
"""Get Stripe Connect account status."""
|
||||
if not self.stripe_service:
|
||||
return None
|
||||
return self.stripe_service.get_connect_account_status(account_id)
|
||||
|
||||
def create_connect_login_link(self, account_id: str) -> Optional[str]:
|
||||
"""Create login link for Stripe Express dashboard."""
|
||||
if not self.stripe_service:
|
||||
return None
|
||||
return self.stripe_service.create_connect_login_link(account_id)
|
||||
|
||||
def create_connect_update_link(self, account_id: str) -> Optional[str]:
|
||||
"""Create account link for updating Connect info."""
|
||||
if not self.stripe_service:
|
||||
return None
|
||||
return self.stripe_service.create_connect_update_link(account_id)
|
||||
|
||||
def get_pending_earnings(self, referrer_email: str) -> List[dict]:
|
||||
"""Get all pending earnings for a referrer."""
|
||||
query = (
|
||||
@@ -443,17 +421,11 @@ class ReferralService:
|
||||
# total_paid = total_earned - pending (since total_earned tracks all time)
|
||||
total_paid = total_earned - pending_balance
|
||||
|
||||
# Check Connect status and fetch account details
|
||||
# Check Connect status
|
||||
from backend.services.user_service import get_user_service
|
||||
user = get_user_service().get_user(user_email)
|
||||
has_connect = bool(user and user.stripe_connect_account_id)
|
||||
|
||||
connect_account = None
|
||||
if has_connect and self.stripe_service:
|
||||
connect_account = self.stripe_service.get_connect_account_status(
|
||||
user.stripe_connect_account_id
|
||||
)
|
||||
|
||||
return {
|
||||
"link": {
|
||||
"code": link.code,
|
||||
@@ -491,7 +463,6 @@ class ReferralService:
|
||||
for p in payouts
|
||||
],
|
||||
"stripe_connect_configured": has_connect,
|
||||
"stripe_connect_account": connect_account,
|
||||
}
|
||||
|
||||
def list_links(self, limit: int = 50, offset: int = 0) -> list[ReferralLink]:
|
||||
|
||||
@@ -6,7 +6,6 @@ Handles:
|
||||
- Processing webhook events
|
||||
- Managing customer records
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional, Dict, Any, Tuple
|
||||
@@ -291,10 +290,7 @@ class StripeService:
|
||||
event = stripe.Webhook.construct_event(
|
||||
payload, signature, self.webhook_secret
|
||||
)
|
||||
# Convert Stripe Event object to plain dict — Stripe SDK v14+
|
||||
# returns StripeObject instances that don't support .get()
|
||||
event_dict = json.loads(str(event))
|
||||
return True, event_dict, "Webhook verified"
|
||||
return True, event, "Webhook verified"
|
||||
except stripe.error.SignatureVerificationError as e:
|
||||
logger.error(f"Invalid webhook signature: {e}")
|
||||
return False, None, "Invalid signature"
|
||||
@@ -396,8 +392,8 @@ class StripeService:
|
||||
)
|
||||
account_link = stripe.AccountLink.create(
|
||||
account=account.id,
|
||||
refresh_url=f"{self.frontend_url}/app/referrals?connect=refresh",
|
||||
return_url=f"{self.frontend_url}/app/referrals?connect=complete",
|
||||
refresh_url=f"{self.frontend_url}/app?tab=referrals&connect=refresh",
|
||||
return_url=f"{self.frontend_url}/app?tab=referrals&connect=complete",
|
||||
type="account_onboarding",
|
||||
)
|
||||
logger.info(f"Created Connect account {account.id} for {email}")
|
||||
@@ -406,50 +402,6 @@ class StripeService:
|
||||
logger.error(f"Failed to create Connect account for {email}: {e}")
|
||||
return None, None
|
||||
|
||||
def get_connect_account_status(self, account_id: str) -> Optional[dict]:
|
||||
"""Retrieve Stripe Connect account status. Returns dict with account details."""
|
||||
if not self.is_configured():
|
||||
return None
|
||||
try:
|
||||
account = stripe.Account.retrieve(account_id)
|
||||
return {
|
||||
"account_id": account.id,
|
||||
"charges_enabled": account.charges_enabled,
|
||||
"payouts_enabled": account.payouts_enabled,
|
||||
"details_submitted": account.details_submitted,
|
||||
"email": account.email,
|
||||
}
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to retrieve Connect account {account_id}: {e}")
|
||||
return None
|
||||
|
||||
def create_connect_login_link(self, account_id: str) -> Optional[str]:
|
||||
"""Create a login link to the Stripe Express dashboard. Returns URL."""
|
||||
if not self.is_configured():
|
||||
return None
|
||||
try:
|
||||
link = stripe.Account.create_login_link(account_id)
|
||||
return link.url
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to create login link for {account_id}: {e}")
|
||||
return None
|
||||
|
||||
def create_connect_update_link(self, account_id: str) -> Optional[str]:
|
||||
"""Create an account link for updating Connect account info. Returns URL."""
|
||||
if not self.is_configured():
|
||||
return None
|
||||
try:
|
||||
account_link = stripe.AccountLink.create(
|
||||
account=account_id,
|
||||
refresh_url=f"{self.frontend_url}/app/referrals?connect=refresh",
|
||||
return_url=f"{self.frontend_url}/app/referrals?connect=complete",
|
||||
type="account_onboarding",
|
||||
)
|
||||
return account_link.url
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to create update link for {account_id}: {e}")
|
||||
return None
|
||||
|
||||
def create_transfer(self, amount_cents: int, destination_account_id: str, description: str = "Nomad Karaoke referral payout") -> Optional[str]:
|
||||
"""Create a transfer to a Connect account. Returns transfer ID."""
|
||||
if not self.is_configured():
|
||||
|
||||
@@ -13,7 +13,6 @@ import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Optional, List, Tuple
|
||||
|
||||
from google.api_core import exceptions as google_exceptions
|
||||
from google.cloud import firestore
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
from google.cloud.firestore_v1 import Increment
|
||||
@@ -532,7 +531,6 @@ class UserService:
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("signup_ip", "==", ip_address))
|
||||
.where(filter=FieldFilter("created_at", ">=", cutoff))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
)
|
||||
|
||||
count = 0
|
||||
@@ -564,7 +562,6 @@ class UserService:
|
||||
self.db.collection(USERS_COLLECTION)
|
||||
.where(filter=FieldFilter("device_fingerprint", "==", device_fingerprint))
|
||||
.where(filter=FieldFilter("created_at", ">=", cutoff))
|
||||
.order_by("created_at", direction=firestore.Query.DESCENDING)
|
||||
)
|
||||
|
||||
count = 0
|
||||
@@ -1002,7 +999,7 @@ class UserService:
|
||||
'amount': amount,
|
||||
'processed_at': datetime.utcnow()
|
||||
})
|
||||
except google_exceptions.AlreadyExists:
|
||||
except Exception:
|
||||
# Document already exists - this session was already processed
|
||||
logger.info(f"Stripe session {stripe_session_id} already processed (idempotent skip)")
|
||||
return False, 0, "Session already processed"
|
||||
|
||||
@@ -1,362 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Nomad Karaoke - Make Your Own Karaoke Videos</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
*, html { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
@page {
|
||||
size: 8.5in 11in;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 8.5in;
|
||||
height: 11in;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
font-family: 'Outfit', sans-serif;
|
||||
background: #0c0a1a;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Dark atmospheric background */
|
||||
.bg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
radial-gradient(ellipse 80% 50% at 50% 0%, rgba(120, 40, 200, 0.35) 0%, transparent 70%),
|
||||
radial-gradient(ellipse 60% 40% at 20% 80%, rgba(255, 50, 120, 0.2) 0%, transparent 60%),
|
||||
radial-gradient(ellipse 50% 30% at 85% 70%, rgba(255, 180, 40, 0.15) 0%, transparent 60%),
|
||||
linear-gradient(180deg, #0c0a1a 0%, #1a1035 40%, #0c0a1a 100%);
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.content {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 0.6in 0.65in 0.5in;
|
||||
}
|
||||
|
||||
/* Logo at top */
|
||||
.logo-container {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.logo-svg {
|
||||
width: 260px;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
/* Headline */
|
||||
.headline {
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
text-align: center;
|
||||
line-height: 0.92;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.headline-main {
|
||||
font-size: 96px;
|
||||
letter-spacing: 3px;
|
||||
background: linear-gradient(180deg, #ffd86b 0%, #ff7acc 50%, #c45aff 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.headline-sub {
|
||||
font-size: 62px;
|
||||
letter-spacing: 2px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* Subtitle */
|
||||
.subtitle {
|
||||
font-size: 20px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
text-align: center;
|
||||
max-width: 5.5in;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
/* Steps section */
|
||||
.steps {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
width: 100%;
|
||||
max-width: 6in;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.step-number {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
flex-shrink: 0;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, #c45aff, #ff7acc);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
font-size: 30px;
|
||||
color: #fff;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.step-content {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.step-title {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
color: #fff;
|
||||
letter-spacing: -0.3px;
|
||||
}
|
||||
|
||||
.step-desc {
|
||||
font-size: 16px;
|
||||
font-weight: 400;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* Divider */
|
||||
.divider {
|
||||
width: 80%;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 122, 204, 0.4), rgba(255, 216, 107, 0.4), transparent);
|
||||
margin: 4px 0 24px;
|
||||
}
|
||||
|
||||
/* CTA section */
|
||||
.cta-section {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 40px;
|
||||
width: 100%;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.qr-container {
|
||||
width: 180px;
|
||||
height: 180px;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
border: 3px solid rgba(255, 255, 255, 0.15);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.06);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.qr-container img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.qr-placeholder {
|
||||
font-size: 14px;
|
||||
color: #999;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.cta-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.cta-label {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 2px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.cta-url {
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
font-size: 38px;
|
||||
letter-spacing: 2px;
|
||||
color: #ffd86b;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cta-url .referral-code {
|
||||
background: linear-gradient(135deg, #ff7acc 0%, #c45aff 40%, #ff5a8a 70%, #ffdf6b 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
letter-spacing: 4px;
|
||||
}
|
||||
|
||||
.cta-note {
|
||||
font-size: 15px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
margin-top: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Bottom section */
|
||||
.bottom {
|
||||
margin-top: auto;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.bottom-features {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.bottom-feature {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.bottom-feature-icon {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.bottom-tagline {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
|
||||
@media print {
|
||||
body {
|
||||
-webkit-print-color-adjust: exact;
|
||||
print-color-adjust: exact;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="bg"></div>
|
||||
|
||||
<div class="content">
|
||||
<!-- Logo -->
|
||||
<div class="logo-container">
|
||||
<svg class="logo-svg" viewBox="45 60 255 135" xmlns="http://www.w3.org/2000/svg">
|
||||
<g fill="#ff7acc" transform="translate(48.368003845214844,62.62239074707031)"><g transform="translate(0,0)"><g transform="scale(1.4000000000000004)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill-opacity="0"><path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)"></path></g><g transform="translate(0,38.959999084472656)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill="#ff7acc" fill-opacity="0" transform="scale(1.02719)"><path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)"></path></g></g></g></g>
|
||||
<g fill-rule="" fill="#ffdf6b" transform="translate(5,111.788818359375)"><rect x="0" height="1" y="5.9832000732421875" width="14.278396606445312"></rect><rect height="1" y="5.9832000732421875" width="14.278396606445312" x="218.985595703125"></rect><g transform="translate(17.278396606445312,0)"><g transform="scale(1.2800000000000002)"><path d="M10.21-8.38L12.02-8.38L9.68 0L7.70 0L6.13-5.96L4.49 0L2.52 0.01L0.26-8.38L2.06-8.38L3.54-1.87L5.24-8.38L7.12-8.38L8.72-1.91L10.21-8.38ZM18.38-8.38L20.06-8.38L20.06 0L18.38 0L18.38-3.56L14.80-3.56L14.80 0L13.12 0L13.12-8.38L14.80-8.38L14.80-4.93L18.38-4.93L18.38-8.38ZM26.58-7.02L23.40-7.02L23.40-4.92L26.22-4.92L26.22-3.59L23.40-3.59L23.40-1.37L26.58-1.37L26.58 0L21.72 0L21.72-8.39L26.58-8.39L26.58-7.02ZM34.37 0L32.42 0L30.58-3.26L29.78-3.26L29.78 0L28.10 0L28.10-8.38L31.25-8.38Q32.22-8.38 32.90-8.03Q33.59-7.69 33.93-7.11Q34.27-6.53 34.27-5.81L34.27-5.81Q34.27-4.98 33.79-4.31Q33.31-3.65 32.36-3.40L32.36-3.40L34.37 0ZM29.78-6.98L29.78-4.52L31.19-4.52Q31.87-4.52 32.21-4.85Q32.54-5.18 32.54-5.77L32.54-5.77Q32.54-6.35 32.21-6.67Q31.87-6.98 31.19-6.98L31.19-6.98L29.78-6.98ZM40.66-7.02L37.48-7.02L37.48-4.92L40.30-4.92L40.30-3.59L37.48-3.59L37.48-1.37L40.66-1.37L40.66 0L35.80 0L35.80-8.39L40.66-8.39L40.66-7.02ZM47.92-8.38L49.70-8.38L46.63 0L44.59 0L41.52-8.38L43.32-8.38L45.62-1.72L47.92-8.38ZM55.57-7.02L52.39-7.02L52.39-4.92L55.21-4.92L55.21-3.59L52.39-3.59L52.39-1.37L55.57-1.37L55.57 0L50.71 0L50.71-8.39L55.57-8.39L55.57-7.02ZM63.36 0L61.42 0L59.57-3.26L58.78-3.26L58.78 0L57.10 0L57.10-8.38L60.24-8.38Q61.21-8.38 61.90-8.03Q62.58-7.69 62.92-7.11Q63.26-6.53 63.26-5.81L63.26-5.81Q63.26-4.98 62.78-4.31Q62.30-3.65 61.36-3.40L61.36-3.40L63.36 0ZM58.78-6.98L58.78-4.52L60.18-4.52Q60.86-4.52 61.20-4.85Q61.54-5.18 61.54-5.77L61.54-5.77Q61.54-6.35 61.20-6.67Q60.86-6.98 60.18-6.98L60.18-6.98L58.78-6.98ZM72.43-8.38L74.30-8.38L71.47-2.92L71.47 0L69.79 0L69.79-2.92L66.95-8.38L68.84-8.38L70.64-4.55L72.43-8.38ZM79.16 0.08Q77.99 0.08 77.00-0.47Q76.02-1.02 75.44-2.00Q74.87-2.98 74.87-4.21L74.87-4.21Q74.87-5.44 75.44-6.41Q76.02-7.39 77.00-7.94Q77.99-8.50 79.16-8.50L79.16-8.50Q80.35-8.50 81.33-7.94Q82.31-7.39 82.88-6.41Q83.45-5.44 83.45-4.21L83.45-4.21Q83.45-2.98 82.88-2.00Q82.31-1.02 81.32-0.47Q80.34 0.08 79.16 0.08L79.16 0.08ZM79.16-1.42Q79.92-1.42 80.50-1.76Q81.07-2.10 81.40-2.74Q81.72-3.37 81.72-4.21L81.72-4.21Q81.72-5.05 81.40-5.68Q81.07-6.31 80.50-6.65Q79.92-6.98 79.16-6.98L79.16-6.98Q78.41-6.98 77.83-6.65Q77.24-6.31 76.92-5.68Q76.60-5.05 76.60-4.21L76.60-4.21Q76.60-3.37 76.92-2.74Q77.24-2.10 77.83-1.76Q78.41-1.42 79.16-1.42L79.16-1.42ZM84.67-8.38L86.35-8.38L86.35-3.19Q86.35-2.34 86.80-1.89Q87.24-1.44 88.04-1.44L88.04-1.44Q88.86-1.44 89.30-1.89Q89.75-2.34 89.75-3.19L89.75-3.19L89.75-8.38L91.44-8.38L91.44-3.20Q91.44-2.14 90.98-1.40Q90.52-0.66 89.74-0.29Q88.97 0.08 88.02 0.08L88.02 0.08Q87.08 0.08 86.32-0.29Q85.56-0.66 85.12-1.40Q84.67-2.14 84.67-3.20L84.67-3.20L84.67-8.38ZM101.60 0L101.05-1.60L97.72-1.60L97.16 0L95.40 0L98.41-8.39L100.37-8.39L103.38 0L101.60 0ZM98.17-2.94L100.60-2.94L99.38-6.44L98.17-2.94ZM110.77 0L108.83 0L106.98-3.26L106.19-3.26L106.19 0L104.51 0L104.51-8.38L107.65-8.38Q108.62-8.38 109.31-8.03Q109.99-7.69 110.33-7.11Q110.68-6.53 110.68-5.81L110.68-5.81Q110.68-4.98 110.20-4.31Q109.72-3.65 108.77-3.40L108.77-3.40L110.77 0ZM106.19-6.98L106.19-4.52L107.59-4.52Q108.28-4.52 108.61-4.85Q108.95-5.18 108.95-5.77L108.95-5.77Q108.95-6.35 108.61-6.67Q108.28-6.98 107.59-6.98L107.59-6.98L106.19-6.98ZM117.06-7.02L113.88-7.02L113.88-4.92L116.70-4.92L116.70-3.59L113.88-3.59L113.88-1.37L117.06-1.37L117.06 0L112.20 0L112.20-8.39L117.06-8.39L117.06-7.02ZM118.72-1.76L120.42-1.76L119.02 1.61L117.94 1.61L118.72-1.76ZM127.38 0.08Q126.50 0.08 125.80-0.22Q125.10-0.52 124.69-1.08Q124.28-1.64 124.27-2.41L124.27-2.41L126.07-2.41Q126.11-1.90 126.44-1.60Q126.77-1.30 127.34-1.30L127.34-1.30Q127.93-1.30 128.27-1.58Q128.60-1.86 128.60-2.32L128.60-2.32Q128.60-2.69 128.38-2.93Q128.15-3.17 127.81-3.31Q127.46-3.44 126.86-3.61L126.86-3.61Q126.05-3.85 125.54-4.09Q125.03-4.32 124.66-4.79Q124.30-5.27 124.30-6.06L124.30-6.06Q124.30-6.80 124.67-7.36Q125.04-7.91 125.71-8.20Q126.38-8.50 127.25-8.50L127.25-8.50Q128.54-8.50 129.35-7.87Q130.16-7.24 130.25-6.11L130.25-6.11L128.40-6.11Q128.38-6.54 128.03-6.82Q127.69-7.10 127.13-7.10L127.13-7.10Q126.64-7.10 126.34-6.85Q126.05-6.60 126.05-6.12L126.05-6.12Q126.05-5.78 126.27-5.56Q126.49-5.34 126.82-5.20Q127.15-5.06 127.75-4.88L127.75-4.88Q128.57-4.64 129.08-4.40Q129.60-4.16 129.97-3.68Q130.34-3.20 130.34-2.42L130.34-2.42Q130.34-1.75 130.00-1.18Q129.65-0.60 128.98-0.26Q128.30 0.08 127.38 0.08L127.38 0.08ZM131.80-8.38L133.48-8.38L133.48 0L131.80 0L131.80-8.38ZM142.30-8.39L142.30 0L140.62 0L136.81-5.75L136.81 0L135.13 0L135.13-8.39L136.81-8.39L140.62-2.63L140.62-8.39L142.30-8.39ZM151.72-5.86L149.78-5.86Q149.50-6.38 148.99-6.66Q148.49-6.94 147.82-6.94L147.82-6.94Q147.07-6.94 146.50-6.60Q145.92-6.26 145.60-5.64Q145.27-5.02 145.27-4.20L145.27-4.20Q145.27-3.36 145.60Line truncated
|
||||
</svg>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Headline -->
|
||||
<div class="headline">
|
||||
<div class="headline-main">MAKE YOUR OWN</div>
|
||||
<div class="headline-sub">KARAOKE VIDEOS</div>
|
||||
</div>
|
||||
|
||||
<!-- Subtitle -->
|
||||
<div class="subtitle">
|
||||
Turn any song into a professional karaoke video with synced lyrics, vocal removal, and automatic YouTube publishing.
|
||||
</div>
|
||||
|
||||
<!-- How it works -->
|
||||
<div class="steps">
|
||||
<div class="step">
|
||||
<div class="step-number">1</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Pick any song</div>
|
||||
<div class="step-desc">Search by artist & title or paste a YouTube link</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">2</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Our system does the work</div>
|
||||
<div class="step-desc">Vocals removed, lyrics synced, video rendered automatically</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">3</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Review & correct the lyrics and instrumental</div>
|
||||
<div class="step-desc">Fine-tune everything before publishing</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">4</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Download or publish to YouTube</div>
|
||||
<div class="step-desc">Get your finished karaoke video in minutes</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- CTA with QR code -->
|
||||
<div class="cta-section">
|
||||
<div class="qr-container">
|
||||
<!-- Replace src with actual QR code image path -->
|
||||
<img src="{{QR_DATA_URL}}" alt="QR Code - nomadkaraoke.com/r/{{REFERRAL_CODE_LOWER}}">
|
||||
</div>
|
||||
<div class="cta-text">
|
||||
<div class="cta-label">First track free + {{DISCOUNT_PERCENT}}% off with this link</div>
|
||||
<div class="cta-url">NOMADKARAOKE.COM/R/<span class="referral-code">{{REFERRAL_CODE}}</span></div>
|
||||
<div class="cta-note">Scan the QR code or visit the link above</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom -->
|
||||
<div class="bottom">
|
||||
<div class="bottom-features">
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">🎤</span>
|
||||
<span>Any Song</span>
|
||||
</div>
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">⚡</span>
|
||||
<span>Automatic</span>
|
||||
</div>
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">🎬</span>
|
||||
<span>Pro Quality</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bottom-tagline">Wherever you are, sing!</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,359 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Nomad Karaoke - Make Your Own Karaoke Videos</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
*, html { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
@page {
|
||||
size: 8.5in 11in;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 8.5in;
|
||||
height: 11in;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
font-family: 'Outfit', sans-serif;
|
||||
background: #faf8f5;
|
||||
color: #1a1a1a;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Simple gradient background */
|
||||
.bg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(180deg, #faf8f5 0%, #f3eff8 100%);
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.content {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 0.6in 0.65in 0.5in;
|
||||
}
|
||||
|
||||
/* Logo at top */
|
||||
.logo-container {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.logo-svg {
|
||||
width: 260px;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
/* Headline */
|
||||
.headline {
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
text-align: center;
|
||||
line-height: 0.92;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.headline-main {
|
||||
font-size: 96px;
|
||||
letter-spacing: 3px;
|
||||
background: linear-gradient(135deg, #c45aff 0%, #ff7acc 50%, #ff5a8a 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.headline-sub {
|
||||
font-size: 62px;
|
||||
letter-spacing: 2px;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
|
||||
/* Subtitle */
|
||||
.subtitle {
|
||||
font-size: 20px;
|
||||
font-weight: 500;
|
||||
color: #555;
|
||||
text-align: center;
|
||||
max-width: 5.5in;
|
||||
line-height: 1.4;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
/* Steps section */
|
||||
.steps {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
width: 100%;
|
||||
max-width: 6in;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.step-number {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
flex-shrink: 0;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, #c45aff, #ff7acc);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
font-size: 30px;
|
||||
color: #fff;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.step-content {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.step-title {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
color: #1a1a1a;
|
||||
letter-spacing: -0.3px;
|
||||
}
|
||||
|
||||
.step-desc {
|
||||
font-size: 16px;
|
||||
font-weight: 400;
|
||||
color: #666;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* Divider */
|
||||
.divider {
|
||||
width: 80%;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, rgba(196, 90, 255, 0.3), rgba(255, 122, 204, 0.3), transparent);
|
||||
margin: 4px 0 24px;
|
||||
}
|
||||
|
||||
/* CTA section */
|
||||
.cta-section {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 40px;
|
||||
width: 100%;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.qr-container {
|
||||
width: 180px;
|
||||
height: 180px;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
border: 3px solid #e8e4e0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
box-shadow: 0 4px 20px rgba(0,0,0,0.06);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.qr-container img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.qr-placeholder {
|
||||
font-size: 14px;
|
||||
color: #999;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.cta-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.cta-label {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #888;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 2px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.cta-url {
|
||||
font-family: 'Bebas Neue', sans-serif;
|
||||
font-size: 38px;
|
||||
letter-spacing: 2px;
|
||||
color: #1a1a1a;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cta-url .referral-code {
|
||||
background: linear-gradient(135deg, #ff7acc 0%, #c45aff 40%, #ff5a8a 70%, #ffdf6b 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
letter-spacing: 4px;
|
||||
}
|
||||
|
||||
.cta-note {
|
||||
font-size: 15px;
|
||||
color: #888;
|
||||
margin-top: 8px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* Bottom section */
|
||||
.bottom {
|
||||
margin-top: auto;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.bottom-features {
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.bottom-feature {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.bottom-feature-icon {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.bottom-tagline {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #aaa;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
|
||||
@media print {
|
||||
body {
|
||||
-webkit-print-color-adjust: exact;
|
||||
print-color-adjust: exact;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="bg"></div>
|
||||
|
||||
<div class="content">
|
||||
<!-- Logo -->
|
||||
<div class="logo-container">
|
||||
<svg class="logo-svg" viewBox="45 60 255 135" xmlns="http://www.w3.org/2000/svg">
|
||||
<g fill="#ff7acc" transform="translate(48.368003845214844,62.62239074707031)"><g transform="translate(0,0)"><g transform="scale(1.4000000000000004)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill-opacity="0"><path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)"></path></g><g transform="translate(0,38.959999084472656)"><g stroke="#ff7acc" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" paint-order="stroke" fill="#ff7acc" fill-opacity="0" transform="scale(1.02719)"><path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)"></path></g></g></g></g>
|
||||
<g fill-rule="" fill="#ffdf6b" transform="translate(5,111.788818359375)"><rect x="0" height="1" y="5.9832000732421875" width="14.278396606445312"></rect><rect height="1" y="5.9832000732421875" width="14.278396606445312" x="218.985595703125"></rect><g transform="translate(17.278396606445312,0)"><g transform="scale(1.2800000000000002)"><path d="M10.21-8.38L12.02-8.38L9.68 0L7.70 0L6.13-5.96L4.49 0L2.52 0.01L0.26-8.38L2.06-8.38L3.54-1.87L5.24-8.38L7.12-8.38L8.72-1.91L10.21-8.38ZM18.38-8.38L20.06-8.38L20.06 0L18.38 0L18.38-3.56L14.80-3.56L14.80 0L13.12 0L13.12-8.38L14.80-8.38L14.80-4.93L18.38-4.93L18.38-8.38ZM26.58-7.02L23.40-7.02L23.40-4.92L26.22-4.92L26.22-3.59L23.40-3.59L23.40-1.37L26.58-1.37L26.58 0L21.72 0L21.72-8.39L26.58-8.39L26.58-7.02ZM34.37 0L32.42 0L30.58-3.26L29.78-3.26L29.78 0L28.10 0L28.10-8.38L31.25-8.38Q32.22-8.38 32.90-8.03Q33.59-7.69 33.93-7.11Q34.27-6.53 34.27-5.81L34.27-5.81Q34.27-4.98 33.79-4.31Q33.31-3.65 32.36-3.40L32.36-3.40L34.37 0ZM29.78-6.98L29.78-4.52L31.19-4.52Q31.87-4.52 32.21-4.85Q32.54-5.18 32.54-5.77L32.54-5.77Q32.54-6.35 32.21-6.67Q31.87-6.98 31.19-6.98L31.19-6.98L29.78-6.98ZM40.66-7.02L37.48-7.02L37.48-4.92L40.30-4.92L40.30-3.59L37.48-3.59L37.48-1.37L40.66-1.37L40.66 0L35.80 0L35.80-8.39L40.66-8.39L40.66-7.02ZM47.92-8.38L49.70-8.38L46.63 0L44.59 0L41.52-8.38L43.32-8.38L45.62-1.72L47.92-8.38ZM55.57-7.02L52.39-7.02L52.39-4.92L55.21-4.92L55.21-3.59L52.39-3.59L52.39-1.37L55.57-1.37L55.57 0L50.71 0L50.71-8.39L55.57-8.39L55.57-7.02ZM63.36 0L61.42 0L59.57-3.26L58.78-3.26L58.78 0L57.10 0L57.10-8.38L60.24-8.38Q61.21-8.38 61.90-8.03Q62.58-7.69 62.92-7.11Q63.26-6.53 63.26-5.81L63.26-5.81Q63.26-4.98 62.78-4.31Q62.30-3.65 61.36-3.40L61.36-3.40L63.36 0ZM58.78-6.98L58.78-4.52L60.18-4.52Q60.86-4.52 61.20-4.85Q61.54-5.18 61.54-5.77L61.54-5.77Q61.54-6.35 61.20-6.67Q60.86-6.98 60.18-6.98L60.18-6.98L58.78-6.98ZM72.43-8.38L74.30-8.38L71.47-2.92L71.47 0L69.79 0L69.79-2.92L66.95-8.38L68.84-8.38L70.64-4.55L72.43-8.38ZM79.16 0.08Q77.99 0.08 77.00-0.47Q76.02-1.02 75.44-2.00Q74.87-2.98 74.87-4.21L74.87-4.21Q74.87-5.44 75.44-6.41Q76.02-7.39 77.00-7.94Q77.99-8.50 79.16-8.50L79.16-8.50Q80.35-8.50 81.33-7.94Q82.31-7.39 82.88-6.41Q83.45-5.44 83.45-4.21L83.45-4.21Q83.45-2.98 82.88-2.00Q82.31-1.02 81.32-0.47Q80.34 0.08 79.16 0.08L79.16 0.08ZM79.16-1.42Q79.92-1.42 80.50-1.76Q81.07-2.10 81.40-2.74Q81.72-3.37 81.72-4.21L81.72-4.21Q81.72-5.05 81.40-5.68Q81.07-6.31 80.50-6.65Q79.92-6.98 79.16-6.98L79.16-6.98Q78.41-6.98 77.83-6.65Q77.24-6.31 76.92-5.68Q76.60-5.05 76.60-4.21L76.60-4.21Q76.60-3.37 76.92-2.74Q77.24-2.10 77.83-1.76Q78.41-1.42 79.16-1.42L79.16-1.42ZM84.67-8.38L86.35-8.38L86.35-3.19Q86.35-2.34 86.80-1.89Q87.24-1.44 88.04-1.44L88.04-1.44Q88.86-1.44 89.30-1.89Q89.75-2.34 89.75-3.19L89.75-3.19L89.75-8.38L91.44-8.38L91.44-3.20Q91.44-2.14 90.98-1.40Q90.52-0.66 89.74-0.29Q88.97 0.08 88.02 0.08L88.02 0.08Q87.08 0.08 86.32-0.29Q85.56-0.66 85.12-1.40Q84.67-2.14 84.67-3.20L84.67-3.20L84.67-8.38ZM101.60 0L101.05-1.60L97.72-1.60L97.16 0L95.40 0L98.41-8.39L100.37-8.39L103.38 0L101.60 0ZM98.17-2.94L100.60-2.94L99.38-6.44L98.17-2.94ZM110.77 0L108.83 0L106.98-3.26L106.19-3.26L106.19 0L104.51 0L104.51-8.38L107.65-8.38Q108.62-8.38 109.31-8.03Q109.99-7.69 110.33-7.11Q110.68-6.53 110.68-5.81L110.68-5.81Q110.68-4.98 110.20-4.31Q109.72-3.65 108.77-3.40L108.77-3.40L110.77 0ZM106.19-6.98L106.19-4.52L107.59-4.52Q108.28-4.52 108.61-4.85Q108.95-5.18 108.95-5.77L108.95-5.77Q108.95-6.35 108.61-6.67Q108.28-6.98 107.59-6.98L107.59-6.98L106.19-6.98ZM117.06-7.02L113.88-7.02L113.88-4.92L116.70-4.92L116.70-3.59L113.88-3.59L113.88-1.37L117.06-1.37L117.06 0L112.20 0L112.20-8.39L117.06-8.39L117.06-7.02ZM118.72-1.76L120.42-1.76L119.02 1.61L117.94 1.61L118.72-1.76ZM127.38 0.08Q126.50 0.08 125.80-0.22Q125.10-0.52 124.69-1.08Q124.28-1.64 124.27-2.41L124.27-2.41L126.07-2.41Q126.11-1.90 126.44-1.60Q126.77-1.30 127.34-1.30L127.34-1.30Q127.93-1.30 128.27-1.58Q128.60-1.86 128.60-2.32L128.60-2.32Q128.60-2.69 128.38-2.93Q128.15-3.17 127.81-3.31Q127.46-3.44 126.86-3.61L126.86-3.61Q126.05-3.85 125.54-4.09Q125.03-4.32 124.66-4.79Q124.30-5.27 124.30-6.06L124.30-6.06Q124.30-6.80 124.67-7.36Q125.04-7.91 125.71-8.20Q126.38-8.50 127.25-8.50L127.25-8.50Q128.54-8.50 129.35-7.87Q130.16-7.24 130.25-6.11L130.25-6.11L128.40-6.11Q128.38-6.54 128.03-6.82Q127.69-7.10 127.13-7.10L127.13-7.10Q126.64-7.10 126.34-6.85Q126.05-6.60 126.05-6.12L126.05-6.12Q126.05-5.78 126.27-5.56Q126.49-5.34 126.82-5.20Q127.15-5.06 127.75-4.88L127.75-4.88Q128.57-4.64 129.08-4.40Q129.60-4.16 129.97-3.68Q130.34-3.20 130.34-2.42L130.34-2.42Q130.34-1.75 130.00-1.18Q129.65-0.60 128.98-0.26Q128.30 0.08 127.38 0.08L127.38 0.08ZM131.80-8.38L133.48-8.38L133.48 0L131.80 0L131.80-8.38ZM142.30-8.39L142.30 0L140.62 0L136.81-5.75L136.81 0L135.13 0L135.13-8.39L136.81-8.39L140.62-2.63L140.62-8.39L142.30-8.39ZM151.72-5.86L149.78-5.86Q149.50-6.38 148.99-6.66Q148.49-6.94 147.82-6.94L147.82-6.94Q147.07-6.94 146.50-6.60Q145.92-6.26 145.60-5.64Q145.27-5.02 145.27-4.20L145.27-4.20Q145.27-3.36 145.60Line truncated
|
||||
</svg>
|
||||
</svg>
|
||||
</div>
|
||||
|
||||
<!-- Headline -->
|
||||
<div class="headline">
|
||||
<div class="headline-main">MAKE YOUR OWN</div>
|
||||
<div class="headline-sub">KARAOKE VIDEOS</div>
|
||||
</div>
|
||||
|
||||
<!-- Subtitle -->
|
||||
<div class="subtitle">
|
||||
Turn any song into a professional karaoke video with synced lyrics, vocal removal, and automatic YouTube publishing.
|
||||
</div>
|
||||
|
||||
<!-- How it works -->
|
||||
<div class="steps">
|
||||
<div class="step">
|
||||
<div class="step-number">1</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Pick any song</div>
|
||||
<div class="step-desc">Search by artist & title or paste a YouTube link</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">2</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Our system does the work</div>
|
||||
<div class="step-desc">Vocals removed, lyrics synced, video rendered automatically</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">3</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Review & correct the lyrics and instrumental</div>
|
||||
<div class="step-desc">Fine-tune everything before publishing</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="step">
|
||||
<div class="step-number">4</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">Download or publish to YouTube</div>
|
||||
<div class="step-desc">Get your finished karaoke video in minutes</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="divider"></div>
|
||||
|
||||
<!-- CTA with QR code -->
|
||||
<div class="cta-section">
|
||||
<div class="qr-container">
|
||||
<!-- Replace src with actual QR code image path -->
|
||||
<img src="{{QR_DATA_URL}}" alt="QR Code - nomadkaraoke.com/r/{{REFERRAL_CODE_LOWER}}">
|
||||
</div>
|
||||
<div class="cta-text">
|
||||
<div class="cta-label">First track free + {{DISCOUNT_PERCENT}}% off with this link</div>
|
||||
<div class="cta-url">NOMADKARAOKE.COM/R/<span class="referral-code">{{REFERRAL_CODE}}</span></div>
|
||||
<div class="cta-note">Scan the QR code or visit the link above</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Bottom -->
|
||||
<div class="bottom">
|
||||
<div class="bottom-features">
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">🎤</span>
|
||||
<span>Any Song</span>
|
||||
</div>
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">⚡</span>
|
||||
<span>Automatic</span>
|
||||
</div>
|
||||
<div class="bottom-feature">
|
||||
<span class="bottom-feature-icon">🎬</span>
|
||||
<span>Pro Quality</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bottom-tagline">Wherever you are, sing!</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -279,7 +279,7 @@ class TestIPRateLimiting:
|
||||
|
||||
# Simulate 2 matching users
|
||||
mock_docs = [MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.return_value.stream.return_value = mock_docs
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
@@ -297,7 +297,7 @@ class TestIPRateLimiting:
|
||||
|
||||
# 2 signups = rate limited
|
||||
mock_docs = [MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.return_value.stream.return_value = mock_docs
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
@@ -312,7 +312,7 @@ class TestIPRateLimiting:
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_docs = [MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.return_value.stream.return_value = mock_docs
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
@@ -348,7 +348,7 @@ class TestFingerprintRateLimiting:
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
mock_docs = [MagicMock(), MagicMock(), MagicMock()]
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.return_value.stream.return_value = mock_docs
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
@@ -377,7 +377,7 @@ class TestFingerprintRateLimiting:
|
||||
return iter([]) # IP query: 0 results
|
||||
return iter([MagicMock(), MagicMock()]) # Fingerprint query: 2 results
|
||||
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.return_value.stream = stream_side_effect
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream = stream_side_effect
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
@@ -396,7 +396,7 @@ class TestFingerprintRateLimiting:
|
||||
mock_fs.Client.return_value = mock_db
|
||||
|
||||
# IP query returns 0
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.return_value.stream.return_value = []
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
"""Tests for flyer PDF generation service."""
|
||||
import os
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.flyer_service import FlyerService, FlyerError
|
||||
|
||||
|
||||
class TestFlyerService:
|
||||
"""Tests for FlyerService."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = FlyerService()
|
||||
|
||||
def test_render_template_light_substitutes_placeholders(self):
|
||||
html = self.service._render_template(
|
||||
theme="light",
|
||||
referral_code="MYCODE",
|
||||
discount_percent=15,
|
||||
qr_data_url="data:image/png;base64,abc123",
|
||||
)
|
||||
assert "MYCODE" in html
|
||||
assert "{{REFERRAL_CODE}}" not in html
|
||||
assert "{{QR_DATA_URL}}" not in html
|
||||
assert "{{DISCOUNT_PERCENT}}" not in html
|
||||
assert "{{REFERRAL_CODE_LOWER}}" not in html
|
||||
assert "15% off" in html
|
||||
assert "data:image/png;base64,abc123" in html
|
||||
assert "mycode" in html # lowercase version in alt text
|
||||
|
||||
def test_render_template_dark_substitutes_placeholders(self):
|
||||
html = self.service._render_template(
|
||||
theme="dark",
|
||||
referral_code="DARKCODE",
|
||||
discount_percent=20,
|
||||
qr_data_url="data:image/png;base64,xyz789",
|
||||
)
|
||||
assert "DARKCODE" in html
|
||||
assert "{{REFERRAL_CODE}}" not in html
|
||||
assert "data:image/png;base64,xyz789" in html
|
||||
assert "20% off" in html
|
||||
|
||||
def test_render_template_invalid_theme_raises(self):
|
||||
with pytest.raises(FlyerError, match="Invalid theme"):
|
||||
self.service._render_template(
|
||||
theme="neon",
|
||||
referral_code="CODE",
|
||||
discount_percent=10,
|
||||
qr_data_url="data:image/png;base64,abc",
|
||||
)
|
||||
|
||||
def test_render_template_uppercases_referral_code(self):
|
||||
html = self.service._render_template(
|
||||
theme="light",
|
||||
referral_code="mycode",
|
||||
discount_percent=10,
|
||||
qr_data_url="data:image/png;base64,abc",
|
||||
)
|
||||
assert '<span class="referral-code">MYCODE</span>' in html
|
||||
|
||||
@patch("backend.services.flyer_service.subprocess.run")
|
||||
def test_generate_pdf_calls_chromium_with_correct_flags(self, mock_run):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
self.service._chromium_path = "/usr/bin/chromium"
|
||||
|
||||
with patch.object(self.service, "_render_template", return_value="<html>test</html>"):
|
||||
with patch("os.path.exists", return_value=True):
|
||||
with patch("builtins.open", MagicMock(return_value=MagicMock(read=MagicMock(return_value=b"%PDF")))):
|
||||
with patch("os.unlink"):
|
||||
self.service.generate_pdf(
|
||||
theme="light",
|
||||
referral_code="TEST",
|
||||
discount_percent=10,
|
||||
qr_data_url="data:image/png;base64,abc",
|
||||
)
|
||||
|
||||
call_args = mock_run.call_args[0][0]
|
||||
assert "--headless" in call_args
|
||||
assert "--no-margins" in call_args
|
||||
assert "--print-background" in call_args
|
||||
assert "--no-pdf-header-footer" in call_args
|
||||
assert "--virtual-time-budget=5000" in call_args
|
||||
assert "--paper-width=8.5" in call_args
|
||||
assert "--paper-height=11" in call_args
|
||||
|
||||
def test_validate_qr_data_url_rejects_non_data_url(self):
|
||||
with pytest.raises(FlyerError, match="Invalid QR"):
|
||||
self.service._validate_qr_data_url("https://evil.com/qr.png")
|
||||
|
||||
def test_validate_qr_data_url_rejects_too_large(self):
|
||||
huge_url = "data:image/png;base64," + "A" * 600_000
|
||||
with pytest.raises(FlyerError, match="too large"):
|
||||
self.service._validate_qr_data_url(huge_url)
|
||||
|
||||
def test_validate_qr_data_url_accepts_valid(self):
|
||||
self.service._validate_qr_data_url("data:image/png;base64,abc123")
|
||||
@@ -130,23 +130,6 @@ class TestGetInterstitial:
|
||||
data = response.json()
|
||||
assert data["valid"] is True
|
||||
|
||||
@patch("backend.api.routes.referrals.get_referral_service")
|
||||
def test_no_track_skips_click_increment(self, mock_get_service, client):
|
||||
"""no_track=true should return data without incrementing clicks."""
|
||||
mock_service = Mock()
|
||||
link = _make_referral_link()
|
||||
mock_service.get_link_by_code.return_value = link
|
||||
mock_get_service.return_value = mock_service
|
||||
|
||||
response = client.get("/api/referrals/r/abc12345?no_track=true")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["valid"] is True
|
||||
assert data["referral_code"] == "abc12345"
|
||||
assert data["referrer_display_name"] == "Test Referrer"
|
||||
mock_service.increment_clicks.assert_not_called()
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# GET /api/referrals/me - Dashboard
|
||||
|
||||
+1
-19
@@ -1894,25 +1894,7 @@ POST /api/referrals/me/connect
|
||||
Authorization: Bearer TOKEN
|
||||
```
|
||||
|
||||
Creates a Stripe Connect Express account and returns an onboarding URL. Saves the Connect account ID to the user doc. The dashboard response (`GET /api/referrals/me`) includes `stripe_connect_account` with account status details (payouts_enabled, details_submitted, etc.).
|
||||
|
||||
### Get Stripe Connect Dashboard Link
|
||||
|
||||
```http
|
||||
POST /api/referrals/me/connect/dashboard-link
|
||||
Authorization: Bearer TOKEN
|
||||
```
|
||||
|
||||
Returns a one-time login URL to the Stripe Express dashboard where the user can manage their payout settings, view transfer history, and update bank details.
|
||||
|
||||
### Get Stripe Connect Update Link
|
||||
|
||||
```http
|
||||
POST /api/referrals/me/connect/update-link
|
||||
Authorization: Bearer TOKEN
|
||||
```
|
||||
|
||||
Returns a Stripe AccountLink URL for re-onboarding — allows the user to update their bank account or complete setup if they didn't finish initially.
|
||||
Creates a Stripe Connect Express account and returns an onboarding URL. Saves the Connect account ID to the user doc.
|
||||
|
||||
### Create Vanity Link (Admin)
|
||||
|
||||
|
||||
@@ -36,21 +36,6 @@
|
||||
Uses immutable deployment pattern - see infrastructure/encoding-worker/README.md.
|
||||
```
|
||||
|
||||
### Error Monitor
|
||||
|
||||
```text
|
||||
Cloud Logging (all services) ──→ Error Monitor (Cloud Run Job, */15 min)
|
||||
│
|
||||
├─ Normalize & deduplicate
|
||||
├─ LLM incident grouping (Gemini Flash)
|
||||
├─ Discord alerts (new patterns, spikes, daily digest)
|
||||
├─ Firestore: error_patterns, error_incidents
|
||||
└─ Auto-resolve silent patterns
|
||||
|
||||
Entry point: python -m backend.services.error_monitor.monitor
|
||||
Design spec: docs/archive/2026-04-12-error-monitor-design.md
|
||||
```
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
```text
|
||||
|
||||
@@ -130,49 +130,6 @@ When two sequential human review steps can be combined into one, do it. We origi
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
### Firestore Timezone-Aware vs Naive Datetime Comparison (Apr 2026)
|
||||
**What happened**: `_build_user_public()` compared `referral_discount_expires_at` (from Firestore, timezone-aware) with `datetime.utcnow()` (naive), causing `TypeError: can't compare offset-naive and offset-aware datetimes`. This crashed the `verify_magic_link` endpoint, **blocking ALL logins for referred users** in production.
|
||||
|
||||
**Fix**: Check `expires.tzinfo` and apply it to `now` before comparing:
|
||||
```python
|
||||
now = datetime.utcnow()
|
||||
if expires.tzinfo is not None:
|
||||
now = now.replace(tzinfo=expires.tzinfo)
|
||||
has_discount = expires > now
|
||||
```
|
||||
|
||||
**Pattern**: Always handle timezone-awareness when comparing Firestore datetimes with Python datetimes. Firestore returns `DatetimeWithNanoseconds` (timezone-aware). The codebase uses `datetime.utcnow()` (naive) everywhere. Any comparison between the two will crash.
|
||||
|
||||
### Firestore Composite Indexes Must Be Created for Multi-Field Queries (Apr 2026)
|
||||
**What happened**: `get_dashboard_data()` queried `referral_earnings` with `.where("referrer_email", "==", ...).order_by("created_at", ...)` which requires a composite index. Without it, Firestore returns `FailedPrecondition: 400 The query requires an index`. This manifested as a 500 error on `/api/referrals/me` with CORS headers suppressed (frontend saw CORS error, not the real error).
|
||||
|
||||
**Fix**: Create indexes via `gcloud firestore indexes composite create`. Firestore error messages include a direct URL to create the needed index.
|
||||
|
||||
**Pattern**: Any Firestore query combining `.where()` + `.order_by()` on different fields needs a composite index. Create them proactively when adding new collection queries. Required indexes for the referral system:
|
||||
- `referral_earnings`: (referrer_email ASC, created_at DESC), (referrer_email ASC, status ASC)
|
||||
- `referral_payouts`: (referrer_email ASC, created_at DESC)
|
||||
|
||||
### Cloudflare Pages _redirects Can't Interpolate in Query Strings (Apr 2026)
|
||||
**What happened**: Tried `/r/* /en/?ref=:splat 302` in Cloudflare Pages `_redirects` file. The `:splat` was passed literally as the string `:splat` instead of being replaced with the captured wildcard value. Multiple attempts with `:code`, `:splat`, and named params all failed.
|
||||
|
||||
**Fix**: Use a Cloudflare Worker (`worker.js` with `env.ASSETS.fetch()` fallback) for any redirect that needs to inject values into query parameters. Workers have full JS string manipulation.
|
||||
|
||||
**Pattern**: Cloudflare Pages `_redirects` `:splat` substitution only works in **path segments**, not in query strings, fragments, or other URL parts. For anything beyond simple path-to-path redirects, use a Worker.
|
||||
|
||||
### Next.js Static Export Cannot Serve Dynamic Routes on Cloudflare Pages (Apr 2026)
|
||||
**What happened**: Created `/app/[locale]/r/[code]/page.tsx` for referral interstitials. Build failed: `Page "/[locale]/r/[code]" is missing "generateStaticParams()"`. Added `generateStaticParams` returning empty array — page existed at `/en/r/` but `/en/r/bevvy` still 404'd because no HTML file was generated for it.
|
||||
|
||||
**Fix**: Use a static page that reads dynamic values from **query parameters** instead of path segments. The interstitial page at `/en/r/page.tsx` reads `?code=bevvy` from `useSearchParams()`. The Cloudflare Worker redirects `/r/bevvy` → `/en/r?code=bevvy`.
|
||||
|
||||
**Pattern**: With `output: 'export'`, every URL must map to a pre-rendered HTML file. Truly dynamic paths (where you can't enumerate all values at build time) must use query params, hash fragments, or catch-all routes with known static paths.
|
||||
|
||||
### CI Deploy Cancellations Can Silently Skip Backend Deploys (Apr 2026)
|
||||
**What happened**: PR #677 merged backend changes (referral attribution fix). The CI run was cancelled by a subsequent push, and the backend deploy job was skipped. The frontend deployed (from a later PR), but the backend was still running old code. Users couldn't get referral attribution because the backend fix never deployed.
|
||||
|
||||
**Fix**: After merging backend changes, verify the deploy job completed successfully — check for `completed (cancelled)` vs `completed (success)`. If cancelled, trigger a manual re-run or push a no-op commit.
|
||||
|
||||
**Pattern**: When multiple PRs merge in quick succession, earlier CI runs get cancelled. Frontend-only PRs won't trigger backend deploys. Always verify backend deploy status after merging backend changes.
|
||||
|
||||
### Gate Resource Recycling on Full Cleanup Confirmation (Feb 2026)
|
||||
**What happened**: Brand code NOMAD-1271 was recycled and reused for a real song while old E2E test job files still existed in Google Drive, creating a duplicate in the public share.
|
||||
|
||||
|
||||
@@ -38,7 +38,6 @@
|
||||
| **Review reminder & auto-expiry** | Working (24h reminder, 48h cancel + refund) |
|
||||
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
|
||||
| **Referral system** | Working (referral links with configurable discounts, 20% cash kickback via Stripe Connect, auto-payout at $20) |
|
||||
| **Error monitor** | New (Cloud Run Job every 15 min — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
# Referral Marketing Flyer Generator — Design Spec
|
||||
|
||||
**Date:** 2026-04-05
|
||||
**Status:** Approved
|
||||
**Scope:** Backend endpoint + frontend integration in karaoke-gen
|
||||
|
||||
## Overview
|
||||
|
||||
Add a "Generate Flyer" feature to the QR Code dialog that produces a professional print-ready PDF marketing flyer personalized with the referrer's code, discount, and styled QR code. Uses the existing flyer templates from kjbox (light + dark variants), rendered server-side with headless Chromium.
|
||||
|
||||
## User Flow
|
||||
|
||||
1. User opens QR Code dialog from referral dashboard
|
||||
2. Customizes QR code style (dot style, colors, logo — already implemented)
|
||||
3. Picks flyer theme: Light or Dark
|
||||
4. Clicks "Generate Flyer"
|
||||
5. Frontend generates QR as base64 PNG data URL using current style prefs
|
||||
6. Frontend POSTs to backend with theme + QR data URL
|
||||
7. Backend injects referral code + QR + discount into HTML template
|
||||
8. Backend renders PDF with headless Chromium (same flags as kjbox)
|
||||
9. PDF returned as download: `nomad-karaoke-referral-flyer.pdf`
|
||||
|
||||
## Backend
|
||||
|
||||
### New Endpoint
|
||||
|
||||
`POST /api/referrals/me/flyer`
|
||||
|
||||
**Auth:** Requires logged-in user (same as other `/me` endpoints).
|
||||
|
||||
**Request body:**
|
||||
```json
|
||||
{
|
||||
"theme": "light" | "dark",
|
||||
"qr_data_url": "data:image/png;base64,..."
|
||||
}
|
||||
```
|
||||
|
||||
**Logic:**
|
||||
1. Look up user's referral link (code, discount_percent)
|
||||
2. Read HTML template for the selected theme
|
||||
3. Replace placeholders: `{{REFERRAL_CODE}}`, `{{QR_DATA_URL}}`, `{{DISCOUNT_PERCENT}}`
|
||||
4. Write substituted HTML to temp file
|
||||
5. Run headless Chromium to generate PDF
|
||||
6. Return PDF as `application/pdf` with `Content-Disposition: attachment`
|
||||
7. Clean up temp files
|
||||
|
||||
**Chromium command:**
|
||||
```bash
|
||||
chromium --headless --print-to-pdf=OUTPUT.pdf --no-margins --print-background \
|
||||
--no-pdf-header-footer --virtual-time-budget=5000 \
|
||||
--paper-width=8.5 --paper-height=11 INPUT.html
|
||||
```
|
||||
|
||||
**Error handling:**
|
||||
- Missing referral link → 404
|
||||
- Chromium render failure → 500 with error message
|
||||
- QR data URL too large (>500KB) → 400 validation error
|
||||
|
||||
### Template Storage
|
||||
|
||||
Two HTML files in `backend/templates/printables/`:
|
||||
- `website-referral-flyer.html` (light theme)
|
||||
- `website-referral-flyer-dark.html` (dark theme)
|
||||
|
||||
Copied from `kjbox/printables/` with three changes:
|
||||
1. Replace `ANGEL` referral code with `{{REFERRAL_CODE}}`
|
||||
2. Replace `src="qr-code-angel.svg"` with `src="{{QR_DATA_URL}}"`
|
||||
3. Replace hardcoded "10% off" CTA text with `{{DISCOUNT_PERCENT}}% off`
|
||||
|
||||
### Flyer Service
|
||||
|
||||
New file `backend/services/flyer_service.py`:
|
||||
- `generate_flyer_pdf(referral_code, discount_percent, theme, qr_data_url) -> bytes`
|
||||
- Handles template loading, placeholder substitution, temp file management, Chromium invocation
|
||||
- Returns raw PDF bytes
|
||||
|
||||
### Dockerfile Change
|
||||
|
||||
Add `chromium` to apt dependencies in `Dockerfile.base`:
|
||||
```dockerfile
|
||||
RUN apt-get update && apt-get install -y chromium && rm -rf /var/lib/apt/lists/*
|
||||
```
|
||||
|
||||
Also need to find the Chromium binary path (typically `/usr/bin/chromium` on Debian).
|
||||
|
||||
## Frontend
|
||||
|
||||
### QRCodeDialog Changes
|
||||
|
||||
Add to the dialog footer (between the controls and download buttons):
|
||||
- **Theme toggle:** Light / Dark radio buttons or segmented control
|
||||
- **"Generate Flyer" button:** Secondary button alongside existing download buttons
|
||||
|
||||
**On click:**
|
||||
1. Get QR as raw data: `qrRef.current.getRawData('png')` → Blob
|
||||
2. Convert Blob to base64 data URL
|
||||
3. POST to `/api/referrals/me/flyer` with `{ theme, qr_data_url }`
|
||||
4. Download PDF from response blob
|
||||
5. Show loading state while generating (flyer takes a few seconds)
|
||||
|
||||
### API Client
|
||||
|
||||
Add to `frontend/lib/api.ts`:
|
||||
```typescript
|
||||
generateFlyer(theme: 'light' | 'dark', qrDataUrl: string): Promise<Blob>
|
||||
```
|
||||
|
||||
### i18n Strings
|
||||
|
||||
Add to `referrals` namespace:
|
||||
```json
|
||||
"flyerTheme": "Flyer Theme",
|
||||
"flyerThemeLight": "Light",
|
||||
"flyerThemeDark": "Dark",
|
||||
"flyerGenerate": "Generate Flyer",
|
||||
"flyerGenerating": "Generating..."
|
||||
```
|
||||
|
||||
## Verification Strategy
|
||||
|
||||
### Phase 1: Local Chrome verification (before any backend changes)
|
||||
- Create templatized HTML file with placeholders
|
||||
- Write a Python script that substitutes values and runs local Chrome headless
|
||||
- Verify PDF output looks correct
|
||||
|
||||
### Phase 2: Docker verification (before merge)
|
||||
- Build the Docker base image locally with Chromium added
|
||||
- Run the container and execute the same Chromium command inside it
|
||||
- Verify PDF renders correctly with container's fonts + Chromium
|
||||
- This catches missing deps, font issues, sandbox problems, etc.
|
||||
|
||||
### Phase 3: Standard CI + deploy
|
||||
- Only after local Docker verification passes
|
||||
|
||||
## Testing
|
||||
|
||||
- **Unit tests:** Flyer service template substitution logic, input validation
|
||||
- **Integration test:** Full endpoint test with mocked Chromium (verify correct flags passed)
|
||||
- **Local Docker test:** Manual verification of PDF rendering in container environment
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Custom flyer text/messaging (uses fixed marketing copy)
|
||||
- Additional flyer layouts beyond light/dark
|
||||
- Batch flyer generation
|
||||
- Flyer analytics
|
||||
@@ -1,87 +0,0 @@
|
||||
# Mobile-Friendly Header Design
|
||||
|
||||
**Date:** 2026-04-06
|
||||
**Status:** Approved
|
||||
**File:** `frontend/components/app-header.tsx`
|
||||
|
||||
## Problem
|
||||
|
||||
The app header crams 6-7 icon-only buttons into a single row on mobile. The referrals icon in particular isn't recognizable, and the row is too crowded for the available width.
|
||||
|
||||
## Solution
|
||||
|
||||
Add a second row on mobile (`< sm` breakpoint) to give action buttons room for text labels. Desktop layout is unchanged.
|
||||
|
||||
## Layout
|
||||
|
||||
### Mobile (`< 640px`)
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────┐
|
||||
│ [Logo] Title [👤 Login] │
|
||||
├──────────────────────────────────────┤
|
||||
│ [↻ Refresh] [👥 Referrals] [? Help] │
|
||||
│ [🇬🇧 Lang] [☀ Theme] │
|
||||
└──────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- **Row 1:** Logo + title (left), AuthStatus (right)
|
||||
- **Row 2:** Action buttons with text labels, wrapped with `flex-wrap`
|
||||
- Separated by a subtle border or spacing
|
||||
|
||||
### Desktop (`≥ 640px`) — unchanged
|
||||
|
||||
Single row: Logo, Title, [children], Help, Referrals, Language, Auth, Theme.
|
||||
|
||||
## Implementation
|
||||
|
||||
### Changes to `app-header.tsx`
|
||||
|
||||
1. **Restructure the outer container** to stack two rows on mobile:
|
||||
- Outer: `flex flex-col sm:flex-row` (or keep current layout and add a second div that's `sm:hidden`)
|
||||
- Row 1 (mobile): logo/title + AuthStatus
|
||||
- Row 2 (mobile): all other action buttons with text labels visible
|
||||
|
||||
2. **Move AuthStatus** into row 1 on mobile. On desktop it stays in the existing position.
|
||||
|
||||
3. **Show text labels on mobile** for row 2 items:
|
||||
- Refresh: show `t('refresh')` text
|
||||
- Referrals: show `t('referrals')` text
|
||||
- Help: show `tHeader('help')` or similar text label
|
||||
- Language: show native language name (remove `hidden sm:inline` from LanguageSwitcher)
|
||||
- Theme: stays icon-only (sun/moon is universally understood)
|
||||
|
||||
4. **`children` prop** (page-specific buttons like Refresh, Admin toggle): render in row 2 on mobile, current position on desktop.
|
||||
|
||||
### Files Changed
|
||||
|
||||
- `frontend/components/app-header.tsx` — layout restructure
|
||||
- `frontend/components/LanguageSwitcher.tsx` — remove `hidden sm:inline` from the native language name span so it's always visible
|
||||
- `frontend/components/auth/AuthStatus.tsx` — may need minor adjustments for row 1 placement on mobile
|
||||
- `frontend/messages/en.json` — add `header.help` key if not already present
|
||||
|
||||
### No i18n Translation Run Needed
|
||||
|
||||
All text labels (`refresh`, `referrals`, login/auth text) already exist as translation keys — they're currently hidden via CSS `hidden sm:inline`. We're just making them visible on mobile. The only potential new key is a "Help" label for the help button.
|
||||
|
||||
## Approach
|
||||
|
||||
Use Tailwind responsive classes (`sm:hidden` / `hidden sm:flex`) to render two different layouts from the same component, rather than duplicating the buttons. Specifically:
|
||||
|
||||
- On mobile: render row 1 (brand + auth) and row 2 (actions with text)
|
||||
- On desktop: render the current single-row layout
|
||||
- Shared button components, just different container layout
|
||||
|
||||
## Spacing
|
||||
|
||||
- Row 2 gets the same horizontal padding as row 1 (`px-3 sm:px-4`)
|
||||
- Slightly reduced vertical padding on mobile to keep total header height reasonable
|
||||
- `pt-[header-height]` on main content needs updating to account for taller mobile header
|
||||
|
||||
## Testing
|
||||
|
||||
- Visual check on mobile viewport (375px, 390px widths)
|
||||
- Verify desktop layout is unchanged
|
||||
- Check with children (dashboard page) and without (referrals page)
|
||||
- Check logged-in vs logged-out states
|
||||
- Verify language switcher dropdown still positions correctly from row 2
|
||||
@@ -1,199 +0,0 @@
|
||||
# Referral Flyer Customisation — Design Spec
|
||||
|
||||
**Date:** 2026-04-09
|
||||
**Branch:** `feat/sess-20260409-1813-referral-flyer-customisation`
|
||||
**Status:** Design approved, ready for implementation planning
|
||||
|
||||
## Overview
|
||||
|
||||
Expand the existing QR Code Generator dialog into a tabbed "Referral Tools" dialog with two tabs: **QR Code** and **Printable Flyer**. The Flyer tab provides a live preview with extensive customisation options and client-side export (PDF, HTML, PNG). This replaces the current server-side flyer generation with a fully client-side approach.
|
||||
|
||||
## Goals
|
||||
|
||||
1. Live flyer preview with instant feedback on customisation changes
|
||||
2. Configurable colors, text, section visibility, branding, and print layout
|
||||
3. Client-side export to PDF (primary), HTML, and PNG — no server round-trip
|
||||
4. Preset themes (Light, Dark) with ability to save/load custom presets
|
||||
5. Multi-per-page PDF layout (1, 2, or 4 flyers per US Letter page)
|
||||
|
||||
## Architecture
|
||||
|
||||
### Approach: Client-Side Rendering
|
||||
|
||||
The flyer is rendered as a React component in the dialog preview. Export uses `html2canvas` + `jsPDF` for PDF/PNG, and DOM serialization for HTML. This gives:
|
||||
- Instant preview of all customisation changes
|
||||
- Export to PDF, HTML, and PNG without backend involvement
|
||||
- No backend changes required — existing server-side endpoints remain but are unused
|
||||
|
||||
### Component Structure
|
||||
|
||||
```
|
||||
frontend/components/referrals/
|
||||
├── ReferralToolsDialog.tsx # Tabbed shell (QR Code | Printable Flyer)
|
||||
├── QRCodeTab.tsx # Extracted from current QRCodeDialog (preview + controls)
|
||||
├── FlyerTab.tsx # Flyer preview + controls container
|
||||
├── FlyerPreview.tsx # Flyer rendered as React component (live preview)
|
||||
├── FlyerControls.tsx # Right-side customisation panel
|
||||
├── FlyerExport.tsx # PDF/HTML/PNG export logic
|
||||
└── flyer-presets.ts # Built-in presets + localStorage save/load helpers
|
||||
```
|
||||
|
||||
### State Flow
|
||||
|
||||
- `ReferralToolsDialog` owns active tab state and QR style prefs (both tabs need them)
|
||||
- `QRCodeTab` receives QR prefs + updater — works exactly as current `QRCodeDialog`
|
||||
- `FlyerTab` receives QR prefs (read-only, for embedding styled QR in flyer) + owns its own flyer config state
|
||||
- Flyer config persisted to localStorage under `nk-flyer-prefs` (same debounced pattern as QR prefs)
|
||||
- A small "Edit QR Style" link on the Flyer tab (near the QR in the preview) switches to the QR tab
|
||||
|
||||
## Flyer Config Model
|
||||
|
||||
```typescript
|
||||
interface FlyerConfig {
|
||||
// Colors
|
||||
bgColor: string; // default: '#faf8f5'
|
||||
headlineGradient: string[]; // default: ['#c45aff', '#ff7acc', '#ff5a8a']
|
||||
headlineSubColor: string; // default: '#1a1a1a'
|
||||
textColor: string; // default: '#1a1a1a'
|
||||
subtextColor: string; // default: '#666'
|
||||
accentColor: string; // step numbers, divider
|
||||
|
||||
// Text overrides (null = use default)
|
||||
headlineMain: string | null;
|
||||
headlineSub: string | null;
|
||||
subtitle: string | null;
|
||||
ctaLabel: string | null;
|
||||
ctaNote: string | null;
|
||||
steps: Array<{ title: string | null; desc: string | null }>;
|
||||
|
||||
// Section visibility
|
||||
showSubtitle: boolean;
|
||||
showSteps: boolean;
|
||||
showDivider: boolean;
|
||||
showBottomFeatures: boolean;
|
||||
showBottomTagline: boolean;
|
||||
|
||||
// Custom branding
|
||||
customLogoUrl: string | null; // data URL from file upload
|
||||
|
||||
// Print layout
|
||||
perPage: 1 | 2 | 4;
|
||||
marginMm: number; // page margin in mm, default 15
|
||||
}
|
||||
```
|
||||
|
||||
## Built-in Presets
|
||||
|
||||
**Light:** Current light template defaults — cream background (`#faf8f5`), dark text, pink/purple accent gradient.
|
||||
|
||||
**Dark:** Current dark template defaults — dark background, light text, pink/purple accent gradient.
|
||||
|
||||
## Custom Presets
|
||||
|
||||
- Stored in localStorage under `nk-flyer-custom-presets` as `Array<{ name: string; config: FlyerConfig }>`
|
||||
- "Save as Preset" button in controls — prompts for a name inline
|
||||
- "Load Preset" dropdown shows built-in + custom presets
|
||||
- "Delete" option on custom presets only
|
||||
- Editing any value after loading a preset shows dropdown as "Custom" / unsaved state
|
||||
|
||||
## Flyer Preview
|
||||
|
||||
`FlyerPreview.tsx` is a React port of the existing `backend/templates/printables/website-referral-flyer.html`.
|
||||
|
||||
- Rendered at fixed internal size matching US Letter proportions (8.5" x 11")
|
||||
- CSS `transform: scale()` fits it into the dialog preview area
|
||||
- All config changes reflect instantly via React re-rendering
|
||||
- QR code rendered via `qr-code-styling` instance using the current QR prefs from the QR tab
|
||||
- Custom logo shown to the right of the Nomad Karaoke logo in the header
|
||||
|
||||
**Multi-page preview:** When `perPage` is 2 or 4, the preview shows the page layout with the flyer duplicated and scaled into a grid (1x2 or 2x2) with configured margins. Shows exactly what the printed page will look like.
|
||||
|
||||
## Flyer Controls Panel
|
||||
|
||||
`FlyerControls.tsx` — right side, scrollable, organized in collapsible sections:
|
||||
|
||||
### Preset Selector (top, always visible)
|
||||
- Dropdown: Light, Dark, custom presets
|
||||
- "Save as Preset" button
|
||||
|
||||
### Colors
|
||||
- Background — color picker
|
||||
- Headline gradient — 3 color pickers (start, mid, end)
|
||||
- Headline sub — color picker
|
||||
- Text — color picker
|
||||
- Subtext — color picker
|
||||
- Accent — color picker
|
||||
- "Reset Colors" button
|
||||
|
||||
### Text Overrides
|
||||
- Each field shows default as placeholder; empty = use default
|
||||
- Headline main, Headline sub, Subtitle, CTA label, CTA note
|
||||
- Steps 1-4: title + description each, collapsible per step
|
||||
|
||||
### Sections
|
||||
- Toggle switches: Subtitle, How-It-Works Steps, Divider, Bottom Features, Bottom Tagline
|
||||
|
||||
### Branding
|
||||
- File upload (png, jpg, svg)
|
||||
- Thumbnail preview + "Remove" button
|
||||
|
||||
### Print Layout
|
||||
- Per page: segmented button (1 / 2 / 4)
|
||||
- Page margins: slider (0-30mm, default 15mm)
|
||||
|
||||
## Export
|
||||
|
||||
### Formats
|
||||
- **PDF** (primary) — `html2canvas` at 2x resolution + `jsPDF`. Multi-per-page: render once, place multiple times at scale with margins.
|
||||
- **HTML** — serialize flyer DOM + inline styles, Google Fonts as links. Self-contained file.
|
||||
- **PNG** — `html2canvas` at 2x, single flyer only (ignores per-page setting).
|
||||
|
||||
### UX
|
||||
- Primary button: "Download PDF"
|
||||
- Secondary buttons: "Download HTML", "Download PNG"
|
||||
- Filename: `nomad-karaoke-flyer-{referralCode}.{ext}` (overridable via `flyerFilename` prop)
|
||||
|
||||
### New Dependencies
|
||||
- `html2canvas` — DOM-to-canvas rasterization
|
||||
- `jspdf` — PDF composition
|
||||
- ~200KB combined, client-side only
|
||||
|
||||
## Migration & Integration
|
||||
|
||||
### Dialog Rename
|
||||
- `QRCodeDialog` → `ReferralToolsDialog` (same props interface)
|
||||
- `ReferralDashboard.tsx` — update import
|
||||
- `admin/referrals/page.tsx` — update import; `onGenerateFlyer` prop becomes unused but kept for backwards compat
|
||||
|
||||
### Dialog Sizing
|
||||
- Expand from `sm:max-w-2xl` to `sm:max-w-4xl`
|
||||
|
||||
### i18n
|
||||
- New keys in `referrals` namespace for tab names, control labels, section headers, preset names, export buttons
|
||||
- Run `translate.py --target all` for all 33 locales
|
||||
- Admin pages are English-only, no concern
|
||||
|
||||
### Backend
|
||||
- No changes. Existing flyer endpoints remain functional but unused by frontend.
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests for preset save/load logic and config defaults (`flyer-presets.ts`)
|
||||
- Unit tests for export functions with mocked html2canvas/jsPDF (`FlyerExport.tsx`)
|
||||
- Update existing `QRCodeDialog.test.tsx` → `ReferralToolsDialog.test.tsx`
|
||||
- Tab switching
|
||||
- Flyer config persistence to localStorage
|
||||
- QR-to-flyer state flow (QR prefs reflected in flyer preview)
|
||||
- Section visibility toggles
|
||||
- Preset loading/saving
|
||||
|
||||
## Decisions Log
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Client-side rendering over server-side | Instant preview, export to HTML/PNG/PDF, no backend changes |
|
||||
| Tabbed dialog over separate modals | Cohesive UX, natural QR→flyer flow |
|
||||
| QR config shared via parent state | Single source of truth, "Edit QR Style" link for easy tab switch |
|
||||
| localStorage for presets | Same pattern as existing QR prefs, no backend persistence needed |
|
||||
| html2canvas + jsPDF over other libs | Well-maintained, reasonable bundle size, handles single-page flyer well |
|
||||
| Keep backend endpoints | No breaking changes, can deprecate later |
|
||||
@@ -1,183 +0,0 @@
|
||||
# Daily E2E Payment + Happy Path Test
|
||||
|
||||
**Date:** 2026-04-12
|
||||
**Status:** Design
|
||||
|
||||
## Motivation
|
||||
|
||||
On April 10, a Stripe SDK upgrade caused all payment webhooks to 500 for ~5 days. Users paid real money but never received credits or confirmation emails. The existing `stripe-credit-purchase.spec.ts` test uses a simulated test-webhook endpoint — a completely different code path from real Stripe Checkout — and would never have caught this.
|
||||
|
||||
This design adds a daily E2E test that exercises the **real payment flow** (Stripe Checkout with a real credit card), then uses the purchased credit to run the existing happy path job creation test.
|
||||
|
||||
## What We're Building
|
||||
|
||||
A single GitHub Actions workflow (`e2e-daily.yml`) that replaces the current `e2e-happy-path.yml`. It runs two sequential Playwright test stages daily at 6 AM UTC:
|
||||
|
||||
1. **Stage 1 — Credit Purchase** (~3-5 min): Sign up a fresh test user with referral code `e2etest70` (70% discount), purchase 1 credit ($3.00) via real Stripe Checkout, verify credits land and email arrives.
|
||||
2. **Stage 2 — Happy Path** (~20-30 min): Same test user spends the purchased credit to create a karaoke job through the full generation pipeline.
|
||||
|
||||
If Stage 1 fails, Stage 2 is skipped. Both stages send Discord + email alerts on failure.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Workflow: `.github/workflows/e2e-daily.yml`
|
||||
|
||||
Replaces `e2e-happy-path.yml`. Same schedule (daily 6 AM UTC), same manual trigger options, but with two sequential test runs.
|
||||
|
||||
```yaml
|
||||
jobs:
|
||||
e2e-credit-purchase:
|
||||
# Stage 1: Buy credits via real Stripe Checkout
|
||||
# Outputs: test user email + session token for Stage 2
|
||||
|
||||
e2e-happy-path:
|
||||
needs: e2e-credit-purchase
|
||||
# Stage 2: Use purchased credit for full job generation
|
||||
# Uses token from Stage 1 (skip signup)
|
||||
```
|
||||
|
||||
The two stages are separate GitHub Actions jobs (not separate Playwright test files run in one job) so that:
|
||||
- Stage 2 is cleanly skipped when Stage 1 fails
|
||||
- Each stage has independent artifact uploads and failure reporting
|
||||
- Stage 1's session token is passed to Stage 2 via job outputs
|
||||
|
||||
### Test File: `frontend/e2e/production/credit-purchase-real.spec.ts`
|
||||
|
||||
New Playwright test for Stage 1. Exercises the real user payment flow:
|
||||
|
||||
```
|
||||
1. Navigate to gen.nomadkaraoke.com/?ref=e2etest70
|
||||
2. Sign up via magic link (testmail.app email capture)
|
||||
3. After auth, verify referral discount badge shows 70% off
|
||||
4. Open Buy Credits dialog
|
||||
5. Select 1-credit package — verify discounted price ($3.00)
|
||||
6. Click Checkout → redirect to checkout.stripe.com
|
||||
7. Fill card details (from env: E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC)
|
||||
8. Submit payment → redirect to /payment/success
|
||||
9. Verify "Payment Successful" page with 1 credit balance
|
||||
10. Verify confirmation email via testmail.app
|
||||
11. Verify credit balance via admin API = 1
|
||||
12. Output session token for Stage 2
|
||||
```
|
||||
|
||||
### Test File: `frontend/e2e/production/happy-path-real-user.spec.ts` (modified)
|
||||
|
||||
The existing happy path test is modified to accept a pre-authenticated session token (it already supports `E2E_TEST_TOKEN`). No changes needed to the core test logic — Stage 2 just passes the token from Stage 1.
|
||||
|
||||
### Notifications
|
||||
|
||||
Both stages report failures via:
|
||||
|
||||
- **Email**: SendGrid to `andrew@nomadkaraoke.com` (existing pattern)
|
||||
- **Discord**: POST to `DISCORD_ALERT_WEBHOOK_URL` secret with an embed showing which stage failed, the workflow URL, and a summary
|
||||
|
||||
Discord notification format:
|
||||
```
|
||||
🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase
|
||||
Run #123 | 2026-04-12 06:05 UTC
|
||||
Details: https://github.com/nomadkaraoke/karaoke-gen/actions/runs/XXX
|
||||
```
|
||||
|
||||
On success, a brief confirmation is posted to Discord (no email on success — keep inbox clean).
|
||||
|
||||
### Existing Workflow: `e2e-happy-path.yml`
|
||||
|
||||
Deleted and replaced by `e2e-daily.yml`. The new workflow is a strict superset — it runs the same happy path test with the addition of the credit purchase stage before it.
|
||||
|
||||
The manual `workflow_dispatch` trigger is preserved with the same inputs (`debug_mode`, `browser`, `use_test_token`), plus a new `skip_payment` input that skips Stage 1 for quick happy-path-only iterations.
|
||||
|
||||
## Stripe Checkout Automation
|
||||
|
||||
The test fills a real credit card on Stripe's hosted checkout page (`checkout.stripe.com`). This is the most fragile part of the test since Stripe can change their UI.
|
||||
|
||||
### Selector Strategy
|
||||
|
||||
Stripe Checkout uses well-known iframe-based card input fields. The test:
|
||||
|
||||
1. Waits for the Stripe Checkout page to load (URL matches `checkout.stripe.com`)
|
||||
2. Locates card input fields by their element IDs within Stripe's iframes (`cardNumber`, `cardExpiry`, `cardCvc`)
|
||||
3. Falls back to `[name="cardnumber"]`, `[name="exp-date"]`, `[name="cvc"]` attribute selectors
|
||||
4. Uses role-based selectors for the Pay button (`getByRole('button', { name: /pay/i })`)
|
||||
5. All interactions have 30s timeouts with screenshots on failure
|
||||
|
||||
### Card Details Storage
|
||||
|
||||
Stored as GitHub Actions secrets:
|
||||
|
||||
| Secret | Example | Notes |
|
||||
|--------|---------|-------|
|
||||
| `E2E_STRIPE_CARD_NUMBER` | `4111111111111111` | Real virtual card from Capital One |
|
||||
| `E2E_STRIPE_CARD_EXPIRY` | `12/28` | MM/YY format |
|
||||
| `E2E_STRIPE_CARD_CVC` | `123` | 3-digit CVC |
|
||||
| `E2E_STRIPE_CARDHOLDER_NAME` | `E2E Test` | Name on card (if Stripe requires it) |
|
||||
|
||||
### Stripe Checkout Page Handling
|
||||
|
||||
Stripe Checkout is a full page redirect (not an embedded iframe). The test:
|
||||
|
||||
1. Clicks "Checkout" in BuyCreditsDialog
|
||||
2. Waits for navigation to `checkout.stripe.com`
|
||||
3. Stripe's card fields are embedded in iframes within the checkout page — the test must locate the correct iframe, then fill fields within it
|
||||
4. After filling all fields and clicking Pay, waits for redirect back to `gen.nomadkaraoke.com/*/payment/success`
|
||||
|
||||
### Resilience
|
||||
|
||||
- **Retries**: Playwright production config already has `retries: 2`
|
||||
- **Screenshots**: Captured on every step and on failure
|
||||
- **Video**: Full video recording for debugging
|
||||
- **Timeout**: 5-minute timeout for the entire Stripe interaction (generous for page loads)
|
||||
|
||||
## Referral Discount Verification
|
||||
|
||||
The test user signs up via `?ref=e2etest70` which attributes them to the `e2etest70` referral link with 70% discount. Verifications:
|
||||
|
||||
1. After auth, the BuyCreditsDialog shows the "Active Referral Discount" badge with "70% off"
|
||||
2. The 1-credit package shows $3.00 (not $10.00)
|
||||
3. The Stripe Checkout total is $3.00
|
||||
|
||||
The referral link `e2etest70` must be pre-configured in production with:
|
||||
- `discount_percent`: 70
|
||||
- `kickback_percent`: 0 (no payouts for test purchases)
|
||||
- `duration_days`: 36500 (effectively permanent — 100 years)
|
||||
|
||||
## New GitHub Actions Secrets
|
||||
|
||||
| Secret | Source | Purpose |
|
||||
|--------|--------|---------|
|
||||
| `E2E_STRIPE_CARD_NUMBER` | User-provided | Virtual credit card number |
|
||||
| `E2E_STRIPE_CARD_EXPIRY` | User-provided | Card expiry MM/YY |
|
||||
| `E2E_STRIPE_CARD_CVC` | User-provided | Card CVC |
|
||||
| `E2E_STRIPE_CARDHOLDER_NAME` | User-provided | Cardholder name |
|
||||
| `DISCORD_ALERT_WEBHOOK_URL` | GCP `discord-alert-webhook` | Discord failure alerts |
|
||||
|
||||
Existing secrets reused: `TESTMAIL_API_KEY`, `TESTMAIL_NAMESPACE`, `E2E_ADMIN_TOKEN`, `E2E_BYPASS_KEY`, `SENDGRID_API_KEY`.
|
||||
|
||||
## Cost
|
||||
|
||||
- 1 credit package at 70% off = **$3.00/day** (~$90/month)
|
||||
- Stripe processing fees: ~$0.60/transaction ($3.00 * 2.9% + $0.30)
|
||||
- Total: **~$3.60/day, ~$108/month**
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change |
|
||||
|------|--------|
|
||||
| `frontend/e2e/production/credit-purchase-real.spec.ts` | **New** — Real Stripe Checkout payment test |
|
||||
| `frontend/e2e/helpers/stripe-checkout.ts` | **New** — Helper for filling Stripe Checkout page |
|
||||
| `.github/workflows/e2e-daily.yml` | **New** — Combined payment + happy path workflow |
|
||||
| `.github/workflows/e2e-happy-path.yml` | **Delete** — Replaced by e2e-daily.yml |
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Testing other credit packages (3, 5, 10) — 1 credit is sufficient to verify the flow
|
||||
- Testing promotion codes (separate from referral coupons)
|
||||
- Refund testing
|
||||
- Made-for-you payment flow (has its own test)
|
||||
- Modifying the existing `stripe-credit-purchase.spec.ts` — that test still has value as a fast API-level check
|
||||
|
||||
## Risks
|
||||
|
||||
1. **Stripe Checkout UI changes**: Most likely failure mode. Mitigated by Discord alerts, video recordings, and resilient selectors. Fix turnaround: update selectors, typically <1 hour.
|
||||
2. **Card decline**: Virtual card could expire or hit limits. Mitigated by Discord alert — replace card and update secret.
|
||||
3. **Referral code expiry**: The `e2etest70` link must have a very long duration. Set to 100 years.
|
||||
4. **Test user accumulates credits**: Harmless — credits pile up on disposable testmail.app accounts. Each day creates a new test user.
|
||||
@@ -1,407 +0,0 @@
|
||||
# Nomad Karaoke Error Monitor — Design Spec
|
||||
|
||||
> **Date:** 2026-04-12
|
||||
> **Status:** Approved
|
||||
> **Scope:** Error Monitor service for production error detection, normalization, dedup, alerting, and resolution tracking across all Nomad Karaoke services.
|
||||
> **Reference:** Based on the Aquarius Error Bot system (`/Users/andrew/Projects/aquarius/docs/archive/error-bot-system-reference.md`)
|
||||
|
||||
---
|
||||
|
||||
## 1. System Overview
|
||||
|
||||
A Cloud Run Job that runs every 15 minutes, queries GCP Cloud Logging for errors across all production services, normalizes and deduplicates them, uses Gemini Flash to group related errors into incidents, sends alerts to Discord, tracks patterns in Firestore, and auto-resolves patterns that go silent.
|
||||
|
||||
### End-to-End Flow
|
||||
|
||||
```
|
||||
Production Errors (Cloud Logging)
|
||||
|
|
||||
v
|
||||
Error Monitor (Cloud Run Job, every 15 min)
|
||||
|-- Query Cloud Logging (ERROR severity, last 15 min)
|
||||
| |-- cloud_run_revision: karaoke-backend, karaoke-decide, audio-separator
|
||||
| |-- cloud_run_job: video-encoding-job, lyrics-transcription-job,
|
||||
| | audio-separation-job, audio-download-job
|
||||
| |-- cloud_function: gdrive-validator, runner_manager, backup_to_aws,
|
||||
| | divebar_mirror, kn_data_sync, divebar_lookup,
|
||||
| | encoding_worker_idle
|
||||
| |-- gce_instance: encoding-worker-a, encoding-worker-b,
|
||||
| flacfetch-vm, divebar-sync-vm
|
||||
|-- Normalize messages (strip IDs, timestamps, emails, job IDs, GCS paths)
|
||||
|-- Group by pattern hash (SHA-256 of service::normalized_message)
|
||||
|-- Check Firestore for existing patterns
|
||||
|-- LLM dedup: check new patterns against existing (Gemini Flash)
|
||||
|-- If 2+ new patterns: LLM incident analysis (group by root cause)
|
||||
|-- Send Discord alerts (per-incident or per-pattern)
|
||||
|-- Auto-resolve stale patterns (frequency-aware thresholds)
|
||||
|
|
||||
v
|
||||
Daily Digest (08:00 UTC, same job with DIGEST_MODE=true)
|
||||
|-- Dedup sweep of all active patterns
|
||||
|-- 24h summary: total errors, new patterns, frequency stats
|
||||
|-- Per-service breakdown
|
||||
|-- Send digest to Discord
|
||||
```
|
||||
|
||||
### Monitored Resources
|
||||
|
||||
| Category | Resources |
|
||||
|----------|-----------|
|
||||
| **Cloud Run Services** | karaoke-backend, karaoke-decide, audio-separator |
|
||||
| **Cloud Run Jobs** | video-encoding-job, lyrics-transcription-job, audio-separation-job, audio-download-job |
|
||||
| **Cloud Functions** | gdrive-validator, runner_manager, backup_to_aws, divebar_mirror, kn_data_sync, divebar_lookup, encoding_worker_idle |
|
||||
| **GCE Instances** | encoding-worker-a, encoding-worker-b, flacfetch-vm, divebar-sync-vm |
|
||||
|
||||
---
|
||||
|
||||
## 2. Log Collection
|
||||
|
||||
Four separate Cloud Logging queries, one per resource type, each scoped to:
|
||||
- Severity: `>=ERROR`
|
||||
- Time window: last 15 minutes (configurable via `LOOKBACK_MINUTES`)
|
||||
- Max entries: 500 total across all queries
|
||||
|
||||
### Query Resource Types
|
||||
|
||||
| Resource Type | Filter Field | Values |
|
||||
|---------------|-------------|--------|
|
||||
| `cloud_run_revision` | `resource.labels.service_name` | karaoke-backend, karaoke-decide, audio-separator |
|
||||
| `cloud_run_job` | `resource.labels.job_name` | video-encoding-job, lyrics-transcription-job, audio-separation-job, audio-download-job |
|
||||
| `cloud_function` | `resource.labels.function_name` | gdrive-validator, runner_manager, backup_to_aws, divebar_mirror, kn_data_sync, divebar_lookup, encoding_worker_idle |
|
||||
| `gce_instance` | `labels."compute.googleapis.com/resource_name"` | encoding-worker-a, encoding-worker-b, flacfetch-vm, divebar-sync-vm |
|
||||
|
||||
### Payload Handling
|
||||
|
||||
Three payload types (same as Aquarius):
|
||||
- Structured JSON dict → extract message from `textPayload` or `jsonPayload.message`
|
||||
- Plain text string → use directly
|
||||
- HTTP request logs (no payload) → skip
|
||||
|
||||
---
|
||||
|
||||
## 3. Message Normalization
|
||||
|
||||
### Standard Normalizers (from Aquarius)
|
||||
|
||||
| Pattern | Placeholder |
|
||||
|---------|-------------|
|
||||
| UUIDs | `<ID>` |
|
||||
| ISO timestamps | `<TS>` |
|
||||
| Epoch timestamps | `<EPOCH>` |
|
||||
| Hex/alphanumeric IDs (8+ chars) | `<ID>` |
|
||||
| Email addresses | `<EMAIL>` |
|
||||
| IP addresses | `<IP>` |
|
||||
| URLs | domain only |
|
||||
| Numbers (4+ digits) | `<NUM>` |
|
||||
|
||||
### NK-Specific Normalizers
|
||||
|
||||
| Pattern | Placeholder |
|
||||
|---------|-------------|
|
||||
| Job IDs (`/jobs/<id>`) | `/jobs/<ID>` |
|
||||
| GCS paths (`gs://nomadkaraoke-*/**`) | `gs://<BUCKET>/<PATH>` |
|
||||
| Firebase UIDs | `<UID>` |
|
||||
| Audio file references (hashes, filenames) | `<FILE>` |
|
||||
| Firestore document paths | `<DOC_PATH>` |
|
||||
|
||||
### Pattern Hash
|
||||
|
||||
`SHA-256(service::normalized_message)` — deterministic, collision-resistant.
|
||||
|
||||
---
|
||||
|
||||
## 4. LLM Analysis
|
||||
|
||||
### Model & Provider
|
||||
|
||||
- **Model:** Gemini 2.0 Flash via Vertex AI
|
||||
- **Auth:** Application Default Credentials (service account)
|
||||
- **Temperature:** 0.2 for incident analysis, 0.1 for dedup
|
||||
- **Retry:** Exponential backoff, 3 attempts, 2s base delay
|
||||
- **Fallback:** If LLM unavailable, group by service name (no root cause analysis)
|
||||
|
||||
### Incident Grouping
|
||||
|
||||
When 2+ new patterns are detected, the LLM analyzes them together. The system prompt provides NK-specific service dependency context:
|
||||
|
||||
```
|
||||
karaoke-backend (API) → orchestrates all workers
|
||||
├── audio-download-job → flacfetch-vm (downloads audio)
|
||||
├── audio-separation-job / audio-separator (GPU stem separation)
|
||||
├── lyrics-transcription-job (AudioShake + AI correction)
|
||||
├── video-encoding-job → encoding-worker-a/b (FFmpeg rendering)
|
||||
└── youtube-upload (distribution)
|
||||
|
||||
karaoke-decide (independent) → BigQuery, Spotify, Last.fm
|
||||
|
||||
Cloud Functions: gdrive-validator, backup_to_aws, divebar_mirror,
|
||||
kn_data_sync, divebar_lookup, runner_manager,
|
||||
encoding_worker_idle
|
||||
```
|
||||
|
||||
### Output Format (JSON)
|
||||
|
||||
```json
|
||||
{
|
||||
"incidents": [
|
||||
{
|
||||
"title": "max 60 chars",
|
||||
"root_cause": "one-liner",
|
||||
"severity": "P0|P1|P2|P3",
|
||||
"suggested_fix": "actionable, 1-2 sentences",
|
||||
"primary_service": "upstream root cause service",
|
||||
"pattern_indices": [1, 3]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Severity Levels
|
||||
|
||||
- **P0:** Service completely down, all jobs failing, payment processing broken
|
||||
- **P1:** Major pipeline stage broken (audio separation, lyrics, encoding), auth failures
|
||||
- **P2:** Degraded but functional — intermittent errors, slow responses, single-job failures
|
||||
- **P3:** Minor — deprecation warnings, cleanup failures, spot VM preemptions
|
||||
|
||||
### Duplicate Detection
|
||||
|
||||
Identifies near-duplicate patterns that regex normalization missed (different phrasing of same error). Only merges new patterns into existing canonical ones to preserve alert history.
|
||||
|
||||
---
|
||||
|
||||
## 5. Firestore Data Model
|
||||
|
||||
### `error_patterns` Collection
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `pattern_id` | string | SHA-256(service::normalized_message) — document ID |
|
||||
| `service` | string | Resource name (e.g., `karaoke-backend`, `video-encoding-job`) |
|
||||
| `resource_type` | string | `cloud_run_service` / `cloud_run_job` / `cloud_function` / `gce_instance` |
|
||||
| `normalized_message` | string | Regex-normalized error (max 200 chars) |
|
||||
| `sample_message` | string | Raw error sample |
|
||||
| `first_seen` | string (ISO) | First occurrence |
|
||||
| `last_seen` | string (ISO) | Most recent occurrence |
|
||||
| `total_count` | int | Cumulative count |
|
||||
| `rolling_counts` | map | `{YYYY-MM-DDTHH:MM → count}` (7-day window) |
|
||||
| `status` | string | `new` / `acknowledged` / `known` / `muted` / `fixed` / `auto_resolved` |
|
||||
| `incident_id` | string? | Link to grouped incident |
|
||||
| `severity` | string | `P0` / `P1` / `P2` / `P3` |
|
||||
| `alerted_at` | string (ISO) | When Discord alert was sent |
|
||||
| `notes` | string? | Free-text notes |
|
||||
| `merged_into` | string? | Pattern ID this was merged into |
|
||||
| `fixed_by` | map? | `{pr_display, pr_url, note, resolved_at}` |
|
||||
|
||||
### `error_incidents` Collection
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `incident_id` | string | `inc_YYYYMMDD_HHMM_<8-hex>` — document ID |
|
||||
| `title` | string | Max 60 chars |
|
||||
| `root_cause` | string? | LLM-identified |
|
||||
| `severity` | string | `P0` / `P1` / `P2` / `P3` |
|
||||
| `suggested_fix` | string? | Actionable next step |
|
||||
| `primary_service` | string | Upstream root cause service |
|
||||
| `pattern_ids` | list | Related pattern IDs |
|
||||
| `used_llm` | bool | Whether LLM analysis was used |
|
||||
| `created_at` | string (ISO) | Creation timestamp |
|
||||
| `status` | string | `open` / `investigating` / `fixed` / `false_positive` |
|
||||
|
||||
### `discord_alerts` Collection
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| Document ID | string | `alert_YYYYMMDD_HHMMSS_<8-hex>` |
|
||||
| `timestamp` | string (ISO) | When sent |
|
||||
| `alert_type` | string | `new_pattern` / `spike` / `incident` / `resolved_batch` / `daily_digest` |
|
||||
| `content` | string | Message text (max 2000 chars) |
|
||||
| `success` | bool | Whether webhook POST succeeded |
|
||||
| + alert-specific metadata | varies | service, pattern, count, severity, etc. |
|
||||
|
||||
### Migration from `known-issues.yaml`
|
||||
|
||||
Existing entries in `known-issues.yaml` are migrated to `error_patterns` documents with status `known` or `muted`. The YAML file is then deprecated.
|
||||
|
||||
---
|
||||
|
||||
## 6. Discord Notifications
|
||||
|
||||
### Webhook
|
||||
|
||||
Reuses the existing `discord-alert-webhook` secret in Secret Manager.
|
||||
|
||||
### Alert Types
|
||||
|
||||
| Alert Type | Trigger | Emoji | Content |
|
||||
|------------|---------|-------|---------|
|
||||
| **New Pattern** | Unrecognized error | `🔴` | Service, resource type, normalized msg, sample, count, timestamps, `/prod-investigate` prompt |
|
||||
| **Incident** | 2+ patterns grouped by LLM | `🚨`/`🔴`/`⚠️`/`🟡` (P0-P3) | Title, root cause, per-pattern details, suggested fix |
|
||||
| **Auto-Resolved** | Pattern silent past threshold | `✅` | Pattern, hours silent, consolidated |
|
||||
| **Spike** | Count > 5x rolling avg (min 5) | `⚠️` | Pattern, current vs. normal count |
|
||||
| **Daily Digest** | 08:00 UTC | `📊` | 24h totals, per-service breakdown, frequency stats |
|
||||
|
||||
### Format Rules
|
||||
|
||||
- Compact inline formatting (no bullet lists)
|
||||
- Show actual error message text, never summarize
|
||||
- Include copy-paste `/prod-investigate` prompts
|
||||
- Rate limited: max 10 messages per run
|
||||
- 2000-char limit with truncation
|
||||
- Timestamps in Eastern time (America/New_York, DST-aware)
|
||||
- Honest when LLM fails: "LLM grouping unavailable"
|
||||
|
||||
---
|
||||
|
||||
## 7. Auto-Resolution
|
||||
|
||||
Frequency-aware thresholds based on historical occurrence rate:
|
||||
|
||||
```
|
||||
threshold_hours = mean_interval_between_occurrences * AUTO_RESOLVE_MULTIPLIER
|
||||
```
|
||||
|
||||
| Setting | Value |
|
||||
|---------|-------|
|
||||
| `AUTO_RESOLVE_MULTIPLIER` | 8 (99.97% confidence, Poisson) |
|
||||
| `AUTO_RESOLVE_MIN_HOURS` | 6 |
|
||||
| `AUTO_RESOLVE_MAX_HOURS` | 168 (1 week) |
|
||||
| `AUTO_RESOLVE_FALLBACK_HOURS` | 48 (when <3 data points) |
|
||||
|
||||
High-frequency errors resolve faster; rare errors wait longer.
|
||||
|
||||
---
|
||||
|
||||
## 8. Known Issues / Ignore Patterns
|
||||
|
||||
Regex patterns for infrastructure noise that never triggers alerts:
|
||||
|
||||
- Cloud Run cold start / startup probe failures
|
||||
- Spot VM preemption events (GitHub runners)
|
||||
- GitHub runner startup/shutdown noise
|
||||
- Encoding worker idle shutdown (expected)
|
||||
- Cloud Scheduler retry transients
|
||||
- Health check 404s from load balancers
|
||||
- Ready condition changes during deploys
|
||||
|
||||
Defined in `known_issues.py`, easy to add to without code changes.
|
||||
|
||||
---
|
||||
|
||||
## 9. Infrastructure (Pulumi)
|
||||
|
||||
### New Resources (`infrastructure/modules/error_monitor.py`)
|
||||
|
||||
1. **Cloud Run Job** (`nomad-error-monitor`)
|
||||
- Image: existing karaoke-backend Docker image
|
||||
- Command: `["python", "-m", "backend.services.error_monitor.monitor"]`
|
||||
- Memory: 512Mi, CPU: 1, Timeout: 300s, Max retries: 0
|
||||
- Env vars: `GCP_PROJECT_ID`, `ENVIRONMENT`, `DISCORD_WEBHOOK_URL` (Secret Manager ref)
|
||||
|
||||
2. **Cloud Scheduler — Monitor** (`error-monitor-trigger`)
|
||||
- Schedule: `*/15 * * * *` (UTC)
|
||||
- Target: Cloud Run Jobs API `:run`
|
||||
- Auth: OAuth token via scheduler service account
|
||||
- Retry: 1 attempt, 60s max
|
||||
|
||||
3. **Cloud Scheduler — Daily Digest** (`error-monitor-daily-digest`)
|
||||
- Schedule: `0 8 * * *` (UTC)
|
||||
- Same job, with `DIGEST_MODE=true` environment override
|
||||
|
||||
4. **Service Account** (`error-monitor-scheduler`)
|
||||
- `roles/run.invoker` on the Cloud Run Job
|
||||
|
||||
### IAM for Error Monitor Job
|
||||
|
||||
The job runs under the existing backend service account (`karaoke-backend-sa`), which already has Firestore and Secret Manager access. Additional role needed:
|
||||
- `roles/logging.viewer` (read Cloud Logging — not currently on the backend SA)
|
||||
|
||||
---
|
||||
|
||||
## 10. Slash Command Updates
|
||||
|
||||
All five `/prod-*` commands updated to use `error_patterns` as primary data source.
|
||||
|
||||
### `/prod-health`
|
||||
Add error pattern summary (active count, new patterns in last hour) alongside existing health endpoint checks.
|
||||
|
||||
### `/prod-errors`
|
||||
**Primary source becomes Firestore `error_patterns`** — fast, pre-deduplicated, pre-categorized. Cloud Logging becomes secondary, used only for stack traces when investigating a specific pattern.
|
||||
|
||||
### `/prod-investigate`
|
||||
Query `error_patterns` first for pattern context (history, frequency, related incidents), then Cloud Logging for stack traces and detailed samples.
|
||||
|
||||
### `/prod-review`
|
||||
Replace raw Cloud Logging categorization with pattern statuses: NEW, REGRESSIONS (previously fixed reoccurred), IN PROGRESS (acknowledged), KNOWN, VERIFIED FIXED. Remove `known-issues.yaml` dependency.
|
||||
|
||||
### `/prod-known-issue`
|
||||
Write to Firestore `error_patterns` (status: `known`/`muted`) instead of YAML file.
|
||||
|
||||
### Helper Scripts
|
||||
|
||||
- `scripts/query-error-patterns.py` — CLI to query patterns from Firestore (used by slash commands)
|
||||
- `scripts/resolve-error-pattern.py` — CLI to mark patterns as fixed with PR reference
|
||||
|
||||
---
|
||||
|
||||
## 11. Code Structure
|
||||
|
||||
```
|
||||
backend/services/error_monitor/
|
||||
├── __init__.py
|
||||
├── monitor.py # Entry point — query, normalize, group, analyze, alert
|
||||
├── config.py # Configuration constants, monitored services list
|
||||
├── normalizer.py # Message normalization (regex replacements)
|
||||
├── known_issues.py # Ignore pattern matching
|
||||
├── llm_analysis.py # Vertex AI Gemini incident grouping + dedup
|
||||
├── discord.py # Discord webhook client
|
||||
└── firestore_adapter.py # CRUD for error_patterns, incidents, alerts
|
||||
```
|
||||
|
||||
### Configuration (`config.py`)
|
||||
|
||||
| Setting | Value |
|
||||
|---------|-------|
|
||||
| `GCP_PROJECT` | `nomadkaraoke` |
|
||||
| `LOOKBACK_MINUTES` | 15 |
|
||||
| `MAX_LOG_ENTRIES` | 500 |
|
||||
| `LLM_ANALYSIS_ENABLED` | true (env var) |
|
||||
| `LLM_ANALYSIS_MODEL` | `gemini-2.0-flash` |
|
||||
| `MIN_PATTERNS_FOR_ANALYSIS` | 2 |
|
||||
| `SPIKE_MULTIPLIER` | 5.0 |
|
||||
| `SPIKE_MIN_COUNT` | 5 |
|
||||
| `MAX_DISCORD_MESSAGES_PER_RUN` | 10 |
|
||||
| `MAX_ACTIVE_PATTERNS` | 500 |
|
||||
| `ROLLING_WINDOW_DAYS` | 7 |
|
||||
| `DISCORD_WEBHOOK_SECRET` | `discord-alert-webhook` |
|
||||
|
||||
---
|
||||
|
||||
## 12. Testing
|
||||
|
||||
### Unit Tests
|
||||
|
||||
```
|
||||
tests/unit/services/error_monitor/
|
||||
├── test_monitor.py # Core grouping, windowing logic
|
||||
├── test_normalizer.py # Message normalization
|
||||
├── test_llm_analysis.py # LLM grouping, dedup
|
||||
├── test_firestore_adapter.py # CRUD, rolling counts, resolution
|
||||
├── test_discord.py # Message formatting
|
||||
├── test_known_issues.py # Ignore pattern matching
|
||||
├── test_dedup.py # Duplicate detection
|
||||
└── test_monitor_orchestration.py # Full pipeline integration
|
||||
```
|
||||
|
||||
### Integration Tests
|
||||
|
||||
- Test against Firestore emulator for pattern CRUD
|
||||
- Test Cloud Logging query construction (mock the API client)
|
||||
- Test Discord webhook formatting (mock HTTP)
|
||||
|
||||
---
|
||||
|
||||
## 13. Out of Scope (Future Work)
|
||||
|
||||
- **Auto-fixer (Nomad-fix):** Autonomous Claude Code agent that receives errors via Pub/Sub, creates fix PRs. Designed as a separate follow-up project.
|
||||
- **Frontend admin dashboard:** Visual error monitoring UI. The slash commands serve this purpose for now.
|
||||
- **Cross-repo error correlation:** Correlating errors between karaoke-gen and karaoke-decide Firestore. Both write to the same `error_patterns` collection, so patterns from both are visible together.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,888 +0,0 @@
|
||||
# Daily E2E Payment + Happy Path Test — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a daily E2E test that purchases credits via real Stripe Checkout, then uses them to run the existing happy path karaoke job creation test.
|
||||
|
||||
**Architecture:** A single GitHub Actions workflow (`e2e-daily.yml`) runs two sequential jobs: Stage 1 (credit purchase via real Stripe) outputs a session token, Stage 2 (happy path) consumes it. Discord + email notifications on both success and failure.
|
||||
|
||||
**Tech Stack:** Playwright, GitHub Actions, Stripe Checkout (live mode), testmail.app, Discord webhooks, SendGrid
|
||||
|
||||
**Spec:** `docs/archive/2026-04-12-daily-e2e-payment-test-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| File | Responsibility |
|
||||
|------|---------------|
|
||||
| `frontend/e2e/helpers/stripe-checkout.ts` | **New** — Helper to fill Stripe's hosted checkout page (card fields in iframes) |
|
||||
| `frontend/e2e/production/credit-purchase-real.spec.ts` | **New** — Playwright test: signup with referral, buy 1 credit via real Stripe, verify credit + email |
|
||||
| `.github/workflows/e2e-daily.yml` | **New** — Combined two-stage workflow (credit purchase → happy path) with Discord + email alerts |
|
||||
| `.github/workflows/e2e-happy-path.yml` | **Delete** — Replaced by e2e-daily.yml |
|
||||
|
||||
No modifications to existing test files. The happy path test already supports `E2E_TEST_TOKEN` for pre-auth.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Stripe Checkout Page Helper
|
||||
|
||||
**Files:**
|
||||
- Create: `frontend/e2e/helpers/stripe-checkout.ts`
|
||||
|
||||
This helper navigates Stripe's hosted checkout page. Stripe Checkout uses iframes for card input fields — the helper must locate the correct iframe, then fill within it.
|
||||
|
||||
- [ ] **Step 1: Create the stripe-checkout helper**
|
||||
|
||||
```typescript
|
||||
// frontend/e2e/helpers/stripe-checkout.ts
|
||||
import { Page, FrameLocator } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Fill card details on Stripe's hosted checkout page (checkout.stripe.com).
|
||||
*
|
||||
* Stripe embeds card inputs in iframes. This helper locates the
|
||||
* correct iframe for each field and fills it.
|
||||
*
|
||||
* Environment variables:
|
||||
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY,
|
||||
* E2E_STRIPE_CARD_CVC, E2E_STRIPE_CARDHOLDER_NAME (optional)
|
||||
*/
|
||||
|
||||
interface CardDetails {
|
||||
number: string;
|
||||
expiry: string;
|
||||
cvc: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
function getCardDetailsFromEnv(): CardDetails {
|
||||
const number = process.env.E2E_STRIPE_CARD_NUMBER;
|
||||
const expiry = process.env.E2E_STRIPE_CARD_EXPIRY;
|
||||
const cvc = process.env.E2E_STRIPE_CARD_CVC;
|
||||
const name = process.env.E2E_STRIPE_CARDHOLDER_NAME;
|
||||
|
||||
if (!number || !expiry || !cvc) {
|
||||
throw new Error(
|
||||
'Missing Stripe card env vars: E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC'
|
||||
);
|
||||
}
|
||||
|
||||
return { number, expiry, cvc, name };
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for the Stripe Checkout page to fully load.
|
||||
* Call after the browser has navigated to checkout.stripe.com.
|
||||
*/
|
||||
async function waitForStripeCheckout(page: Page, timeoutMs = 30_000): Promise<void> {
|
||||
await page.waitForURL(/checkout\.stripe\.com/, { timeout: timeoutMs });
|
||||
// Wait for the payment form to be interactive
|
||||
await page.waitForSelector('#cardNumber, [data-testid="card-number-input"]', {
|
||||
state: 'visible',
|
||||
timeout: timeoutMs,
|
||||
}).catch(() => {
|
||||
// Stripe may use iframe-based fields — check for that
|
||||
});
|
||||
// Give Stripe JS time to initialize iframes
|
||||
await page.waitForTimeout(2000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill a single field inside a Stripe iframe.
|
||||
* Stripe card inputs live in individual iframes identified by their title or name.
|
||||
*/
|
||||
async function fillStripeField(
|
||||
page: Page,
|
||||
iframeSelector: string,
|
||||
inputSelector: string,
|
||||
value: string,
|
||||
): Promise<void> {
|
||||
// Try direct input first (some Stripe Checkout versions use plain inputs)
|
||||
const directInput = page.locator(inputSelector).first();
|
||||
if (await directInput.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||
await directInput.fill(value);
|
||||
return;
|
||||
}
|
||||
|
||||
// Fall back to iframe-based input
|
||||
const frame = page.frameLocator(iframeSelector).first();
|
||||
const input = frame.locator(inputSelector).first();
|
||||
await input.waitFor({ state: 'visible', timeout: 10_000 });
|
||||
// Use type() instead of fill() — Stripe's custom inputs often reject fill()
|
||||
await input.type(value, { delay: 50 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete the Stripe Checkout page with card details from environment.
|
||||
*
|
||||
* @param page - Playwright page already navigated to checkout.stripe.com
|
||||
* @returns void — after this, the page will redirect to the success URL
|
||||
*/
|
||||
export async function completeStripeCheckout(page: Page): Promise<void> {
|
||||
const card = getCardDetailsFromEnv();
|
||||
|
||||
console.log(' Waiting for Stripe Checkout page...');
|
||||
await waitForStripeCheckout(page);
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
|
||||
console.log(' Stripe Checkout loaded');
|
||||
|
||||
// Fill email if Stripe asks for it (sometimes pre-filled from session)
|
||||
const emailInput = page.locator('#email');
|
||||
if (await emailInput.isVisible({ timeout: 3000 }).catch(() => false)) {
|
||||
// Email should be pre-filled from checkout session, but clear and re-enter if empty
|
||||
const currentEmail = await emailInput.inputValue();
|
||||
if (!currentEmail) {
|
||||
console.log(' Stripe email field is empty — cannot fill without knowing email');
|
||||
} else {
|
||||
console.log(` Stripe email pre-filled: ${currentEmail}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Fill card number
|
||||
console.log(' Filling card number...');
|
||||
await fillStripeField(
|
||||
page,
|
||||
'iframe[title*="card number" i], iframe[name*="cardNumber" i]',
|
||||
'input[name="cardnumber"], input[name="number"], input[autocomplete="cc-number"]',
|
||||
card.number,
|
||||
);
|
||||
|
||||
// Fill expiry
|
||||
console.log(' Filling card expiry...');
|
||||
await fillStripeField(
|
||||
page,
|
||||
'iframe[title*="expir" i], iframe[name*="cardExpiry" i]',
|
||||
'input[name="exp-date"], input[name="expiry"], input[autocomplete="cc-exp"]',
|
||||
card.expiry,
|
||||
);
|
||||
|
||||
// Fill CVC
|
||||
console.log(' Filling CVC...');
|
||||
await fillStripeField(
|
||||
page,
|
||||
'iframe[title*="cvc" i], iframe[title*="security" i], iframe[name*="cardCvc" i]',
|
||||
'input[name="cvc"], input[autocomplete="cc-csc"]',
|
||||
card.cvc,
|
||||
);
|
||||
|
||||
// Fill cardholder name if field exists and name is provided
|
||||
if (card.name) {
|
||||
const nameInput = page.locator('#billingName, input[name="billingName"]');
|
||||
if (await nameInput.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||
console.log(' Filling cardholder name...');
|
||||
await nameInput.fill(card.name);
|
||||
}
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
|
||||
console.log(' Card details filled');
|
||||
|
||||
// Click the Pay button
|
||||
console.log(' Clicking Pay button...');
|
||||
const payButton = page.getByRole('button', { name: /pay/i }).first();
|
||||
await payButton.waitFor({ state: 'visible', timeout: 10_000 });
|
||||
await payButton.click();
|
||||
|
||||
console.log(' Payment submitted, waiting for redirect...');
|
||||
// Wait for redirect back to our site (success page)
|
||||
await page.waitForURL(/nomadkaraoke\.com.*payment\/success|nomadkaraoke\.com.*\/app/, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-complete.png' });
|
||||
console.log(' Stripe Checkout complete — redirected to success page');
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/e2e/helpers/stripe-checkout.ts
|
||||
git commit -m "feat(e2e): add Stripe Checkout page automation helper"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Credit Purchase E2E Test
|
||||
|
||||
**Files:**
|
||||
- Create: `frontend/e2e/production/credit-purchase-real.spec.ts`
|
||||
|
||||
This is the Stage 1 Playwright test. It signs up a fresh user with referral code, buys 1 credit via real Stripe, and verifies the credit lands.
|
||||
|
||||
- [ ] **Step 1: Create the credit purchase test**
|
||||
|
||||
```typescript
|
||||
// frontend/e2e/production/credit-purchase-real.spec.ts
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
|
||||
import { completeStripeCheckout } from '../helpers/stripe-checkout';
|
||||
import { getPageAuthToken, verifyToken } from '../helpers/auth';
|
||||
import { URLS, TIMEOUTS } from '../helpers/constants';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
/**
|
||||
* E2E Test: Real Credit Purchase via Stripe Checkout
|
||||
*
|
||||
* Tests the REAL payment flow that customers use:
|
||||
* 1. Sign up with referral code e2etest70 (70% discount)
|
||||
* 2. Open Buy Credits dialog
|
||||
* 3. Purchase 1 credit via real Stripe Checkout ($3.00 after discount)
|
||||
* 4. Verify credits allocated and confirmation email received
|
||||
*
|
||||
* This test uses a REAL credit card and processes a REAL charge.
|
||||
* The 70% referral discount keeps cost to ~$3/day.
|
||||
*
|
||||
* Prerequisites:
|
||||
* - E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC
|
||||
* - TESTMAIL_API_KEY + TESTMAIL_NAMESPACE
|
||||
* - E2E_ADMIN_TOKEN (for credit verification + cleanup)
|
||||
*
|
||||
* Output:
|
||||
* - Writes session token to test-results/e2e-session-token.txt
|
||||
* for Stage 2 (happy path) to consume
|
||||
*/
|
||||
|
||||
const PROD_URL = URLS.production.frontend;
|
||||
const API_URL = URLS.production.api;
|
||||
|
||||
test.describe('Real Credit Purchase Flow', () => {
|
||||
test('purchase 1 credit via Stripe Checkout with referral discount', async ({ page, request }) => {
|
||||
// ===== PREREQUISITES =====
|
||||
test.skip(!process.env.E2E_STRIPE_CARD_NUMBER, 'E2E_STRIPE_CARD_NUMBER not set');
|
||||
test.skip(!isEmailTestingAvailable(), 'Testmail credentials not set');
|
||||
|
||||
const adminToken = process.env.E2E_ADMIN_TOKEN;
|
||||
test.skip(!adminToken, 'E2E_ADMIN_TOKEN not set');
|
||||
|
||||
const emailHelper = await createEmailHelper();
|
||||
const inbox = await emailHelper.createInbox();
|
||||
console.log(`Test email: ${inbox.emailAddress}`);
|
||||
|
||||
try {
|
||||
// ===== STEP 1: Navigate with referral code =====
|
||||
console.log('\n=== STEP 1: Navigate with referral code ===');
|
||||
await page.goto(`${PROD_URL}/?ref=e2etest70`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.screenshot({ path: 'test-results/01-landing-with-referral.png' });
|
||||
console.log(' Landed with ?ref=e2etest70');
|
||||
|
||||
// ===== STEP 2: Sign up via magic link =====
|
||||
console.log('\n=== STEP 2: Sign up via magic link ===');
|
||||
|
||||
// Click Sign Up Free
|
||||
const signUpButton = page.getByRole('button', { name: /sign up free/i });
|
||||
await expect(signUpButton).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await signUpButton.click();
|
||||
|
||||
// Fill email in AuthDialog
|
||||
const authDialog = page.getByRole('dialog');
|
||||
await expect(authDialog).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
const emailInput = authDialog.getByPlaceholder('you@example.com');
|
||||
await emailInput.fill(inbox.emailAddress!);
|
||||
await page.screenshot({ path: 'test-results/02-auth-dialog.png' });
|
||||
|
||||
// Send magic link
|
||||
const sendButton = page.getByRole('button', { name: /send sign-in link/i });
|
||||
await sendButton.click();
|
||||
await expect(page.getByText(/check your email/i)).toBeVisible({ timeout: 15000 });
|
||||
console.log(' Magic link sent');
|
||||
|
||||
// Wait for email and extract link
|
||||
const magicEmail = await emailHelper.waitForEmail(inbox.id!, 60000);
|
||||
const magicLink = emailHelper.extractMagicLink(magicEmail);
|
||||
if (!magicLink) throw new Error('Could not extract magic link from email');
|
||||
console.log(` Magic link received`);
|
||||
|
||||
// Navigate to magic link
|
||||
await page.goto(magicLink);
|
||||
|
||||
// Handle verification result (new user interstitial or direct success)
|
||||
const verifyResult = await Promise.race([
|
||||
page.getByText(/successfully signed in/i).waitFor({ state: 'visible', timeout: 30000 }).then(() => 'success'),
|
||||
page.getByText(/welcome to nomad karaoke/i).waitFor({ state: 'visible', timeout: 30000 }).then(() => 'credits_interstitial'),
|
||||
]);
|
||||
console.log(` Verification: ${verifyResult}`);
|
||||
|
||||
if (verifyResult === 'credits_interstitial') {
|
||||
const startButton = page.getByRole('button', { name: /start creating|go to dashboard|explore the app/i });
|
||||
await expect(startButton).toBeVisible({ timeout: 5000 });
|
||||
await startButton.click();
|
||||
}
|
||||
|
||||
await page.waitForURL(/\/app/, { timeout: 15000 });
|
||||
await page.screenshot({ path: 'test-results/03-authenticated.png' });
|
||||
console.log(' Authenticated and on /app');
|
||||
|
||||
// Extract session token for Stage 2
|
||||
const sessionToken = await getPageAuthToken(page);
|
||||
if (!sessionToken) throw new Error('No session token after auth');
|
||||
|
||||
// ===== STEP 3: Open Buy Credits and verify discount =====
|
||||
console.log('\n=== STEP 3: Open Buy Credits dialog ===');
|
||||
|
||||
// Click "Buy Credits" button in header
|
||||
const buyButton = page.getByRole('button', { name: /buy credits/i });
|
||||
await expect(buyButton).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await buyButton.click();
|
||||
|
||||
// Wait for BuyCreditsDialog
|
||||
const creditsDialog = page.getByRole('dialog');
|
||||
await expect(creditsDialog).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.screenshot({ path: 'test-results/04-buy-credits-dialog.png' });
|
||||
|
||||
// Verify referral discount badge is showing
|
||||
const discountBadge = creditsDialog.getByText(/70%\s*off/i);
|
||||
await expect(discountBadge).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
console.log(' Referral discount badge visible (70% off)');
|
||||
|
||||
// ===== STEP 4: Select 1-credit package =====
|
||||
console.log('\n=== STEP 4: Select 1-credit package ===');
|
||||
|
||||
// Click the 1-credit package button
|
||||
// Packages are buttons within the dialog showing credit counts
|
||||
const oneCredit = creditsDialog.getByRole('button').filter({ hasText: /\b1\b/ }).filter({ hasText: /credit/i }).first();
|
||||
await oneCredit.click();
|
||||
await page.screenshot({ path: 'test-results/05-package-selected.png' });
|
||||
console.log(' Selected 1-credit package');
|
||||
|
||||
// Verify the discounted price ($3.00) is shown
|
||||
// The checkout button should show the price
|
||||
const checkoutButton = creditsDialog.getByRole('button', { name: /continue|checkout|pay/i }).last();
|
||||
await expect(checkoutButton).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
const buttonText = await checkoutButton.textContent();
|
||||
console.log(` Checkout button: "${buttonText}"`);
|
||||
|
||||
// ===== STEP 5: Proceed to Stripe Checkout =====
|
||||
console.log('\n=== STEP 5: Stripe Checkout ===');
|
||||
await checkoutButton.click();
|
||||
|
||||
// Complete Stripe Checkout with real card
|
||||
await completeStripeCheckout(page);
|
||||
|
||||
// ===== STEP 6: Verify payment success page =====
|
||||
console.log('\n=== STEP 6: Verify payment success ===');
|
||||
await page.waitForURL(/payment\/success/, { timeout: 30000 });
|
||||
|
||||
// Verify success indicators
|
||||
const successText = page.getByText(/payment successful/i);
|
||||
await expect(successText).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
// Verify credit balance shows 1
|
||||
const creditBalance = page.getByText(/1\s+credit/i);
|
||||
await expect(creditBalance).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.screenshot({ path: 'test-results/06-payment-success.png' });
|
||||
console.log(' Payment success page shows 1 credit');
|
||||
|
||||
// ===== STEP 7: Verify via admin API =====
|
||||
console.log('\n=== STEP 7: Verify credits via API ===');
|
||||
const userResponse = await request.get(`${API_URL}/api/users/me`, {
|
||||
headers: { Authorization: `Bearer ${sessionToken}` },
|
||||
});
|
||||
expect(userResponse.ok()).toBe(true);
|
||||
const userData = await userResponse.json();
|
||||
console.log(` API credits: ${userData.credits}`);
|
||||
expect(userData.credits).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// ===== STEP 8: Verify confirmation email =====
|
||||
console.log('\n=== STEP 8: Verify confirmation email ===');
|
||||
try {
|
||||
// Wait for the second email (first was magic link, second is payment confirmation)
|
||||
const confirmEmail = await emailHelper.waitForEmail(inbox.id!, 30000);
|
||||
console.log(` Confirmation email: "${confirmEmail.subject}"`);
|
||||
const emailText = ((confirmEmail.subject || '') + ' ' + (confirmEmail.body || '')).toLowerCase();
|
||||
expect(emailText).toContain('credit');
|
||||
} catch (e) {
|
||||
// Email verification is best-effort — don't fail the payment test for email issues
|
||||
console.log(` Email verification skipped: ${e}`);
|
||||
}
|
||||
|
||||
// ===== OUTPUT: Save token for Stage 2 =====
|
||||
console.log('\n=== OUTPUT: Saving session token for Stage 2 ===');
|
||||
const outputDir = path.join(process.cwd(), 'test-results');
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(outputDir, 'e2e-session-token.txt'), sessionToken);
|
||||
console.log(' Token saved to test-results/e2e-session-token.txt');
|
||||
|
||||
console.log('\n✅ CREDIT PURCHASE TEST PASSED');
|
||||
|
||||
} finally {
|
||||
if (inbox?.id) {
|
||||
await emailHelper.deleteInbox(inbox.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Commit**
|
||||
|
||||
```bash
|
||||
git add frontend/e2e/production/credit-purchase-real.spec.ts
|
||||
git commit -m "feat(e2e): add real Stripe Checkout credit purchase test"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: GitHub Actions Workflow
|
||||
|
||||
**Files:**
|
||||
- Create: `.github/workflows/e2e-daily.yml`
|
||||
- Delete: `.github/workflows/e2e-happy-path.yml`
|
||||
|
||||
Two-stage workflow: credit purchase → happy path. Discord + email notifications.
|
||||
|
||||
- [ ] **Step 1: Create the new e2e-daily workflow**
|
||||
|
||||
```yaml
|
||||
# .github/workflows/e2e-daily.yml
|
||||
name: E2E Daily Test (Payment + Happy Path)
|
||||
|
||||
# Full production E2E: buy credits via real Stripe, then use them for karaoke generation.
|
||||
# Replaces the previous e2e-happy-path.yml with an additional payment stage.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 6 * * *' # Daily at 6 AM UTC
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
debug_mode:
|
||||
description: 'Enable debug mode (slower, more screenshots)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
browser:
|
||||
description: 'Browser to test with'
|
||||
required: false
|
||||
default: 'chromium'
|
||||
type: choice
|
||||
options:
|
||||
- chromium
|
||||
- firefox
|
||||
- webkit
|
||||
skip_payment:
|
||||
description: 'Skip Stage 1 (payment) — use admin-granted credits for happy path only'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
use_test_token:
|
||||
description: 'Skip signup entirely — use E2E_TEST_TOKEN (for quick iterations)'
|
||||
required: false
|
||||
default: 'false'
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
# =========================================================================
|
||||
# Stage 1: Purchase credits via real Stripe Checkout
|
||||
# =========================================================================
|
||||
e2e-credit-purchase:
|
||||
name: "Stage 1: Credit Purchase"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
if: ${{ github.event.inputs.skip_payment != 'true' && github.event.inputs.use_test_token != 'true' }}
|
||||
|
||||
outputs:
|
||||
session_token: ${{ steps.extract_token.outputs.token }}
|
||||
result: ${{ steps.test_result.outputs.result }}
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps ${{ inputs.browser || 'chromium' }}
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Run Credit Purchase Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_STRIPE_CARD_NUMBER: ${{ secrets.E2E_STRIPE_CARD_NUMBER }}
|
||||
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
|
||||
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
|
||||
E2E_STRIPE_CARDHOLDER_NAME: ${{ secrets.E2E_STRIPE_CARDHOLDER_NAME }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
|
||||
echo "Time: $(date)"
|
||||
npx playwright test credit-purchase-real.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=${{ inputs.browser || 'chromium' }} \
|
||||
--reporter=list \
|
||||
--timeout=600000 \
|
||||
2>&1 | tee test-output-payment.log
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if grep -q "CREDIT PURCHASE TEST PASSED" test-output-payment.log; then
|
||||
echo "result=success" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "result=failure" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Extract session token
|
||||
id: extract_token
|
||||
if: steps.test_result.outputs.result == 'success'
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if [ -f test-results/e2e-session-token.txt ]; then
|
||||
TOKEN=$(cat test-results/e2e-session-token.txt)
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
echo "Session token extracted for Stage 2"
|
||||
else
|
||||
echo "No session token file found"
|
||||
echo "token=" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Upload artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-payment-results-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/test-output-payment.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase\", \"description\": \"Payment flow is broken. Customers may not be receiving credits.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
|
||||
# =========================================================================
|
||||
# Stage 2: Happy Path (uses credit from Stage 1)
|
||||
# =========================================================================
|
||||
e2e-happy-path:
|
||||
name: "Stage 2: Happy Path"
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
needs: e2e-credit-purchase
|
||||
# Run if: Stage 1 succeeded, OR Stage 1 was skipped (skip_payment/use_test_token)
|
||||
if: |
|
||||
always() && (
|
||||
needs.e2e-credit-purchase.result == 'success' ||
|
||||
github.event.inputs.skip_payment == 'true' ||
|
||||
github.event.inputs.use_test_token == 'true'
|
||||
)
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: frontend
|
||||
run: npm ci --legacy-peer-deps
|
||||
|
||||
- name: Install Playwright browsers
|
||||
working-directory: frontend
|
||||
run: npx playwright install --with-deps ${{ inputs.browser || 'chromium' }}
|
||||
|
||||
- name: Create test-results directory
|
||||
working-directory: frontend
|
||||
run: mkdir -p test-results
|
||||
|
||||
- name: Ensure testmail.app domain is allowlisted
|
||||
run: |
|
||||
curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
|
||||
|
||||
- name: Refresh E2E session token (when use_test_token enabled)
|
||||
id: refresh_token
|
||||
if: github.event.inputs.use_test_token == 'true'
|
||||
run: |
|
||||
RESPONSE=$(curl -sf -X POST \
|
||||
"https://api.nomadkaraoke.com/api/admin/users/e2e-test-runner@nomadkaraoke.com/impersonate" \
|
||||
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
|
||||
-H "Content-Type: application/json")
|
||||
TOKEN=$(echo "$RESPONSE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["session_token"])')
|
||||
echo "::add-mask::$TOKEN"
|
||||
echo "token=$TOKEN" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Run Happy Path Test
|
||||
working-directory: frontend
|
||||
env:
|
||||
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
|
||||
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
|
||||
# Token priority: use_test_token > Stage 1 output > empty (full signup)
|
||||
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || needs.e2e-credit-purchase.outputs.session_token || '' }}
|
||||
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
|
||||
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
|
||||
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
|
||||
run: |
|
||||
echo "=== Stage 2: Happy Path ==="
|
||||
echo "Time: $(date)"
|
||||
TOKEN_SOURCE="none"
|
||||
if [ -n "${{ steps.refresh_token.outputs.token }}" ]; then
|
||||
TOKEN_SOURCE="use_test_token (impersonation)"
|
||||
elif [ -n "${{ needs.e2e-credit-purchase.outputs.session_token }}" ]; then
|
||||
TOKEN_SOURCE="Stage 1 (credit purchase)"
|
||||
fi
|
||||
echo "Token source: $TOKEN_SOURCE"
|
||||
|
||||
npx playwright test happy-path-real-user.spec.ts \
|
||||
--config=playwright.production.config.ts \
|
||||
--project=${{ inputs.browser || 'chromium' }} \
|
||||
--reporter=list \
|
||||
--timeout=3600000 \
|
||||
2>&1 | tee test-output-happy-path.log
|
||||
continue-on-error: true
|
||||
|
||||
- name: Check test result
|
||||
id: test_result
|
||||
working-directory: frontend
|
||||
run: |
|
||||
if grep -q "passed" test-output-happy-path.log && ! grep -q "failed" test-output-happy-path.log; then
|
||||
echo "result=success" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "result=failure" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: Upload test artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-results-${{ github.run_number }}
|
||||
path: |
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
frontend/test-output-happy-path.log
|
||||
retention-days: 30
|
||||
|
||||
- name: Upload video recordings
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: e2e-happy-path-videos-${{ github.run_number }}
|
||||
path: frontend/test-results/**/*.webm
|
||||
retention-days: 30
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Create summary
|
||||
if: always()
|
||||
run: |
|
||||
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
|
||||
STAGE2="${{ steps.test_result.outputs.result || 'unknown' }}"
|
||||
echo "## E2E Daily Test Results" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage | Result |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage 1: Credit Purchase | ${STAGE1} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Stage 2: Happy Path | ${STAGE2} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Property | Value |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "|----------|-------|" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Run | #${{ github.run_number }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Trigger | ${{ github.event_name }} |" >> $GITHUB_STEP_SUMMARY
|
||||
echo "| Browser | ${{ inputs.browser || 'chromium' }} |" >> $GITHUB_STEP_SUMMARY
|
||||
|
||||
- name: Discord notification (failure)
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: |
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 2: Happy Path\", \"description\": \"Karaoke generation flow is broken.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Fail if test failed
|
||||
if: steps.test_result.outputs.result == 'failure'
|
||||
run: exit 1
|
||||
|
||||
# =========================================================================
|
||||
# Final: Send notifications
|
||||
# =========================================================================
|
||||
notify:
|
||||
name: "Notify"
|
||||
runs-on: ubuntu-latest
|
||||
needs: [e2e-credit-purchase, e2e-happy-path]
|
||||
if: always()
|
||||
|
||||
steps:
|
||||
- name: Discord notification (success)
|
||||
if: needs.e2e-happy-path.result == 'success'
|
||||
run: |
|
||||
STAGE1="${{ needs.e2e-credit-purchase.result || 'skipped' }}"
|
||||
curl -s -H "Content-Type: application/json" \
|
||||
-d "{\"embeds\": [{\"title\": \"✅ E2E Daily Test PASSED\", \"description\": \"Payment: ${STAGE1} | Happy Path: success\n\n**Run:** #${{ github.run_number }}\", \"color\": 3066993}]}" \
|
||||
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
|
||||
|
||||
- name: Send email notification
|
||||
if: github.event_name == 'schedule'
|
||||
uses: dawidd6/action-send-mail@v3
|
||||
with:
|
||||
server_address: smtp.sendgrid.net
|
||||
server_port: 587
|
||||
username: apikey
|
||||
password: ${{ secrets.SENDGRID_API_KEY }}
|
||||
subject: "E2E Daily Test ${{ needs.e2e-happy-path.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
|
||||
to: andrew@nomadkaraoke.com
|
||||
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
|
||||
body: |
|
||||
E2E Daily Test Results
|
||||
======================
|
||||
|
||||
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
|
||||
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
|
||||
|
||||
Run: #${{ github.run_number }}
|
||||
Trigger: ${{ github.event_name }}
|
||||
|
||||
View details: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Delete the old workflow**
|
||||
|
||||
```bash
|
||||
rm .github/workflows/e2e-happy-path.yml
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
git add .github/workflows/e2e-daily.yml
|
||||
git rm .github/workflows/e2e-happy-path.yml
|
||||
git commit -m "feat(ci): replace e2e-happy-path with e2e-daily (payment + happy path)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Configure Referral Link and GitHub Secrets
|
||||
|
||||
This task is manual setup — no code changes, but must be done before the test can run.
|
||||
|
||||
- [ ] **Step 1: Verify or create the `e2etest70` referral link in production**
|
||||
|
||||
```bash
|
||||
# Check if it exists
|
||||
curl -s "https://api.nomadkaraoke.com/api/referrals/e2etest70/interstitial" | python3 -m json.tool
|
||||
|
||||
# If it doesn't exist, create it via admin API:
|
||||
ADMIN_TOKEN=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1)
|
||||
curl -s -X POST "https://api.nomadkaraoke.com/api/referrals/admin/links" \
|
||||
-H "X-Admin-Token: $ADMIN_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"code": "e2etest70",
|
||||
"owner_email": "admin@nomadkaraoke.com",
|
||||
"display_name": "E2E Test",
|
||||
"discount_percent": 70,
|
||||
"kickback_percent": 0,
|
||||
"duration_days": 36500
|
||||
}' | python3 -m json.tool
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add GitHub Actions secrets**
|
||||
|
||||
```bash
|
||||
# Card details (user will provide these)
|
||||
gh secret set E2E_STRIPE_CARD_NUMBER --repo nomadkaraoke/karaoke-gen
|
||||
gh secret set E2E_STRIPE_CARD_EXPIRY --repo nomadkaraoke/karaoke-gen
|
||||
gh secret set E2E_STRIPE_CARD_CVC --repo nomadkaraoke/karaoke-gen
|
||||
gh secret set E2E_STRIPE_CARDHOLDER_NAME --repo nomadkaraoke/karaoke-gen
|
||||
|
||||
# Discord webhook (from GCP Secret Manager)
|
||||
DISCORD_URL=$(gcloud secrets versions access latest --secret=discord-alert-webhook --project=nomadkaraoke)
|
||||
gh secret set DISCORD_ALERT_WEBHOOK_URL --repo nomadkaraoke/karaoke-gen --body "$DISCORD_URL"
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify secrets are set**
|
||||
|
||||
```bash
|
||||
gh secret list --repo nomadkaraoke/karaoke-gen | grep -E "E2E_STRIPE|DISCORD_ALERT"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Manual Test Run and Verification
|
||||
|
||||
- [ ] **Step 1: Push the branch and trigger the workflow manually**
|
||||
|
||||
```bash
|
||||
git push origin HEAD
|
||||
```
|
||||
|
||||
Then trigger via GitHub UI or CLI:
|
||||
```bash
|
||||
gh workflow run e2e-daily.yml --ref $(git branch --show-current) -f skip_payment=false -f debug_mode=true
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Monitor the run**
|
||||
|
||||
```bash
|
||||
# Watch the latest run
|
||||
gh run list --workflow=e2e-daily.yml --limit 1
|
||||
gh run watch $(gh run list --workflow=e2e-daily.yml --limit 1 --json databaseId -q '.[0].databaseId')
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify Stage 1 (credit purchase) passed**
|
||||
|
||||
Check:
|
||||
- Stripe dashboard shows the $3.00 charge
|
||||
- Test user has 1 credit in Firestore
|
||||
- Confirmation email was received
|
||||
|
||||
- [ ] **Step 4: Verify Stage 2 (happy path) passed**
|
||||
|
||||
Check:
|
||||
- The token from Stage 1 was used (logs show "Using token: ...")
|
||||
- A karaoke job was created and completed
|
||||
- Discord received a success notification
|
||||
|
||||
- [ ] **Step 5: If any issues, fix and re-run**
|
||||
|
||||
The Stripe Checkout selectors are the most likely failure point. Check screenshots in the artifacts to see what Stripe's current UI looks like, then update `stripe-checkout.ts` selectors accordingly.
|
||||
|
||||
- [ ] **Step 6: Commit any selector fixes from the test run**
|
||||
|
||||
```bash
|
||||
git add -A
|
||||
git commit -m "fix(e2e): update Stripe Checkout selectors from test run"
|
||||
```
|
||||
@@ -1,891 +0,0 @@
|
||||
# Referral Marketing Flyer Generator — Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a "Generate Flyer" feature to the QR Code dialog that produces a personalized print-ready PDF marketing flyer using headless Chromium.
|
||||
|
||||
**Architecture:** Frontend sends the user's styled QR code (as a base64 data URL) + theme choice to a new backend endpoint. Backend injects the QR code, referral code, and discount into an HTML template, renders it to PDF with headless Chromium, and returns the PDF. Templates are copied from kjbox with placeholder substitution.
|
||||
|
||||
**Tech Stack:** Python (FastAPI), headless Chromium (`--print-to-pdf`), HTML/CSS templates, React/TypeScript frontend, `qr-code-styling` (existing)
|
||||
|
||||
**Spec:** `docs/archive/2026-04-05-referral-flyer-generator-design.md`
|
||||
|
||||
---
|
||||
|
||||
## File Map
|
||||
|
||||
| Action | File | Responsibility |
|
||||
|--------|------|----------------|
|
||||
| Create | `backend/templates/printables/website-referral-flyer.html` | Light theme template with placeholders |
|
||||
| Create | `backend/templates/printables/website-referral-flyer-dark.html` | Dark theme template with placeholders |
|
||||
| Create | `backend/services/flyer_service.py` | Template rendering + Chromium PDF generation |
|
||||
| Create | `backend/tests/test_flyer_service.py` | Unit tests for flyer service |
|
||||
| Modify | `backend/api/routes/referrals.py` | Add `POST /me/flyer` endpoint |
|
||||
| Modify | `backend/Dockerfile.base` | Add `chromium` apt package |
|
||||
| Modify | `frontend/components/referrals/QRCodeDialog.tsx` | Add theme picker + Generate Flyer button |
|
||||
| Modify | `frontend/lib/api.ts` | Add `generateFlyer()` function |
|
||||
| Modify | `frontend/messages/en.json` | Add flyer i18n strings |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Local Chrome verification (proof of concept)
|
||||
|
||||
Verify the template + headless Chrome PDF approach works locally before writing any production code.
|
||||
|
||||
**Files:**
|
||||
- Create (temporary): `backend/templates/printables/website-referral-flyer.html`
|
||||
|
||||
- [ ] **Step 1: Copy and templatize the light flyer**
|
||||
|
||||
Copy `/Users/andrew/Projects/nomadkaraoke/kjbox/printables/website-referral-flyer.html` to `backend/templates/printables/website-referral-flyer.html`.
|
||||
|
||||
Then make 3 substitutions in the new file:
|
||||
|
||||
1. Replace `src="qr-code-angel.svg"` with `src="{{QR_DATA_URL}}"` (line 330 of the original)
|
||||
2. Replace `<span class="referral-code">ANGEL</span>` with `<span class="referral-code">{{REFERRAL_CODE}}</span>` (line 334)
|
||||
3. Replace `First track free + 10% off with this link` with `First track free + {{DISCOUNT_PERCENT}}% off with this link` (line 336)
|
||||
4. Replace `alt="QR Code - nomadkaraoke.com/r/angel"` with `alt="QR Code - nomadkaraoke.com/r/{{REFERRAL_CODE_LOWER}}"` (line 330)
|
||||
|
||||
- [ ] **Step 2: Write a quick test script**
|
||||
|
||||
Create a temporary script `backend/test_flyer_local.py` (gitignored — add `test_flyer_local.py` to `.gitignore` or just delete after):
|
||||
|
||||
```python
|
||||
#!/usr/bin/env python3
|
||||
"""Local verification: generate a flyer PDF using Chrome headless."""
|
||||
import subprocess
|
||||
import tempfile
|
||||
import os
|
||||
import sys
|
||||
|
||||
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "templates/printables/website-referral-flyer.html")
|
||||
|
||||
# Read template
|
||||
with open(TEMPLATE_PATH) as f:
|
||||
html = f.read()
|
||||
|
||||
# Substitute placeholders
|
||||
html = html.replace("{{REFERRAL_CODE}}", "TESTCODE")
|
||||
html = html.replace("{{REFERRAL_CODE_LOWER}}", "testcode")
|
||||
html = html.replace("{{DISCOUNT_PERCENT}}", "10")
|
||||
# Use a simple black QR placeholder (1x1 black pixel as data URL for now)
|
||||
html = html.replace("{{QR_DATA_URL}}", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")
|
||||
|
||||
# Write to temp file
|
||||
with tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode="w") as tmp:
|
||||
tmp.write(html)
|
||||
tmp_html = tmp.name
|
||||
|
||||
output_pdf = "/tmp/test-flyer-output.pdf"
|
||||
|
||||
# Find Chrome
|
||||
chrome_paths = [
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
"/usr/bin/google-chrome",
|
||||
]
|
||||
chrome = None
|
||||
for p in chrome_paths:
|
||||
if os.path.exists(p):
|
||||
chrome = p
|
||||
break
|
||||
|
||||
if not chrome:
|
||||
print("ERROR: No Chrome/Chromium found")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Using: {chrome}")
|
||||
print(f"Template: {tmp_html}")
|
||||
print(f"Output: {output_pdf}")
|
||||
|
||||
cmd = [
|
||||
chrome,
|
||||
"--headless",
|
||||
f"--print-to-pdf={output_pdf}",
|
||||
"--no-margins",
|
||||
"--print-background",
|
||||
"--no-pdf-header-footer",
|
||||
"--virtual-time-budget=5000",
|
||||
"--paper-width=8.5",
|
||||
"--paper-height=11",
|
||||
tmp_html,
|
||||
]
|
||||
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
||||
os.unlink(tmp_html)
|
||||
|
||||
if result.returncode != 0:
|
||||
print(f"FAILED (exit {result.returncode})")
|
||||
print(result.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if os.path.exists(output_pdf):
|
||||
size = os.path.getsize(output_pdf)
|
||||
print(f"SUCCESS: {output_pdf} ({size} bytes)")
|
||||
# Open the PDF for visual inspection
|
||||
subprocess.run(["open", output_pdf])
|
||||
else:
|
||||
print("FAILED: No output PDF generated")
|
||||
sys.exit(1)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run the test**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
python3 backend/test_flyer_local.py
|
||||
```
|
||||
|
||||
Expected: PDF opens in Preview showing the flyer with "TESTCODE" referral code and a placeholder QR image. Verify: correct layout, gradients render, fonts load, no second blank page, no margins.
|
||||
|
||||
- [ ] **Step 4: Clean up and commit the template**
|
||||
|
||||
Delete the test script:
|
||||
```bash
|
||||
rm backend/test_flyer_local.py
|
||||
```
|
||||
|
||||
Commit the templatized flyer:
|
||||
```bash
|
||||
git add backend/templates/printables/website-referral-flyer.html
|
||||
git commit -m "feat(referral): add templatized light flyer from kjbox printables"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Templatize dark flyer + add Chromium to Dockerfile
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/templates/printables/website-referral-flyer-dark.html`
|
||||
- Modify: `backend/Dockerfile.base`
|
||||
|
||||
- [ ] **Step 1: Copy and templatize the dark flyer**
|
||||
|
||||
Copy `/Users/andrew/Projects/nomadkaraoke/kjbox/printables/website-referral-flyer-dark.html` to `backend/templates/printables/website-referral-flyer-dark.html`.
|
||||
|
||||
Make the same 4 substitutions as Task 1 Step 1:
|
||||
|
||||
1. `src="qr-code-angel.svg"` → `src="{{QR_DATA_URL}}"`
|
||||
2. `<span class="referral-code">ANGEL</span>` → `<span class="referral-code">{{REFERRAL_CODE}}</span>`
|
||||
3. `First track free + 10% off with this link` → `First track free + {{DISCOUNT_PERCENT}}% off with this link`
|
||||
4. `alt="QR Code - nomadkaraoke.com/r/angel"` → `alt="QR Code - nomadkaraoke.com/r/{{REFERRAL_CODE_LOWER}}"`
|
||||
|
||||
- [ ] **Step 2: Add Chromium to Dockerfile.base**
|
||||
|
||||
In `backend/Dockerfile.base`, add `chromium` to the first `apt-get install` block (the system dependencies section, around line 19-26). Add it after `xz-utils`:
|
||||
|
||||
```dockerfile
|
||||
RUN apt-get update && apt-get install -y \
|
||||
libsndfile1 \
|
||||
libsox-dev \
|
||||
sox \
|
||||
build-essential \
|
||||
curl \
|
||||
xz-utils \
|
||||
chromium \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
git add backend/templates/printables/website-referral-flyer-dark.html backend/Dockerfile.base
|
||||
git commit -m "feat(referral): add dark flyer template and chromium to Dockerfile"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Implement flyer service with tests
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/services/flyer_service.py`
|
||||
- Create: `backend/tests/test_flyer_service.py`
|
||||
|
||||
- [ ] **Step 1: Write the failing tests**
|
||||
|
||||
Create `backend/tests/test_flyer_service.py`:
|
||||
|
||||
```python
|
||||
"""Tests for flyer PDF generation service."""
|
||||
import os
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.flyer_service import FlyerService, FlyerError
|
||||
|
||||
|
||||
class TestFlyerService:
|
||||
"""Tests for FlyerService."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = FlyerService()
|
||||
|
||||
def test_render_template_light_substitutes_placeholders(self):
|
||||
html = self.service._render_template(
|
||||
theme="light",
|
||||
referral_code="MYCODE",
|
||||
discount_percent=15,
|
||||
qr_data_url="data:image/png;base64,abc123",
|
||||
)
|
||||
assert "MYCODE" in html
|
||||
assert "{{REFERRAL_CODE}}" not in html
|
||||
assert "{{QR_DATA_URL}}" not in html
|
||||
assert "{{DISCOUNT_PERCENT}}" not in html
|
||||
assert "{{REFERRAL_CODE_LOWER}}" not in html
|
||||
assert "15% off" in html
|
||||
assert "data:image/png;base64,abc123" in html
|
||||
assert "mycode" in html # lowercase version in alt text
|
||||
|
||||
def test_render_template_dark_substitutes_placeholders(self):
|
||||
html = self.service._render_template(
|
||||
theme="dark",
|
||||
referral_code="DARKCODE",
|
||||
discount_percent=20,
|
||||
qr_data_url="data:image/png;base64,xyz789",
|
||||
)
|
||||
assert "DARKCODE" in html
|
||||
assert "{{REFERRAL_CODE}}" not in html
|
||||
assert "data:image/png;base64,xyz789" in html
|
||||
assert "20% off" in html
|
||||
|
||||
def test_render_template_invalid_theme_raises(self):
|
||||
with pytest.raises(FlyerError, match="Invalid theme"):
|
||||
self.service._render_template(
|
||||
theme="neon",
|
||||
referral_code="CODE",
|
||||
discount_percent=10,
|
||||
qr_data_url="data:image/png;base64,abc",
|
||||
)
|
||||
|
||||
def test_render_template_uppercases_referral_code(self):
|
||||
html = self.service._render_template(
|
||||
theme="light",
|
||||
referral_code="mycode",
|
||||
discount_percent=10,
|
||||
qr_data_url="data:image/png;base64,abc",
|
||||
)
|
||||
# The code in the URL display should be uppercased
|
||||
assert '<span class="referral-code">MYCODE</span>' in html
|
||||
|
||||
@patch("backend.services.flyer_service.subprocess.run")
|
||||
def test_generate_pdf_calls_chromium_with_correct_flags(self, mock_run):
|
||||
mock_run.return_value = MagicMock(returncode=0)
|
||||
|
||||
# Mock the temp file to exist
|
||||
with patch("backend.services.flyer_service.tempfile.NamedTemporaryFile") as mock_tmp:
|
||||
mock_tmp_instance = MagicMock()
|
||||
mock_tmp_instance.__enter__ = MagicMock(return_value=mock_tmp_instance)
|
||||
mock_tmp_instance.__exit__ = MagicMock(return_value=False)
|
||||
mock_tmp_instance.name = "/tmp/test.html"
|
||||
mock_tmp.return_value = mock_tmp_instance
|
||||
|
||||
with patch("builtins.open", MagicMock()):
|
||||
with patch("os.path.exists", return_value=True):
|
||||
with patch("os.unlink"):
|
||||
self.service.generate_pdf(
|
||||
theme="light",
|
||||
referral_code="TEST",
|
||||
discount_percent=10,
|
||||
qr_data_url="data:image/png;base64,abc",
|
||||
)
|
||||
|
||||
# Verify chromium was called with the right flags
|
||||
call_args = mock_run.call_args[0][0]
|
||||
assert "--headless" in call_args
|
||||
assert "--no-margins" in call_args
|
||||
assert "--print-background" in call_args
|
||||
assert "--no-pdf-header-footer" in call_args
|
||||
assert "--virtual-time-budget=5000" in call_args
|
||||
assert "--paper-width=8.5" in call_args
|
||||
assert "--paper-height=11" in call_args
|
||||
|
||||
def test_validate_qr_data_url_rejects_non_data_url(self):
|
||||
with pytest.raises(FlyerError, match="Invalid QR"):
|
||||
self.service._validate_qr_data_url("https://evil.com/qr.png")
|
||||
|
||||
def test_validate_qr_data_url_rejects_too_large(self):
|
||||
huge_url = "data:image/png;base64," + "A" * 600_000
|
||||
with pytest.raises(FlyerError, match="too large"):
|
||||
self.service._validate_qr_data_url(huge_url)
|
||||
|
||||
def test_validate_qr_data_url_accepts_valid(self):
|
||||
# Should not raise
|
||||
self.service._validate_qr_data_url("data:image/png;base64,abc123")
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify they fail**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
python -m pytest backend/tests/test_flyer_service.py -v 2>&1 | tail -20
|
||||
```
|
||||
|
||||
Expected: FAIL — `backend.services.flyer_service` module doesn't exist.
|
||||
|
||||
- [ ] **Step 3: Implement the flyer service**
|
||||
|
||||
Create `backend/services/flyer_service.py`:
|
||||
|
||||
```python
|
||||
"""Service for generating personalized referral flyer PDFs."""
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), "..", "templates", "printables")
|
||||
|
||||
CHROMIUM_PATHS = [
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
"/usr/bin/google-chrome",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
]
|
||||
|
||||
VALID_THEMES = {"light", "dark"}
|
||||
MAX_QR_DATA_URL_BYTES = 500_000
|
||||
|
||||
|
||||
class FlyerError(Exception):
|
||||
"""Error during flyer generation."""
|
||||
|
||||
|
||||
class FlyerService:
|
||||
"""Generates personalized referral flyer PDFs."""
|
||||
|
||||
def __init__(self):
|
||||
self._chromium_path = self._find_chromium()
|
||||
|
||||
def _find_chromium(self) -> str:
|
||||
for path in CHROMIUM_PATHS:
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
# Also try shutil.which
|
||||
for name in ["chromium", "chromium-browser", "google-chrome"]:
|
||||
found = shutil.which(name)
|
||||
if found:
|
||||
return found
|
||||
raise FlyerError("Chromium not found. Install chromium to generate flyer PDFs.")
|
||||
|
||||
def _validate_qr_data_url(self, qr_data_url: str) -> None:
|
||||
if not qr_data_url.startswith("data:image/"):
|
||||
raise FlyerError("Invalid QR data URL: must be a data:image/ URL")
|
||||
if len(qr_data_url) > MAX_QR_DATA_URL_BYTES:
|
||||
raise FlyerError(f"QR data URL too large (>{MAX_QR_DATA_URL_BYTES} bytes)")
|
||||
|
||||
def _render_template(
|
||||
self,
|
||||
theme: str,
|
||||
referral_code: str,
|
||||
discount_percent: int,
|
||||
qr_data_url: str,
|
||||
) -> str:
|
||||
if theme not in VALID_THEMES:
|
||||
raise FlyerError(f"Invalid theme: {theme}. Must be one of: {VALID_THEMES}")
|
||||
|
||||
suffix = "-dark" if theme == "dark" else ""
|
||||
template_path = os.path.join(TEMPLATE_DIR, f"website-referral-flyer{suffix}.html")
|
||||
|
||||
with open(template_path) as f:
|
||||
html = f.read()
|
||||
|
||||
html = html.replace("{{REFERRAL_CODE}}", referral_code.upper())
|
||||
html = html.replace("{{REFERRAL_CODE_LOWER}}", referral_code.lower())
|
||||
html = html.replace("{{DISCOUNT_PERCENT}}", str(discount_percent))
|
||||
html = html.replace("{{QR_DATA_URL}}", qr_data_url)
|
||||
|
||||
return html
|
||||
|
||||
def generate_pdf(
|
||||
self,
|
||||
theme: str,
|
||||
referral_code: str,
|
||||
discount_percent: int,
|
||||
qr_data_url: str,
|
||||
) -> bytes:
|
||||
"""Generate a personalized flyer PDF.
|
||||
|
||||
Returns the raw PDF bytes.
|
||||
"""
|
||||
self._validate_qr_data_url(qr_data_url)
|
||||
html = self._render_template(theme, referral_code, discount_percent, qr_data_url)
|
||||
|
||||
# Write HTML to temp file (Chromium needs a file path)
|
||||
with tempfile.NamedTemporaryFile(
|
||||
suffix=".html", delete=False, mode="w", encoding="utf-8"
|
||||
) as tmp_html:
|
||||
tmp_html.write(html)
|
||||
tmp_html_path = tmp_html.name
|
||||
|
||||
tmp_pdf_path = tmp_html_path.replace(".html", ".pdf")
|
||||
|
||||
try:
|
||||
cmd = [
|
||||
self._chromium_path,
|
||||
"--headless",
|
||||
f"--print-to-pdf={tmp_pdf_path}",
|
||||
"--no-margins",
|
||||
"--print-background",
|
||||
"--no-pdf-header-footer",
|
||||
"--virtual-time-budget=5000",
|
||||
"--paper-width=8.5",
|
||||
"--paper-height=11",
|
||||
"--disable-gpu",
|
||||
"--no-sandbox",
|
||||
tmp_html_path,
|
||||
]
|
||||
|
||||
result = subprocess.run(
|
||||
cmd, capture_output=True, text=True, timeout=30
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
logger.error("Chromium PDF generation failed: %s", result.stderr)
|
||||
raise FlyerError(f"PDF generation failed: {result.stderr[:200]}")
|
||||
|
||||
if not os.path.exists(tmp_pdf_path):
|
||||
raise FlyerError("PDF generation failed: no output file created")
|
||||
|
||||
with open(tmp_pdf_path, "rb") as f:
|
||||
return f.read()
|
||||
|
||||
finally:
|
||||
# Clean up temp files
|
||||
for path in [tmp_html_path, tmp_pdf_path]:
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
# Singleton
|
||||
_flyer_service = None
|
||||
|
||||
|
||||
def get_flyer_service() -> FlyerService:
|
||||
global _flyer_service
|
||||
if _flyer_service is None:
|
||||
_flyer_service = FlyerService()
|
||||
return _flyer_service
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run tests to verify they pass**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
python -m pytest backend/tests/test_flyer_service.py -v 2>&1 | tail -20
|
||||
```
|
||||
|
||||
Expected: All 8 tests PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
git add backend/services/flyer_service.py backend/tests/test_flyer_service.py
|
||||
git commit -m "feat(referral): add flyer PDF generation service with tests"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Add flyer endpoint to referral routes
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/api/routes/referrals.py`
|
||||
|
||||
- [ ] **Step 1: Add the flyer endpoint**
|
||||
|
||||
In `backend/api/routes/referrals.py`, add after the existing imports at the top:
|
||||
|
||||
```python
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field
|
||||
from backend.services.flyer_service import get_flyer_service, FlyerError
|
||||
```
|
||||
|
||||
Add a request model after the existing imports:
|
||||
|
||||
```python
|
||||
class GenerateFlyerRequest(BaseModel):
|
||||
theme: str = Field(..., pattern="^(light|dark)$")
|
||||
qr_data_url: str = Field(..., max_length=500_000)
|
||||
```
|
||||
|
||||
Add the endpoint after the `start_stripe_connect` endpoint (around line 118), before the Admin section:
|
||||
|
||||
```python
|
||||
@router.post("/me/flyer")
|
||||
async def generate_flyer(
|
||||
request: GenerateFlyerRequest,
|
||||
auth=Depends(require_auth),
|
||||
):
|
||||
"""Generate a personalized referral flyer PDF."""
|
||||
service = get_referral_service()
|
||||
link = service.get_or_create_link(auth.user_email)
|
||||
|
||||
try:
|
||||
flyer_service = get_flyer_service()
|
||||
pdf_bytes = flyer_service.generate_pdf(
|
||||
theme=request.theme,
|
||||
referral_code=link.code,
|
||||
discount_percent=link.discount_percent,
|
||||
qr_data_url=request.qr_data_url,
|
||||
)
|
||||
except FlyerError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": 'attachment; filename="nomad-karaoke-referral-flyer.pdf"',
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run backend tests**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
python -m pytest backend/tests/ -v --timeout=30 2>&1 | tail -30
|
||||
```
|
||||
|
||||
Expected: All tests pass (new endpoint doesn't break existing tests).
|
||||
|
||||
- [ ] **Step 3: Commit**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
git add backend/api/routes/referrals.py
|
||||
git commit -m "feat(referral): add POST /me/flyer endpoint for PDF generation"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Docker verification
|
||||
|
||||
Build the base image locally with Chromium and verify PDF generation works inside the container.
|
||||
|
||||
**Files:** None changed — this is a verification step.
|
||||
|
||||
- [ ] **Step 1: Build the Docker base image locally**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
docker build -f backend/Dockerfile.base -t karaoke-backend-base:local .
|
||||
```
|
||||
|
||||
This will take a while (~5-10 min) as it installs Chromium + all deps. Watch for errors.
|
||||
|
||||
- [ ] **Step 2: Test Chromium works inside the container**
|
||||
|
||||
```bash
|
||||
docker run --rm karaoke-backend-base:local chromium --version
|
||||
```
|
||||
|
||||
Expected: Prints Chromium version (e.g., `Chromium 120.0.6099.224 built on Debian ...`).
|
||||
|
||||
- [ ] **Step 3: Test PDF generation inside the container**
|
||||
|
||||
```bash
|
||||
docker run --rm -v $(pwd)/backend/templates:/app/backend/templates karaoke-backend-base:local \
|
||||
python3 -c "
|
||||
import subprocess, tempfile, os
|
||||
# Read template
|
||||
with open('/app/backend/templates/printables/website-referral-flyer.html') as f:
|
||||
html = f.read()
|
||||
html = html.replace('{{REFERRAL_CODE}}', 'DOCKERTEST')
|
||||
html = html.replace('{{REFERRAL_CODE_LOWER}}', 'dockertest')
|
||||
html = html.replace('{{DISCOUNT_PERCENT}}', '10')
|
||||
html = html.replace('{{QR_DATA_URL}}', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==')
|
||||
tmp = '/tmp/test.html'
|
||||
with open(tmp, 'w') as f:
|
||||
f.write(html)
|
||||
result = subprocess.run([
|
||||
'chromium', '--headless', '--print-to-pdf=/tmp/out.pdf',
|
||||
'--no-margins', '--print-background', '--no-pdf-header-footer',
|
||||
'--virtual-time-budget=5000', '--paper-width=8.5', '--paper-height=11',
|
||||
'--disable-gpu', '--no-sandbox', tmp
|
||||
], capture_output=True, text=True, timeout=30)
|
||||
if result.returncode != 0:
|
||||
print('FAILED:', result.stderr[:500])
|
||||
elif os.path.exists('/tmp/out.pdf'):
|
||||
print(f'SUCCESS: PDF generated ({os.path.getsize(\"/tmp/out.pdf\")} bytes)')
|
||||
else:
|
||||
print('FAILED: no output')
|
||||
"
|
||||
```
|
||||
|
||||
Expected: `SUCCESS: PDF generated (XXXXX bytes)`.
|
||||
|
||||
- [ ] **Step 4: Extract and verify the Docker-generated PDF**
|
||||
|
||||
```bash
|
||||
# Run again but copy the PDF out
|
||||
docker run --rm -v $(pwd)/backend/templates:/app/backend/templates -v /tmp:/output karaoke-backend-base:local \
|
||||
python3 -c "
|
||||
import subprocess, os
|
||||
with open('/app/backend/templates/printables/website-referral-flyer.html') as f:
|
||||
html = f.read()
|
||||
html = html.replace('{{REFERRAL_CODE}}', 'DOCKERTEST')
|
||||
html = html.replace('{{REFERRAL_CODE_LOWER}}', 'dockertest')
|
||||
html = html.replace('{{DISCOUNT_PERCENT}}', '10')
|
||||
html = html.replace('{{QR_DATA_URL}}', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==')
|
||||
with open('/tmp/test.html', 'w') as f:
|
||||
f.write(html)
|
||||
subprocess.run([
|
||||
'chromium', '--headless', '--print-to-pdf=/output/docker-flyer-test.pdf',
|
||||
'--no-margins', '--print-background', '--no-pdf-header-footer',
|
||||
'--virtual-time-budget=5000', '--paper-width=8.5', '--paper-height=11',
|
||||
'--disable-gpu', '--no-sandbox', '/tmp/test.html'
|
||||
], capture_output=True, text=True, timeout=30)
|
||||
print(f'PDF size: {os.path.getsize(\"/output/docker-flyer-test.pdf\")} bytes')
|
||||
"
|
||||
open /tmp/docker-flyer-test.pdf
|
||||
```
|
||||
|
||||
Expected: PDF opens showing the flyer with correct layout, fonts (Google Fonts loaded via `--virtual-time-budget`), gradients, and "DOCKERTEST" referral code. No second blank page, no margins, no URL header/footer.
|
||||
|
||||
If fonts are missing or rendering is wrong, troubleshoot before proceeding. Common fixes:
|
||||
- Add `fonts-liberation` to apt-get for fallback fonts
|
||||
- Increase `--virtual-time-budget` if Google Fonts don't load in time
|
||||
- Add `--font-render-hinting=none` for better font rendering
|
||||
|
||||
- [ ] **Step 5: Report result**
|
||||
|
||||
No commit needed — this is a verification gate. If it passes, proceed. If it fails, fix the Dockerfile or template before continuing.
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Frontend — add flyer generation to QRCodeDialog
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/components/referrals/QRCodeDialog.tsx`
|
||||
- Modify: `frontend/lib/api.ts`
|
||||
- Modify: `frontend/messages/en.json`
|
||||
|
||||
- [ ] **Step 1: Add i18n strings**
|
||||
|
||||
Add to the `"referrals"` namespace in `frontend/messages/en.json`, after the existing QR strings:
|
||||
|
||||
```json
|
||||
"flyerTheme": "Flyer Theme",
|
||||
"flyerThemeLight": "Light",
|
||||
"flyerThemeDark": "Dark",
|
||||
"flyerGenerate": "Generate Flyer",
|
||||
"flyerGenerating": "Generating..."
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add generateFlyer to API client**
|
||||
|
||||
Add to `frontend/lib/api.ts`, after the `startConnectOnboarding` function (around line 3550):
|
||||
|
||||
```typescript
|
||||
export async function generateFlyer(theme: 'light' | 'dark', qrDataUrl: string): Promise<Blob> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/referrals/me/flyer`, {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme, qr_data_url: qrDataUrl }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ detail: 'Failed to generate flyer' }));
|
||||
throw new Error(error.detail || 'Failed to generate flyer');
|
||||
}
|
||||
return response.blob();
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Add flyer generation to QRCodeDialog**
|
||||
|
||||
In `frontend/components/referrals/QRCodeDialog.tsx`, make these changes:
|
||||
|
||||
**Add import** at the top:
|
||||
|
||||
```typescript
|
||||
import { generateFlyer } from '@/lib/api';
|
||||
```
|
||||
|
||||
**Add state** inside the component (after `const debounceRef`):
|
||||
|
||||
```typescript
|
||||
const [flyerTheme, setFlyerTheme] = useState<'light' | 'dark'>('light');
|
||||
const [flyerLoading, setFlyerLoading] = useState(false);
|
||||
```
|
||||
|
||||
**Add the handleGenerateFlyer function** after `handleDownload`:
|
||||
|
||||
```typescript
|
||||
const handleGenerateFlyer = async () => {
|
||||
setFlyerLoading(true);
|
||||
try {
|
||||
// Get QR as PNG data URL from the qr-code-styling instance
|
||||
let qrDataUrl: string;
|
||||
if (qrRef.current) {
|
||||
const blob = await qrRef.current.getRawData('png');
|
||||
if (blob) {
|
||||
qrDataUrl = await new Promise<string>((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => resolve(reader.result as string);
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
} else {
|
||||
throw new Error('Failed to generate QR code image');
|
||||
}
|
||||
} else {
|
||||
throw new Error('QR code not initialized');
|
||||
}
|
||||
|
||||
const pdfBlob = await generateFlyer(flyerTheme, qrDataUrl);
|
||||
const url = URL.createObjectURL(pdfBlob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'nomad-karaoke-referral-flyer.pdf';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (err) {
|
||||
console.error('Failed to generate flyer:', err);
|
||||
} finally {
|
||||
setFlyerLoading(false);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
**Add the flyer section in the dialog footer**, replacing the existing `<DialogFooter>` block with:
|
||||
|
||||
```tsx
|
||||
<DialogFooter>
|
||||
<div className="w-full space-y-3">
|
||||
{/* Flyer generation */}
|
||||
<div className="flex items-center gap-3 pt-2 border-t border-border">
|
||||
<span className="text-sm font-medium text-foreground">{t('flyerTheme')}</span>
|
||||
<div className="flex gap-1.5">
|
||||
{(['light', 'dark'] as const).map(theme => (
|
||||
<button
|
||||
key={theme}
|
||||
onClick={() => setFlyerTheme(theme)}
|
||||
className={`px-2 py-1 text-xs rounded border transition-colors ${
|
||||
flyerTheme === theme
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(theme === 'light' ? 'flyerThemeLight' : 'flyerThemeDark')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleGenerateFlyer}
|
||||
disabled={flyerLoading}
|
||||
className="ml-auto px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{flyerLoading ? t('flyerGenerating') : t('flyerGenerate')}
|
||||
</button>
|
||||
</div>
|
||||
{/* QR download buttons */}
|
||||
<div className="flex gap-2 sm:justify-end">
|
||||
<button
|
||||
onClick={() => handleDownload('png')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadPng')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDownload('svg')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadSvg')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run frontend tests**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator/frontend
|
||||
npx jest components/referrals/__tests__/QRCodeDialog.test.tsx --no-coverage 2>&1 | tail -20
|
||||
```
|
||||
|
||||
Expected: Existing tests still pass. The new flyer UI elements are present but don't break existing tests (they're just buttons and toggles). If the "Generate Flyer" text assertion is needed, add a quick test:
|
||||
|
||||
```typescript
|
||||
it('renders flyer generation controls', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Generate Flyer')).toBeInTheDocument();
|
||||
expect(screen.getByText('Light')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dark')).toBeInTheDocument();
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
git add frontend/components/referrals/QRCodeDialog.tsx frontend/lib/api.ts frontend/messages/en.json
|
||||
git commit -m "feat(referral): add flyer generation UI to QR code dialog"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Update tests and final verification
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/components/referrals/__tests__/QRCodeDialog.test.tsx` (add flyer test)
|
||||
|
||||
- [ ] **Step 1: Add flyer UI test**
|
||||
|
||||
Add this test to the existing `describe('QRCodeDialog')` block in `frontend/components/referrals/__tests__/QRCodeDialog.test.tsx`:
|
||||
|
||||
```typescript
|
||||
it('renders flyer generation controls', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Generate Flyer')).toBeInTheDocument();
|
||||
expect(screen.getByText('Light')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dark')).toBeInTheDocument();
|
||||
expect(screen.getByText('Flyer Theme')).toBeInTheDocument();
|
||||
});
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run all frontend tests**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator/frontend
|
||||
npx jest --no-coverage 2>&1 | tail -20
|
||||
```
|
||||
|
||||
Expected: All tests pass.
|
||||
|
||||
- [ ] **Step 3: Run all backend tests**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
python -m pytest backend/tests/ -v --timeout=30 2>&1 | tail -30
|
||||
```
|
||||
|
||||
Expected: All tests pass.
|
||||
|
||||
- [ ] **Step 4: Verify frontend build**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator/frontend
|
||||
npx next build 2>&1 | tail -20
|
||||
```
|
||||
|
||||
Expected: Build succeeds.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
|
||||
git add frontend/components/referrals/__tests__/QRCodeDialog.test.tsx
|
||||
git commit -m "test(referral): add flyer UI rendering test"
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
@@ -16,18 +16,21 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select"
|
||||
import { Music2, RefreshCw, Loader2, Search, Gift, X, Shield, ShieldOff } from "lucide-react"
|
||||
import { Music2, RefreshCw, Loader2, Moon, Sun, Search, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone, Users } from "lucide-react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { sortJobsByDate } 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 { AppHeader } from "@/components/app-header"
|
||||
import LanguageSwitcher from "@/components/LanguageSwitcher"
|
||||
import { useTheme } from "@/lib/theme"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import {
|
||||
Tooltip,
|
||||
@@ -46,6 +49,7 @@ import {
|
||||
|
||||
function AppPageContent() {
|
||||
const t = useTranslations('dashboard')
|
||||
const tHeader = useTranslations('header')
|
||||
const router = useRouter()
|
||||
const searchParams = useSearchParams()
|
||||
const [allJobs, setAllJobs] = useState<Job[]>([])
|
||||
@@ -55,8 +59,9 @@ function AppPageContent() {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null)
|
||||
const [isVerifyingToken, setIsVerifyingToken] = useState(false)
|
||||
const adminTokenHandled = useRef(false) // Track if admin_token was already processed
|
||||
const { isDarkMode, toggleTheme, mounted } = useTheme()
|
||||
const { user, fetchUser, verifyMagicLink } = useAuth()
|
||||
const { isDefault: isDefaultTenant } = useTenant()
|
||||
const { isDefault: isDefaultTenant, branding } = useTenant()
|
||||
const { showTestData } = useAdminSettings()
|
||||
const [jobLimit, setJobLimit] = useState<number>(() => {
|
||||
if (typeof window === "undefined") return 10
|
||||
@@ -77,10 +82,6 @@ function AppPageContent() {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-feedback-banner-dismissed") === "true"
|
||||
})
|
||||
const [discountBannerDismissed, setDiscountBannerDismissed] = useState(() => {
|
||||
if (typeof window === "undefined") return false
|
||||
return localStorage.getItem("nomad-discount-banner-dismissed") === "true"
|
||||
})
|
||||
const [showFeedbackDialog, setShowFeedbackDialog] = useState(false)
|
||||
|
||||
// Check if user is admin (for exclude_test parameter)
|
||||
@@ -212,43 +213,119 @@ function AppPageContent() {
|
||||
<AutoProcessor jobs={allJobs} onJobsChanged={loadJobs} />
|
||||
|
||||
{/* Header */}
|
||||
<AppHeader>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={loadJobs}
|
||||
disabled={isLoadingJobs || !isAuthenticated}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 me-1.5 ${isLoadingJobs ? 'animate-spin' : ''}`} />
|
||||
<span className="text-sm">{t('refresh')}</span>
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<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">
|
||||
{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)' }}>
|
||||
{isDefaultTenant ? t('title') : branding.site_title}
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={loadJobs}
|
||||
disabled={isLoadingJobs || !isAuthenticated}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 sm:me-2 ${isLoadingJobs ? 'animate-spin' : ''}`} />
|
||||
<span className="hidden sm:inline">{t('refresh')}</span>
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const next = !showAdminControls
|
||||
setShowAdminControls(next)
|
||||
localStorage.setItem("nomad-karaoke-admin-controls", String(next))
|
||||
}}
|
||||
className={`min-h-[40px] px-2 sm:px-3 ${showAdminControls ? 'text-amber-400' : ''}`}
|
||||
style={showAdminControls ? undefined : { color: 'var(--text-muted)' }}
|
||||
>
|
||||
{showAdminControls ? <Shield className="w-4 h-4" /> : <ShieldOff className="w-4 h-4" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{showAdminControls ? t('hideAdminControls') : t('showAdminControls')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
const next = !showAdminControls
|
||||
setShowAdminControls(next)
|
||||
localStorage.setItem("nomad-karaoke-admin-controls", String(next))
|
||||
}}
|
||||
className={`min-h-[40px] px-2 sm:px-3 ${showAdminControls ? 'text-amber-400' : ''}`}
|
||||
style={showAdminControls ? undefined : { color: 'var(--text-muted)' }}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{showAdminControls ? <Shield className="w-4 h-4" /> : <ShieldOff className="w-4 h-4" />}
|
||||
<HelpCircle className="w-4 h-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{showAdminControls ? t('hideAdminControls') : t('showAdminControls')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</AppHeader>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64">
|
||||
<DropdownMenuLabel className="text-sm font-normal">
|
||||
{tHeader('helpPrompt')}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="mailto:andrew@nomadkaraoke.com">
|
||||
<Mail className="w-4 h-4 me-2" />
|
||||
andrew@nomadkaraoke.com
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="tel:+18036363267">
|
||||
<Phone className="w-4 h-4 me-2" />
|
||||
+1 (803) 636-3267
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Link href="/app/referrals" className="flex items-center gap-1.5 text-sm hover:underline min-h-[40px] px-2 sm:px-3" style={{ color: 'var(--text-muted)' }}>
|
||||
<Users className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">{t('referrals')}</span>
|
||||
</Link>
|
||||
<LanguageSwitcher />
|
||||
<AuthStatus />
|
||||
{mounted && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={toggleTheme}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{isDarkMode ? (
|
||||
<Sun className="w-4 h-4" />
|
||||
) : (
|
||||
<Moon className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{isDarkMode ? t('switchToLightMode') : t('switchToDarkMode')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Feedback dialog */}
|
||||
<FeedbackDialog
|
||||
@@ -256,12 +333,12 @@ function AppPageContent() {
|
||||
onClose={() => setShowFeedbackDialog(false)}
|
||||
/>
|
||||
|
||||
<main className="px-4 pt-28 sm:pt-24 pb-8 space-y-6">
|
||||
<main className="px-4 pt-24 pb-8 space-y-6">
|
||||
{/* Push notification prompt - shows once when appropriate */}
|
||||
<PushNotificationPrompt />
|
||||
|
||||
{/* Referral discount banner */}
|
||||
{user?.has_active_referral_discount && user?.referral_discount_percent && user?.referral_discount_expires_at && !discountBannerDismissed && (
|
||||
{user?.has_active_referral_discount && user?.referral_discount_percent && user?.referral_discount_expires_at && (
|
||||
<div
|
||||
className="rounded-xl p-4 flex items-center gap-3 border"
|
||||
style={{
|
||||
@@ -270,7 +347,7 @@ function AppPageContent() {
|
||||
}}
|
||||
>
|
||||
<Gift className="w-5 h-5 shrink-0" style={{ color: 'var(--accent)' }} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>
|
||||
{user.referral_discount_percent}% referral discount active
|
||||
</p>
|
||||
@@ -279,16 +356,6 @@ function AppPageContent() {
|
||||
Expires {new Date(user.referral_discount_expires_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
localStorage.setItem("nomad-discount-banner-dismissed", "true")
|
||||
setDiscountBannerDismissed(true)
|
||||
}}
|
||||
className="shrink-0 p-1 rounded-md hover:bg-white/10 transition-colors"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,31 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { Suspense } from 'react';
|
||||
import ReferralDashboard from '@/components/referrals/ReferralDashboard';
|
||||
import { AppHeader } from '@/components/app-header';
|
||||
import { Link } from '@/i18n/routing';
|
||||
import { ChevronLeft, Loader2 } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
export default function ReferralsPage() {
|
||||
const t = useTranslations('referrals');
|
||||
|
||||
return (
|
||||
<div className="min-h-screen" style={{ backgroundColor: 'var(--background)' }}>
|
||||
<AppHeader />
|
||||
<main className="container mx-auto max-w-4xl px-4 pt-24 sm:pt-20 pb-6">
|
||||
<Link
|
||||
href="/app"
|
||||
className="inline-flex items-center gap-1 text-sm mb-4 hover:underline"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
{t('backToDashboard')}
|
||||
</Link>
|
||||
<Suspense fallback={<Loader2 className="w-6 h-6 animate-spin mx-auto mt-8" style={{ color: 'var(--text-muted)' }} />}>
|
||||
<ReferralDashboard />
|
||||
</Suspense>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
return <ReferralDashboard />;
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { useTranslations } from 'next-intl';
|
||||
import { getReferralInterstitial } from '@/lib/api';
|
||||
import { setReferralCode } from '@/lib/referral';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { getAccessToken, clearAccessToken, API_BASE_URL } from '@/lib/api';
|
||||
import { getAccessToken } from '@/lib/api';
|
||||
import type { ReferralInterstitial } from '@/lib/types';
|
||||
import { Gift, ArrowRight, Mail, CheckCircle, Loader2 } from 'lucide-react';
|
||||
|
||||
@@ -34,23 +34,9 @@ export function ReferralInterstitialClient() {
|
||||
// Store referral code immediately
|
||||
setReferralCode(code);
|
||||
|
||||
// Validate token with backend (don't trust localStorage alone — token may be stale)
|
||||
const token = getAccessToken();
|
||||
if (token) {
|
||||
fetch(`${API_BASE_URL}/api/users/me`, {
|
||||
headers: { 'Authorization': `Bearer ${token}` },
|
||||
})
|
||||
.then((res) => {
|
||||
if (res.ok) {
|
||||
setIsLoggedIn(true);
|
||||
} else {
|
||||
// Stale token — clear it so the user can re-authenticate
|
||||
clearAccessToken();
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
// Network error — don't assume logged in
|
||||
});
|
||||
// Check if already logged in
|
||||
if (getAccessToken()) {
|
||||
setIsLoggedIn(true);
|
||||
}
|
||||
|
||||
getReferralInterstitial(code)
|
||||
|
||||
@@ -18,11 +18,8 @@ import {
|
||||
} from "@/components/ui/dialog"
|
||||
import {
|
||||
Share2, Link as LinkIcon, Users, MousePointerClick, DollarSign,
|
||||
Plus, Copy, Check, RefreshCw, Loader2, ToggleLeft, ToggleRight, Pencil, QrCode,
|
||||
Plus, Copy, Check, RefreshCw, Loader2, ToggleLeft, ToggleRight, Pencil,
|
||||
} from "lucide-react"
|
||||
import ReferralToolsDialog from "@/components/referrals/ReferralToolsDialog"
|
||||
import { NextIntlClientProvider } from "next-intl"
|
||||
import enMessages from "@/messages/en.json"
|
||||
|
||||
function formatCents(cents: number): string {
|
||||
return `$${(cents / 100).toFixed(2)}`
|
||||
@@ -46,15 +43,12 @@ export default function ReferralsPage() {
|
||||
const [editLink, setEditLink] = useState<AdminReferralLink | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [editError, setEditError] = useState<string | null>(null)
|
||||
const [qrDialogCode, setQrDialogCode] = useState<string | null>(null)
|
||||
|
||||
// Edit form state
|
||||
const [editDisplayName, setEditDisplayName] = useState("")
|
||||
const [editMessage, setEditMessage] = useState("")
|
||||
const [editDiscount, setEditDiscount] = useState("10")
|
||||
const [editKickback, setEditKickback] = useState("20")
|
||||
const [editDiscountDays, setEditDiscountDays] = useState("30")
|
||||
const [editEarningDays, setEditEarningDays] = useState("365")
|
||||
|
||||
// Create form state
|
||||
const [formCode, setFormCode] = useState("")
|
||||
@@ -63,8 +57,6 @@ export default function ReferralsPage() {
|
||||
const [formMessage, setFormMessage] = useState("")
|
||||
const [formDiscount, setFormDiscount] = useState("10")
|
||||
const [formKickback, setFormKickback] = useState("20")
|
||||
const [formDiscountDays, setFormDiscountDays] = useState("30")
|
||||
const [formEarningDays, setFormEarningDays] = useState("365")
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
setLoading(true)
|
||||
@@ -122,8 +114,6 @@ export default function ReferralsPage() {
|
||||
custom_message: formMessage || undefined,
|
||||
discount_percent: Number(formDiscount) || 10,
|
||||
kickback_percent: Number(formKickback) || 20,
|
||||
discount_duration_days: Number(formDiscountDays) || 30,
|
||||
earning_duration_days: Number(formEarningDays) || 365,
|
||||
})
|
||||
setCreateOpen(false)
|
||||
resetForm()
|
||||
@@ -142,8 +132,6 @@ export default function ReferralsPage() {
|
||||
setEditMessage(link.custom_message || "")
|
||||
setEditDiscount(String(link.discount_percent))
|
||||
setEditKickback(String(link.kickback_percent))
|
||||
setEditDiscountDays(String(link.discount_duration_days))
|
||||
setEditEarningDays(String(link.earning_duration_days))
|
||||
setEditError(null)
|
||||
setEditOpen(true)
|
||||
}
|
||||
@@ -159,8 +147,6 @@ export default function ReferralsPage() {
|
||||
custom_message: editMessage || null,
|
||||
discount_percent: Number(editDiscount) || 10,
|
||||
kickback_percent: Number(editKickback) || 20,
|
||||
discount_duration_days: Number(editDiscountDays) || 30,
|
||||
earning_duration_days: Number(editEarningDays) || 365,
|
||||
})
|
||||
setEditOpen(false)
|
||||
setEditLink(null)
|
||||
@@ -180,8 +166,6 @@ export default function ReferralsPage() {
|
||||
setFormMessage("")
|
||||
setFormDiscount("10")
|
||||
setFormKickback("20")
|
||||
setFormDiscountDays("30")
|
||||
setFormEarningDays("365")
|
||||
setCreateError(null)
|
||||
}
|
||||
|
||||
@@ -278,30 +262,6 @@ export default function ReferralsPage() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="formDiscountDays">Discount Duration (days)</Label>
|
||||
<Input
|
||||
id="formDiscountDays"
|
||||
type="number"
|
||||
min="1"
|
||||
value={formDiscountDays}
|
||||
onChange={(e) => setFormDiscountDays(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">How long referred users get the discount</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="formEarningDays">Earning Duration (days)</Label>
|
||||
<Input
|
||||
id="formEarningDays"
|
||||
type="number"
|
||||
min="1"
|
||||
value={formEarningDays}
|
||||
onChange={(e) => setFormEarningDays(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">How long referrer earns from purchases</p>
|
||||
</div>
|
||||
</div>
|
||||
{createError && (
|
||||
<p className="text-sm text-destructive">{createError}</p>
|
||||
)}
|
||||
@@ -378,7 +338,7 @@ export default function ReferralsPage() {
|
||||
<TableHead>Code</TableHead>
|
||||
<TableHead>Owner</TableHead>
|
||||
<TableHead>Display Name</TableHead>
|
||||
<TableHead className="text-center">Rates</TableHead>
|
||||
<TableHead className="text-center">Discount / Kickback</TableHead>
|
||||
<TableHead className="text-right">Clicks</TableHead>
|
||||
<TableHead className="text-right">Signups</TableHead>
|
||||
<TableHead className="text-right">Purchases</TableHead>
|
||||
@@ -432,10 +392,7 @@ export default function ReferralsPage() {
|
||||
{link.display_name || "-"}
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-sm">
|
||||
<div>
|
||||
<span>{link.discount_percent}% / {link.kickback_percent}%</span>
|
||||
<span className="block text-xs text-muted-foreground">{link.discount_duration_days}d / {link.earning_duration_days}d</span>
|
||||
</div>
|
||||
{link.discount_percent}% / {link.kickback_percent}%
|
||||
</TableCell>
|
||||
<TableCell className="text-right text-sm">{link.stats?.clicks ?? 0}</TableCell>
|
||||
<TableCell className="text-right text-sm">{link.stats?.signups ?? 0}</TableCell>
|
||||
@@ -450,15 +407,6 @@ export default function ReferralsPage() {
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={() => setQrDialogCode(link.code)}
|
||||
title="QR Code / Flyer"
|
||||
>
|
||||
<QrCode className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
@@ -495,19 +443,6 @@ export default function ReferralsPage() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* QR Code / Flyer Dialog */}
|
||||
{qrDialogCode && (
|
||||
<NextIntlClientProvider locale="en" messages={enMessages}>
|
||||
<ReferralToolsDialog
|
||||
referralUrl={`https://nomadkaraoke.com/r/${qrDialogCode}`}
|
||||
open={!!qrDialogCode}
|
||||
onOpenChange={(open) => { if (!open) setQrDialogCode(null) }}
|
||||
flyerFilename={`nomad-karaoke-flyer-${qrDialogCode}`}
|
||||
referralCode={qrDialogCode}
|
||||
/>
|
||||
</NextIntlClientProvider>
|
||||
)}
|
||||
|
||||
{/* Edit Link Dialog */}
|
||||
<Dialog open={editOpen} onOpenChange={(open) => { setEditOpen(open); if (!open) setEditLink(null) }}>
|
||||
<DialogContent>
|
||||
@@ -560,30 +495,6 @@ export default function ReferralsPage() {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="editDiscountDays">Discount Duration (days)</Label>
|
||||
<Input
|
||||
id="editDiscountDays"
|
||||
type="number"
|
||||
min="1"
|
||||
value={editDiscountDays}
|
||||
onChange={(e) => setEditDiscountDays(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">How long referred users get the discount</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="editEarningDays">Earning Duration (days)</Label>
|
||||
<Input
|
||||
id="editEarningDays"
|
||||
type="number"
|
||||
min="1"
|
||||
value={editEarningDays}
|
||||
onChange={(e) => setEditEarningDays(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">How long referrer earns from purchases</p>
|
||||
</div>
|
||||
</div>
|
||||
{editError && (
|
||||
<p className="text-sm text-destructive">{editError}</p>
|
||||
)}
|
||||
|
||||
@@ -2,9 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
import { useSearchParams, useRouter } from "next/navigation"
|
||||
import NextLink from "next/link"
|
||||
import { adminApi, AdminUserDetail, UserPaymentHistory } from "@/lib/api"
|
||||
import type { ReferralLink } from "@/lib/types"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
@@ -36,19 +34,6 @@ import {
|
||||
} from "@/components/ui/alert-dialog"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import {
|
||||
Command,
|
||||
CommandEmpty,
|
||||
CommandGroup,
|
||||
CommandInput,
|
||||
CommandItem,
|
||||
CommandList,
|
||||
} from "@/components/ui/command"
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover"
|
||||
import {
|
||||
ArrowLeft,
|
||||
RefreshCw,
|
||||
@@ -63,10 +48,7 @@ import {
|
||||
DollarSign,
|
||||
LogIn,
|
||||
Tag,
|
||||
Check,
|
||||
ChevronsUpDown,
|
||||
} from "lucide-react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { useToast } from "@/hooks/use-toast"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { IpInfo } from "@/components/admin/ip-info"
|
||||
@@ -95,12 +77,10 @@ export default function AdminUserDetailPage() {
|
||||
|
||||
// Discount dialog
|
||||
const [discountDialogOpen, setDiscountDialogOpen] = useState(false)
|
||||
const [discountCode, setDiscountCode] = useState("")
|
||||
const [codePopoverOpen, setCodePopoverOpen] = useState(false)
|
||||
const [discountPercent, setDiscountPercent] = useState("50")
|
||||
const [discountDays, setDiscountDays] = useState("365")
|
||||
const [discountCode, setDiscountCode] = useState("loyalty")
|
||||
const [applyingDiscount, setApplyingDiscount] = useState(false)
|
||||
const [referralLinks, setReferralLinks] = useState<ReferralLink[]>([])
|
||||
const [referralLinksLoading, setReferralLinksLoading] = useState(false)
|
||||
|
||||
const loadUser = async () => {
|
||||
if (!email) {
|
||||
@@ -136,18 +116,6 @@ export default function AdminUserDetailPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const loadReferralLinks = async () => {
|
||||
try {
|
||||
setReferralLinksLoading(true)
|
||||
const data = await adminApi.listReferralLinks({ limit: 200 })
|
||||
setReferralLinks(data.links.filter((l) => l.enabled))
|
||||
} catch (err) {
|
||||
console.error("Failed to load referral links:", err)
|
||||
} finally {
|
||||
setReferralLinksLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadUser()
|
||||
loadPayments()
|
||||
@@ -189,17 +157,12 @@ export default function AdminUserDetailPage() {
|
||||
}
|
||||
|
||||
const handleApplyDiscount = async () => {
|
||||
const selectedLink = referralLinks.find((l) => l.code === discountCode)
|
||||
if (!selectedLink) {
|
||||
toast({ title: "Error", description: "Please select a referral code", variant: "destructive" })
|
||||
return
|
||||
}
|
||||
setApplyingDiscount(true)
|
||||
try {
|
||||
const result = await adminApi.applyDiscount(email, {
|
||||
discount_percent: selectedLink.discount_percent,
|
||||
discount_percent: Number(discountPercent) || 50,
|
||||
duration_days: Number(discountDays) || 365,
|
||||
referral_code: discountCode,
|
||||
referral_code: discountCode || "loyalty",
|
||||
})
|
||||
toast({ title: "Discount Applied", description: result.message })
|
||||
setDiscountDialogOpen(false)
|
||||
@@ -380,10 +343,7 @@ export default function AdminUserDetailPage() {
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setDiscountDialogOpen(true)
|
||||
if (referralLinks.length === 0) loadReferralLinks()
|
||||
}}
|
||||
onClick={() => setDiscountDialogOpen(true)}
|
||||
disabled={actionLoading}
|
||||
title="Apply a referral discount to this user"
|
||||
>
|
||||
@@ -770,78 +730,21 @@ export default function AdminUserDetailPage() {
|
||||
<DialogHeader>
|
||||
<DialogTitle>Apply Discount</DialogTitle>
|
||||
<DialogDescription>
|
||||
Link {email} to an existing referral code. They'll get the code's discount on credit purchases.
|
||||
Apply a referral discount to {email}. This sets the same discount fields as if they used a referral link.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Referral Code</Label>
|
||||
{referralLinksLoading ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground py-2">
|
||||
<Loader2 className="w-4 h-4 animate-spin" /> Loading codes…
|
||||
</div>
|
||||
) : (
|
||||
<Popover open={codePopoverOpen} onOpenChange={setCodePopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
role="combobox"
|
||||
aria-expanded={codePopoverOpen}
|
||||
className="w-full justify-between font-normal"
|
||||
>
|
||||
{discountCode
|
||||
? (() => {
|
||||
const sel = referralLinks.find((l) => l.code === discountCode)
|
||||
return sel
|
||||
? `${sel.code} — ${sel.discount_percent}% off${sel.display_name ? ` (${sel.display_name})` : ""}`
|
||||
: discountCode
|
||||
})()
|
||||
: "Search referral codes…"}
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-[--radix-popover-trigger-width] p-0" align="start">
|
||||
<Command>
|
||||
<CommandInput placeholder="Type to filter…" />
|
||||
<CommandList>
|
||||
<CommandEmpty>No codes found.</CommandEmpty>
|
||||
<CommandGroup>
|
||||
{referralLinks.map((link) => (
|
||||
<CommandItem
|
||||
key={link.code}
|
||||
value={`${link.code} ${link.display_name || ""}`}
|
||||
onSelect={() => {
|
||||
setDiscountCode(link.code)
|
||||
setDiscountDays(String(link.discount_duration_days))
|
||||
setCodePopoverOpen(false)
|
||||
}}
|
||||
>
|
||||
<Check className={cn("mr-2 h-4 w-4", discountCode === link.code ? "opacity-100" : "opacity-0")} />
|
||||
{link.code} — {link.discount_percent}% off
|
||||
{link.display_name ? ` (${link.display_name})` : ""}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
{referralLinks.length > 0 && !referralLinksLoading && referralLinks.every((l) => l.code !== discountCode) && !discountCode && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Create codes in <NextLink href="/admin/referrals" className="underline">Referral Management</NextLink> first.
|
||||
</p>
|
||||
)}
|
||||
<Label>Discount %</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
value={discountPercent}
|
||||
onChange={(e) => setDiscountPercent(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Percentage off credit purchases at Stripe checkout</p>
|
||||
</div>
|
||||
{discountCode && (() => {
|
||||
const sel = referralLinks.find((l) => l.code === discountCode)
|
||||
return sel ? (
|
||||
<div className="rounded-md bg-muted p-3 text-sm space-y-1">
|
||||
<p><strong>Discount:</strong> {sel.discount_percent}% off credit purchases</p>
|
||||
<p><strong>Default duration:</strong> {sel.discount_duration_days} days (override below)</p>
|
||||
</div>
|
||||
) : null
|
||||
})()}
|
||||
<div className="space-y-2">
|
||||
<Label>Duration (days)</Label>
|
||||
<Input
|
||||
@@ -852,12 +755,21 @@ export default function AdminUserDetailPage() {
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">How long the discount stays active. Use 3650 for ~10 years.</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Referral Code</Label>
|
||||
<Input
|
||||
value={discountCode}
|
||||
onChange={(e) => setDiscountCode(e.target.value)}
|
||||
placeholder="loyalty"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">Shows as the referral source. Use "loyalty" for grandfathered pricing, or an actual referral code.</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setDiscountDialogOpen(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleApplyDiscount} disabled={applyingDiscount || !discountCode}>
|
||||
<Button onClick={handleApplyDiscount} disabled={applyingDiscount}>
|
||||
{applyingDiscount && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
Apply Discount
|
||||
</Button>
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import { LocaleRedirect } from "@/components/LocaleRedirect"
|
||||
|
||||
export default function ReferralsRedirect() {
|
||||
return <LocaleRedirect />
|
||||
}
|
||||
@@ -40,7 +40,7 @@ const LOCALE_INFO: { code: string; native: string; english: string; flag: string
|
||||
{ code: 'ca', native: 'Catal\u00e0', english: 'Catalan', flag: '\u{1F3F4}' },
|
||||
];
|
||||
|
||||
export default function LanguageSwitcher({ showLabel }: { showLabel?: boolean } = {}) {
|
||||
export default function LanguageSwitcher() {
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
@@ -87,7 +87,7 @@ export default function LanguageSwitcher({ showLabel }: { showLabel?: boolean }
|
||||
className="inline-flex items-center gap-1.5 bg-transparent border border-border/50 rounded-md px-2 py-1 text-sm cursor-pointer text-muted-foreground hover:text-foreground hover:border-border transition-colors"
|
||||
>
|
||||
<span className="text-base leading-none">{current.flag}</span>
|
||||
<span className={showLabel ? '' : 'hidden sm:inline'}>{current.native}</span>
|
||||
<span className="hidden sm:inline">{current.native}</span>
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
|
||||
@@ -7,12 +7,6 @@ import { AuthStatus } from '../auth/AuthStatus'
|
||||
import { AuthDialog } from '../auth/AuthDialog'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
|
||||
// Mock next/navigation
|
||||
const mockPush = jest.fn()
|
||||
jest.mock('next/navigation', () => ({
|
||||
useRouter: () => ({ push: mockPush }),
|
||||
}))
|
||||
|
||||
// Mock the auth module
|
||||
jest.mock('@/lib/auth', () => ({
|
||||
useAuth: jest.fn(),
|
||||
|
||||
+136
-152
@@ -1,6 +1,9 @@
|
||||
"use client"
|
||||
|
||||
import { Link } from "@/i18n/routing"
|
||||
import { useRouter, Link } from "@/i18n/routing"
|
||||
import NextLink from "next/link"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { Logo } from "./logo"
|
||||
import { Button } from "./ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -10,167 +13,148 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "./ui/dropdown-menu"
|
||||
import { HelpCircle, Mail, Phone, Users, Moon, Sun } from "lucide-react"
|
||||
import { User, LogOut, Settings, Shield, Mail, Phone, HelpCircle, Eye } from "lucide-react"
|
||||
import LanguageSwitcher from "./LanguageSwitcher"
|
||||
import { AuthStatus } from "./auth"
|
||||
import { TenantLogo } from "./tenant-logo"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
import { useTheme } from "@/lib/theme"
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "./ui/tooltip"
|
||||
import { ReactNode, useState, useEffect } from "react"
|
||||
|
||||
/**
|
||||
* Shared app header used across all /app/* pages.
|
||||
* Matches the dashboard header style. Pass page-specific
|
||||
* buttons via the `children` prop (rendered before the
|
||||
* standard right-side controls).
|
||||
*
|
||||
* Mobile: two rows — row 1 (brand + auth), row 2 (actions with text labels).
|
||||
* Desktop (sm+): single row as before.
|
||||
*/
|
||||
export function AppHeader({ children }: { children?: ReactNode }) {
|
||||
const t = useTranslations('dashboard')
|
||||
const tHeader = useTranslations('header')
|
||||
const { branding, isDefault: isDefaultTenant } = useTenant()
|
||||
const { isDarkMode, toggleTheme } = useTheme()
|
||||
const [mounted, setMounted] = useState(false)
|
||||
export function AppHeader() {
|
||||
const t = useTranslations('header')
|
||||
const { user, logout, isImpersonating, impersonatedUserEmail, endImpersonation } = useAuth()
|
||||
const router = useRouter()
|
||||
|
||||
useEffect(() => { setMounted(true) }, [])
|
||||
const handleLogout = () => {
|
||||
logout()
|
||||
router.push("/")
|
||||
}
|
||||
|
||||
const handleBackToAdmin = () => {
|
||||
endImpersonation()
|
||||
window.location.href = "/admin"
|
||||
}
|
||||
|
||||
if (!user) return null
|
||||
|
||||
return (
|
||||
<header className="fixed top-0 left-0 right-0 z-50 bg-dark-900/80 backdrop-blur-md border-b border-dark-700">
|
||||
{/* Desktop: single row (sm+) */}
|
||||
<div className="hidden sm:flex px-4 py-3 items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
<Link href="/app">
|
||||
{isDefaultTenant ? (
|
||||
/* eslint-disable-next-line @next/next/no-img-element */
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-10 shrink-0" />
|
||||
) : (
|
||||
<TenantLogo size="sm" />
|
||||
)}
|
||||
</Link>
|
||||
<div className="min-w-0">
|
||||
<Link href="/app" className="text-xl font-bold truncate block" style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? t('title') : branding.site_title}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{children}
|
||||
<HelpDropdown tHeader={tHeader} />
|
||||
<Link href="/app/referrals" className="flex items-center gap-1.5 text-sm hover:underline min-h-[40px] px-3" style={{ color: 'var(--text-muted)' }}>
|
||||
<Users className="w-4 h-4" />
|
||||
<span>{t('referrals')}</span>
|
||||
</Link>
|
||||
<LanguageSwitcher />
|
||||
<AuthStatus />
|
||||
{mounted && <ThemeToggle isDarkMode={isDarkMode} toggleTheme={toggleTheme} t={t} />}
|
||||
</div>
|
||||
</div>
|
||||
<header className="sticky top-0 z-50 border-b border-border/50 bg-background/80 backdrop-blur supports-[backdrop-filter]:bg-background/60">
|
||||
<div className="container mx-auto px-4 h-16 flex items-center justify-between">
|
||||
<Link href="/app" className="h-10">
|
||||
<Logo className="h-10" />
|
||||
</Link>
|
||||
|
||||
{/* Mobile: two rows (< sm) */}
|
||||
<div className="sm:hidden">
|
||||
{/* Row 1: Brand + Auth */}
|
||||
<div className="px-3 py-2 flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<Link href="/app">
|
||||
{isDefaultTenant ? (
|
||||
/* eslint-disable-next-line @next/next/no-img-element */
|
||||
<img src="/nomad-karaoke-logo.svg" alt="Nomad Karaoke" className="h-8 shrink-0" />
|
||||
) : (
|
||||
<TenantLogo size="sm" />
|
||||
)}
|
||||
</Link>
|
||||
<div className="min-w-0">
|
||||
<Link href="/app" className="text-base font-bold truncate block" style={{ color: 'var(--text)' }}>
|
||||
{isDefaultTenant ? t('title') : branding.site_title}
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<AuthStatus />
|
||||
</div>
|
||||
{/* Row 2: Action buttons with text labels */}
|
||||
<div className="px-3 pb-2 flex items-center gap-1 flex-wrap">
|
||||
{children}
|
||||
<HelpDropdown tHeader={tHeader} showLabel />
|
||||
<Link href="/app/referrals" className="flex items-center gap-1.5 text-sm hover:underline min-h-[36px] px-2" style={{ color: 'var(--text-muted)' }}>
|
||||
<Users className="w-4 h-4" />
|
||||
<span>{t('referrals')}</span>
|
||||
<nav className="hidden md:flex items-center gap-6">
|
||||
<Link href="/app" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
{t('dashboard')}
|
||||
</Link>
|
||||
<LanguageSwitcher showLabel />
|
||||
{mounted && <ThemeToggle isDarkMode={isDarkMode} toggleTheme={toggleTheme} t={t} />}
|
||||
<Link href="/jobs" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
{t('myJobs')}
|
||||
</Link>
|
||||
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
|
||||
<NextLink href="/admin" className="text-sm font-medium hover:text-primary transition-colors">
|
||||
{t('admin')}
|
||||
</NextLink>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<LanguageSwitcher />
|
||||
|
||||
{isImpersonating && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleBackToAdmin}
|
||||
className="h-8 gap-1.5 border-purple-500/40 text-purple-300 hover:text-white hover:bg-purple-800/40"
|
||||
>
|
||||
<Shield className="w-3.5 h-3.5" />
|
||||
{t('backToAdmin')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button className="hidden lg:flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors">
|
||||
<HelpCircle className="w-3.5 h-3.5" />
|
||||
<span>{t('needHelp')}</span>
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64">
|
||||
<DropdownMenuLabel className="text-sm">
|
||||
{t('helpPrompt')}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="mailto:andrew@nomadkaraoke.com">
|
||||
<Mail className="w-4 h-4 mr-2" />
|
||||
andrew@nomadkaraoke.com
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="tel:+18036363267">
|
||||
<Phone className="w-4 h-4 mr-2" />
|
||||
+1 (803) 636-3267
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
<div className="hidden sm:flex items-center gap-2 px-4 py-2 rounded-lg bg-primary/10 border border-primary/20">
|
||||
<div className="w-2 h-2 rounded-full bg-primary animate-pulse" />
|
||||
<span className="text-sm font-medium text-primary">{t('credits', { count: user.credits })}</span>
|
||||
</div>
|
||||
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="rounded-full">
|
||||
<User className="w-5 h-5" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-56">
|
||||
<DropdownMenuLabel>
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="text-sm font-medium">{t('account')}</p>
|
||||
<p className="text-xs text-muted-foreground">{user.role === "admin" ? t('adminRole') : t('userRole')}</p>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="sm:hidden">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2 h-2 rounded-full bg-primary" />
|
||||
<span>{t('credits', { count: user.credits })}</span>
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
{(user.role === "admin" || user.email?.endsWith("@nomadkaraoke.com")) && (
|
||||
<DropdownMenuItem asChild>
|
||||
<NextLink href="/admin">
|
||||
<Shield className="w-4 h-4 mr-2" />
|
||||
{t('adminDashboard')}
|
||||
</NextLink>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem>
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
{t('settings')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="mailto:andrew@nomadkaraoke.com">
|
||||
<Mail className="w-4 h-4 mr-2" />
|
||||
andrew@nomadkaraoke.com
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="tel:+18036363267">
|
||||
<Phone className="w-4 h-4 mr-2" />
|
||||
+1 (803) 636-3267
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout} className="text-destructive focus:text-destructive">
|
||||
<LogOut className="w-4 h-4 mr-2" />
|
||||
{t('logout')}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
function HelpDropdown({ tHeader, showLabel }: { tHeader: ReturnType<typeof useTranslations>; showLabel?: boolean }) {
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
<HelpCircle className="w-4 h-4" />
|
||||
{showLabel && <span className="ms-1.5 text-sm">{tHeader('needHelp')}</span>}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64">
|
||||
<DropdownMenuLabel className="text-sm font-normal">
|
||||
{tHeader('helpPrompt')}
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="mailto:andrew@nomadkaraoke.com">
|
||||
<Mail className="w-4 h-4 me-2" />
|
||||
andrew@nomadkaraoke.com
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<a href="tel:+18036363267">
|
||||
<Phone className="w-4 h-4 me-2" />
|
||||
+1 (803) 636-3267
|
||||
</a>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function ThemeToggle({ isDarkMode, toggleTheme, t }: { isDarkMode: boolean; toggleTheme: () => void; t: ReturnType<typeof useTranslations> }) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={toggleTheme}
|
||||
className="min-h-[40px] px-2 sm:px-3"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{isDarkMode ? (
|
||||
<Sun className="w-4 h-4" />
|
||||
) : (
|
||||
<Moon className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="bottom">
|
||||
<p>{isDarkMode ? t('switchToLightMode') : t('switchToDarkMode')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useState, useEffect } from "react"
|
||||
import { useRouter } from "next/navigation"
|
||||
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift, Tag } from "lucide-react"
|
||||
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift } from "lucide-react"
|
||||
import NextLink from "next/link"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
@@ -28,7 +27,6 @@ interface AuthStatusProps {
|
||||
export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
const t = useTranslations('auth.status')
|
||||
const tHeader = useTranslations('header')
|
||||
const router = useRouter()
|
||||
const { user, logout } = useAuth()
|
||||
const { showTestData, setShowTestData } = useAdminSettings()
|
||||
const [showAuthDialog, setShowAuthDialog] = useState(false)
|
||||
@@ -106,19 +104,6 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
|
||||
<Coins className="w-4 h-4 mr-2 text-warning" />
|
||||
<span>{t('creditsAvailable', { count: user.credits })}</span>
|
||||
</DropdownMenuItem>
|
||||
{user.has_active_referral_discount && user.referral_discount_percent && (
|
||||
<DropdownMenuItem
|
||||
className="text-green-500 focus:text-green-400 focus:bg-secondary cursor-pointer"
|
||||
onClick={() => {
|
||||
localStorage.removeItem("nomad-discount-banner-dismissed")
|
||||
router.push("/app")
|
||||
}}
|
||||
title={t('discountActiveHint')}
|
||||
>
|
||||
<Tag className="w-4 h-4 mr-2" />
|
||||
<span>{user.referral_discount_percent}% {t('discountActive')}</span>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={handleBuyCredits}
|
||||
className="text-muted-foreground focus:text-foreground focus:bg-secondary"
|
||||
|
||||
@@ -4,37 +4,33 @@ import { useState, useEffect } from 'react'
|
||||
import { CreditCard, Loader2 } from 'lucide-react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { api, CreditPackage, getReferralInterstitial } from '@/lib/api'
|
||||
import { api, CreditPackage } from '@/lib/api'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { useTranslations, useLocale } from 'next-intl'
|
||||
import { useTranslations } from 'next-intl'
|
||||
|
||||
interface BuyCreditsDialogProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const formatPrice = (cents: number) =>
|
||||
cents % 100 === 0 ? `$${(cents / 100).toFixed(0)}` : `$${(cents / 100).toFixed(2)}`
|
||||
const pricePerVideo = (cents: number, credits: number) =>
|
||||
`$${(cents / 100 / credits).toFixed(2)}`
|
||||
const formatPrice = (cents: number) => `$${(cents / 100).toFixed(0)}`
|
||||
const pricePerVideo = (pkg: CreditPackage) =>
|
||||
`$${(pkg.price_cents / 100 / pkg.credits).toFixed(2)}`
|
||||
|
||||
export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
const t = useTranslations('credits')
|
||||
const tCommon = useTranslations('common')
|
||||
const tRef = useTranslations('referrals')
|
||||
const locale = useLocale()
|
||||
const { user } = useAuth()
|
||||
const [packages, setPackages] = useState<CreditPackage[]>([])
|
||||
const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [checkoutLoading, setCheckoutLoading] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [referrerName, setReferrerName] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
setError('')
|
||||
setCheckoutLoading(false)
|
||||
setLoading(true)
|
||||
api.getCreditPackages()
|
||||
.then((pkgs) => {
|
||||
@@ -47,15 +43,7 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to load packages')
|
||||
})
|
||||
.finally(() => setLoading(false))
|
||||
|
||||
// Fetch referrer details if user has an active referral discount
|
||||
setReferrerName(null)
|
||||
if (user?.referred_by_code) {
|
||||
getReferralInterstitial(user.referred_by_code, true)
|
||||
.then((info) => setReferrerName(info.referrer_display_name))
|
||||
.catch(() => setReferrerName(null))
|
||||
}
|
||||
}, [open, user?.referred_by_code])
|
||||
}, [open])
|
||||
|
||||
const handleCheckout = async () => {
|
||||
if (!selectedPackage || !user?.email) return
|
||||
@@ -89,19 +77,9 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
<p className="text-green-600 dark:text-green-400 text-sm font-medium">
|
||||
{tRef('discountBadge', { percent: user.referral_discount_percent })}
|
||||
</p>
|
||||
{referrerName && (
|
||||
<p className="text-green-600/80 dark:text-green-400/80 text-xs mt-1">
|
||||
{tRef('referredBy', { name: referrerName })}
|
||||
</p>
|
||||
)}
|
||||
{user.referred_by_code && (
|
||||
<p className="text-green-600/60 dark:text-green-400/60 text-xs mt-0.5">
|
||||
{tRef('usingCode', { code: user.referred_by_code })}
|
||||
</p>
|
||||
)}
|
||||
{user.referral_discount_expires_at && (
|
||||
<p className="text-green-600/70 dark:text-green-400/70 text-xs mt-1">
|
||||
{tRef('appliedAtCheckout')} · {tRef('expires', { date: new Date(user.referral_discount_expires_at).toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' }) })}
|
||||
Applied automatically at checkout · Expires {new Date(user.referral_discount_expires_at).toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -117,21 +95,14 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
<div className="text-center py-4 text-sm text-destructive">{error}</div>
|
||||
)}
|
||||
|
||||
{!loading && !error && packages.length > 0 && (() => {
|
||||
const discountPct = user?.has_active_referral_discount ? (user.referral_discount_percent ?? 0) : 0
|
||||
const applyDiscount = (cents: number) =>
|
||||
discountPct > 0 ? Math.round(cents * (1 - discountPct / 100)) : cents
|
||||
|
||||
return (
|
||||
{!loading && !error && packages.length > 0 && (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{packages.map((pkg) => {
|
||||
const isSelected = selectedPackage?.id === pkg.id
|
||||
const isBestValue = pkg.credits === 5
|
||||
const discountedCents = applyDiscount(pkg.price_cents)
|
||||
const hasDiscount = discountedCents < pkg.price_cents
|
||||
const savings = pkg.credits > 1
|
||||
? Math.round((1 - discountedCents / (pkg.credits * applyDiscount(1000))) * 100)
|
||||
? Math.round((1 - pkg.price_cents / (pkg.credits * 1000)) * 100)
|
||||
: 0
|
||||
|
||||
return (
|
||||
@@ -153,28 +124,10 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
<div className="text-sm text-muted-foreground mb-1">
|
||||
{pkg.credits === 1 ? tCommon('credit') : tCommon('credits')}
|
||||
</div>
|
||||
{hasDiscount ? (
|
||||
<>
|
||||
<div className="text-lg font-semibold text-green-500">
|
||||
{formatPrice(discountedCents)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground line-through">
|
||||
{formatPrice(pkg.price_cents)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{t('pricePerVideo', { price: pricePerVideo(discountedCents, pkg.credits) })}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-lg font-semibold text-primary">
|
||||
{formatPrice(pkg.price_cents)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{t('pricePerVideo', { price: pricePerVideo(pkg.price_cents, pkg.credits) })}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className="text-lg font-semibold text-primary">
|
||||
{formatPrice(pkg.price_cents)}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground">{t('pricePerVideo', { price: pricePerVideo(pkg) })}</div>
|
||||
{savings > 0 && (
|
||||
<div className="text-xs text-green-500 mt-1">{t('savePct', { savings })}</div>
|
||||
)}
|
||||
@@ -194,14 +147,13 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
|
||||
{t('redirecting')}
|
||||
</>
|
||||
) : selectedPackage ? (
|
||||
t('continuePayment', { price: formatPrice(applyDiscount(selectedPackage.price_cents)) })
|
||||
t('continuePayment', { price: formatPrice(selectedPackage.price_cents) })
|
||||
) : (
|
||||
t('selectPackage')
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
})()}
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import { TenantLogo } from "./tenant-logo"
|
||||
import Image from "next/image"
|
||||
|
||||
export function Logo({ className = "", size = "sm" }: { className?: string; size?: "sm" | "lg" }) {
|
||||
return <TenantLogo className={className} size={size} />
|
||||
const sizeClasses = size === "lg" ? "max-w-[600px] max-h-[120px]" : "max-w-[200px] max-h-10"
|
||||
|
||||
return (
|
||||
<div className={`flex items-center ${className}`}>
|
||||
<Image
|
||||
src="https://nomadkaraoke.com/wp-content/uploads/2024/07/Nomad-Karaoke-Logo-TextOnly-Cropped-FromSVG-HQ-2048x1088.png"
|
||||
alt="Nomad Karaoke"
|
||||
width={200}
|
||||
height={106}
|
||||
className={`w-auto h-auto ${sizeClasses} object-contain`}
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -207,33 +207,6 @@ export default function LyricsAnalyzer({
|
||||
[history, historyIndex]
|
||||
)
|
||||
|
||||
// Compute which word IDs have been edited by the user (compared to initial state)
|
||||
const editedWordIds = useMemo(() => {
|
||||
const initial = history[0]
|
||||
if (!initial || data === initial) return new Set<string>()
|
||||
// Build map of word ID → text from initial state
|
||||
const initialWordText = new Map<string, string>()
|
||||
for (const segment of initial.corrected_segments) {
|
||||
for (const word of segment.words) {
|
||||
initialWordText.set(word.id, word.text)
|
||||
}
|
||||
}
|
||||
const edited = new Set<string>()
|
||||
for (const segment of data.corrected_segments) {
|
||||
for (const word of segment.words) {
|
||||
const originalText = initialWordText.get(word.id)
|
||||
if (originalText === undefined) {
|
||||
// Word was added by the user
|
||||
edited.add(word.id)
|
||||
} else if (originalText !== word.text) {
|
||||
// Word text was changed
|
||||
edited.add(word.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
return edited
|
||||
}, [data, history])
|
||||
|
||||
// Reset history when initial data changes
|
||||
useEffect(() => {
|
||||
setHistory([initialData])
|
||||
@@ -1142,20 +1115,15 @@ export default function LyricsAnalyzer({
|
||||
}, [])
|
||||
|
||||
const handleSaveReplaceAllLyrics = useCallback(
|
||||
(
|
||||
newSegments: LyricsSegment[],
|
||||
meta?: { operation: 'replace_all_lyrics' | 'change_case'; details?: Record<string, unknown> }
|
||||
) => {
|
||||
const operation = meta?.operation ?? 'replace_all_lyrics'
|
||||
const details =
|
||||
meta?.details ?? {
|
||||
(newSegments: LyricsSegment[]) => {
|
||||
addEditEntry(editLog, 'replace_all_lyrics', {
|
||||
details: {
|
||||
segments_before: data.corrected_segments.length,
|
||||
segments_after: newSegments.length,
|
||||
}
|
||||
addEditEntry(editLog, operation, { details })
|
||||
},
|
||||
})
|
||||
const newData = { ...data, corrected_segments: newSegments }
|
||||
const historyLabel = operation === 'change_case' ? 'change case' : 'replace all lyrics'
|
||||
updateDataWithHistory(newData, historyLabel)
|
||||
updateDataWithHistory(newData, 'replace all lyrics')
|
||||
setIsReplaceAllLyricsModalOpen(false)
|
||||
},
|
||||
[data, updateDataWithHistory, editLog]
|
||||
@@ -1286,7 +1254,6 @@ export default function LyricsAnalyzer({
|
||||
activeGapWordIds={activeGapWordIds}
|
||||
advancedMode={advancedMode}
|
||||
onAdvancedModeToggle={handleAdvancedModeToggle}
|
||||
editedWordIds={editedWordIds}
|
||||
/>
|
||||
<ReferenceView
|
||||
referenceSources={data.reference_lyrics}
|
||||
|
||||
@@ -33,7 +33,6 @@ export default function TranscriptionView({
|
||||
activeGapWordIds,
|
||||
advancedMode = false,
|
||||
onAdvancedModeToggle,
|
||||
editedWordIds,
|
||||
}: TranscriptionViewProps) {
|
||||
const t = useTranslations('lyricsReview.transcription')
|
||||
const [selectedSegmentIndex, setSelectedSegmentIndex] = useState<number | null>(null)
|
||||
@@ -202,7 +201,6 @@ export default function TranscriptionView({
|
||||
onEditCorrection={onEditCorrection}
|
||||
onAcceptCorrection={onAcceptCorrection}
|
||||
onShowCorrectionDetail={onShowCorrectionDetail}
|
||||
editedWordIds={editedWordIds}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import ReplaceAllLyricsModal from '../modals/ReplaceAllLyricsModal'
|
||||
import { LyricsSegment } from '@/lib/lyrics-review/types'
|
||||
|
||||
jest.mock('../synchronizer/LyricsSynchronizer', () => {
|
||||
return function MockLyricsSynchronizer() {
|
||||
return <div data-testid="lyrics-synchronizer">Synchronizer</div>
|
||||
}
|
||||
})
|
||||
|
||||
const mockSegments: LyricsSegment[] = [
|
||||
{
|
||||
id: 'seg1',
|
||||
text: 'Hello world',
|
||||
start_time: 0,
|
||||
end_time: 2,
|
||||
words: [
|
||||
{ id: 'w1', text: 'Hello', start_time: 0, end_time: 1, confidence: 0.9 },
|
||||
{ id: 'w2', text: 'world', start_time: 1, end_time: 2, confidence: 0.95 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'seg2',
|
||||
text: 'Goodbye MOON',
|
||||
start_time: 3,
|
||||
end_time: 5,
|
||||
words: [
|
||||
{ id: 'w3', text: 'Goodbye', start_time: 3, end_time: 4, confidence: 0.88 },
|
||||
{ id: 'w4', text: 'MOON', start_time: 4, end_time: 5, confidence: 0.92 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const defaultProps = {
|
||||
open: true,
|
||||
onClose: jest.fn(),
|
||||
onSave: jest.fn(),
|
||||
setModalSpacebarHandler: jest.fn(),
|
||||
existingSegments: mockSegments,
|
||||
}
|
||||
|
||||
async function openChangeCaseMode() {
|
||||
const user = userEvent.setup()
|
||||
render(<ReplaceAllLyricsModal {...defaultProps} />)
|
||||
await user.click(screen.getByText('Change Case'))
|
||||
return user
|
||||
}
|
||||
|
||||
describe('Change Case Mode', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
it('shows Change Case option in mode selection when existing lyrics exist', () => {
|
||||
render(<ReplaceAllLyricsModal {...defaultProps} />)
|
||||
expect(screen.getByText('Change Case')).toBeInTheDocument()
|
||||
expect(screen.getByText(/Convert all lyrics to/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show Change Case option when no existing lyrics', () => {
|
||||
render(<ReplaceAllLyricsModal {...defaultProps} existingSegments={[]} />)
|
||||
expect(screen.queryByText('Change Case')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders all four case buttons when opened', async () => {
|
||||
await openChangeCaseMode()
|
||||
expect(screen.getByRole('button', { name: /^UPPERCASE/ })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /^lowercase/ })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /^Title Case/ })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /^Sentence case/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows preview of UPPERCASE by default', async () => {
|
||||
await openChangeCaseMode()
|
||||
expect(screen.getByText(/HELLO WORLD/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/GOODBYE MOON/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('updates preview when lowercase is selected', async () => {
|
||||
const user = await openChangeCaseMode()
|
||||
await user.click(screen.getByRole('button', { name: /^lowercase/ }))
|
||||
expect(screen.getByText(/hello world/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/goodbye moon/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('updates preview when Title Case is selected', async () => {
|
||||
const user = await openChangeCaseMode()
|
||||
await user.click(screen.getByRole('button', { name: /^Title Case/ }))
|
||||
expect(screen.getByText(/Hello World/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/Goodbye Moon/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onSave with UPPERCASE segments and change_case meta', async () => {
|
||||
const onSave = jest.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<ReplaceAllLyricsModal {...defaultProps} onSave={onSave} />)
|
||||
await user.click(screen.getByText('Change Case'))
|
||||
await user.click(screen.getByRole('button', { name: /^Apply/ }))
|
||||
|
||||
expect(onSave).toHaveBeenCalledTimes(1)
|
||||
const [segments, meta] = onSave.mock.calls[0]
|
||||
expect(segments[0].text).toBe('HELLO WORLD')
|
||||
expect(segments[0].words.map((w: { text: string }) => w.text)).toEqual(['HELLO', 'WORLD'])
|
||||
expect(segments[1].text).toBe('GOODBYE MOON')
|
||||
expect(meta).toEqual({ operation: 'change_case', details: { case_type: 'upper' } })
|
||||
})
|
||||
|
||||
it('preserves word start_time and end_time on apply', async () => {
|
||||
const onSave = jest.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<ReplaceAllLyricsModal {...defaultProps} onSave={onSave} />)
|
||||
await user.click(screen.getByText('Change Case'))
|
||||
await user.click(screen.getByRole('button', { name: /^lowercase/ }))
|
||||
await user.click(screen.getByRole('button', { name: /^Apply/ }))
|
||||
|
||||
const [segments] = onSave.mock.calls[0]
|
||||
expect(segments[0].words[0].start_time).toBe(0)
|
||||
expect(segments[0].words[0].end_time).toBe(1)
|
||||
expect(segments[0].words[0].id).toBe('w1')
|
||||
expect(segments[0].start_time).toBe(0)
|
||||
expect(segments[0].end_time).toBe(2)
|
||||
})
|
||||
|
||||
it('applies Sentence case per-line (first word only capitalized)', async () => {
|
||||
const onSave = jest.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<ReplaceAllLyricsModal {...defaultProps} onSave={onSave} />)
|
||||
await user.click(screen.getByText('Change Case'))
|
||||
await user.click(screen.getByRole('button', { name: /^Sentence case/ }))
|
||||
await user.click(screen.getByRole('button', { name: /^Apply/ }))
|
||||
|
||||
const [segments, meta] = onSave.mock.calls[0]
|
||||
expect(segments[0].text).toBe('Hello world')
|
||||
expect(segments[0].words.map((w: { text: string }) => w.text)).toEqual(['Hello', 'world'])
|
||||
expect(segments[1].text).toBe('Goodbye moon')
|
||||
expect(segments[1].words.map((w: { text: string }) => w.text)).toEqual(['Goodbye', 'moon'])
|
||||
expect(meta.details).toEqual({ case_type: 'sentence' })
|
||||
})
|
||||
|
||||
it('back button returns to mode selection', async () => {
|
||||
const user = await openChangeCaseMode()
|
||||
// There are two back-like buttons in the dialog header; the left-arrow is first
|
||||
const backButtons = screen.getAllByRole('button')
|
||||
// The ArrowLeft icon button is the one just before the title
|
||||
// Simpler: click the ArrowLeft (first icon button in the heading)
|
||||
const arrowBack = backButtons.find((b) => b.querySelector('svg.lucide-arrow-left'))
|
||||
expect(arrowBack).toBeDefined()
|
||||
await user.click(arrowBack!)
|
||||
expect(screen.getByText('Choose how you want to edit the lyrics:')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { RefreshCw, ClipboardPaste, TextCursorInput, CaseSensitive, X } from 'lucide-react'
|
||||
import { RefreshCw, ClipboardPaste, TextCursorInput, X } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface ModeSelectionModalProps {
|
||||
@@ -12,7 +12,6 @@ interface ModeSelectionModalProps {
|
||||
onSelectReplace: () => void
|
||||
onSelectResync: () => void
|
||||
onSelectReplaceSegments: () => void
|
||||
onSelectChangeCase: () => void
|
||||
hasExistingLyrics: boolean
|
||||
}
|
||||
|
||||
@@ -22,7 +21,6 @@ export default function ModeSelectionModal({
|
||||
onSelectReplace,
|
||||
onSelectResync,
|
||||
onSelectReplaceSegments,
|
||||
onSelectChangeCase,
|
||||
hasExistingLyrics,
|
||||
}: ModeSelectionModalProps) {
|
||||
const t = useTranslations('lyricsReview.modals.modeSelection')
|
||||
@@ -86,28 +84,6 @@ export default function ModeSelectionModal({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Change Case option - only show if there are existing lyrics */}
|
||||
{hasExistingLyrics && (
|
||||
<div
|
||||
className={cn(
|
||||
'p-4 border rounded-lg cursor-pointer',
|
||||
'hover:bg-muted/30 hover:border-muted-foreground transition-colors'
|
||||
)}
|
||||
onClick={onSelectChangeCase}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<CaseSensitive className="h-10 w-10 text-muted-foreground mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h3 className="text-lg font-semibold">{t('changeCaseTitle')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('changeCaseDesc')}
|
||||
</p>
|
||||
<p className="text-xs text-green-500 mt-2">{t('changeCaseRecommended')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Replace All option */}
|
||||
<div
|
||||
className={cn(
|
||||
|
||||
@@ -9,7 +9,6 @@ import { X, ArrowLeft, ClipboardPaste, Sparkles, Info, Check, AlertTriangle } fr
|
||||
import { nanoid } from 'nanoid'
|
||||
import { LyricsSegment, Word } from '@/lib/lyrics-review/types'
|
||||
import { createWordsWithDistributedTiming } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
import { applyCaseToSegments, convertCase, type CaseType } from '@/lib/lyrics-review/utils/caseConversion'
|
||||
import ModeSelectionModal from './ModeSelectionModal'
|
||||
import LyricsSynchronizer from '../synchronizer/LyricsSynchronizer'
|
||||
|
||||
@@ -21,19 +20,12 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
type ModalMode = 'selection' | 'replace' | 'resync' | 'replaceSegments' | 'changeCase'
|
||||
|
||||
export type ReplaceAllOperation = 'replace_all_lyrics' | 'change_case'
|
||||
|
||||
export interface ReplaceAllSaveMeta {
|
||||
operation: ReplaceAllOperation
|
||||
details?: Record<string, unknown>
|
||||
}
|
||||
type ModalMode = 'selection' | 'replace' | 'resync' | 'replaceSegments'
|
||||
|
||||
interface ReplaceAllLyricsModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSave: (newSegments: LyricsSegment[], meta?: ReplaceAllSaveMeta) => void
|
||||
onSave: (newSegments: LyricsSegment[]) => void
|
||||
onPlaySegment?: (startTime: number) => void
|
||||
currentTime?: number
|
||||
setModalSpacebarHandler: (handler: ((e: KeyboardEvent) => void) | undefined) => void
|
||||
@@ -53,7 +45,6 @@ export default function ReplaceAllLyricsModal({
|
||||
const [mode, setMode] = useState<ModalMode>('selection')
|
||||
const [inputText, setInputText] = useState('')
|
||||
const [newSegments, setNewSegments] = useState<LyricsSegment[]>([])
|
||||
const [selectedCase, setSelectedCase] = useState<CaseType>('upper')
|
||||
|
||||
// Reset state when modal opens
|
||||
useEffect(() => {
|
||||
@@ -61,7 +52,6 @@ export default function ReplaceAllLyricsModal({
|
||||
setMode('selection')
|
||||
setInputText('')
|
||||
setNewSegments([])
|
||||
setSelectedCase('upper')
|
||||
}
|
||||
}, [open])
|
||||
|
||||
@@ -198,33 +188,6 @@ export default function ReplaceAllLyricsModal({
|
||||
setMode('replaceSegments')
|
||||
}, [existingSegments])
|
||||
|
||||
const handleSelectChangeCase = useCallback(() => {
|
||||
setSelectedCase('upper')
|
||||
setMode('changeCase')
|
||||
}, [])
|
||||
|
||||
// Apply case change: transform every segment/word text, keep all timing
|
||||
const handleApplyChangeCase = useCallback(() => {
|
||||
const updated = applyCaseToSegments(existingSegments, selectedCase)
|
||||
onSave(updated, { operation: 'change_case', details: { case_type: selectedCase } })
|
||||
handleClose()
|
||||
}, [existingSegments, selectedCase, onSave, handleClose])
|
||||
|
||||
const casePreview = useMemo(() => {
|
||||
if (existingSegments.length === 0) return ''
|
||||
return existingSegments
|
||||
.slice(0, 4)
|
||||
.map((s) => convertCase(s.text, selectedCase))
|
||||
.join('\n')
|
||||
}, [existingSegments, selectedCase])
|
||||
|
||||
const caseOptions: Array<{ type: CaseType; label: string; desc: string }> = [
|
||||
{ type: 'upper', label: t('caseUpper'), desc: t('caseUpperDesc') },
|
||||
{ type: 'lower', label: t('caseLower'), desc: t('caseLowerDesc') },
|
||||
{ type: 'title', label: t('caseTitle'), desc: t('caseTitleDesc') },
|
||||
{ type: 'sentence', label: t('caseSentence'), desc: t('caseSentenceDesc') },
|
||||
]
|
||||
|
||||
// Handle back to selection
|
||||
const handleBackToSelection = useCallback(() => {
|
||||
setMode('selection')
|
||||
@@ -248,7 +211,6 @@ export default function ReplaceAllLyricsModal({
|
||||
onSelectReplace={handleSelectReplace}
|
||||
onSelectResync={handleSelectResync}
|
||||
onSelectReplaceSegments={handleSelectReplaceSegments}
|
||||
onSelectChangeCase={handleSelectChangeCase}
|
||||
hasExistingLyrics={hasExistingLyrics}
|
||||
/>
|
||||
|
||||
@@ -381,68 +343,6 @@ export default function ReplaceAllLyricsModal({
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Change Case Modal */}
|
||||
<Dialog open={open && mode === 'changeCase'} onOpenChange={(isOpen) => !isOpen && handleClose()}>
|
||||
<DialogContent className="max-w-2xl flex flex-col">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Button variant="ghost" size="icon" onClick={handleBackToSelection} className="h-8 w-8">
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<span className="flex-1">{t('changeCase')}</span>
|
||||
<Button variant="ghost" size="icon" onClick={handleClose} className="h-8 w-8">
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">{t('changeCasePrompt')}</h3>
|
||||
<div className="flex items-start gap-2 p-3 mt-2 rounded-md bg-muted/50 text-sm text-muted-foreground">
|
||||
<Info className="h-4 w-4 mt-0.5 shrink-0" />
|
||||
<p>{t('changeCaseNote')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{caseOptions.map((opt) => (
|
||||
<button
|
||||
key={opt.type}
|
||||
type="button"
|
||||
onClick={() => setSelectedCase(opt.type)}
|
||||
className={`p-3 border-2 rounded-lg text-left transition-colors ${
|
||||
selectedCase === opt.type
|
||||
? 'border-primary bg-primary/10'
|
||||
: 'border-border hover:border-muted-foreground hover:bg-muted/30'
|
||||
}`}
|
||||
>
|
||||
<div className="text-base font-semibold">{opt.label}</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">{opt.desc}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm font-medium text-muted-foreground mb-2">{t('changeCasePreview')}</p>
|
||||
<div className="p-3 rounded-md bg-muted/30 border font-mono text-sm whitespace-pre-wrap break-words max-h-48 overflow-y-auto">
|
||||
{casePreview || '—'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={handleClose}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleApplyChangeCase} disabled={existingSegments.length === 0}>
|
||||
<Sparkles className="h-4 w-4 mr-2" />
|
||||
{t('changeCaseApply', { case: caseOptions.find((o) => o.type === selectedCase)?.label ?? '' })}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Synchronizer Modal */}
|
||||
<Dialog open={open && mode === 'resync'} onOpenChange={(isOpen) => !isOpen && handleClose()}>
|
||||
<DialogContent className="max-w-[calc(100vw-4vw)] w-[calc(100vw-4vw)] h-[90vh] max-h-[90vh] flex flex-col">
|
||||
|
||||
@@ -49,8 +49,6 @@ export interface HighlightedTextProps {
|
||||
onEditCorrection?: (wordId: string) => void
|
||||
onAcceptCorrection?: (wordId: string) => void
|
||||
onShowCorrectionDetail?: (wordId: string) => void
|
||||
// User-edited word tracking
|
||||
editedWordIds?: Set<string>
|
||||
}
|
||||
|
||||
export function HighlightedText({
|
||||
@@ -78,7 +76,6 @@ export function HighlightedText({
|
||||
onEditCorrection,
|
||||
onAcceptCorrection,
|
||||
onShowCorrectionDetail,
|
||||
editedWordIds,
|
||||
}: HighlightedTextProps) {
|
||||
const { handleWordClick } = useWordClick({
|
||||
mode,
|
||||
@@ -245,7 +242,6 @@ export function HighlightedText({
|
||||
isUncorrectedGap={wordPos.type === 'gap' && !wordPos.isCorrected}
|
||||
isCurrentlyPlaying={shouldHighlightWord(wordPos)}
|
||||
isActiveGap={activeGapWordIds?.has(wordPos.word.id)}
|
||||
isUserEdited={editedWordIds?.has(wordPos.word.id)}
|
||||
id={`word-${wordPos.word.id}`}
|
||||
onClick={() =>
|
||||
handleWordClick(
|
||||
@@ -352,7 +348,6 @@ export function HighlightedText({
|
||||
wordPos || { word: word.text, id: word.id }
|
||||
)}
|
||||
isActiveGap={activeGapWordIds?.has(word.id)}
|
||||
isUserEdited={editedWordIds?.has(word.id)}
|
||||
id={`word-${word.id}`}
|
||||
onClick={() => handleWordClick(word.text, word.id, anchor, sequence)}
|
||||
correction={correctionInfo}
|
||||
|
||||
@@ -14,7 +14,6 @@ export const WordComponent = React.memo(function Word({
|
||||
isUncorrectedGap,
|
||||
isCurrentlyPlaying,
|
||||
isActiveGap,
|
||||
isUserEdited,
|
||||
padding = 'px-[3px] py-[1px]',
|
||||
onClick,
|
||||
id,
|
||||
@@ -25,18 +24,15 @@ export const WordComponent = React.memo(function Word({
|
||||
}
|
||||
|
||||
// Determine background color class
|
||||
// User-edited takes priority over gap states (but not currently-playing or anchor)
|
||||
const bgColorClass = isCurrentlyPlaying
|
||||
? 'bg-blue-500 text-white'
|
||||
: isAnchor
|
||||
? HIGHLIGHT_CLASSES.anchor
|
||||
: isUserEdited
|
||||
? HIGHLIGHT_CLASSES.userEdited
|
||||
: isCorrectedGap
|
||||
? HIGHLIGHT_CLASSES.corrected
|
||||
: isUncorrectedGap
|
||||
? HIGHLIGHT_CLASSES.uncorrectedGap
|
||||
: ''
|
||||
: isCorrectedGap
|
||||
? HIGHLIGHT_CLASSES.corrected
|
||||
: isUncorrectedGap
|
||||
? HIGHLIGHT_CLASSES.uncorrectedGap
|
||||
: ''
|
||||
|
||||
const wordElement = (
|
||||
<span
|
||||
|
||||
@@ -1,339 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useRef, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { ChevronDown, Trash2, Upload, X } from 'lucide-react';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import type { FlyerConfig, NamedPreset } from './flyer-presets';
|
||||
import {
|
||||
BUILT_IN_PRESETS,
|
||||
loadCustomPresets,
|
||||
saveCustomPreset,
|
||||
deleteCustomPreset,
|
||||
} from './flyer-presets';
|
||||
|
||||
interface FlyerControlsProps {
|
||||
config: FlyerConfig;
|
||||
onChange: <K extends keyof FlyerConfig>(key: K, value: FlyerConfig[K]) => void;
|
||||
onLoadPreset: (config: FlyerConfig) => void;
|
||||
}
|
||||
|
||||
function ColorPicker({ label, value, onChange }: { label: string; value: string; onChange: (v: string) => void }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={value.startsWith('#') ? value : '#000000'}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, defaultOpen, children }: { title: string; defaultOpen?: boolean; children: React.ReactNode }) {
|
||||
const [open, setOpen] = useState(defaultOpen ?? true);
|
||||
return (
|
||||
<Collapsible open={open} onOpenChange={setOpen}>
|
||||
<CollapsibleTrigger className="flex items-center justify-between w-full py-1.5 text-sm font-medium text-foreground hover:text-primary transition-colors">
|
||||
{title}
|
||||
<ChevronDown className={`w-4 h-4 transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="pt-2 pb-3 space-y-3">
|
||||
{children}
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
const STEP_PLACEHOLDERS = [
|
||||
{ title: 'Pick any song', desc: 'Search by artist & title...' },
|
||||
{ title: 'Our system does the work', desc: 'Vocals removed, lyrics synced...' },
|
||||
{ title: 'Review & correct the lyrics and instrumental', desc: 'Fine-tune everything...' },
|
||||
{ title: 'Download or publish to YouTube', desc: 'Get your finished karaoke video...' },
|
||||
];
|
||||
|
||||
function detectActivePreset(config: FlyerConfig): string {
|
||||
const all = [...BUILT_IN_PRESETS, ...loadCustomPresets()];
|
||||
for (const preset of all) {
|
||||
if (preset.config.bgColor === config.bgColor
|
||||
&& preset.config.textColor === config.textColor
|
||||
&& preset.config.accentColor === config.accentColor
|
||||
&& JSON.stringify(preset.config.headlineGradient) === JSON.stringify(config.headlineGradient)) {
|
||||
return preset.name;
|
||||
}
|
||||
}
|
||||
return 'Custom';
|
||||
}
|
||||
|
||||
export default function FlyerControls({ config, onChange, onLoadPreset }: FlyerControlsProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const [customPresets, setCustomPresets] = useState<NamedPreset[]>(loadCustomPresets);
|
||||
const [activePreset, setActivePreset] = useState<string>(() => detectActivePreset(config));
|
||||
const [saveName, setSaveName] = useState('');
|
||||
const [showSave, setShowSave] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const allPresets = [...BUILT_IN_PRESETS, ...customPresets];
|
||||
|
||||
const handleLoadPreset = (name: string) => {
|
||||
const preset = allPresets.find(p => p.name === name);
|
||||
if (preset) {
|
||||
onLoadPreset(preset.config);
|
||||
setActivePreset(name);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSavePreset = () => {
|
||||
if (!saveName.trim()) return;
|
||||
saveCustomPreset(saveName.trim(), config);
|
||||
setCustomPresets(loadCustomPresets());
|
||||
setActivePreset(saveName.trim());
|
||||
setSaveName('');
|
||||
setShowSave(false);
|
||||
};
|
||||
|
||||
const handleDeletePreset = (name: string) => {
|
||||
deleteCustomPreset(name);
|
||||
setCustomPresets(loadCustomPresets());
|
||||
if (activePreset === name) setActivePreset('Custom');
|
||||
};
|
||||
|
||||
const handleConfigChange = <K extends keyof FlyerConfig>(key: K, value: FlyerConfig[K]) => {
|
||||
setActivePreset('Custom');
|
||||
onChange(key, value);
|
||||
};
|
||||
|
||||
const handleStepChange = (index: number, field: 'title' | 'desc', value: string) => {
|
||||
const newSteps = [...config.steps];
|
||||
newSteps[index] = { ...newSteps[index], [field]: value || null };
|
||||
handleConfigChange('steps', newSteps);
|
||||
};
|
||||
|
||||
const handleGradientChange = (index: number, value: string) => {
|
||||
const newGradient = [...config.headlineGradient];
|
||||
newGradient[index] = value;
|
||||
handleConfigChange('headlineGradient', newGradient);
|
||||
};
|
||||
|
||||
const handleLogoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
handleConfigChange('customLogoUrl', reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex-1 space-y-1 min-w-0 overflow-y-auto max-h-[65vh] pr-1">
|
||||
{/* Preset selector */}
|
||||
<div className="flex items-center gap-2 pb-2 border-b border-border">
|
||||
<select
|
||||
value={activePreset}
|
||||
onChange={(e) => handleLoadPreset(e.target.value)}
|
||||
className="flex-1 rounded border border-border bg-background text-foreground text-sm px-2 py-1.5"
|
||||
>
|
||||
{activePreset === 'Custom' && <option value="Custom">{t('flyerPresetCustom')}</option>}
|
||||
{allPresets.map(p => (
|
||||
<option key={p.name} value={p.name}>{p.name}</option>
|
||||
))}
|
||||
</select>
|
||||
{showSave ? (
|
||||
<div className="flex gap-1">
|
||||
<input
|
||||
value={saveName}
|
||||
onChange={(e) => setSaveName(e.target.value)}
|
||||
onKeyDown={(e) => e.key === 'Enter' && handleSavePreset()}
|
||||
placeholder={t('flyerPresetName')}
|
||||
className="w-28 rounded border border-border bg-background text-foreground text-xs px-2 py-1"
|
||||
autoFocus
|
||||
/>
|
||||
<button onClick={handleSavePreset} className="text-xs px-2 py-1 bg-primary text-primary-foreground rounded">
|
||||
{t('save')}
|
||||
</button>
|
||||
<button onClick={() => setShowSave(false)} className="text-xs px-1 py-1 text-muted-foreground">
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button onClick={() => setShowSave(true)} className="text-xs px-2 py-1.5 border border-border rounded text-muted-foreground hover:text-foreground">
|
||||
{t('flyerPresetSave')}
|
||||
</button>
|
||||
)}
|
||||
{customPresets.some(p => p.name === activePreset) && (
|
||||
<button onClick={() => handleDeletePreset(activePreset)} className="text-xs px-1 py-1 text-destructive">
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Colors */}
|
||||
<Section title={t('flyerColors')}>
|
||||
<ColorPicker label={t('qrBackground')} value={config.bgColor} onChange={(v) => handleConfigChange('bgColor', v)} />
|
||||
<div>
|
||||
<span className="text-xs text-muted-foreground">{t('flyerHeadlineGradient')}</span>
|
||||
<div className="flex gap-2 mt-1">
|
||||
{config.headlineGradient.map((c, i) => (
|
||||
<input
|
||||
key={i}
|
||||
type="color"
|
||||
value={c}
|
||||
onChange={(e) => handleGradientChange(i, e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<ColorPicker label={t('flyerHeadlineSubColor')} value={config.headlineSubColor} onChange={(v) => handleConfigChange('headlineSubColor', v)} />
|
||||
<ColorPicker label={t('flyerTextColor')} value={config.textColor} onChange={(v) => handleConfigChange('textColor', v)} />
|
||||
<ColorPicker label={t('flyerSubtextColor')} value={config.subtextColor} onChange={(v) => handleConfigChange('subtextColor', v)} />
|
||||
<ColorPicker label={t('flyerAccentColor')} value={config.accentColor} onChange={(v) => handleConfigChange('accentColor', v)} />
|
||||
</Section>
|
||||
|
||||
{/* Text Overrides */}
|
||||
<Section title={t('flyerTextOverrides')} defaultOpen={false}>
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
value={config.headlineMain ?? ''}
|
||||
onChange={(e) => handleConfigChange('headlineMain', e.target.value || null)}
|
||||
placeholder="MAKE YOUR OWN"
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5"
|
||||
/>
|
||||
<input
|
||||
value={config.headlineSub ?? ''}
|
||||
onChange={(e) => handleConfigChange('headlineSub', e.target.value || null)}
|
||||
placeholder="KARAOKE VIDEOS"
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5"
|
||||
/>
|
||||
<textarea
|
||||
value={config.subtitle ?? ''}
|
||||
onChange={(e) => handleConfigChange('subtitle', e.target.value || null)}
|
||||
placeholder="Turn any song into a professional karaoke video..."
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5 h-16 resize-none"
|
||||
/>
|
||||
<input
|
||||
value={config.ctaLabel ?? ''}
|
||||
onChange={(e) => handleConfigChange('ctaLabel', e.target.value || null)}
|
||||
placeholder="First track free + X% off with this link"
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5"
|
||||
/>
|
||||
<input
|
||||
value={config.ctaNote ?? ''}
|
||||
onChange={(e) => handleConfigChange('ctaNote', e.target.value || null)}
|
||||
placeholder="Scan the QR code or visit the link above"
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1.5"
|
||||
/>
|
||||
{config.steps.map((step, i) => (
|
||||
<Collapsible key={i}>
|
||||
<CollapsibleTrigger className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1">
|
||||
<ChevronDown className="w-3 h-3" /> Step {i + 1}
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent className="pl-4 pt-1 space-y-1">
|
||||
<input
|
||||
value={step.title ?? ''}
|
||||
onChange={(e) => handleStepChange(i, 'title', e.target.value)}
|
||||
placeholder={STEP_PLACEHOLDERS[i].title}
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1"
|
||||
/>
|
||||
<input
|
||||
value={step.desc ?? ''}
|
||||
onChange={(e) => handleStepChange(i, 'desc', e.target.value)}
|
||||
placeholder={STEP_PLACEHOLDERS[i].desc}
|
||||
className="w-full rounded border border-border bg-background text-foreground text-xs px-2 py-1"
|
||||
/>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
{/* Sections */}
|
||||
<Section title={t('flyerSections')}>
|
||||
{([
|
||||
['showSubtitle', t('flyerToggleSubtitle')],
|
||||
['showSteps', t('flyerToggleSteps')],
|
||||
['showDivider', t('flyerToggleDivider')],
|
||||
['showBottomFeatures', t('flyerToggleFeatures')],
|
||||
['showBottomTagline', t('flyerToggleTagline')],
|
||||
] as const).map(([key, label]) => (
|
||||
<div key={key} className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">{label}</span>
|
||||
<Switch
|
||||
checked={config[key] as boolean}
|
||||
onCheckedChange={(v) => handleConfigChange(key, v)}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</Section>
|
||||
|
||||
{/* Branding */}
|
||||
<Section title={t('flyerBranding')} defaultOpen={false}>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/svg+xml"
|
||||
onChange={handleLogoUpload}
|
||||
className="hidden"
|
||||
/>
|
||||
{config.customLogoUrl ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<img src={config.customLogoUrl} alt="Custom logo" className="h-10 w-auto rounded border border-border" />
|
||||
<button
|
||||
onClick={() => handleConfigChange('customLogoUrl', null)}
|
||||
className="text-xs text-destructive flex items-center gap-1"
|
||||
>
|
||||
<X className="w-3 h-3" /> {t('flyerRemoveLogo')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="text-xs px-3 py-1.5 border border-border rounded text-muted-foreground hover:text-foreground flex items-center gap-1.5"
|
||||
>
|
||||
<Upload className="w-3.5 h-3.5" /> {t('flyerUploadLogo')}
|
||||
</button>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{/* Print Layout */}
|
||||
<Section title={t('flyerPrintLayout')}>
|
||||
<div>
|
||||
<span className="text-xs text-muted-foreground">{t('flyerPerPage')}</span>
|
||||
<div className="flex gap-1.5 mt-1">
|
||||
{([1, 2, 4] as const).map(n => (
|
||||
<button
|
||||
key={n}
|
||||
onClick={() => handleConfigChange('perPage', n)}
|
||||
className={`px-3 py-1.5 text-xs rounded border transition-colors ${
|
||||
config.perPage === n
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{n}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">{t('flyerMargins')}</span>
|
||||
<span className="text-xs text-muted-foreground">{config.marginMm}mm</span>
|
||||
</div>
|
||||
<Slider
|
||||
value={[config.marginMm]}
|
||||
onValueChange={([v]) => handleConfigChange('marginMm', v)}
|
||||
min={0}
|
||||
max={30}
|
||||
className="mt-1"
|
||||
/>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
import { toPng } from 'html-to-image';
|
||||
import jsPDF from 'jspdf';
|
||||
|
||||
// US Letter in mm
|
||||
const PAGE_W_MM = 215.9;
|
||||
const PAGE_H_MM = 279.4;
|
||||
|
||||
/** Capture the flyer at full size by temporarily removing the preview scale transform. */
|
||||
async function captureFlyer(flyerElement: HTMLElement, pixelRatio: number): Promise<string> {
|
||||
const savedTransform = flyerElement.style.transform;
|
||||
const savedOrigin = flyerElement.style.transformOrigin;
|
||||
flyerElement.style.transform = 'none';
|
||||
flyerElement.style.transformOrigin = '';
|
||||
try {
|
||||
return await toPng(flyerElement, {
|
||||
pixelRatio,
|
||||
width: 816,
|
||||
height: 1056,
|
||||
});
|
||||
} finally {
|
||||
flyerElement.style.transform = savedTransform;
|
||||
flyerElement.style.transformOrigin = savedOrigin;
|
||||
}
|
||||
}
|
||||
|
||||
interface PdfOptions {
|
||||
perPage: 1 | 2 | 4;
|
||||
marginMm: number;
|
||||
filename: string;
|
||||
}
|
||||
|
||||
export async function exportFlyerPdf(
|
||||
flyerElement: HTMLElement,
|
||||
options: PdfOptions,
|
||||
): Promise<void> {
|
||||
const { perPage, marginMm, filename } = options;
|
||||
|
||||
const imgData = await captureFlyer(flyerElement, 2);
|
||||
const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'letter' });
|
||||
|
||||
const margin = marginMm;
|
||||
const usableW = PAGE_W_MM - margin * 2;
|
||||
const usableH = PAGE_H_MM - margin * 2;
|
||||
const flyerAspect = 8.5 / 11;
|
||||
|
||||
if (perPage === 1) {
|
||||
let w = usableW;
|
||||
let h = w / flyerAspect;
|
||||
if (h > usableH) {
|
||||
h = usableH;
|
||||
w = h * flyerAspect;
|
||||
}
|
||||
const x = margin + (usableW - w) / 2;
|
||||
const y = margin + (usableH - h) / 2;
|
||||
pdf.addImage(imgData, 'PNG', x, y, w, h);
|
||||
} else if (perPage === 2) {
|
||||
const gapMm = margin;
|
||||
const slotH = (usableH - gapMm) / 2;
|
||||
let w = usableW;
|
||||
let h = w / flyerAspect;
|
||||
if (h > slotH) {
|
||||
h = slotH;
|
||||
w = h * flyerAspect;
|
||||
}
|
||||
const x = margin + (usableW - w) / 2;
|
||||
pdf.addImage(imgData, 'PNG', x, margin, w, h);
|
||||
pdf.addImage(imgData, 'PNG', x, margin + slotH + gapMm, w, h);
|
||||
} else {
|
||||
const gapMm = margin;
|
||||
const slotW = (usableW - gapMm) / 2;
|
||||
const slotH = (usableH - gapMm) / 2;
|
||||
let w = slotW;
|
||||
let h = w / flyerAspect;
|
||||
if (h > slotH) {
|
||||
h = slotH;
|
||||
w = h * flyerAspect;
|
||||
}
|
||||
const positions = [
|
||||
[margin, margin],
|
||||
[margin + slotW + gapMm, margin],
|
||||
[margin, margin + slotH + gapMm],
|
||||
[margin + slotW + gapMm, margin + slotH + gapMm],
|
||||
];
|
||||
for (const [px, py] of positions) {
|
||||
const offsetX = px + (slotW - w) / 2;
|
||||
const offsetY = py + (slotH - h) / 2;
|
||||
pdf.addImage(imgData, 'PNG', offsetX, offsetY, w, h);
|
||||
}
|
||||
}
|
||||
|
||||
pdf.save(filename);
|
||||
}
|
||||
|
||||
export function exportFlyerHtml(flyerElement: HTMLElement): Blob {
|
||||
const html = `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Nomad Karaoke Referral Flyer</title>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
*, html { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
@page { size: 8.5in 11in; margin: 0; }
|
||||
body { display: flex; justify-content: center; }
|
||||
@media print { body { -webkit-print-color-adjust: exact; print-color-adjust: exact; } }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
${flyerElement.outerHTML}
|
||||
</body>
|
||||
</html>`;
|
||||
return new Blob([html], { type: 'text/html' });
|
||||
}
|
||||
|
||||
export async function exportFlyerPng(
|
||||
flyerElement: HTMLElement,
|
||||
filename: string,
|
||||
): Promise<void> {
|
||||
const imgData = await captureFlyer(flyerElement, 2);
|
||||
|
||||
const a = document.createElement('a');
|
||||
a.href = imgData;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
}
|
||||
@@ -1,301 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { FlyerConfig } from './flyer-presets';
|
||||
|
||||
// Default text values matching the original HTML template
|
||||
const DEFAULTS = {
|
||||
headlineMain: 'MAKE YOUR OWN',
|
||||
headlineSub: 'KARAOKE VIDEOS',
|
||||
subtitle:
|
||||
'Turn any song into a professional karaoke video with synced lyrics, vocal removal, and automatic YouTube publishing.',
|
||||
ctaLabel: (discountPercent: number) =>
|
||||
`First track free + ${discountPercent}% off with this link`,
|
||||
ctaNote: 'Scan the QR code or visit the link above',
|
||||
steps: [
|
||||
{ title: 'Pick any song', desc: 'Search by artist & title or paste a YouTube link' },
|
||||
{ title: 'Our system does the work', desc: 'Vocals removed, lyrics synced, video rendered automatically' },
|
||||
{ title: 'Review & correct the lyrics and instrumental', desc: 'Fine-tune everything before publishing' },
|
||||
{ title: 'Download or publish to YouTube', desc: 'Get your finished karaoke video in minutes' },
|
||||
],
|
||||
};
|
||||
|
||||
// Inline SVG Nomad Karaoke wordmark (from the HTML template)
|
||||
function NomadLogo({ color }: { color: string }) {
|
||||
return (
|
||||
<svg style={{ width: 260, height: 'auto' }} viewBox="45 60 255 135" xmlns="http://www.w3.org/2000/svg">
|
||||
<g fill={color} transform="translate(48.368003845214844,62.62239074707031)">
|
||||
<g transform="translate(0,0)">
|
||||
<g transform="scale(1.4000000000000004)">
|
||||
<g stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" paintOrder="stroke" fillOpacity="0">
|
||||
<path d="M1.4-33.44L1.4 0C31.48 0 3.96 0 34.04 0L34.04-32.64 17.81-32.64 17.81-20.61 1.4-33.44ZM52.21-33.76C42.6-33.76 34.81-25.97 34.81-16.37 34.81-6.76 42.6 1.03 52.21 1.03 61.81 1.03 69.6-6.76 69.6-16.37 69.6-25.97 61.81-33.76 52.21-33.76ZM70.7 0L103.34 0 103.25-33.9 86.93-21.54 70.61-33.9 70.7 0ZM102.34 0C138.2 0 107.52 0 143.56 0L122.95-34.93 102.34 0ZM158.84 0.05C167.84 0.05 175.16-7.27 175.16-16.27 175.16-25.27 167.84-32.64 158.84-32.64L142.52-32.64C142.52 0.75 142.52-33.34 142.52 0.05L158.84 0.05Z" transform="translate(-1.399999976158142, 34.93000030517578)" />
|
||||
</g>
|
||||
<g transform="translate(0,38.959999084472656)">
|
||||
<g stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" paintOrder="stroke" fill={color} fillOpacity="0" transform="scale(1.02719)">
|
||||
<path d="M24.43 0L17.67 0 7.98-11.87 7.98 0 2.63 0 2.63-26.64 7.98-26.64 7.98-14.69 17.67-26.64 24.12-26.64 13.13-13.44 24.43 0ZM45.03 0L43.27-5.08 32.66-5.08 30.91 0 25.3 0 34.88-26.68 41.1-26.68 50.68 0 45.03 0ZM34.11-9.35L41.82-9.35 37.97-20.5 34.11-9.35ZM73.19 0L67.01 0 61.13-10.38 58.61-10.38 58.61 0 53.27 0 53.27-26.64 63.27-26.64Q66.36-26.64 68.53-25.55 70.71-24.47 71.8-22.61 72.89-20.76 72.89-18.47L72.89-18.47Q72.89-15.84 71.36-13.72 69.83-11.6 66.82-10.8L66.82-10.8 73.19 0ZM58.61-22.21L58.61-14.39 63.08-14.39Q65.25-14.39 66.32-15.44 67.39-16.49 67.39-18.36L67.39-18.36Q67.39-20.19 66.32-21.2 65.25-22.21 63.08-22.21L63.08-22.21 58.61-22.21ZM94.82 0L93.07-5.08 82.46-5.08 80.7 0 75.09 0 84.67-26.68 90.89-26.68 100.47 0 94.82 0ZM83.91-9.35L91.62-9.35 87.76-20.5 83.91-9.35ZM115.43 0.27Q111.69 0.27 108.56-1.49 105.43-3.24 103.6-6.35 101.76-9.47 101.76-13.4L101.76-13.4Q101.76-17.29 103.6-20.4 105.43-23.51 108.56-25.27 111.69-27.02 115.43-27.02L115.43-27.02Q119.21-27.02 122.32-25.27 125.43-23.51 127.24-20.4 129.05-17.29 129.05-13.4L129.05-13.4Q129.05-9.47 127.24-6.35 125.43-3.24 122.3-1.49 119.17 0.27 115.43 0.27L115.43 0.27ZM115.43-4.5Q117.83-4.5 119.66-5.59 121.5-6.68 122.53-8.7 123.56-10.73 123.56-13.4L123.56-13.4Q123.56-16.07 122.53-18.07 121.5-20.08 119.66-21.15 117.83-22.21 115.43-22.21L115.43-22.21Q113.02-22.21 111.17-21.15 109.32-20.08 108.29-18.07 107.26-16.07 107.26-13.4L107.26-13.4Q107.26-10.73 108.29-8.7 109.32-6.68 111.17-5.59 113.02-4.5 115.43-4.5L115.43-4.5ZM153.82 0L147.06 0 137.37-11.87 137.37 0 132.02 0 132.02-26.64 137.37-26.64 137.37-14.69 147.06-26.64 153.51-26.64 142.52-13.44 153.82 0ZM171.79-22.33L161.67-22.33 161.67-15.65 170.64-15.65 170.64-11.41 161.67-11.41 161.67-4.35 171.79-4.35 171.79 0 156.33 0 156.33-26.68 171.79-26.68 171.79-22.33Z" transform="translate(-2.630000114440918, 27.020000457763672)" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
interface FlyerPreviewProps {
|
||||
config: FlyerConfig;
|
||||
referralCode: string;
|
||||
discountPercent: number;
|
||||
qrDataUrl: string | null;
|
||||
/** Ref to the inner flyer element for export */
|
||||
flyerRef?: React.RefObject<HTMLDivElement | null>;
|
||||
}
|
||||
|
||||
export default function FlyerPreview({
|
||||
config,
|
||||
referralCode,
|
||||
discountPercent,
|
||||
qrDataUrl,
|
||||
flyerRef,
|
||||
}: FlyerPreviewProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Scale flyer to fit its preview container
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const resize = () => {
|
||||
const flyerEl = container.querySelector('[data-flyer-page]') as HTMLElement;
|
||||
if (!flyerEl) return;
|
||||
const parentW = container.parentElement?.clientWidth || container.clientWidth;
|
||||
// Flyer: 8.5in x 11in at 96dpi = 816 x 1056 px
|
||||
const flyerW = 816;
|
||||
const flyerH = 1056;
|
||||
const scale = Math.min(parentW / flyerW, 1);
|
||||
flyerEl.style.transform = `scale(${scale})`;
|
||||
flyerEl.style.transformOrigin = 'top left';
|
||||
container.style.width = `${flyerW * scale}px`;
|
||||
container.style.height = `${flyerH * scale}px`;
|
||||
};
|
||||
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(container.parentElement || container);
|
||||
resize();
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const headlineMain = config.headlineMain ?? DEFAULTS.headlineMain;
|
||||
const headlineSub = config.headlineSub ?? DEFAULTS.headlineSub;
|
||||
const subtitle = config.subtitle ?? DEFAULTS.subtitle;
|
||||
const ctaLabel = config.ctaLabel ?? DEFAULTS.ctaLabel(discountPercent);
|
||||
const ctaNote = config.ctaNote ?? DEFAULTS.ctaNote;
|
||||
const steps = DEFAULTS.steps.map((def, i) => ({
|
||||
title: config.steps[i]?.title ?? def.title,
|
||||
desc: config.steps[i]?.desc ?? def.desc,
|
||||
}));
|
||||
|
||||
// Unique ID per render for SVG gradient defs (avoids clashes if multiple previews)
|
||||
const gradientId = 'flyer-grad-headline';
|
||||
const gradientCodeId = 'flyer-grad-code';
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className="relative overflow-hidden">
|
||||
<div
|
||||
ref={flyerRef}
|
||||
data-flyer-page=""
|
||||
style={{
|
||||
width: 816,
|
||||
height: 1056,
|
||||
fontFamily: "'Outfit', sans-serif",
|
||||
background: config.bgColor,
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
alignItems: 'center',
|
||||
padding: '0.6in 0.65in 0.5in',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{/* Logo row */}
|
||||
<div style={{ marginBottom: 24, display: 'flex', alignItems: 'center', gap: 16 }}>
|
||||
<NomadLogo color={config.accentColor} />
|
||||
{config.customLogoUrl && (
|
||||
<img
|
||||
src={config.customLogoUrl}
|
||||
alt="Custom logo"
|
||||
style={{ height: 60, width: 'auto', objectFit: 'contain' }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Headline — uses inline SVG for gradient text (background-clip:text breaks in image export) */}
|
||||
<div style={{ fontFamily: "'Bebas Neue', sans-serif", textAlign: 'center', lineHeight: 0.92, marginBottom: 6 }}>
|
||||
<svg width="100%" height="96" style={{ overflow: 'visible' }}>
|
||||
<defs>
|
||||
<linearGradient id={gradientId} x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
{config.headlineGradient.map((c, i) => (
|
||||
<stop key={i} offset={`${(i / (config.headlineGradient.length - 1)) * 100}%`} stopColor={c} />
|
||||
))}
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<text
|
||||
x="50%"
|
||||
y="80"
|
||||
textAnchor="middle"
|
||||
fill={`url(#${gradientId})`}
|
||||
fontFamily="'Bebas Neue', sans-serif"
|
||||
fontSize="96"
|
||||
letterSpacing="3"
|
||||
>
|
||||
{headlineMain}
|
||||
</text>
|
||||
</svg>
|
||||
<div style={{ fontSize: 62, letterSpacing: 2, color: config.headlineSubColor }}>
|
||||
{headlineSub}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Subtitle */}
|
||||
{config.showSubtitle && (
|
||||
<div
|
||||
style={{
|
||||
fontSize: 20,
|
||||
fontWeight: 500,
|
||||
color: config.subtextColor,
|
||||
textAlign: 'center',
|
||||
maxWidth: '5.5in',
|
||||
lineHeight: 1.4,
|
||||
marginBottom: 28,
|
||||
}}
|
||||
>
|
||||
{subtitle}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Steps */}
|
||||
{config.showSteps && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 18, width: '100%', maxWidth: '6in', marginBottom: 28 }}>
|
||||
{steps.map((step, i) => (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
|
||||
<div
|
||||
style={{
|
||||
width: 52,
|
||||
height: 52,
|
||||
flexShrink: 0,
|
||||
borderRadius: '50%',
|
||||
background: `linear-gradient(135deg, ${config.accentColor}, ${config.headlineGradient[1] || config.accentColor})`,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
fontFamily: "'Bebas Neue', sans-serif",
|
||||
fontSize: 30,
|
||||
color: '#fff',
|
||||
letterSpacing: 1,
|
||||
}}
|
||||
>
|
||||
{i + 1}
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontSize: 22, fontWeight: 800, color: config.textColor, letterSpacing: -0.3 }}>
|
||||
{step.title}
|
||||
</div>
|
||||
<div style={{ fontSize: 16, fontWeight: 400, color: config.subtextColor, marginTop: 2 }}>
|
||||
{step.desc}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Divider */}
|
||||
{config.showDivider && (
|
||||
<div
|
||||
style={{
|
||||
width: '80%',
|
||||
height: 2,
|
||||
background: `linear-gradient(90deg, transparent, ${config.accentColor}4D, ${config.headlineGradient[1] || config.accentColor}4D, transparent)`,
|
||||
margin: '4px 0 24px',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* CTA section */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 40, width: '100%', marginBottom: 20 }}>
|
||||
<div
|
||||
style={{
|
||||
width: 180,
|
||||
height: 180,
|
||||
borderRadius: 16,
|
||||
background: '#fff',
|
||||
border: '3px solid #e8e4e0',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
boxShadow: '0 4px 20px rgba(0,0,0,0.06)',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{qrDataUrl ? (
|
||||
<img src={qrDataUrl} alt={`QR Code - nomadkaraoke.com/r/${referralCode.toLowerCase()}`} style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
|
||||
) : (
|
||||
<span style={{ fontSize: 14, color: '#999', textAlign: 'center', padding: 20 }}>QR Code</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
|
||||
<div style={{ fontSize: 16, fontWeight: 600, color: config.subtextColor, textTransform: 'uppercase', letterSpacing: 2, marginBottom: 6 }}>
|
||||
{ctaLabel}
|
||||
</div>
|
||||
<svg width="100%" height="42" style={{ overflow: 'visible' }}>
|
||||
<defs>
|
||||
<linearGradient id={gradientCodeId} x1="0%" y1="0%" x2="100%" y2="100%">
|
||||
{[...config.headlineGradient, '#ffdf6b'].map((c, i, arr) => (
|
||||
<stop key={i} offset={`${(i / (arr.length - 1)) * 100}%`} stopColor={c} />
|
||||
))}
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<text
|
||||
x="0"
|
||||
y="34"
|
||||
fontFamily="'Bebas Neue', sans-serif"
|
||||
fontSize="38"
|
||||
letterSpacing="2"
|
||||
>
|
||||
<tspan fill={config.textColor}>NOMADKARAOKE.COM/R/</tspan>
|
||||
<tspan fill={`url(#${gradientCodeId})`} letterSpacing="4">{referralCode.toUpperCase()}</tspan>
|
||||
</text>
|
||||
</svg>
|
||||
<div style={{ fontSize: 15, color: config.subtextColor, marginTop: 8, fontWeight: 500 }}>
|
||||
{ctaNote}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bottom */}
|
||||
<div style={{ marginTop: 'auto', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
{config.showBottomFeatures && (
|
||||
<div style={{ display: 'flex', gap: 24 }}>
|
||||
{[
|
||||
{ icon: '\u{1F3A4}', label: 'Any Song' },
|
||||
{ icon: '\u26A1', label: 'Automatic' },
|
||||
{ icon: '\u{1F3AC}', label: 'Pro Quality' },
|
||||
].map(({ icon, label }) => (
|
||||
<div key={label} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, fontWeight: 600, color: config.subtextColor }}>
|
||||
<span style={{ fontSize: 20 }}>{icon}</span>
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{config.showBottomTagline && (
|
||||
<div style={{ fontSize: 14, fontWeight: 500, color: config.subtextColor, letterSpacing: 1, marginLeft: 'auto' }}>
|
||||
Wherever you are, sing!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Download, Pencil } from 'lucide-react';
|
||||
import type { QRStylePrefs } from './QRCodeTab';
|
||||
import type { FlyerConfig } from './flyer-presets';
|
||||
import { DEFAULT_FLYER_CONFIG, loadFlyerConfig, saveFlyerConfig } from './flyer-presets';
|
||||
import FlyerPreview from './FlyerPreview';
|
||||
import FlyerControls from './FlyerControls';
|
||||
import { exportFlyerPdf, exportFlyerHtml, exportFlyerPng } from './FlyerExport';
|
||||
|
||||
interface FlyerTabProps {
|
||||
referralCode: string;
|
||||
discountPercent: number;
|
||||
qrPrefs: QRStylePrefs;
|
||||
onSwitchToQr: () => void;
|
||||
flyerFilename?: string;
|
||||
}
|
||||
|
||||
export default function FlyerTab({ referralCode, discountPercent, qrPrefs, onSwitchToQr, flyerFilename }: FlyerTabProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const flyerRef = useRef<HTMLDivElement>(null);
|
||||
const [config, setConfig] = useState<FlyerConfig>(DEFAULT_FLYER_CONFIG);
|
||||
const [exporting, setExporting] = useState<string | null>(null);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
|
||||
|
||||
// Load saved config
|
||||
useEffect(() => {
|
||||
setConfig(loadFlyerConfig());
|
||||
}, []);
|
||||
|
||||
// Debounced save
|
||||
const updateConfig = useCallback(<K extends keyof FlyerConfig>(key: K, value: FlyerConfig[K]) => {
|
||||
setConfig(prev => {
|
||||
const next = { ...prev, [key]: value };
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => saveFlyerConfig(next), 300);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const loadPreset = useCallback((presetConfig: FlyerConfig) => {
|
||||
// Cancel any pending debounce to avoid overwriting the preset
|
||||
if (debounceRef.current) {
|
||||
clearTimeout(debounceRef.current);
|
||||
debounceRef.current = null;
|
||||
}
|
||||
setConfig(presetConfig);
|
||||
saveFlyerConfig(presetConfig);
|
||||
}, []);
|
||||
|
||||
// Render QR code for flyer using qr-code-styling
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const renderQr = async () => {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
if (cancelled) return;
|
||||
|
||||
let image: string | undefined;
|
||||
if (qrPrefs.logo === 'nomad') {
|
||||
image = '/nomad-karaoke-logo.svg';
|
||||
} else if (qrPrefs.logo === 'emoji' && qrPrefs.logoEmoji) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 64;
|
||||
canvas.height = 64;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
ctx.font = '52px serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(qrPrefs.logoEmoji, 32, 36);
|
||||
image = canvas.toDataURL('image/png');
|
||||
}
|
||||
}
|
||||
|
||||
const qr = new QRCodeStyling({
|
||||
width: 160,
|
||||
height: 160,
|
||||
data: `https://nomadkaraoke.com/r/${referralCode.toLowerCase()}`,
|
||||
dotsOptions: { type: qrPrefs.dotStyle, color: qrPrefs.fgColor },
|
||||
cornersSquareOptions: { type: qrPrefs.cornerSquareStyle, color: qrPrefs.fgColor },
|
||||
cornersDotOptions: { type: qrPrefs.cornerDotStyle, color: qrPrefs.fgColor },
|
||||
backgroundOptions: { color: qrPrefs.bgColor },
|
||||
image,
|
||||
imageOptions: { hideBackgroundDots: true, imageSize: 0.2, margin: 4 },
|
||||
});
|
||||
|
||||
if (cancelled) return;
|
||||
|
||||
const blob = await qr.getRawData('png');
|
||||
if (blob && !cancelled) {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => {
|
||||
if (!cancelled) setQrDataUrl(reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(blob as Blob);
|
||||
}
|
||||
};
|
||||
renderQr();
|
||||
return () => { cancelled = true; };
|
||||
}, [qrPrefs, referralCode]);
|
||||
|
||||
// Cleanup debounce
|
||||
useEffect(() => {
|
||||
return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
|
||||
}, []);
|
||||
|
||||
const baseFilename = flyerFilename?.replace(/\.[^.]+$/, '') || `nomad-karaoke-flyer-${referralCode}`;
|
||||
|
||||
const handleExport = async (format: 'pdf' | 'html' | 'png') => {
|
||||
const el = flyerRef.current;
|
||||
if (!el) return;
|
||||
setExporting(format);
|
||||
try {
|
||||
if (format === 'pdf') {
|
||||
await exportFlyerPdf(el, {
|
||||
perPage: config.perPage,
|
||||
marginMm: config.marginMm,
|
||||
filename: `${baseFilename}.pdf`,
|
||||
});
|
||||
} else if (format === 'html') {
|
||||
const blob = exportFlyerHtml(el);
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `${baseFilename}.html`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} else {
|
||||
await exportFlyerPng(el, `${baseFilename}.png`);
|
||||
}
|
||||
} finally {
|
||||
setExporting(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col md:flex-row gap-6">
|
||||
{/* Left: Flyer Preview */}
|
||||
<div className="flex-shrink-0 relative w-[240px]">
|
||||
<FlyerPreview
|
||||
config={config}
|
||||
referralCode={referralCode}
|
||||
discountPercent={discountPercent}
|
||||
qrDataUrl={qrDataUrl}
|
||||
flyerRef={flyerRef}
|
||||
/>
|
||||
{/* Edit QR Style link */}
|
||||
<button
|
||||
onClick={onSwitchToQr}
|
||||
className="absolute bottom-2 left-2 text-xs text-primary flex items-center gap-1 hover:underline bg-background/80 rounded px-1.5 py-0.5"
|
||||
>
|
||||
<Pencil className="w-3 h-3" />
|
||||
{t('flyerEditQr')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Right: Controls */}
|
||||
<FlyerControls config={config} onChange={updateConfig} onLoadPreset={loadPreset} />
|
||||
</div>
|
||||
|
||||
{/* Export buttons */}
|
||||
<div className="flex gap-2 pt-2 border-t border-border sm:justify-end">
|
||||
<button
|
||||
onClick={() => handleExport('pdf')}
|
||||
disabled={!!exporting || !qrDataUrl}
|
||||
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{exporting === 'pdf' ? t('flyerExporting') : t('flyerDownloadPdf')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleExport('html')}
|
||||
disabled={!!exporting || !qrDataUrl}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary disabled:opacity-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('flyerDownloadHtml')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleExport('png')}
|
||||
disabled={!!exporting || !qrDataUrl}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary disabled:opacity-50"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('flyerDownloadPng')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { QrCode, Download, Mic, Music } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
|
||||
const STORAGE_KEY = 'nk-qr-style-prefs';
|
||||
|
||||
type DotStyle = 'square' | 'rounded' | 'dots' | 'classy' | 'classy-rounded' | 'extra-rounded';
|
||||
type CornerSquareStyle = 'square' | 'dot' | 'extra-rounded';
|
||||
type CornerDotStyle = 'square' | 'dot';
|
||||
type LogoOption = 'none' | 'nomad' | 'mic' | 'music';
|
||||
|
||||
interface QRStylePrefs {
|
||||
dotStyle: DotStyle;
|
||||
cornerSquareStyle: CornerSquareStyle;
|
||||
cornerDotStyle: CornerDotStyle;
|
||||
fgColor: string;
|
||||
bgColor: string;
|
||||
logo: LogoOption;
|
||||
}
|
||||
|
||||
const DEFAULT_PREFS: QRStylePrefs = {
|
||||
dotStyle: 'square',
|
||||
cornerSquareStyle: 'square',
|
||||
cornerDotStyle: 'square',
|
||||
fgColor: '#000000',
|
||||
bgColor: '#ffffff',
|
||||
logo: 'none',
|
||||
};
|
||||
|
||||
const DOT_STYLES: DotStyle[] = ['square', 'rounded', 'dots', 'classy', 'classy-rounded', 'extra-rounded'];
|
||||
const CORNER_SQUARE_STYLES: CornerSquareStyle[] = ['square', 'dot', 'extra-rounded'];
|
||||
const CORNER_DOT_STYLES: CornerDotStyle[] = ['square', 'dot'];
|
||||
|
||||
const DOT_STYLE_LABELS: Record<DotStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'rounded': 'qrStyleRounded',
|
||||
'dots': 'qrStyleDots',
|
||||
'classy': 'qrStyleClassy',
|
||||
'classy-rounded': 'qrStyleClassyRounded',
|
||||
'extra-rounded': 'qrStyleExtraRounded',
|
||||
};
|
||||
|
||||
const CORNER_SQUARE_LABELS: Record<CornerSquareStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'dot': 'qrStyleDot',
|
||||
'extra-rounded': 'qrStyleExtraRounded',
|
||||
};
|
||||
|
||||
const CORNER_DOT_LABELS: Record<CornerDotStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'dot': 'qrStyleDot',
|
||||
};
|
||||
|
||||
function loadPrefs(): QRStylePrefs {
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
if (saved) {
|
||||
return { ...DEFAULT_PREFS, ...JSON.parse(saved) };
|
||||
}
|
||||
} catch {}
|
||||
return { ...DEFAULT_PREFS };
|
||||
}
|
||||
|
||||
function savePrefs(prefs: QRStylePrefs) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function getLucideIconDataUrl(IconComponent: typeof Mic, color: string = '#000000'): string {
|
||||
const svgNs = 'http://www.w3.org/2000/svg';
|
||||
const svg = document.createElementNS(svgNs, 'svg');
|
||||
svg.setAttribute('xmlns', svgNs);
|
||||
svg.setAttribute('width', '48');
|
||||
svg.setAttribute('height', '48');
|
||||
svg.setAttribute('viewBox', '0 0 24 24');
|
||||
svg.setAttribute('fill', 'none');
|
||||
svg.setAttribute('stroke', color);
|
||||
svg.setAttribute('stroke-width', '2');
|
||||
svg.setAttribute('stroke-linecap', 'round');
|
||||
svg.setAttribute('stroke-linejoin', 'round');
|
||||
|
||||
const iconNode = (IconComponent as unknown as { iconNode: Array<[string, Record<string, string>]> }).iconNode;
|
||||
if (iconNode) {
|
||||
for (const [tag, attrs] of iconNode) {
|
||||
const el = document.createElementNS(svgNs, tag);
|
||||
for (const [key, val] of Object.entries(attrs)) {
|
||||
el.setAttribute(key, val);
|
||||
}
|
||||
svg.appendChild(el);
|
||||
}
|
||||
}
|
||||
|
||||
const svgStr = new XMLSerializer().serializeToString(svg);
|
||||
return `data:image/svg+xml;base64,${btoa(svgStr)}`;
|
||||
}
|
||||
|
||||
interface QRCodeDialogProps {
|
||||
referralUrl: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export default function QRCodeDialog({ referralUrl, open, onOpenChange }: QRCodeDialogProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const qrRef = useRef<InstanceType<typeof import('qr-code-styling').default> | null>(null);
|
||||
const [prefs, setPrefs] = useState<QRStylePrefs>(DEFAULT_PREFS);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Load prefs from localStorage on open
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setPrefs(loadPrefs());
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Build QR options from prefs
|
||||
const buildOptions = useCallback((p: QRStylePrefs) => {
|
||||
let image: string | undefined;
|
||||
if (p.logo === 'nomad') {
|
||||
image = '/nomad-karaoke-logo.svg';
|
||||
} else if (p.logo === 'mic') {
|
||||
image = getLucideIconDataUrl(Mic, p.fgColor);
|
||||
} else if (p.logo === 'music') {
|
||||
image = getLucideIconDataUrl(Music, p.fgColor);
|
||||
}
|
||||
|
||||
return {
|
||||
width: 250,
|
||||
height: 250,
|
||||
data: referralUrl,
|
||||
dotsOptions: { type: p.dotStyle, color: p.fgColor },
|
||||
cornersSquareOptions: { type: p.cornerSquareStyle, color: p.fgColor },
|
||||
cornersDotOptions: { type: p.cornerDotStyle, color: p.fgColor },
|
||||
backgroundOptions: { color: p.bgColor },
|
||||
image,
|
||||
imageOptions: image ? { hideBackgroundDots: true, imageSize: 0.2, margin: 4 } : undefined,
|
||||
};
|
||||
}, [referralUrl]);
|
||||
|
||||
// Initialize / update QR code
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const init = async () => {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
|
||||
if (cancelled) return;
|
||||
|
||||
if (!qrRef.current) {
|
||||
qrRef.current = new QRCodeStyling(buildOptions(prefs));
|
||||
if (!cancelled && containerRef.current) {
|
||||
containerRef.current.innerHTML = '';
|
||||
qrRef.current.append(containerRef.current);
|
||||
}
|
||||
} else if (!cancelled) {
|
||||
qrRef.current.update(buildOptions(prefs));
|
||||
}
|
||||
|
||||
if (!cancelled) {
|
||||
setLoaded(true);
|
||||
}
|
||||
};
|
||||
|
||||
init();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [open, prefs, buildOptions]);
|
||||
|
||||
// Clean up on close
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
qrRef.current = null;
|
||||
setLoaded(false);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const updatePref = <K extends keyof QRStylePrefs>(key: K, value: QRStylePrefs[K]) => {
|
||||
setPrefs(prev => {
|
||||
const next = { ...prev, [key]: value };
|
||||
// Debounce localStorage save
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => savePrefs(next), 300);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleDownload = async (extension: 'png' | 'svg') => {
|
||||
// Initialize QR instance if not yet ready (e.g., download clicked before init effect completes)
|
||||
if (!qrRef.current) {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
qrRef.current = new QRCodeStyling(buildOptions(prefs));
|
||||
}
|
||||
await qrRef.current.download({ name: 'referral-qr', extension });
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-2xl bg-card border-border max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<QrCode className="w-5 h-5" />
|
||||
{t('qrTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col md:flex-row gap-6">
|
||||
{/* Left: QR Preview */}
|
||||
<div className="flex-shrink-0 flex items-center justify-center">
|
||||
<div
|
||||
className="relative w-[250px] h-[250px] rounded-lg border border-border"
|
||||
style={{ backgroundColor: prefs.bgColor }}
|
||||
>
|
||||
{/* QR code is appended into this container by qr-code-styling */}
|
||||
<div ref={containerRef} className="w-full h-full" />
|
||||
{/* Loading skeleton rendered as a sibling so innerHTML clear doesn't affect React tree */}
|
||||
{!loaded && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="animate-pulse w-[200px] h-[200px] bg-muted rounded" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Controls */}
|
||||
<div className="flex-1 space-y-4 min-w-0">
|
||||
{/* Dot Style */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrDotStyle')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{DOT_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('dotStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.dotStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(DOT_STYLE_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Frame */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrCornerFrame')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{CORNER_SQUARE_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('cornerSquareStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.cornerSquareStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(CORNER_SQUARE_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Dot */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrCornerDot')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{CORNER_DOT_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('cornerDotStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.cornerDotStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(CORNER_DOT_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Colors */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrColors')}</label>
|
||||
<div className="flex gap-4 mt-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={prefs.fgColor}
|
||||
onChange={(e) => updatePref('fgColor', e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('qrForeground')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={prefs.bgColor}
|
||||
onChange={(e) => updatePref('bgColor', e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('qrBackground')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Center Logo */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrLogo')}</label>
|
||||
<div className="grid grid-cols-2 gap-1.5 mt-1">
|
||||
{(['none', 'nomad', 'mic', 'music'] as LogoOption[]).map(option => {
|
||||
const labelKeys: Record<LogoOption, string> = {
|
||||
none: 'qrLogoNone',
|
||||
nomad: 'qrLogoNomad',
|
||||
mic: 'qrLogoMic',
|
||||
music: 'qrLogoMusic',
|
||||
};
|
||||
return (
|
||||
<button
|
||||
key={option}
|
||||
onClick={() => updatePref('logo', option)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.logo === option
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(labelKeys[option])}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<div className="flex gap-2 w-full sm:w-auto">
|
||||
<button
|
||||
onClick={() => handleDownload('png')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadPng')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDownload('svg')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadSvg')}
|
||||
</button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,332 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Download } from 'lucide-react';
|
||||
|
||||
export type DotStyle = 'square' | 'rounded' | 'dots' | 'classy' | 'classy-rounded' | 'extra-rounded';
|
||||
export type CornerSquareStyle = 'square' | 'dot' | 'extra-rounded';
|
||||
export type CornerDotStyle = 'square' | 'dot';
|
||||
export type LogoOption = 'none' | 'nomad' | 'emoji';
|
||||
|
||||
export interface QRStylePrefs {
|
||||
dotStyle: DotStyle;
|
||||
cornerSquareStyle: CornerSquareStyle;
|
||||
cornerDotStyle: CornerDotStyle;
|
||||
fgColor: string;
|
||||
bgColor: string;
|
||||
logo: LogoOption;
|
||||
logoEmoji: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_QR_PREFS: QRStylePrefs = {
|
||||
dotStyle: 'square',
|
||||
cornerSquareStyle: 'square',
|
||||
cornerDotStyle: 'square',
|
||||
fgColor: '#000000',
|
||||
bgColor: '#ffffff',
|
||||
logo: 'none',
|
||||
logoEmoji: '🎤',
|
||||
};
|
||||
|
||||
const QR_STORAGE_KEY = 'nk-qr-style-prefs';
|
||||
|
||||
const DOT_STYLES: DotStyle[] = ['square', 'rounded', 'dots', 'classy', 'classy-rounded', 'extra-rounded'];
|
||||
const CORNER_SQUARE_STYLES: CornerSquareStyle[] = ['square', 'dot', 'extra-rounded'];
|
||||
const CORNER_DOT_STYLES: CornerDotStyle[] = ['square', 'dot'];
|
||||
|
||||
const DOT_STYLE_LABELS: Record<DotStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'rounded': 'qrStyleRounded',
|
||||
'dots': 'qrStyleDots',
|
||||
'classy': 'qrStyleClassy',
|
||||
'classy-rounded': 'qrStyleClassyRounded',
|
||||
'extra-rounded': 'qrStyleExtraRounded',
|
||||
};
|
||||
|
||||
const CORNER_SQUARE_LABELS: Record<CornerSquareStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'dot': 'qrStyleDot',
|
||||
'extra-rounded': 'qrStyleExtraRounded',
|
||||
};
|
||||
|
||||
const CORNER_DOT_LABELS: Record<CornerDotStyle, string> = {
|
||||
'square': 'qrStyleSquare',
|
||||
'dot': 'qrStyleDot',
|
||||
};
|
||||
|
||||
export function loadQrPrefs(): QRStylePrefs {
|
||||
try {
|
||||
const saved = localStorage.getItem(QR_STORAGE_KEY);
|
||||
if (saved) {
|
||||
return { ...DEFAULT_QR_PREFS, ...JSON.parse(saved) };
|
||||
}
|
||||
} catch {}
|
||||
return { ...DEFAULT_QR_PREFS };
|
||||
}
|
||||
|
||||
export function saveQrPrefs(prefs: QRStylePrefs): void {
|
||||
try {
|
||||
localStorage.setItem(QR_STORAGE_KEY, JSON.stringify(prefs));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function emojiToDataUrl(emoji: string): string {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 64;
|
||||
canvas.height = 64;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return '';
|
||||
ctx.font = '52px serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(emoji, 32, 36);
|
||||
return canvas.toDataURL('image/png');
|
||||
}
|
||||
|
||||
interface QRCodeTabProps {
|
||||
referralUrl: string;
|
||||
prefs: QRStylePrefs;
|
||||
onPrefsChange: (prefs: QRStylePrefs) => void;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
export default function QRCodeTab({ referralUrl, prefs, onPrefsChange, visible }: QRCodeTabProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const qrRef = useRef<InstanceType<typeof import('qr-code-styling').default> | null>(null);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
const buildOptions = useCallback((p: QRStylePrefs) => {
|
||||
let image: string | undefined;
|
||||
if (p.logo === 'nomad') {
|
||||
image = '/nomad-karaoke-logo.svg';
|
||||
} else if (p.logo === 'emoji' && p.logoEmoji) {
|
||||
image = emojiToDataUrl(p.logoEmoji);
|
||||
}
|
||||
return {
|
||||
width: 250,
|
||||
height: 250,
|
||||
data: referralUrl,
|
||||
dotsOptions: { type: p.dotStyle, color: p.fgColor },
|
||||
cornersSquareOptions: { type: p.cornerSquareStyle, color: p.fgColor },
|
||||
cornersDotOptions: { type: p.cornerDotStyle, color: p.fgColor },
|
||||
backgroundOptions: { color: p.bgColor },
|
||||
image,
|
||||
imageOptions: { hideBackgroundDots: true, imageSize: 0.2, margin: 4 },
|
||||
};
|
||||
}, [referralUrl]);
|
||||
|
||||
// Initialize / update QR code
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
let cancelled = false;
|
||||
const init = async () => {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
if (cancelled) return;
|
||||
if (!qrRef.current) {
|
||||
qrRef.current = new QRCodeStyling(buildOptions(prefs));
|
||||
if (!cancelled && containerRef.current) {
|
||||
containerRef.current.innerHTML = '';
|
||||
qrRef.current.append(containerRef.current);
|
||||
}
|
||||
} else if (!cancelled) {
|
||||
qrRef.current.update(buildOptions(prefs));
|
||||
}
|
||||
if (!cancelled) setLoaded(true);
|
||||
};
|
||||
init();
|
||||
return () => { cancelled = true; };
|
||||
}, [visible, prefs, buildOptions]);
|
||||
|
||||
// Clean up on hide
|
||||
useEffect(() => {
|
||||
if (!visible) {
|
||||
qrRef.current = null;
|
||||
setLoaded(false);
|
||||
}
|
||||
}, [visible]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => { if (debounceRef.current) clearTimeout(debounceRef.current); };
|
||||
}, []);
|
||||
|
||||
const updatePref = <K extends keyof QRStylePrefs>(key: K, value: QRStylePrefs[K]) => {
|
||||
const next = { ...prefs, [key]: value };
|
||||
onPrefsChange(next);
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => saveQrPrefs(next), 300);
|
||||
};
|
||||
|
||||
const handleDownload = async (extension: 'png' | 'svg') => {
|
||||
if (!qrRef.current) {
|
||||
const QRCodeStyling = (await import('qr-code-styling')).default;
|
||||
qrRef.current = new QRCodeStyling(buildOptions(prefs));
|
||||
}
|
||||
await qrRef.current.download({ name: 'referral-qr', extension });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col md:flex-row gap-6">
|
||||
{/* Left: QR Preview */}
|
||||
<div className="flex-shrink-0 flex items-center justify-center">
|
||||
<div
|
||||
className="relative w-[250px] h-[250px] rounded-lg border border-border"
|
||||
style={{ backgroundColor: prefs.bgColor }}
|
||||
>
|
||||
<div ref={containerRef} className="w-full h-full" />
|
||||
{!loaded && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="animate-pulse w-[200px] h-[200px] bg-muted rounded" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right: Controls */}
|
||||
<div className="flex-1 space-y-4 min-w-0">
|
||||
{/* Dot Style */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrDotStyle')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{DOT_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('dotStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.dotStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(DOT_STYLE_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Frame */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrCornerFrame')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{CORNER_SQUARE_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('cornerSquareStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.cornerSquareStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(CORNER_SQUARE_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Corner Dot */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrCornerDot')}</label>
|
||||
<div className="grid grid-cols-3 gap-1.5 mt-1">
|
||||
{CORNER_DOT_STYLES.map(style => (
|
||||
<button
|
||||
key={style}
|
||||
onClick={() => updatePref('cornerDotStyle', style)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.cornerDotStyle === style
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(CORNER_DOT_LABELS[style])}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Colors */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrColors')}</label>
|
||||
<div className="flex gap-4 mt-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={prefs.fgColor}
|
||||
onChange={(e) => updatePref('fgColor', e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('qrForeground')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="color"
|
||||
value={prefs.bgColor}
|
||||
onChange={(e) => updatePref('bgColor', e.target.value)}
|
||||
className="w-8 h-8 rounded border border-border cursor-pointer"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('qrBackground')}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Center Logo */}
|
||||
<div>
|
||||
<label className="text-sm font-medium text-foreground">{t('qrLogo')}</label>
|
||||
<div className="flex gap-1.5 mt-1">
|
||||
{(['none', 'nomad', 'emoji'] as const).map(option => {
|
||||
const labelKeys = { none: 'qrLogoNone', nomad: 'qrLogoNomad', emoji: 'qrLogoEmoji' } as const;
|
||||
return (
|
||||
<button
|
||||
key={option}
|
||||
onClick={() => updatePref('logo', option)}
|
||||
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
|
||||
prefs.logo === option
|
||||
? 'border-primary bg-primary/10 text-primary font-medium'
|
||||
: 'border-border text-muted-foreground hover:border-primary/50'
|
||||
}`}
|
||||
>
|
||||
{t(labelKeys[option])}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{prefs.logo === 'emoji' && (
|
||||
<input
|
||||
type="text"
|
||||
value={prefs.logoEmoji}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
const emoji = [...val].pop() || '';
|
||||
updatePref('logoEmoji', emoji);
|
||||
}}
|
||||
className="w-10 h-7 text-center text-base rounded border border-border"
|
||||
maxLength={4}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* QR download buttons */}
|
||||
<div className="flex gap-2 pt-2 border-t border-border sm:justify-end">
|
||||
<button
|
||||
onClick={() => handleDownload('png')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadPng')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDownload('svg')}
|
||||
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
{t('qrDownloadSvg')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,22 +1,15 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import {
|
||||
getReferralDashboard,
|
||||
updateReferralLink,
|
||||
startConnectOnboarding,
|
||||
getConnectDashboardLink,
|
||||
getConnectUpdateLink,
|
||||
requestVanityUrl,
|
||||
} from '@/lib/api';
|
||||
import type { ReferralDashboard as ReferralDashboardData } from '@/lib/types';
|
||||
import {
|
||||
QrCode, Sparkles, ExternalLink, CheckCircle, AlertCircle,
|
||||
Loader2, Banknote, Settings,
|
||||
} from 'lucide-react';
|
||||
import ReferralToolsDialog from './ReferralToolsDialog';
|
||||
import { QrCode } from 'lucide-react';
|
||||
import QRCodeDialog from './QRCodeDialog';
|
||||
|
||||
function formatCents(cents: number): string {
|
||||
return `$${(cents / 100).toFixed(2)}`;
|
||||
@@ -24,7 +17,6 @@ function formatCents(cents: number): string {
|
||||
|
||||
export default function ReferralDashboard() {
|
||||
const t = useTranslations('referrals');
|
||||
const searchParams = useSearchParams();
|
||||
const [data, setData] = useState<ReferralDashboardData | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [copied, setCopied] = useState(false);
|
||||
@@ -32,16 +24,6 @@ export default function ReferralDashboard() {
|
||||
const [displayName, setDisplayName] = useState('');
|
||||
const [customMessage, setCustomMessage] = useState('');
|
||||
const [qrOpen, setQrOpen] = useState(false);
|
||||
const [vanityRequested, setVanityRequested] = useState(false);
|
||||
const [vanityError, setVanityError] = useState('');
|
||||
const [vanitySubmitting, setVanitySubmitting] = useState(false);
|
||||
const [desiredVanity, setDesiredVanity] = useState('');
|
||||
const [showVanityForm, setShowVanityForm] = useState(false);
|
||||
const [connectStatus, setConnectStatus] = useState<'complete' | 'refresh' | null>(null);
|
||||
const [connectLoading, setConnectLoading] = useState(false);
|
||||
const [connectError, setConnectError] = useState('');
|
||||
const [dashboardLinkLoading, setDashboardLinkLoading] = useState(false);
|
||||
const [actionError, setActionError] = useState('');
|
||||
|
||||
const fetchDashboard = useCallback(async () => {
|
||||
try {
|
||||
@@ -60,21 +42,9 @@ export default function ReferralDashboard() {
|
||||
fetchDashboard();
|
||||
}, [fetchDashboard]);
|
||||
|
||||
// Handle Stripe Connect redirect params
|
||||
useEffect(() => {
|
||||
const connect = searchParams.get('connect');
|
||||
if (connect === 'complete') {
|
||||
setConnectStatus('complete');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
} else if (connect === 'refresh') {
|
||||
setConnectStatus('refresh');
|
||||
window.history.replaceState({}, '', window.location.pathname);
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
const copyLink = () => {
|
||||
if (!data) return;
|
||||
const url = `https://nomadkaraoke.com/r/${data.link.code}`;
|
||||
const url = `${window.location.origin}/r/${data.link.code}`;
|
||||
navigator.clipboard.writeText(url);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
@@ -91,58 +61,11 @@ export default function ReferralDashboard() {
|
||||
};
|
||||
|
||||
const handleConnectBank = async () => {
|
||||
setConnectLoading(true);
|
||||
setConnectError('');
|
||||
try {
|
||||
const { onboarding_url } = await startConnectOnboarding();
|
||||
window.location.href = onboarding_url;
|
||||
} catch (err) {
|
||||
console.error('Failed to start Connect onboarding:', err);
|
||||
setConnectError(t('connectFailed'));
|
||||
setConnectLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleManagePayouts = async () => {
|
||||
setDashboardLinkLoading(true);
|
||||
setActionError('');
|
||||
try {
|
||||
const { url } = await getConnectDashboardLink();
|
||||
window.open(url, '_blank');
|
||||
} catch (err) {
|
||||
console.error('Failed to get dashboard link:', err);
|
||||
setActionError(t('connectFailed'));
|
||||
} finally {
|
||||
setDashboardLinkLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateAccount = async () => {
|
||||
setConnectLoading(true);
|
||||
setActionError('');
|
||||
try {
|
||||
const { url } = await getConnectUpdateLink();
|
||||
window.location.href = url;
|
||||
} catch (err) {
|
||||
console.error('Failed to get update link:', err);
|
||||
setActionError(t('connectFailed'));
|
||||
setConnectLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleVanityRequest = async () => {
|
||||
if (!data || !desiredVanity.trim()) return;
|
||||
setVanityError('');
|
||||
setVanitySubmitting(true);
|
||||
try {
|
||||
await requestVanityUrl(desiredVanity.trim());
|
||||
setVanityRequested(true);
|
||||
setShowVanityForm(false);
|
||||
setDesiredVanity('');
|
||||
} catch (err) {
|
||||
setVanityError(err instanceof Error ? err.message : 'Request failed');
|
||||
} finally {
|
||||
setVanitySubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -155,63 +78,17 @@ export default function ReferralDashboard() {
|
||||
|
||||
if (!data) return null;
|
||||
|
||||
const connectAccount = data.stripe_connect_account;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-6 p-4">
|
||||
<h2 className="text-xl font-bold">{t('title')}</h2>
|
||||
|
||||
{/* How It Works */}
|
||||
<div className="rounded-lg p-5 space-y-4" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
|
||||
<h3 className="font-semibold text-lg flex items-center gap-2">
|
||||
<Sparkles className="w-5 h-5" style={{ color: 'var(--accent)' }} />
|
||||
{t('howItWorksTitle')}
|
||||
</h3>
|
||||
<p className="text-sm leading-relaxed" style={{ color: 'var(--text-muted)' }}>
|
||||
{t('howItWorksIntro')}
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4 pt-2">
|
||||
<div className="flex gap-3">
|
||||
<div className="shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold" style={{ backgroundColor: 'var(--accent)', color: 'var(--background)' }}>1</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{t('howStep1Title')}</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>{t('howStep1Desc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<div className="shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold" style={{ backgroundColor: 'var(--accent)', color: 'var(--background)' }}>2</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{t('howStep2Title')}</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
{t('howStep2Desc', { discount: data.link.discount_percent, days: data.link.discount_duration_days })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<div className="shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold" style={{ backgroundColor: 'var(--accent)', color: 'var(--background)' }}>3</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{t('howStep3Title')}</p>
|
||||
<p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
|
||||
{t('howStep3Desc', { kickback: data.link.kickback_percent, days: data.link.earning_duration_days })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md p-3 text-sm" style={{ backgroundColor: 'var(--secondary)' }}>
|
||||
<p className="font-medium mb-1">{t('howPayoutTitle')}</p>
|
||||
<p style={{ color: 'var(--text-muted)' }}>{t('howPayoutDesc')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Referral Link */}
|
||||
<div className="rounded-lg p-4 space-y-3" style={{ backgroundColor: 'var(--card)', borderColor: 'var(--card-border)', border: '1px solid' }}>
|
||||
<h3 className="font-semibold">{t('yourLink')}</h3>
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
readOnly
|
||||
value={`https://nomadkaraoke.com/r/${data.link.code}`}
|
||||
value={`${typeof window !== 'undefined' ? window.location.origin : ''}/r/${data.link.code}`}
|
||||
className="flex-1 rounded px-3 py-2 text-sm font-mono"
|
||||
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text)' }}
|
||||
/>
|
||||
@@ -221,66 +98,15 @@ export default function ReferralDashboard() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setQrOpen(true)}
|
||||
className="px-3 py-2 rounded text-sm border flex items-center gap-1.5"
|
||||
className="px-3 py-2 rounded text-sm border"
|
||||
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
title={t('qrCode')}
|
||||
aria-label={t('qrCode')}
|
||||
>
|
||||
<QrCode className="w-4 h-4" />
|
||||
{t('qrOrFlyer')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Vanity URL request */}
|
||||
{!data.link.is_vanity && (
|
||||
<div className="pt-1">
|
||||
{vanityRequested ? (
|
||||
<p className="text-sm" style={{ color: 'var(--accent)' }}>
|
||||
{t('vanityRequested')}
|
||||
</p>
|
||||
) : showVanityForm ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2 items-center">
|
||||
<span className="text-sm font-mono shrink-0" style={{ color: 'var(--text-muted)' }}>
|
||||
nomadkaraoke.com/r/
|
||||
</span>
|
||||
<input
|
||||
value={desiredVanity}
|
||||
onChange={(e) => { setDesiredVanity(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '')); setVanityError(''); }}
|
||||
placeholder={t('vanityPlaceholder')}
|
||||
className="flex-1 rounded px-3 py-1.5 text-sm font-mono"
|
||||
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text)' }}
|
||||
maxLength={30}
|
||||
/>
|
||||
<button
|
||||
onClick={handleVanityRequest}
|
||||
disabled={!desiredVanity.trim() || vanitySubmitting}
|
||||
className="px-3 py-1.5 bg-primary text-primary-foreground rounded text-sm disabled:opacity-50"
|
||||
>
|
||||
{vanitySubmitting ? '...' : t('vanitySubmit')}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => { setShowVanityForm(false); setDesiredVanity(''); setVanityError(''); }}
|
||||
className="px-3 py-1.5 rounded text-sm"
|
||||
style={{ backgroundColor: 'var(--secondary)' }}
|
||||
>
|
||||
{t('cancel')}
|
||||
</button>
|
||||
</div>
|
||||
{vanityError && (
|
||||
<p className="text-sm text-red-500">{vanityError}</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setShowVanityForm(true)}
|
||||
className="text-sm hover:underline"
|
||||
style={{ color: 'var(--text-muted)' }}
|
||||
>
|
||||
{t('vanityRequest')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editing ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
@@ -314,26 +140,6 @@ export default function ReferralDashboard() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Link Terms */}
|
||||
<div className="rounded-lg p-4 grid grid-cols-2 md:grid-cols-4 gap-4 text-center" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
|
||||
<div>
|
||||
<p className="text-lg font-bold" style={{ color: 'var(--accent)' }}>{data.link.discount_percent}%</p>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('termDiscount')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-lg font-bold">{data.link.discount_duration_days}d</p>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('termDiscountWindow')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-lg font-bold" style={{ color: 'var(--accent)' }}>{data.link.kickback_percent}%</p>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('termKickback')}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-lg font-bold">{data.link.earning_duration_days}d</p>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('termEarningWindow')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="rounded-lg p-4" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
|
||||
<h3 className="font-semibold mb-3">{t('stats')}</h3>
|
||||
@@ -357,122 +163,25 @@ export default function ReferralDashboard() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payout & Bank Account section */}
|
||||
<div className="rounded-lg p-4 space-y-4" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
|
||||
{/* Payout section */}
|
||||
<div className="rounded-lg p-4 space-y-3" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
|
||||
<div className="flex justify-between items-center">
|
||||
<h3 className="font-semibold flex items-center gap-2">
|
||||
<Banknote className="w-5 h-5" style={{ color: 'var(--text-muted)' }} />
|
||||
{t('payoutTitle')}
|
||||
</h3>
|
||||
<h3 className="font-semibold">{t('earnings')}</h3>
|
||||
<div className="text-right">
|
||||
<p className="text-lg font-bold">{formatCents(data.pending_balance_cents)}</p>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('pendingBalance')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Connect complete banner */}
|
||||
{connectStatus === 'complete' && (
|
||||
<div className="rounded-lg p-3 flex items-center gap-2 border border-green-500/30" style={{ backgroundColor: 'rgba(34, 197, 94, 0.1)' }}>
|
||||
<CheckCircle className="w-5 h-5 text-green-500 shrink-0" />
|
||||
<p className="text-sm text-green-500">{t('connectComplete')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Connect refresh banner */}
|
||||
{connectStatus === 'refresh' && !data.stripe_connect_configured && (
|
||||
<div className="rounded-lg p-3 flex items-center gap-2 border" style={{ borderColor: 'var(--card-border)', backgroundColor: 'var(--secondary)' }}>
|
||||
<AlertCircle className="w-4 h-4 shrink-0" style={{ color: 'var(--text-muted)' }} />
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('connectRefresh')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{data.stripe_connect_configured ? (
|
||||
/* Connected state — show account status and management */
|
||||
<div className="space-y-3">
|
||||
{/* Account status */}
|
||||
<div className="rounded-lg p-3 space-y-2" style={{ backgroundColor: 'var(--secondary)' }}>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className={`w-2 h-2 rounded-full ${connectAccount?.payouts_enabled ? 'bg-green-500' : 'bg-yellow-500'}`} />
|
||||
<span className="text-sm font-medium">
|
||||
{connectAccount?.payouts_enabled ? t('connectStatusActive') : t('connectStatusPending')}
|
||||
</span>
|
||||
</div>
|
||||
{connectAccount?.email && (
|
||||
<span className="text-xs font-mono" style={{ color: 'var(--text-muted)' }}>
|
||||
{connectAccount.email}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{connectAccount && !connectAccount.details_submitted && (
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
|
||||
{t('connectDetailsNeeded')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Payout info */}
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('payoutThreshold')}</p>
|
||||
|
||||
{/* Management buttons */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{connectAccount?.details_submitted && (
|
||||
<button
|
||||
onClick={handleManagePayouts}
|
||||
disabled={dashboardLinkLoading}
|
||||
className="px-3 py-1.5 rounded text-sm border flex items-center gap-1.5 hover:bg-white/5 transition-colors disabled:opacity-50"
|
||||
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
|
||||
>
|
||||
{dashboardLinkLoading ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<ExternalLink className="w-3.5 h-3.5" />
|
||||
)}
|
||||
{t('managePayouts')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={handleUpdateAccount}
|
||||
disabled={connectLoading}
|
||||
className="px-3 py-1.5 rounded text-sm border flex items-center gap-1.5 hover:bg-white/5 transition-colors disabled:opacity-50"
|
||||
style={{ borderColor: 'var(--card-border)', color: 'var(--text-muted)' }}
|
||||
>
|
||||
{connectLoading ? (
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
) : (
|
||||
<Settings className="w-3.5 h-3.5" />
|
||||
)}
|
||||
{t('updateBankAccount')}
|
||||
</button>
|
||||
</div>
|
||||
{actionError && (
|
||||
<p className="text-sm text-red-500">{actionError}</p>
|
||||
)}
|
||||
{!data.stripe_connect_configured ? (
|
||||
<div className="rounded-lg p-4 space-y-2" style={{ backgroundColor: 'var(--secondary)' }}>
|
||||
<p className="text-sm">{t('connectDescription')}</p>
|
||||
<button onClick={handleConnectBank} className="px-4 py-2 bg-primary text-primary-foreground rounded text-sm">
|
||||
{t('connectBank')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
/* Not connected — show setup prompt */
|
||||
<div className="rounded-lg p-4 space-y-3" style={{ backgroundColor: 'var(--secondary)' }}>
|
||||
<p className="text-sm">{t('connectDescription')}</p>
|
||||
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('connectStripeNote')}</p>
|
||||
<button
|
||||
onClick={handleConnectBank}
|
||||
disabled={connectLoading}
|
||||
className="px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center gap-2 disabled:opacity-70"
|
||||
>
|
||||
{connectLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
{t('connectBankLoading')}
|
||||
</>
|
||||
) : (
|
||||
t('connectBank')
|
||||
)}
|
||||
</button>
|
||||
{connectError && (
|
||||
<p className="text-sm text-red-500">{connectError}</p>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('payoutThreshold')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -513,12 +222,10 @@ export default function ReferralDashboard() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ReferralToolsDialog
|
||||
referralUrl={`https://nomadkaraoke.com/r/${data.link.code}`}
|
||||
<QRCodeDialog
|
||||
referralUrl={`${typeof window !== 'undefined' ? window.location.origin : ''}/r/${data.link.code}`}
|
||||
open={qrOpen}
|
||||
onOpenChange={setQrOpen}
|
||||
referralCode={data.link.code}
|
||||
discountPercent={data.link.discount_percent}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,97 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { QrCode, FileText } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
|
||||
import QRCodeTab, { type QRStylePrefs, DEFAULT_QR_PREFS, loadQrPrefs } from './QRCodeTab';
|
||||
import FlyerTab from './FlyerTab';
|
||||
|
||||
interface ReferralToolsDialogProps {
|
||||
referralUrl: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** @deprecated — flyer generation is now client-side. Kept for backwards compat. */
|
||||
onGenerateFlyer?: (theme: 'light' | 'dark', qrDataUrl: string) => Promise<Blob>;
|
||||
flyerFilename?: string;
|
||||
/** Referral code (for flyer CTA display). Extracted from referralUrl if not provided. */
|
||||
referralCode?: string;
|
||||
/** Discount percentage (for flyer CTA). Defaults to 20. */
|
||||
discountPercent?: number;
|
||||
}
|
||||
|
||||
export default function ReferralToolsDialog({
|
||||
referralUrl,
|
||||
open,
|
||||
onOpenChange,
|
||||
flyerFilename,
|
||||
referralCode: referralCodeProp,
|
||||
discountPercent = 20,
|
||||
}: ReferralToolsDialogProps) {
|
||||
const t = useTranslations('referrals');
|
||||
const [activeTab, setActiveTab] = useState('qr');
|
||||
const [qrPrefs, setQrPrefs] = useState<QRStylePrefs>(DEFAULT_QR_PREFS);
|
||||
|
||||
// Extract referral code from URL if not provided, stripping query/hash/path
|
||||
const referralCode = referralCodeProp
|
||||
|| referralUrl.split('/r/').pop()?.split(/[?#/]/)[0]
|
||||
|| 'CODE';
|
||||
|
||||
// Load QR prefs on open
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setQrPrefs(loadQrPrefs());
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-6xl bg-card border-border max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-foreground flex items-center gap-2">
|
||||
<QrCode className="w-5 h-5" />
|
||||
{t('toolsTitle')}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<Tabs value={activeTab} onValueChange={setActiveTab}>
|
||||
<TabsList>
|
||||
<TabsTrigger value="qr" className="flex items-center gap-1.5">
|
||||
<QrCode className="w-3.5 h-3.5" />
|
||||
{t('tabQrCode')}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="flyer" className="flex items-center gap-1.5">
|
||||
<FileText className="w-3.5 h-3.5" />
|
||||
{t('tabFlyer')}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="qr">
|
||||
<QRCodeTab
|
||||
referralUrl={referralUrl}
|
||||
prefs={qrPrefs}
|
||||
onPrefsChange={setQrPrefs}
|
||||
visible={activeTab === 'qr' && open}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="flyer">
|
||||
<FlyerTab
|
||||
referralCode={referralCode}
|
||||
discountPercent={discountPercent}
|
||||
qrPrefs={qrPrefs}
|
||||
onSwitchToQr={() => setActiveTab('qr')}
|
||||
flyerFilename={flyerFilename}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
import { exportFlyerPdf, exportFlyerHtml, exportFlyerPng } from '../FlyerExport';
|
||||
|
||||
// Mock html-to-image
|
||||
jest.mock('html-to-image', () => ({
|
||||
toPng: jest.fn().mockResolvedValue('data:image/png;base64,fakepng'),
|
||||
}));
|
||||
|
||||
// Mock jsPDF
|
||||
const mockAddImage = jest.fn();
|
||||
const mockSave = jest.fn();
|
||||
jest.mock('jspdf', () => {
|
||||
return function JsPDFMock() {
|
||||
return {
|
||||
addImage: (...args: unknown[]) => mockAddImage(...args),
|
||||
save: (...args: unknown[]) => mockSave(...args),
|
||||
addPage: jest.fn(),
|
||||
internal: { pageSize: { getWidth: () => 215.9, getHeight: () => 279.4 } },
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('FlyerExport', () => {
|
||||
const mockElement = document.createElement('div');
|
||||
mockElement.setAttribute('data-flyer-page', '');
|
||||
Object.defineProperty(mockElement, 'outerHTML', { value: '<div data-flyer-page="">test</div>' });
|
||||
|
||||
describe('exportFlyerPdf', () => {
|
||||
it('generates PDF with 1 per page', async () => {
|
||||
await exportFlyerPdf(mockElement, { perPage: 1, marginMm: 15, filename: 'test.pdf' });
|
||||
expect(mockAddImage).toHaveBeenCalledTimes(1);
|
||||
expect(mockSave).toHaveBeenCalledWith('test.pdf');
|
||||
});
|
||||
|
||||
it('generates PDF with 2 per page', async () => {
|
||||
await exportFlyerPdf(mockElement, { perPage: 2, marginMm: 10, filename: 'test-2up.pdf' });
|
||||
expect(mockAddImage).toHaveBeenCalledTimes(2);
|
||||
expect(mockSave).toHaveBeenCalledWith('test-2up.pdf');
|
||||
});
|
||||
|
||||
it('generates PDF with 4 per page', async () => {
|
||||
await exportFlyerPdf(mockElement, { perPage: 4, marginMm: 5, filename: 'test-4up.pdf' });
|
||||
expect(mockAddImage).toHaveBeenCalledTimes(4);
|
||||
expect(mockSave).toHaveBeenCalledWith('test-4up.pdf');
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportFlyerHtml', () => {
|
||||
it('returns a blob containing the flyer HTML', () => {
|
||||
const blob = exportFlyerHtml(mockElement);
|
||||
expect(blob).toBeInstanceOf(Blob);
|
||||
expect(blob.type).toBe('text/html');
|
||||
});
|
||||
});
|
||||
|
||||
describe('exportFlyerPng', () => {
|
||||
it('calls toPng and triggers download', async () => {
|
||||
const mockClick = jest.fn();
|
||||
const origCreateElement = document.createElement.bind(document);
|
||||
jest.spyOn(document, 'createElement').mockImplementation((tag: string) => {
|
||||
const el = origCreateElement(tag);
|
||||
if (tag === 'a') {
|
||||
el.click = mockClick;
|
||||
}
|
||||
return el;
|
||||
});
|
||||
|
||||
await exportFlyerPng(mockElement, 'test.png');
|
||||
|
||||
const { toPng } = require('html-to-image');
|
||||
expect(toPng).toHaveBeenCalledWith(mockElement, { pixelRatio: 2, width: 816, height: 1056 });
|
||||
expect(mockClick).toHaveBeenCalled();
|
||||
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import QRCodeDialog from '../QRCodeDialog';
|
||||
|
||||
// Mock qr-code-styling — it requires canvas/DOM APIs not available in jsdom
|
||||
const mockAppend = jest.fn();
|
||||
const mockUpdate = jest.fn();
|
||||
const mockDownload = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
jest.mock('qr-code-styling', () => {
|
||||
return jest.fn().mockImplementation(() => ({
|
||||
append: mockAppend,
|
||||
update: mockUpdate,
|
||||
download: mockDownload,
|
||||
}));
|
||||
});
|
||||
|
||||
// Load real English messages for the referrals namespace
|
||||
const messages = require('../../../messages/en.json');
|
||||
|
||||
function renderDialog(props: Partial<React.ComponentProps<typeof QRCodeDialog>> = {}) {
|
||||
return render(
|
||||
<NextIntlClientProvider locale="en" messages={messages}>
|
||||
<QRCodeDialog
|
||||
referralUrl="https://nomadkaraoke.com/r/testcode"
|
||||
open={true}
|
||||
onOpenChange={jest.fn()}
|
||||
{...props}
|
||||
/>
|
||||
</NextIntlClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('QRCodeDialog', () => {
|
||||
it('renders the dialog title and download buttons when open', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('QR Code Generator')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download PNG')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download SVG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
renderDialog({ open: false });
|
||||
expect(screen.queryByText('QR Code Generator')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders all dot style options', () => {
|
||||
renderDialog();
|
||||
// "Square" appears multiple times (dot style, corner frame, corner dot) — use getAllByText
|
||||
expect(screen.getAllByText('Square').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText('Rounded')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dots')).toBeInTheDocument();
|
||||
expect(screen.getByText('Classy')).toBeInTheDocument();
|
||||
expect(screen.getByText('Classy Rounded')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Extra Rounded').length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('renders corner frame and corner dot style sections', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Corner Frame')).toBeInTheDocument();
|
||||
expect(screen.getByText('Corner Dot')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders center logo options', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Center Logo')).toBeInTheDocument();
|
||||
expect(screen.getByText('None')).toBeInTheDocument();
|
||||
expect(screen.getByText('Nomad Karaoke')).toBeInTheDocument();
|
||||
expect(screen.getByText('Microphone')).toBeInTheDocument();
|
||||
expect(screen.getByText('Music')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders color picker inputs', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Foreground')).toBeInTheDocument();
|
||||
expect(screen.getByText('Background')).toBeInTheDocument();
|
||||
// Color inputs
|
||||
const colorInputs = screen.getAllByDisplayValue('#000000');
|
||||
expect(colorInputs.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('saves style prefs to localStorage on change', async () => {
|
||||
jest.useFakeTimers();
|
||||
renderDialog();
|
||||
// Click "Rounded" dot style
|
||||
fireEvent.click(screen.getByText('Rounded'));
|
||||
// Flush the debounce timer
|
||||
act(() => { jest.runAllTimers(); });
|
||||
const saved = JSON.parse(localStorage.getItem('nk-qr-style-prefs') || '{}');
|
||||
expect(saved.dotStyle).toBe('rounded');
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('restores style prefs from localStorage on open', () => {
|
||||
localStorage.setItem('nk-qr-style-prefs', JSON.stringify({
|
||||
dotStyle: 'dots',
|
||||
cornerSquareStyle: 'dot',
|
||||
cornerDotStyle: 'dot',
|
||||
fgColor: '#ff0000',
|
||||
bgColor: '#00ff00',
|
||||
logo: 'nomad',
|
||||
}));
|
||||
renderDialog();
|
||||
// The foreground color input should have the saved value
|
||||
const fgInput = screen.getByDisplayValue('#ff0000');
|
||||
expect(fgInput).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls download with PNG extension when Download PNG clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Download PNG'));
|
||||
await waitFor(() => {
|
||||
expect(mockDownload).toHaveBeenCalledWith({
|
||||
name: 'referral-qr',
|
||||
extension: 'png',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('calls download with SVG extension when Download SVG clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Download SVG'));
|
||||
await waitFor(() => {
|
||||
expect(mockDownload).toHaveBeenCalledWith({
|
||||
name: 'referral-qr',
|
||||
extension: 'svg',
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,194 +0,0 @@
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { NextIntlClientProvider } from 'next-intl';
|
||||
import ReferralToolsDialog from '../ReferralToolsDialog';
|
||||
|
||||
// Mock qr-code-styling
|
||||
const mockAppend = jest.fn();
|
||||
const mockUpdate = jest.fn();
|
||||
const mockDownload = jest.fn().mockResolvedValue(undefined);
|
||||
const mockGetRawData = jest.fn().mockResolvedValue(new Blob(['fake'], { type: 'image/png' }));
|
||||
|
||||
jest.mock('qr-code-styling', () => {
|
||||
return jest.fn().mockImplementation(() => ({
|
||||
append: mockAppend,
|
||||
update: mockUpdate,
|
||||
download: mockDownload,
|
||||
getRawData: mockGetRawData,
|
||||
}));
|
||||
});
|
||||
|
||||
// Mock html-to-image
|
||||
jest.mock('html-to-image', () => ({
|
||||
toPng: jest.fn().mockResolvedValue('data:image/png;base64,fake'),
|
||||
}));
|
||||
|
||||
// Mock jsPDF
|
||||
jest.mock('jspdf', () => {
|
||||
return function JsPDFMock() {
|
||||
return {
|
||||
addImage: jest.fn(),
|
||||
save: jest.fn(),
|
||||
addPage: jest.fn(),
|
||||
internal: { pageSize: { getWidth: () => 215.9, getHeight: () => 279.4 } },
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
const messages = require('../../../messages/en.json');
|
||||
|
||||
function renderDialog(props: Partial<React.ComponentProps<typeof ReferralToolsDialog>> = {}) {
|
||||
return render(
|
||||
<NextIntlClientProvider locale="en" messages={messages}>
|
||||
<ReferralToolsDialog
|
||||
referralUrl="https://nomadkaraoke.com/r/testcode"
|
||||
open={true}
|
||||
onOpenChange={jest.fn()}
|
||||
referralCode="testcode"
|
||||
discountPercent={20}
|
||||
{...props}
|
||||
/>
|
||||
</NextIntlClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('ReferralToolsDialog', () => {
|
||||
it('renders with tabs for QR Code and Flyer', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('QR Code & Flyer Generator')).toBeInTheDocument();
|
||||
expect(screen.getByText('QR Code')).toBeInTheDocument();
|
||||
expect(screen.getByText('Printable Flyer')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when closed', () => {
|
||||
renderDialog({ open: false });
|
||||
expect(screen.queryByText('QR Code & Flyer Generator')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows QR Code tab content by default', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Dot Style')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download PNG')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download SVG')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders all QR dot style options on QR tab', () => {
|
||||
renderDialog();
|
||||
expect(screen.getAllByText('Square').length).toBeGreaterThanOrEqual(1);
|
||||
expect(screen.getByText('Rounded')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dots')).toBeInTheDocument();
|
||||
expect(screen.getByText('Classy')).toBeInTheDocument();
|
||||
expect(screen.getByText('Classy Rounded')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('Extra Rounded').length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('renders corner frame and corner dot style sections', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Corner Frame')).toBeInTheDocument();
|
||||
expect(screen.getByText('Corner Dot')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders center logo options', () => {
|
||||
renderDialog();
|
||||
expect(screen.getByText('Center Logo')).toBeInTheDocument();
|
||||
expect(screen.getByText('None')).toBeInTheDocument();
|
||||
expect(screen.getByText('NK Logo')).toBeInTheDocument();
|
||||
expect(screen.getByText('Emoji')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('saves QR style prefs to localStorage on change', async () => {
|
||||
jest.useFakeTimers();
|
||||
renderDialog();
|
||||
fireEvent.click(screen.getByText('Rounded'));
|
||||
act(() => { jest.runAllTimers(); });
|
||||
const saved = JSON.parse(localStorage.getItem('nk-qr-style-prefs') || '{}');
|
||||
expect(saved.dotStyle).toBe('rounded');
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('restores QR style prefs from localStorage on open', () => {
|
||||
localStorage.setItem('nk-qr-style-prefs', JSON.stringify({
|
||||
dotStyle: 'dots',
|
||||
cornerSquareStyle: 'dot',
|
||||
cornerDotStyle: 'dot',
|
||||
fgColor: '#ff0000',
|
||||
bgColor: '#00ff00',
|
||||
logo: 'nomad',
|
||||
logoEmoji: '🎤',
|
||||
}));
|
||||
renderDialog();
|
||||
const fgInput = screen.getByDisplayValue('#ff0000');
|
||||
expect(fgInput).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('switches to Flyer tab when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Download PDF')).toBeInTheDocument();
|
||||
expect(screen.getByText('Download HTML')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders flyer controls on Flyer tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Colors')).toBeInTheDocument();
|
||||
expect(screen.getByText('Sections')).toBeInTheDocument();
|
||||
expect(screen.getByText('Print Layout')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows flyer per-page options on Flyer tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Flyers Per Page')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '1' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '2' })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '4' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders section visibility toggles on Flyer tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Subtitle')).toBeInTheDocument();
|
||||
expect(screen.getByText('How It Works Steps')).toBeInTheDocument();
|
||||
expect(screen.getByText('Divider')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bottom Features')).toBeInTheDocument();
|
||||
expect(screen.getByText('Bottom Tagline')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows Edit QR Style link on Flyer tab', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Printable Flyer'));
|
||||
expect(screen.getByText('Edit QR Style')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls download with PNG extension when Download PNG clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Download PNG'));
|
||||
// QR download should be triggered
|
||||
expect(mockDownload).toHaveBeenCalledWith({
|
||||
name: 'referral-qr',
|
||||
extension: 'png',
|
||||
});
|
||||
});
|
||||
|
||||
it('calls download with SVG extension when Download SVG clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderDialog();
|
||||
await user.click(screen.getByText('Download SVG'));
|
||||
expect(mockDownload).toHaveBeenCalledWith({
|
||||
name: 'referral-qr',
|
||||
extension: 'svg',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,125 +0,0 @@
|
||||
import {
|
||||
type FlyerConfig,
|
||||
DEFAULT_FLYER_CONFIG,
|
||||
LIGHT_PRESET,
|
||||
DARK_PRESET,
|
||||
BUILT_IN_PRESETS,
|
||||
loadFlyerConfig,
|
||||
saveFlyerConfig,
|
||||
loadCustomPresets,
|
||||
saveCustomPreset,
|
||||
deleteCustomPreset,
|
||||
} from '../flyer-presets';
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('flyer-presets', () => {
|
||||
describe('DEFAULT_FLYER_CONFIG', () => {
|
||||
it('has all required fields with sensible defaults', () => {
|
||||
expect(DEFAULT_FLYER_CONFIG.bgColor).toBe('#faf8f5');
|
||||
expect(DEFAULT_FLYER_CONFIG.headlineGradient).toEqual(['#c45aff', '#ff7acc', '#ff5a8a']);
|
||||
expect(DEFAULT_FLYER_CONFIG.headlineSubColor).toBe('#1a1a1a');
|
||||
expect(DEFAULT_FLYER_CONFIG.textColor).toBe('#1a1a1a');
|
||||
expect(DEFAULT_FLYER_CONFIG.subtextColor).toBe('#666666');
|
||||
expect(DEFAULT_FLYER_CONFIG.accentColor).toBe('#c45aff');
|
||||
expect(DEFAULT_FLYER_CONFIG.headlineMain).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.headlineSub).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.subtitle).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.ctaLabel).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.ctaNote).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.steps).toHaveLength(4);
|
||||
expect(DEFAULT_FLYER_CONFIG.steps[0]).toEqual({ title: null, desc: null });
|
||||
expect(DEFAULT_FLYER_CONFIG.showSubtitle).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.showSteps).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.showDivider).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.showBottomFeatures).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.showBottomTagline).toBe(true);
|
||||
expect(DEFAULT_FLYER_CONFIG.customLogoUrl).toBeNull();
|
||||
expect(DEFAULT_FLYER_CONFIG.perPage).toBe(1);
|
||||
expect(DEFAULT_FLYER_CONFIG.marginMm).toBe(15);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BUILT_IN_PRESETS', () => {
|
||||
it('has Light and Dark presets', () => {
|
||||
expect(BUILT_IN_PRESETS).toHaveLength(2);
|
||||
expect(BUILT_IN_PRESETS[0].name).toBe('Light');
|
||||
expect(BUILT_IN_PRESETS[1].name).toBe('Dark');
|
||||
});
|
||||
|
||||
it('Light preset matches default config colors', () => {
|
||||
expect(LIGHT_PRESET.bgColor).toBe('#faf8f5');
|
||||
expect(LIGHT_PRESET.textColor).toBe('#1a1a1a');
|
||||
});
|
||||
|
||||
it('Dark preset has dark background and light text', () => {
|
||||
expect(DARK_PRESET.bgColor).toBe('#0c0a1a');
|
||||
expect(DARK_PRESET.textColor).toBe('#ffffff');
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadFlyerConfig / saveFlyerConfig', () => {
|
||||
it('returns default config when nothing saved', () => {
|
||||
const config = loadFlyerConfig();
|
||||
expect(config).toEqual(DEFAULT_FLYER_CONFIG);
|
||||
});
|
||||
|
||||
it('round-trips a config through save and load', () => {
|
||||
const custom: FlyerConfig = {
|
||||
...DEFAULT_FLYER_CONFIG,
|
||||
bgColor: '#ffffff',
|
||||
perPage: 2,
|
||||
marginMm: 5,
|
||||
};
|
||||
saveFlyerConfig(custom);
|
||||
expect(loadFlyerConfig()).toEqual(custom);
|
||||
});
|
||||
|
||||
it('merges partial saved data with defaults', () => {
|
||||
localStorage.setItem('nk-flyer-prefs', JSON.stringify({ bgColor: '#ff0000' }));
|
||||
const config = loadFlyerConfig();
|
||||
expect(config.bgColor).toBe('#ff0000');
|
||||
expect(config.textColor).toBe('#1a1a1a');
|
||||
});
|
||||
});
|
||||
|
||||
describe('custom presets', () => {
|
||||
it('returns empty array when no custom presets saved', () => {
|
||||
expect(loadCustomPresets()).toEqual([]);
|
||||
});
|
||||
|
||||
it('saves and loads a custom preset', () => {
|
||||
const config: FlyerConfig = { ...DEFAULT_FLYER_CONFIG, bgColor: '#ff0000' };
|
||||
saveCustomPreset('My Red Theme', config);
|
||||
const presets = loadCustomPresets();
|
||||
expect(presets).toHaveLength(1);
|
||||
expect(presets[0].name).toBe('My Red Theme');
|
||||
expect(presets[0].config.bgColor).toBe('#ff0000');
|
||||
});
|
||||
|
||||
it('overwrites preset with same name', () => {
|
||||
saveCustomPreset('Theme A', { ...DEFAULT_FLYER_CONFIG, bgColor: '#111111' });
|
||||
saveCustomPreset('Theme A', { ...DEFAULT_FLYER_CONFIG, bgColor: '#222222' });
|
||||
const presets = loadCustomPresets();
|
||||
expect(presets).toHaveLength(1);
|
||||
expect(presets[0].config.bgColor).toBe('#222222');
|
||||
});
|
||||
|
||||
it('deletes a custom preset by name', () => {
|
||||
saveCustomPreset('To Delete', DEFAULT_FLYER_CONFIG);
|
||||
saveCustomPreset('To Keep', DEFAULT_FLYER_CONFIG);
|
||||
deleteCustomPreset('To Delete');
|
||||
const presets = loadCustomPresets();
|
||||
expect(presets).toHaveLength(1);
|
||||
expect(presets[0].name).toBe('To Keep');
|
||||
});
|
||||
|
||||
it('no-ops when deleting non-existent preset', () => {
|
||||
saveCustomPreset('Exists', DEFAULT_FLYER_CONFIG);
|
||||
deleteCustomPreset('Does Not Exist');
|
||||
expect(loadCustomPresets()).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,152 +0,0 @@
|
||||
export interface FlyerConfig {
|
||||
// Colors
|
||||
bgColor: string;
|
||||
headlineGradient: string[];
|
||||
headlineSubColor: string;
|
||||
textColor: string;
|
||||
subtextColor: string;
|
||||
accentColor: string;
|
||||
|
||||
// Text overrides (null = use default)
|
||||
headlineMain: string | null;
|
||||
headlineSub: string | null;
|
||||
subtitle: string | null;
|
||||
ctaLabel: string | null;
|
||||
ctaNote: string | null;
|
||||
steps: Array<{ title: string | null; desc: string | null }>;
|
||||
|
||||
// Section visibility
|
||||
showSubtitle: boolean;
|
||||
showSteps: boolean;
|
||||
showDivider: boolean;
|
||||
showBottomFeatures: boolean;
|
||||
showBottomTagline: boolean;
|
||||
|
||||
// Custom branding
|
||||
customLogoUrl: string | null;
|
||||
|
||||
// Print layout
|
||||
perPage: 1 | 2 | 4;
|
||||
marginMm: number;
|
||||
}
|
||||
|
||||
export interface NamedPreset {
|
||||
name: string;
|
||||
config: FlyerConfig;
|
||||
}
|
||||
|
||||
const FLYER_CONFIG_KEY = 'nk-flyer-prefs';
|
||||
const CUSTOM_PRESETS_KEY = 'nk-flyer-custom-presets';
|
||||
|
||||
const DEFAULT_STEPS: Array<{ title: string | null; desc: string | null }> = [
|
||||
{ title: null, desc: null },
|
||||
{ title: null, desc: null },
|
||||
{ title: null, desc: null },
|
||||
{ title: null, desc: null },
|
||||
];
|
||||
|
||||
export const LIGHT_PRESET: FlyerConfig = {
|
||||
bgColor: '#faf8f5',
|
||||
headlineGradient: ['#c45aff', '#ff7acc', '#ff5a8a'],
|
||||
headlineSubColor: '#1a1a1a',
|
||||
textColor: '#1a1a1a',
|
||||
subtextColor: '#666666',
|
||||
accentColor: '#c45aff',
|
||||
headlineMain: null,
|
||||
headlineSub: null,
|
||||
subtitle: null,
|
||||
ctaLabel: null,
|
||||
ctaNote: null,
|
||||
steps: [...DEFAULT_STEPS],
|
||||
showSubtitle: true,
|
||||
showSteps: true,
|
||||
showDivider: true,
|
||||
showBottomFeatures: true,
|
||||
showBottomTagline: true,
|
||||
customLogoUrl: null,
|
||||
perPage: 1,
|
||||
marginMm: 15,
|
||||
};
|
||||
|
||||
export const DARK_PRESET: FlyerConfig = {
|
||||
bgColor: '#0c0a1a',
|
||||
headlineGradient: ['#ffd86b', '#ff7acc', '#c45aff'],
|
||||
headlineSubColor: '#ffffff',
|
||||
textColor: '#ffffff',
|
||||
subtextColor: 'rgba(255, 255, 255, 0.6)',
|
||||
accentColor: '#c45aff',
|
||||
headlineMain: null,
|
||||
headlineSub: null,
|
||||
subtitle: null,
|
||||
ctaLabel: null,
|
||||
ctaNote: null,
|
||||
steps: [...DEFAULT_STEPS],
|
||||
showSubtitle: true,
|
||||
showSteps: true,
|
||||
showDivider: true,
|
||||
showBottomFeatures: true,
|
||||
showBottomTagline: true,
|
||||
customLogoUrl: null,
|
||||
perPage: 1,
|
||||
marginMm: 15,
|
||||
};
|
||||
|
||||
export const DEFAULT_FLYER_CONFIG: FlyerConfig = { ...LIGHT_PRESET };
|
||||
|
||||
export const BUILT_IN_PRESETS: NamedPreset[] = [
|
||||
{ name: 'Light', config: LIGHT_PRESET },
|
||||
{ name: 'Dark', config: DARK_PRESET },
|
||||
];
|
||||
|
||||
const isBrowser = typeof window !== 'undefined';
|
||||
|
||||
export function loadFlyerConfig(): FlyerConfig {
|
||||
if (!isBrowser) return { ...DEFAULT_FLYER_CONFIG };
|
||||
try {
|
||||
const saved = localStorage.getItem(FLYER_CONFIG_KEY);
|
||||
if (saved) {
|
||||
return { ...DEFAULT_FLYER_CONFIG, ...JSON.parse(saved) };
|
||||
}
|
||||
} catch {}
|
||||
return { ...DEFAULT_FLYER_CONFIG };
|
||||
}
|
||||
|
||||
export function saveFlyerConfig(config: FlyerConfig): void {
|
||||
if (!isBrowser) return;
|
||||
try {
|
||||
localStorage.setItem(FLYER_CONFIG_KEY, JSON.stringify(config));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function loadCustomPresets(): NamedPreset[] {
|
||||
if (!isBrowser) return [];
|
||||
try {
|
||||
const saved = localStorage.getItem(CUSTOM_PRESETS_KEY);
|
||||
if (saved) {
|
||||
return JSON.parse(saved);
|
||||
}
|
||||
} catch {}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function saveCustomPreset(name: string, config: FlyerConfig): void {
|
||||
if (!isBrowser) return;
|
||||
const presets = loadCustomPresets();
|
||||
const idx = presets.findIndex(p => p.name === name);
|
||||
if (idx >= 0) {
|
||||
presets[idx] = { name, config };
|
||||
} else {
|
||||
presets.push({ name, config });
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(CUSTOM_PRESETS_KEY, JSON.stringify(presets));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
export function deleteCustomPreset(name: string): void {
|
||||
if (!isBrowser) return;
|
||||
const presets = loadCustomPresets().filter(p => p.name !== name);
|
||||
try {
|
||||
localStorage.setItem(CUSTOM_PRESETS_KEY, JSON.stringify(presets));
|
||||
} catch {}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
"use client"
|
||||
|
||||
import Image from "next/image"
|
||||
import { useTenant } from "@/lib/tenant"
|
||||
|
||||
// Default Nomad Karaoke logo URL (local SVG in /public)
|
||||
const DEFAULT_LOGO_URL = "/nomad-karaoke-logo.svg"
|
||||
// Default Nomad Karaoke logo URL
|
||||
const DEFAULT_LOGO_URL =
|
||||
"https://nomadkaraoke.com/wp-content/uploads/2024/07/Nomad-Karaoke-Logo-TextOnly-Cropped-FromSVG-HQ-2048x1088.png"
|
||||
|
||||
interface TenantLogoProps {
|
||||
className?: string
|
||||
@@ -28,17 +30,45 @@ export function TenantLogo({ className = "", size = "sm" }: TenantLogoProps) {
|
||||
logoUrl = DEFAULT_LOGO_URL
|
||||
}
|
||||
}
|
||||
const logoHeight = branding.logo_height || 40
|
||||
|
||||
const heightClass = size === "lg" ? "h-20 sm:h-[120px]" : "h-8 sm:h-10"
|
||||
const maxWidthClass = size === "lg" ? "max-w-[600px]" : "max-w-[200px]"
|
||||
// Size classes based on size prop - use static Tailwind classes only
|
||||
// Dynamic height is applied via inline style
|
||||
const sizeClasses =
|
||||
size === "lg"
|
||||
? "max-w-[600px]"
|
||||
: "max-w-[200px]"
|
||||
|
||||
// Compute max height for inline style
|
||||
const maxHeight = size === "lg" ? 120 : logoHeight
|
||||
|
||||
// For tenant logos, use img tag since they come from GCS signed URLs
|
||||
// For default logo, use Next.js Image for optimization
|
||||
if (!isDefault && branding.logo_url) {
|
||||
return (
|
||||
<div className={`flex items-center ${className}`}>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={logoUrl}
|
||||
alt={tenant?.name || "Logo"}
|
||||
className={`w-auto h-auto ${sizeClasses} object-contain`}
|
||||
style={{ maxHeight }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Default Nomad Karaoke logo with Next.js Image optimization
|
||||
return (
|
||||
<div className={`flex items-center ${className}`}>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img
|
||||
src={logoUrl}
|
||||
alt={(!isDefault && tenant?.name) ? tenant.name : "Nomad Karaoke"}
|
||||
className={`${heightClass} ${maxWidthClass} w-auto object-contain shrink-0`}
|
||||
<Image
|
||||
src={DEFAULT_LOGO_URL}
|
||||
alt="Nomad Karaoke"
|
||||
width={200}
|
||||
height={106}
|
||||
className={`w-auto h-auto ${sizeClasses} object-contain`}
|
||||
style={{ maxHeight }}
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
// frontend/e2e/helpers/stripe-checkout.ts
|
||||
import { Page } from '@playwright/test';
|
||||
|
||||
/**
|
||||
* Automate Stripe's hosted checkout page (checkout.stripe.com).
|
||||
*
|
||||
* Stripe Checkout (as of April 2026) shows:
|
||||
* - "Pay with Link" / "Pay with Klarna" buttons at top
|
||||
* - Payment method radio buttons: Card, Cash App Pay, Klarna, Bank
|
||||
* - Clicking "Card" reveals card input fields (number, expiry, CVC)
|
||||
* - Card fields are inside iframes within the page
|
||||
* - A "Pay" button at the bottom
|
||||
*
|
||||
* Environment variables:
|
||||
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY,
|
||||
* E2E_STRIPE_CARD_CVC, E2E_STRIPE_CARDHOLDER_NAME (optional)
|
||||
*/
|
||||
|
||||
interface CardDetails {
|
||||
number: string;
|
||||
expiry: string;
|
||||
cvc: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
function getCardDetailsFromEnv(): CardDetails {
|
||||
const number = process.env.E2E_STRIPE_CARD_NUMBER;
|
||||
const expiry = process.env.E2E_STRIPE_CARD_EXPIRY;
|
||||
const cvc = process.env.E2E_STRIPE_CARD_CVC;
|
||||
const name = process.env.E2E_STRIPE_CARDHOLDER_NAME;
|
||||
|
||||
if (!number || !expiry || !cvc) {
|
||||
throw new Error(
|
||||
'Missing Stripe card env vars: E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC'
|
||||
);
|
||||
}
|
||||
|
||||
return { number, expiry, cvc, name };
|
||||
}
|
||||
|
||||
/**
|
||||
* Complete the Stripe Checkout page with card details from environment.
|
||||
*
|
||||
* @param page - Playwright page that will be redirected to checkout.stripe.com
|
||||
* @returns void — after this, the page will redirect to the success URL
|
||||
*/
|
||||
export async function completeStripeCheckout(page: Page): Promise<void> {
|
||||
const card = getCardDetailsFromEnv();
|
||||
|
||||
// Step 1: Wait for Stripe Checkout page to fully load
|
||||
console.log(' Waiting for Stripe Checkout page...');
|
||||
await page.waitForURL(/checkout\.stripe\.com/, { timeout: 30_000 });
|
||||
// Wait for the page to be fully interactive — look for the "Pay" button
|
||||
// which is one of the last elements to render
|
||||
await page.getByRole('button', { name: /^Pay$/i }).waitFor({
|
||||
state: 'visible',
|
||||
timeout: 30_000,
|
||||
});
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
|
||||
console.log(' Stripe Checkout loaded');
|
||||
|
||||
// Step 2: Select "Card" payment method
|
||||
// Stripe uses an accordion with radio buttons overlaid by buttons.
|
||||
// Use force:true to bypass the overlay interception.
|
||||
console.log(' Selecting Card payment method...');
|
||||
const cardRadio = page.getByRole('radio', { name: 'Card' });
|
||||
await cardRadio.check({ force: true, timeout: 10_000 });
|
||||
console.log(' Card payment method selected');
|
||||
|
||||
// Wait for card input fields to appear after selecting Card
|
||||
// Stripe renders card fields inside iframes after the radio is clicked
|
||||
await page.waitForTimeout(2000);
|
||||
await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
|
||||
|
||||
// Step 3: Fill card number
|
||||
// After clicking "Card", Stripe shows card input fields.
|
||||
// These may be direct inputs (#cardNumber) or inside iframes.
|
||||
console.log(' Filling card number...');
|
||||
await fillCardField(page, 'cardNumber', card.number);
|
||||
|
||||
// Step 4: Fill expiry
|
||||
console.log(' Filling card expiry...');
|
||||
await fillCardField(page, 'cardExpiry', card.expiry);
|
||||
|
||||
// Step 5: Fill CVC
|
||||
console.log(' Filling CVC...');
|
||||
await fillCardField(page, 'cardCvc', card.cvc);
|
||||
|
||||
// Step 6: Fill cardholder name if field exists
|
||||
if (card.name) {
|
||||
const nameInput = page.locator('#billingName, input[name="billingName"]');
|
||||
if (await nameInput.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||
console.log(' Filling cardholder name...');
|
||||
await nameInput.fill(card.name);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 6b: Fill ZIP code (required for US cards)
|
||||
const zipInput = page.locator('#billingPostalCode, input[name="billingPostalCode"], input[placeholder="ZIP"]');
|
||||
if (await zipInput.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||
console.log(' Filling ZIP code...');
|
||||
await zipInput.fill(process.env.E2E_STRIPE_ZIP || '10001');
|
||||
}
|
||||
|
||||
// Step 6c: Uncheck "Save my information" to avoid phone number requirement
|
||||
const saveCheckbox = page.getByRole('checkbox', { name: /save my information/i });
|
||||
if (await saveCheckbox.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||
if (await saveCheckbox.isChecked()) {
|
||||
console.log(' Unchecking "Save my information"...');
|
||||
await saveCheckbox.uncheck({ force: true });
|
||||
}
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
|
||||
console.log(' Card details filled');
|
||||
|
||||
// Step 7: Click "Pay" button
|
||||
console.log(' Clicking Pay button...');
|
||||
const payButton = page.getByRole('button', { name: /^Pay$/i });
|
||||
await payButton.waitFor({ state: 'visible', timeout: 10_000 });
|
||||
await payButton.click();
|
||||
|
||||
console.log(' Payment submitted, waiting for redirect...');
|
||||
// Wait for redirect back to our site
|
||||
await page.waitForURL(/nomadkaraoke\.com.*payment\/success|nomadkaraoke\.com.*\/app/, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-complete.png' });
|
||||
console.log(' Stripe Checkout complete — redirected to success page');
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill a card field by name. Tries direct input first, then iframe-based.
|
||||
*
|
||||
* Stripe Checkout card fields use IDs like #cardNumber, #cardExpiry, #cardCvc
|
||||
* when rendered as direct inputs, or are inside iframes when using Elements.
|
||||
*/
|
||||
async function fillCardField(page: Page, fieldName: string, value: string): Promise<void> {
|
||||
// Try 1: Direct input by ID
|
||||
const directInput = page.locator(`#${fieldName}`);
|
||||
if (await directInput.isVisible({ timeout: 3000 }).catch(() => false)) {
|
||||
await directInput.click();
|
||||
await directInput.type(value, { delay: 50 });
|
||||
return;
|
||||
}
|
||||
|
||||
// Try 2: Direct input by data attribute
|
||||
const dataInput = page.locator(`[data-elements-stable-field-name="${fieldName}"]`);
|
||||
if (await dataInput.isVisible({ timeout: 2000 }).catch(() => false)) {
|
||||
await dataInput.click();
|
||||
await dataInput.type(value, { delay: 50 });
|
||||
return;
|
||||
}
|
||||
|
||||
// Try 3: Input inside an iframe (Stripe Elements)
|
||||
// Find all iframes and try each one for the card input
|
||||
const iframes = page.locator('iframe');
|
||||
const iframeCount = await iframes.count();
|
||||
for (let i = 0; i < iframeCount; i++) {
|
||||
const frame = iframes.nth(i).contentFrame();
|
||||
// Look for inputs inside this iframe
|
||||
const input = frame.locator(`input[name="${fieldName}"], input[autocomplete*="cc"]`).first();
|
||||
if (await input.isVisible({ timeout: 1000 }).catch(() => false)) {
|
||||
await input.type(value, { delay: 50 });
|
||||
console.log(` Found ${fieldName} in iframe ${i}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Could not find card field: ${fieldName} (tried direct input, data attribute, and ${iframeCount} iframes)`);
|
||||
}
|
||||
@@ -1,236 +0,0 @@
|
||||
// frontend/e2e/production/credit-purchase-real.spec.ts
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
|
||||
import { completeStripeCheckout } from '../helpers/stripe-checkout';
|
||||
import { getPageAuthToken } from '../helpers/auth';
|
||||
import { URLS, TIMEOUTS } from '../helpers/constants';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
/**
|
||||
* E2E Test: Real Credit Purchase via Stripe Checkout
|
||||
*
|
||||
* Tests the REAL payment flow that customers use:
|
||||
* 1. Sign up with referral code e2etest70 (70% discount)
|
||||
* 2. Open Buy Credits dialog
|
||||
* 3. Purchase 1 credit via real Stripe Checkout ($3.00 after discount)
|
||||
* 4. Verify credits allocated and confirmation email received
|
||||
*
|
||||
* This test uses a REAL credit card and processes a REAL charge.
|
||||
* The 70% referral discount keeps cost to ~$3/day.
|
||||
*
|
||||
* Prerequisites:
|
||||
* - E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC
|
||||
* - TESTMAIL_API_KEY + TESTMAIL_NAMESPACE
|
||||
* - E2E_ADMIN_TOKEN (for credit verification + cleanup)
|
||||
*
|
||||
* Output:
|
||||
* - Writes session token to test-results/e2e-session-token.txt
|
||||
* for Stage 2 (happy path) to consume
|
||||
*/
|
||||
|
||||
const PROD_URL = URLS.production.frontend;
|
||||
const API_URL = URLS.production.api;
|
||||
|
||||
test.describe('Real Credit Purchase Flow', () => {
|
||||
test('purchase 1 credit via Stripe Checkout with referral discount', async ({ page, request }) => {
|
||||
// ===== PREREQUISITES =====
|
||||
test.skip(!process.env.E2E_STRIPE_CARD_NUMBER, 'E2E_STRIPE_CARD_NUMBER not set');
|
||||
test.skip(!isEmailTestingAvailable(), 'Testmail credentials not set');
|
||||
|
||||
const adminToken = process.env.E2E_ADMIN_TOKEN;
|
||||
test.skip(!adminToken, 'E2E_ADMIN_TOKEN not set');
|
||||
|
||||
const emailHelper = await createEmailHelper();
|
||||
const inbox = await emailHelper.createInbox();
|
||||
console.log(`Test email: ${inbox.emailAddress}`);
|
||||
|
||||
try {
|
||||
// ===== STEP 1: Navigate with referral code =====
|
||||
console.log('\n=== STEP 1: Navigate with referral code ===');
|
||||
await page.goto(`${PROD_URL}/?ref=e2etest70`);
|
||||
await page.waitForLoadState('networkidle');
|
||||
await page.screenshot({ path: 'test-results/01-landing-with-referral.png' });
|
||||
console.log(' Landed with ?ref=e2etest70');
|
||||
|
||||
// ===== STEP 2: Sign up via magic link =====
|
||||
console.log('\n=== STEP 2: Sign up via magic link ===');
|
||||
|
||||
// Click Sign Up Free
|
||||
const signUpButton = page.getByRole('button', { name: /sign up free/i });
|
||||
await expect(signUpButton).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await signUpButton.click();
|
||||
|
||||
// Fill email in AuthDialog
|
||||
const authDialog = page.getByRole('dialog');
|
||||
await expect(authDialog).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
const emailInput = authDialog.getByPlaceholder('you@example.com');
|
||||
await emailInput.fill(inbox.emailAddress!);
|
||||
await page.screenshot({ path: 'test-results/02-auth-dialog.png' });
|
||||
|
||||
// Send magic link
|
||||
const sendButton = page.getByRole('button', { name: /send sign-in link/i });
|
||||
await sendButton.click();
|
||||
await expect(page.getByText(/check your email/i)).toBeVisible({ timeout: 15000 });
|
||||
console.log(' Magic link sent');
|
||||
|
||||
// Wait for email and extract link
|
||||
const magicEmail = await emailHelper.waitForEmail(inbox.id!, 60000);
|
||||
const magicLink = emailHelper.extractMagicLink(magicEmail);
|
||||
if (!magicLink) throw new Error('Could not extract magic link from email');
|
||||
console.log(` Magic link received`);
|
||||
|
||||
// Navigate to magic link
|
||||
await page.goto(magicLink);
|
||||
|
||||
// Handle verification result (new user interstitial or direct success)
|
||||
const verifyResult = await Promise.race([
|
||||
page.getByText(/successfully signed in/i).waitFor({ state: 'visible', timeout: 30000 }).then(() => 'success'),
|
||||
page.getByText(/welcome to nomad karaoke/i).waitFor({ state: 'visible', timeout: 30000 }).then(() => 'credits_interstitial'),
|
||||
]);
|
||||
console.log(` Verification: ${verifyResult}`);
|
||||
|
||||
if (verifyResult === 'credits_interstitial') {
|
||||
const startButton = page.getByRole('button', { name: /start creating|go to dashboard|explore the app/i });
|
||||
await expect(startButton).toBeVisible({ timeout: 5000 });
|
||||
await startButton.click();
|
||||
}
|
||||
|
||||
await page.waitForURL(/\/app/, { timeout: 15000 });
|
||||
await page.screenshot({ path: 'test-results/03-authenticated.png' });
|
||||
console.log(' Authenticated and on /app');
|
||||
|
||||
// Extract session token for Stage 2
|
||||
const sessionToken = await getPageAuthToken(page);
|
||||
if (!sessionToken) throw new Error('No session token after auth');
|
||||
|
||||
// ===== STEP 3: Open Buy Credits and verify discount =====
|
||||
console.log('\n=== STEP 3: Open Buy Credits dialog ===');
|
||||
|
||||
// "Buy More Credits" is inside the user dropdown menu in the header.
|
||||
// Open the dropdown by clicking the button containing "credits available",
|
||||
// then click the "Buy More Credits" menu item.
|
||||
const userDropdownButton = page.locator('button').filter({ hasText: /credits?\s+available/i }).first();
|
||||
await expect(userDropdownButton).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await userDropdownButton.click();
|
||||
console.log(' Opened user dropdown');
|
||||
|
||||
// Wait for dropdown menu and click "Buy More Credits"
|
||||
const buyMenuItem = page.getByRole('menuitem', { name: /buy more credits/i });
|
||||
await expect(buyMenuItem).toBeVisible({ timeout: 5000 });
|
||||
console.log(' Found Buy More Credits menu item');
|
||||
await buyMenuItem.click();
|
||||
|
||||
// Wait for BuyCreditsDialog
|
||||
const creditsDialog = page.getByRole('dialog');
|
||||
await expect(creditsDialog).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.screenshot({ path: 'test-results/04-buy-credits-dialog.png' });
|
||||
|
||||
// Check for referral discount badge (may say "70% referral discount")
|
||||
// This is informational — don't fail the test if the badge isn't visible,
|
||||
// as the discount is applied server-side regardless of the UI badge
|
||||
const discountBadge = creditsDialog.getByText(/70%/i).first();
|
||||
if (await discountBadge.isVisible({ timeout: 5000 }).catch(() => false)) {
|
||||
console.log(' Referral discount badge visible');
|
||||
} else {
|
||||
console.log(' WARNING: Referral discount badge not visible — discount may still apply at checkout');
|
||||
}
|
||||
|
||||
// ===== STEP 4: Select 1-credit package =====
|
||||
console.log('\n=== STEP 4: Select 1-credit package ===');
|
||||
|
||||
// The packages grid has buttons with large credit-count numbers.
|
||||
// Find all package buttons and log them for debugging.
|
||||
const packageButtons = creditsDialog.locator('button').filter({ hasText: /credit/i });
|
||||
const btnCount = await packageButtons.count();
|
||||
console.log(` Found ${btnCount} package buttons`);
|
||||
for (let i = 0; i < Math.min(btnCount, 4); i++) {
|
||||
const txt = await packageButtons.nth(i).textContent();
|
||||
console.log(` Button ${i}: "${txt?.replace(/\s+/g, ' ').trim().substring(0, 80)}"`);
|
||||
}
|
||||
|
||||
// Select the 1-credit package — first button in the 2-column grid
|
||||
const oneCredit = packageButtons.first();
|
||||
await oneCredit.click();
|
||||
await page.screenshot({ path: 'test-results/05-package-selected.png' });
|
||||
console.log(' Selected 1-credit package');
|
||||
|
||||
// Verify the discounted price ($3.00) is shown
|
||||
// The checkout button should show the price
|
||||
const checkoutButton = creditsDialog.getByRole('button', { name: /continue|checkout|pay/i }).last();
|
||||
await expect(checkoutButton).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
const buttonText = await checkoutButton.textContent();
|
||||
console.log(` Checkout button: "${buttonText}"`);
|
||||
|
||||
// ===== STEP 5: Proceed to Stripe Checkout =====
|
||||
console.log('\n=== STEP 5: Stripe Checkout ===');
|
||||
await checkoutButton.click();
|
||||
|
||||
// Complete Stripe Checkout with real card
|
||||
await completeStripeCheckout(page);
|
||||
|
||||
// ===== STEP 6: Verify payment success page =====
|
||||
console.log('\n=== STEP 6: Verify payment success ===');
|
||||
await page.waitForURL(/payment\/success/, { timeout: 30000 });
|
||||
|
||||
// Verify success indicators
|
||||
const successText = page.getByText(/payment successful/i);
|
||||
await expect(successText).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
// Verify credit balance is shown — the number and "credits available"
|
||||
// may be in separate DOM elements, so check for each independently
|
||||
const creditsAvailableText = page.getByText(/credits?\s+available/i);
|
||||
await expect(creditsAvailableText).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.screenshot({ path: 'test-results/06-payment-success.png' });
|
||||
console.log(' Payment success page confirmed with credits');
|
||||
|
||||
// ===== STEP 7: Verify via API =====
|
||||
console.log('\n=== STEP 7: Verify credits via API ===');
|
||||
try {
|
||||
const userResponse = await request.get(`${API_URL}/api/users/me`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${sessionToken}`,
|
||||
'X-Session-Token': sessionToken,
|
||||
},
|
||||
});
|
||||
if (userResponse.ok()) {
|
||||
const userData = await userResponse.json();
|
||||
console.log(` API response keys: ${Object.keys(userData).join(', ')}`);
|
||||
console.log(` API credits: ${userData.credits ?? userData.credit_balance ?? 'N/A'}`);
|
||||
} else {
|
||||
console.log(` API returned ${userResponse.status()} — session token may use different auth`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(` API check skipped: ${e}`);
|
||||
}
|
||||
// The success page already confirmed credits — API check is informational
|
||||
|
||||
// ===== STEP 8: Verify confirmation email =====
|
||||
console.log('\n=== STEP 8: Verify confirmation email ===');
|
||||
try {
|
||||
// Wait for the second email (first was magic link, second is payment confirmation)
|
||||
const confirmEmail = await emailHelper.waitForEmail(inbox.id!, 30000);
|
||||
console.log(` Confirmation email: "${confirmEmail.subject}"`);
|
||||
const emailText = ((confirmEmail.subject || '') + ' ' + (confirmEmail.body || '')).toLowerCase();
|
||||
expect(emailText).toContain('credit');
|
||||
} catch (e) {
|
||||
// Email verification is best-effort — don't fail the payment test for email issues
|
||||
console.log(` Email verification skipped: ${e}`);
|
||||
}
|
||||
|
||||
// ===== OUTPUT: Save token for Stage 2 =====
|
||||
console.log('\n=== OUTPUT: Saving session token for Stage 2 ===');
|
||||
const outputDir = path.join(process.cwd(), 'test-results');
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(outputDir, 'e2e-session-token.txt'), sessionToken);
|
||||
console.log(' Token saved to test-results/e2e-session-token.txt');
|
||||
|
||||
console.log('\n✅ CREDIT PURCHASE TEST PASSED');
|
||||
|
||||
} finally {
|
||||
if (inbox?.id) {
|
||||
await emailHelper.deleteInbox(inbox.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,7 @@
|
||||
/**
|
||||
* Tests for auth store's fetchUser() behavior, specifically:
|
||||
* - Abort errors (from page navigation) should NOT clear auth
|
||||
* - 401 errors (expired session) SHOULD clear auth
|
||||
* - Network errors (fetch failures) should NOT clear auth
|
||||
* - Other errors (expired session) SHOULD clear auth
|
||||
*/
|
||||
|
||||
// Mock api module before importing auth
|
||||
@@ -51,31 +50,18 @@ describe('fetchUser', () => {
|
||||
expect(useAuth.getState().isLoading).toBe(false)
|
||||
})
|
||||
|
||||
it('clears auth state when API returns 401 (expired session)', async () => {
|
||||
const err = new Error('Unauthorized') as Error & { status: number }
|
||||
err.status = 401
|
||||
mockGetCurrentUser.mockRejectedValueOnce(err)
|
||||
it('clears auth state when API returns a non-abort error (expired session)', async () => {
|
||||
mockGetCurrentUser.mockRejectedValueOnce(new Error('Unauthorized'))
|
||||
|
||||
const result = await useAuth.getState().fetchUser()
|
||||
|
||||
expect(result).toBe(false)
|
||||
// Auth SHOULD be cleared on explicit 401
|
||||
// Auth SHOULD be cleared
|
||||
expect(clearAccessToken).toHaveBeenCalled()
|
||||
expect(useAuth.getState().user).toBeNull()
|
||||
expect(useAuth.getState().isLoading).toBe(false)
|
||||
})
|
||||
|
||||
it('preserves auth state on network errors (non-401)', async () => {
|
||||
mockGetCurrentUser.mockRejectedValueOnce(new TypeError('Failed to fetch'))
|
||||
|
||||
const result = await useAuth.getState().fetchUser()
|
||||
|
||||
expect(result).toBe(false)
|
||||
// Auth should NOT be cleared on network errors
|
||||
expect(clearAccessToken).not.toHaveBeenCalled()
|
||||
expect(useAuth.getState().isLoading).toBe(false)
|
||||
})
|
||||
|
||||
it('sets user on successful fetch', async () => {
|
||||
mockGetCurrentUser.mockResolvedValueOnce({
|
||||
user: {
|
||||
|
||||
+2
-60
@@ -2573,19 +2573,6 @@ export const adminApi = {
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
async generateFlyer(code: string, theme: 'light' | 'dark', qrDataUrl: string): Promise<Blob> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/referrals/admin/links/${encodeURIComponent(code)}/flyer`, {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme, qr_data_url: qrDataUrl }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ detail: 'Failed to generate flyer' }));
|
||||
throw new Error(error.detail || 'Failed to generate flyer');
|
||||
}
|
||||
return response.blob();
|
||||
},
|
||||
};
|
||||
|
||||
export interface EditReviewSummary {
|
||||
@@ -3548,9 +3535,8 @@ export { ApiError };
|
||||
// Referral API
|
||||
// ============================================================================
|
||||
|
||||
export async function getReferralInterstitial(code: string, noTrack = false): Promise<ReferralInterstitial> {
|
||||
const url = `${API_BASE_URL}/api/referrals/r/${encodeURIComponent(code)}${noTrack ? '?no_track=true' : ''}`;
|
||||
const response = await fetch(url);
|
||||
export async function getReferralInterstitial(code: string): Promise<ReferralInterstitial> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/referrals/r/${encodeURIComponent(code)}`);
|
||||
if (!response.ok) throw new Error('Failed to fetch referral info');
|
||||
return response.json();
|
||||
}
|
||||
@@ -3584,47 +3570,3 @@ export async function startConnectOnboarding(): Promise<{ account_id: string; on
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function getConnectDashboardLink(): Promise<{ url: string }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/referrals/me/connect/dashboard-link`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to get dashboard link');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function getConnectUpdateLink(): Promise<{ url: string }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/referrals/me/connect/update-link`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to get update link');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function requestVanityUrl(desiredCode: string): Promise<{ ok: boolean; message: string }> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/referrals/me/vanity-request`, {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ desired_code: desiredCode }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ detail: 'Request failed' }));
|
||||
throw new Error(error.detail || 'Request failed');
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export async function generateFlyer(theme: 'light' | 'dark', qrDataUrl: string): Promise<Blob> {
|
||||
const response = await fetch(`${API_BASE_URL}/api/referrals/me/flyer`, {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ theme, qr_data_url: qrDataUrl }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ detail: 'Failed to generate flyer' }));
|
||||
throw new Error(error.detail || 'Failed to generate flyer');
|
||||
}
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
@@ -152,14 +152,9 @@ export const useAuth = create<AuthStore>()(
|
||||
set({ isLoading: false })
|
||||
return false
|
||||
}
|
||||
// Only clear token on explicit 401 (session expired/invalid)
|
||||
// Network errors, timeouts, cold-start delays, etc. should not log the user out
|
||||
if (err && typeof err === 'object' && 'status' in err && (err as any).status === 401) {
|
||||
clearAccessToken()
|
||||
set({ user: null, isLoading: false })
|
||||
} else {
|
||||
set({ isLoading: false })
|
||||
}
|
||||
// Session may have expired
|
||||
clearAccessToken()
|
||||
set({ user: null, isLoading: false })
|
||||
return false
|
||||
}
|
||||
},
|
||||
|
||||
@@ -30,7 +30,6 @@ export const HIGHLIGHT_CLASSES = {
|
||||
uncorrectedGap: 'bg-orange-500/25',
|
||||
highlighted: 'bg-amber-400/40',
|
||||
playing: 'text-blue-500',
|
||||
userEdited: 'bg-lime-400/40',
|
||||
} as const
|
||||
|
||||
// CSS keyframes for flash animation (use with Tailwind animate utilities)
|
||||
|
||||
@@ -172,7 +172,7 @@ export type EditOperationType =
|
||||
| 'word_change' | 'word_delete' | 'word_add'
|
||||
| 'word_split' | 'word_merge'
|
||||
| 'segment_delete' | 'segment_add' | 'segment_split' | 'segment_merge'
|
||||
| 'find_replace' | 'replace_all_lyrics' | 'change_case'
|
||||
| 'find_replace' | 'replace_all_lyrics'
|
||||
| 'timing_change' | 'revert_correction' | 'revert_all'
|
||||
|
||||
export type EditFeedbackReason =
|
||||
@@ -337,7 +337,6 @@ export interface WordProps {
|
||||
isUncorrectedGap?: boolean
|
||||
isCurrentlyPlaying?: boolean
|
||||
isActiveGap?: boolean
|
||||
isUserEdited?: boolean
|
||||
padding?: string
|
||||
onClick?: () => void
|
||||
id?: string
|
||||
@@ -382,7 +381,6 @@ export interface TranscriptionViewProps {
|
||||
onShowCorrectionDetail?: (wordId: string) => void
|
||||
advancedMode?: boolean
|
||||
onAdvancedModeToggle?: (enabled: boolean) => void
|
||||
editedWordIds?: Set<string>
|
||||
}
|
||||
|
||||
export interface ReferenceViewProps extends BaseViewProps {
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
import { convertCase, applyCaseToSegments } from '../caseConversion'
|
||||
import type { LyricsSegment } from '../../types'
|
||||
|
||||
describe('convertCase', () => {
|
||||
describe('upper', () => {
|
||||
it('uppercases all letters', () => {
|
||||
expect(convertCase('Hello World', 'upper')).toBe('HELLO WORLD')
|
||||
})
|
||||
|
||||
it('preserves punctuation and spacing', () => {
|
||||
expect(convertCase("don't stop, believin'", 'upper')).toBe("DON'T STOP, BELIEVIN'")
|
||||
})
|
||||
|
||||
it('handles empty string', () => {
|
||||
expect(convertCase('', 'upper')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('lower', () => {
|
||||
it('lowercases all letters', () => {
|
||||
expect(convertCase('HELLO WORLD', 'lower')).toBe('hello world')
|
||||
})
|
||||
|
||||
it('handles mixed case', () => {
|
||||
expect(convertCase('HeLLo WoRLD', 'lower')).toBe('hello world')
|
||||
})
|
||||
})
|
||||
|
||||
describe('title', () => {
|
||||
it('capitalizes first letter of every word', () => {
|
||||
expect(convertCase('hello world', 'title')).toBe('Hello World')
|
||||
})
|
||||
|
||||
it('lowercases subsequent letters', () => {
|
||||
expect(convertCase('HELLO WORLD', 'title')).toBe('Hello World')
|
||||
})
|
||||
|
||||
it('handles short words uniformly (no AP-style exceptions)', () => {
|
||||
expect(convertCase('the quick brown fox', 'title')).toBe('The Quick Brown Fox')
|
||||
})
|
||||
|
||||
it('handles contractions by capitalizing only first letter', () => {
|
||||
expect(convertCase("don't stop", 'title')).toBe("Don't Stop")
|
||||
})
|
||||
|
||||
it('preserves multiple spaces between words', () => {
|
||||
expect(convertCase('hello world', 'title')).toBe('Hello World')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sentence', () => {
|
||||
it('capitalizes first letter only', () => {
|
||||
expect(convertCase('hello world', 'sentence')).toBe('Hello world')
|
||||
})
|
||||
|
||||
it('lowercases everything else', () => {
|
||||
expect(convertCase('HELLO WORLD HOW ARE YOU', 'sentence')).toBe('Hello world how are you')
|
||||
})
|
||||
|
||||
it('skips leading punctuation when capitalizing', () => {
|
||||
expect(convertCase('"hello world"', 'sentence')).toBe('"Hello world"')
|
||||
})
|
||||
|
||||
it('handles string with no letters', () => {
|
||||
expect(convertCase('123 !@#', 'sentence')).toBe('123 !@#')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyCaseToSegments', () => {
|
||||
const segments: LyricsSegment[] = [
|
||||
{
|
||||
id: 'seg-1',
|
||||
text: 'Hello world',
|
||||
start_time: 0,
|
||||
end_time: 2,
|
||||
words: [
|
||||
{ id: 'w1', text: 'Hello', start_time: 0, end_time: 1, confidence: 1 },
|
||||
{ id: 'w2', text: 'world', start_time: 1, end_time: 2, confidence: 1 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'seg-2',
|
||||
text: 'How are YOU',
|
||||
start_time: 2,
|
||||
end_time: 5,
|
||||
words: [
|
||||
{ id: 'w3', text: 'How', start_time: 2, end_time: 3, confidence: 1 },
|
||||
{ id: 'w4', text: 'are', start_time: 3, end_time: 4, confidence: 1 },
|
||||
{ id: 'w5', text: 'YOU', start_time: 4, end_time: 5, confidence: 1 },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
it('preserves word timing and IDs', () => {
|
||||
const result = applyCaseToSegments(segments, 'upper')
|
||||
expect(result[0].words[0].id).toBe('w1')
|
||||
expect(result[0].words[0].start_time).toBe(0)
|
||||
expect(result[0].words[0].end_time).toBe(1)
|
||||
expect(result[0].start_time).toBe(0)
|
||||
expect(result[0].end_time).toBe(2)
|
||||
})
|
||||
|
||||
it('uppercases all text', () => {
|
||||
const result = applyCaseToSegments(segments, 'upper')
|
||||
expect(result[0].text).toBe('HELLO WORLD')
|
||||
expect(result[0].words.map((w) => w.text)).toEqual(['HELLO', 'WORLD'])
|
||||
expect(result[1].text).toBe('HOW ARE YOU')
|
||||
})
|
||||
|
||||
it('lowercases all text', () => {
|
||||
const result = applyCaseToSegments(segments, 'lower')
|
||||
expect(result[0].text).toBe('hello world')
|
||||
expect(result[1].words.map((w) => w.text)).toEqual(['how', 'are', 'you'])
|
||||
})
|
||||
|
||||
it('title-cases all words', () => {
|
||||
const result = applyCaseToSegments(segments, 'title')
|
||||
expect(result[1].text).toBe('How Are You')
|
||||
expect(result[1].words.map((w) => w.text)).toEqual(['How', 'Are', 'You'])
|
||||
})
|
||||
|
||||
it('sentence-cases per line (only first word capitalized)', () => {
|
||||
const result = applyCaseToSegments(segments, 'sentence')
|
||||
expect(result[0].text).toBe('Hello world')
|
||||
expect(result[0].words.map((w) => w.text)).toEqual(['Hello', 'world'])
|
||||
expect(result[1].text).toBe('How are you')
|
||||
expect(result[1].words.map((w) => w.text)).toEqual(['How', 'are', 'you'])
|
||||
})
|
||||
|
||||
it('does not mutate original segments', () => {
|
||||
const original = JSON.parse(JSON.stringify(segments))
|
||||
applyCaseToSegments(segments, 'upper')
|
||||
expect(segments).toEqual(original)
|
||||
})
|
||||
|
||||
it('sentence-cases the first cased word even when a punctuation-only token precedes it', () => {
|
||||
const punctSegments: LyricsSegment[] = [
|
||||
{
|
||||
id: 'seg-p',
|
||||
text: '"hello there"',
|
||||
start_time: 0,
|
||||
end_time: 2,
|
||||
words: [
|
||||
{ id: 'p1', text: '"', start_time: 0, end_time: 0.1, confidence: 1 },
|
||||
{ id: 'p2', text: 'hello', start_time: 0.1, end_time: 1, confidence: 1 },
|
||||
{ id: 'p3', text: 'there"', start_time: 1, end_time: 2, confidence: 1 },
|
||||
],
|
||||
},
|
||||
]
|
||||
const result = applyCaseToSegments(punctSegments, 'sentence')
|
||||
expect(result[0].words[0].text).toBe('"')
|
||||
expect(result[0].words[1].text).toBe('Hello')
|
||||
expect(result[0].words[2].text).toBe('there"')
|
||||
})
|
||||
})
|
||||
@@ -100,7 +100,7 @@ describe('addEditEntry', () => {
|
||||
'word_change', 'word_delete', 'word_add',
|
||||
'word_split', 'word_merge',
|
||||
'segment_delete', 'segment_add', 'segment_split', 'segment_merge',
|
||||
'find_replace', 'replace_all_lyrics', 'change_case',
|
||||
'find_replace', 'replace_all_lyrics',
|
||||
'timing_change', 'revert_correction', 'revert_all',
|
||||
] as const
|
||||
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { LyricsSegment } from '../types'
|
||||
|
||||
export type CaseType = 'upper' | 'lower' | 'title' | 'sentence'
|
||||
|
||||
export function convertCase(text: string, caseType: CaseType): string {
|
||||
switch (caseType) {
|
||||
case 'upper':
|
||||
return text.toUpperCase()
|
||||
case 'lower':
|
||||
return text.toLowerCase()
|
||||
case 'title':
|
||||
return toTitleCase(text)
|
||||
case 'sentence':
|
||||
return toSentenceCase(text)
|
||||
}
|
||||
}
|
||||
|
||||
function toTitleCase(text: string): string {
|
||||
return text.replace(/\S+/g, (word) => {
|
||||
const lower = word.toLowerCase()
|
||||
return lower.charAt(0).toUpperCase() + lower.slice(1)
|
||||
})
|
||||
}
|
||||
|
||||
function toSentenceCase(text: string): string {
|
||||
const lower = text.toLowerCase()
|
||||
const firstLetter = lower.search(/[a-z]/i)
|
||||
if (firstLetter === -1) return lower
|
||||
return lower.slice(0, firstLetter) + lower.charAt(firstLetter).toUpperCase() + lower.slice(firstLetter + 1)
|
||||
}
|
||||
|
||||
export function applyCaseToSegments(
|
||||
segments: LyricsSegment[],
|
||||
caseType: CaseType
|
||||
): LyricsSegment[] {
|
||||
const perLine = caseType === 'sentence'
|
||||
return segments.map((segment) => {
|
||||
const transform = (s: string) => convertCase(s, caseType)
|
||||
// For sentence case, find the first word containing a cased letter — so a
|
||||
// leading punctuation-only token doesn't steal the capitalization.
|
||||
const firstCasedIndex = perLine
|
||||
? segment.words.findIndex((w) => /[A-Za-z]/.test(w.text))
|
||||
: -1
|
||||
const newWords = segment.words.map((word, index) => ({
|
||||
...word,
|
||||
text: perLine
|
||||
? index === firstCasedIndex
|
||||
? convertCase(word.text, 'sentence')
|
||||
: word.text.toLowerCase()
|
||||
: transform(word.text),
|
||||
}))
|
||||
return {
|
||||
...segment,
|
||||
text: transform(segment.text),
|
||||
words: newWords,
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -113,14 +113,6 @@ export interface ReferralPayout {
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface StripeConnectAccount {
|
||||
account_id: string;
|
||||
charges_enabled: boolean;
|
||||
payouts_enabled: boolean;
|
||||
details_submitted: boolean;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface ReferralDashboard {
|
||||
link: ReferralLink;
|
||||
pending_balance_cents: number;
|
||||
@@ -129,7 +121,6 @@ export interface ReferralDashboard {
|
||||
recent_earnings: ReferralEarning[];
|
||||
recent_payouts: ReferralPayout[];
|
||||
stripe_connect_configured: boolean;
|
||||
stripe_connect_account: StripeConnectAccount | null;
|
||||
}
|
||||
|
||||
export interface ReferralInterstitial {
|
||||
|
||||
+183
-326
File diff suppressed because it is too large.
Load diff
+224
-367
File diff suppressed because it is too large.
Load diff
+236
-379
File diff suppressed because it is too large.
Load diff
+170
-313
@@ -55,7 +55,7 @@
|
||||
"subtitle": "Opret professionelle karaokevideoer på under 30 minutter. Ægte instrumentaler fra den originale sang, præcis synkronisering af sangtekster og 4K-videooutput."
|
||||
},
|
||||
"heroCTA": {
|
||||
"createYourself": "Opret den selv",
|
||||
"createYourself": "Lav den selv",
|
||||
"createYourselfPrice": "$10",
|
||||
"createYourselfNote": "1 gratis credit inkluderet - ingen betaling påkrævet",
|
||||
"makeForYou": "Vi laver den for dig",
|
||||
@@ -69,8 +69,8 @@
|
||||
"title": "Sådan fungerer det",
|
||||
"step1Title": "Vælg en sang",
|
||||
"step1Desc": "Søg, indsæt et YouTube-link, eller upload lyd",
|
||||
"step2Title": "Vi gør det hårde arbejde",
|
||||
"step2Desc": "Vokaler fjernes, sangtekster transskriberes og synkroniseres",
|
||||
"step2Title": "Vi tager det tunge slæb",
|
||||
"step2Desc": "Vokal fjernet, sangtekster transskriberet og synkroniseret",
|
||||
"step3Title": "Gennemgå og ret",
|
||||
"step3Desc": "Ret eventuelle transskriptionsfejl (normalt 5-10 min)",
|
||||
"step4Title": "Få din video",
|
||||
@@ -82,13 +82,13 @@
|
||||
"features": {
|
||||
"title": "Hvad du får",
|
||||
"feature1Title": "Ægte instrumentaler",
|
||||
"feature1Desc": "Bruger den faktiske instrumental fra din sang—ikke et coverband eller en MIDI-kopi.",
|
||||
"feature1Desc": "Bruger den rigtige instrumental fra din sang — ikke et coverband eller MIDI-genskabelse.",
|
||||
"feature2Title": "Præcis synkronisering af sangtekster",
|
||||
"feature2Desc": "Ord-for-ord timing, der fremhæver præcis, hvornår du skal synge. Du gennemgår sangteksterne for nøjagtighed.",
|
||||
"feature3Title": "Behold eller fjern baggrundsvokaler",
|
||||
"feature3Title": "Behold eller fjern baggrundsvokal",
|
||||
"feature3Desc": "Vælg en ren instrumental eller en, der bevarer baggrundsvokalen for en fyldigere lyd.",
|
||||
"feature4Title": "4K-video + flere formater",
|
||||
"feature4Desc": "Få en 4K-karaokevideo, en syng-med-version med vokal og CDG+MP3 til ældre systemer.",
|
||||
"feature4Desc": "Få en 4K karaokevideo, en syng-med-version med vokal og CDG+MP3 til ældre systemer.",
|
||||
"feature5Title": "Udgivet på YouTube",
|
||||
"feature5Desc": "Hver video udgives automatisk på vores YouTube-kanal for nem deling.",
|
||||
"feature6Title": "Fuld kontrol før eksport",
|
||||
@@ -99,19 +99,19 @@
|
||||
"subtitle": "Her er, hvordan processen ser ud på hvert trin",
|
||||
"jobCreationAlt": "Guidet joboprettelsesflow med indtastning af kunstner og titel",
|
||||
"jobCreationTitle": "Opret din video",
|
||||
"jobCreationDesc": "Indtast enhver sang, og vi finder den bedste lyd automatisk",
|
||||
"lyricsReviewAlt": "Gennemgang af sangtekster med synkroniserede sangtekster ved siden af referencetekster til rettelse",
|
||||
"jobCreationDesc": "Indtast enhver sang, og vi finder automatisk den bedste lyd",
|
||||
"lyricsReviewAlt": "Gennemgang af sangtekster med synkroniserede tekster ved siden af referencetekster til rettelse",
|
||||
"lyricsReviewTitle": "Gennemgå sangtekster",
|
||||
"lyricsReviewDesc": "Sammenlign synkroniserede sangtekster med referencer og ret eventuelle fejl",
|
||||
"instrumentalReviewAlt": "Gennemgang af instrumental med bølgeformsvisning og muligheder for baggrundsvokal",
|
||||
"instrumentalReviewTitle": "Vælg din instrumental",
|
||||
"instrumentalReviewDesc": "Lyt til lydmuligheder og vælg det bedste backing track",
|
||||
"exampleOutputAlt": "Fuldført karaokejob med downloadmuligheder for 4K, 720p, CDG og mere",
|
||||
"instrumentalReviewDesc": "Lyt til lydmuligheder og vælg det bedste backingtrack",
|
||||
"exampleOutputAlt": "Færdigt karaokejob med downloadmuligheder for 4K, 720p, CDG og mere",
|
||||
"exampleOutputTitle": "Download og del",
|
||||
"exampleOutputDesc": "Få din 4K-video, 720p, CDG og mere på få minutter"
|
||||
},
|
||||
"pricing": {
|
||||
"title": "Simpel prissætning",
|
||||
"title": "Enkel prissætning",
|
||||
"subtitle": "Start med 1 gratis credit, og køb derefter flere for at spare mere.",
|
||||
"freeCredit": "1 gratis credit",
|
||||
"freeCreditLabel": "Hver ny konto inkluderer",
|
||||
@@ -119,7 +119,7 @@
|
||||
"signUpFree": "Tilmeld dig gratis",
|
||||
"selectedPackage": "Valgt pakke",
|
||||
"emailLabel": "E-mailadresse",
|
||||
"emailPlaceholder": "dig@eksempel.dk",
|
||||
"emailPlaceholder": "you@example.com",
|
||||
"emailHint": "Vi sender dit login-link til denne e-mail",
|
||||
"continuePayment": "Fortsæt til betaling",
|
||||
"redirecting": "Omdirigerer...",
|
||||
@@ -134,15 +134,15 @@
|
||||
"madeForYou": {
|
||||
"badgeLabel": "Fuld service-mulighed",
|
||||
"title": "Vi laver den for dig",
|
||||
"subtitle": "Vil du ikke bruge Generator og gennemgå sangteksterne selv? Intet problem. Fortæl os sangen, betal $50, og vi leverer din karaokevideo inden for 24 timer.",
|
||||
"subtitle": "Vil du ikke bruge Generator og selv gennemgå sangteksterne? Intet problem. Fortæl os sangen, betal $50, og vi leverer din karaokevideo inden for 24 timer.",
|
||||
"secondarySubtitle": "Vil du ikke bruge 10 minutter på at gennemgå sangtekster? For kun $10 mere end gør-det-selv, tager vi os af alt.",
|
||||
"benefitsTitle": "Hvad du får",
|
||||
"benefit1Title": "Professionel 4K-video",
|
||||
"benefit1Desc": "Høj kvalitet karaokevideo med perfekt synkroniserede sangtekster",
|
||||
"benefit1Desc": "Karaokevideo i høj kvalitet med perfekt synkroniserede sangtekster",
|
||||
"benefit2Title": "24-timers levering",
|
||||
"benefit2Desc": "Vi tager os af alt — du skal bare vente på, at din video ankommer",
|
||||
"benefit2Desc": "Vi tager os af alt — bare vent på, at din video ankommer",
|
||||
"benefit3Title": "Alle formater inkluderet",
|
||||
"benefit3Desc": "MP4-video, CDG+MP3 til karaokemaskiner, lydspor",
|
||||
"benefit3Desc": "MP4-video, CDG+MP3 til karaokemaskiner, lydstems",
|
||||
"benefit4Title": "1000+ ægte eksempler på YouTube",
|
||||
"benefit4Desc": "Gennemse vores YouTube-kanal for at se præcis, hvad du får",
|
||||
"deliveryIncludesTitle": "Din levering inkluderer:",
|
||||
@@ -167,17 +167,17 @@
|
||||
"youtubeUrlFieldLabel": "YouTube-URL",
|
||||
"youtubeUrlPlaceholder": "https://youtube.com/watch?v=...",
|
||||
"emailLabel2": "Din e-mail",
|
||||
"emailPlaceholder2": "dig@eksempel.dk",
|
||||
"emailPlaceholder2": "you@example.com",
|
||||
"emailHint2": "Vi sender dine videofiler til denne adresse",
|
||||
"notesLabel": "Særlige anmodninger",
|
||||
"notesOptional": "(valgfrit)",
|
||||
"notesPlaceholder": "Eventuelle særlige anmodninger eller noter om sangen...",
|
||||
"submitButton": "Betal $50 og bestil",
|
||||
"processing": "Behandler...",
|
||||
"paymentDisclaimer": "Sikker betaling via Stripe. 24-timers levering garanteret, eller pengene tilbage.",
|
||||
"paymentDisclaimer": "Sikker betaling via Stripe. 24-timers levering garanteret eller pengene tilbage.",
|
||||
"requiredField": "*",
|
||||
"artistRequired": "Indtast venligst kunstnerens navn",
|
||||
"titleRequired": "Indtast venligst sangens titel",
|
||||
"titleRequired": "Indtast venligst sangtitlen",
|
||||
"emailRequired": "Indtast venligst din e-mailadresse",
|
||||
"youtubeUrlRequired": "Indtast venligst en YouTube-URL",
|
||||
"submitError": "Noget gik galt. Prøv venligst igen."
|
||||
@@ -185,13 +185,13 @@
|
||||
"faq": {
|
||||
"title": "Spørgsmål?",
|
||||
"faq1Question": "Hvordan fungerer det?",
|
||||
"faq1Answer": "Indtast en kunstner og sangtitel (eller indsæt et YouTube-link, eller upload din egen lydfil). Vores system finder lyden, adskiller vokalen fra instrumentalen, transskriberer sangteksterne og synkroniserer dem til musikken. Du gennemgår og retter derefter eventuelle transskriptionsfejl, før vi genererer din endelige karaokevideo.",
|
||||
"faq1Answer": "Indtast en kunstner og sangtitel (eller indsæt et YouTube-link, eller upload din egen lydfil). Vores system finder lyden, adskiller vokalen fra instrumentalen, transskriberer sangteksterne og synkroniserer dem til musikken. Derefter gennemgår og retter du eventuelle transskriptionsfejl, før vi genererer din endelige karaokevideo.",
|
||||
"faq2Question": "Hvilke sange kan jeg bruge?",
|
||||
"faq2Answer": "Enhver sang! Søg efter kunstner og titel, indsæt en YouTube-URL, eller upload din egen lydfil. Hvis du kan skaffe lyden, kan vi lave den til karaoke.",
|
||||
"faq2Answer": "Enhver sang! Søg efter kunstner og titel, indsæt en YouTube-URL, eller upload din egen lydfil. Hvis du kan få fat i lyden, kan vi lave den til karaoke.",
|
||||
"faq3Question": "Hvilket format er outputtet?",
|
||||
"faq3Answer": "Du får flere filer: en 4K MP4-karaokevideo, en \"Med vokal\"-version til syng-med-øvelse og en CDG+MP3 ZIP til ældre karaokesystemer. Alle videoer udgives også på vores YouTube-kanal for nem deling.",
|
||||
"faq3Answer": "Du får flere filer: en 4K MP4 karaokevideo, en \"Med vokal\"-version til at øve dig på at synge med, og en CDG+MP3 ZIP til ældre karaokesystemer. Alle videoer udgives også på vores YouTube-kanal for nem deling.",
|
||||
"faq4Question": "Skal jeg gøre noget, eller er det fuldautomatisk?",
|
||||
"faq4Answer": "Sangteksttransskriptionen er meget nøjagtig, men du skal gennemgå den og rette eventuelle misforståede ord, før den endelige video genereres. For sange med tydelig vokal kan der være få eller ingen rettelser nødvendige. For komplekse sange skal du forvente at bruge 5-10 minutter på at rette fejl. Ord-timingen/synkroniseringen håndteres automatisk og er meget præcis.",
|
||||
"faq4Answer": "Sangteksttransskriptionen er meget nøjagtig, men du skal gennemgå den og rette eventuelle forkert hørte ord, før den endelige video genereres. For sange med tydelig vokal kan der være få eller ingen rettelser nødvendige. For komplekse sange kan du forvente at bruge 5-10 minutter på at rette fejl. Ordtimingen/synkroniseringen håndteres automatisk og er meget præcis.",
|
||||
"faq5Question": "Udløber credits?",
|
||||
"faq5Answer": "Nej! Dine credits udløber aldrig. Brug dem, når du vil."
|
||||
},
|
||||
@@ -207,32 +207,31 @@
|
||||
"refresh": "Opdater",
|
||||
"hideAdminControls": "Skjul admin-kontroller",
|
||||
"showAdminControls": "Vis admin-kontroller",
|
||||
"switchToLightMode": "Skift til lyst tema",
|
||||
"switchToDarkMode": "Skift til mørkt tema",
|
||||
"switchToLightMode": "Skift til lys tilstand",
|
||||
"switchToDarkMode": "Skift til mørk tilstand",
|
||||
"earnFreeCredit": "Tjen 1 gratis credit!",
|
||||
"feedbackPrompt": "Del din feedback om karaokeoprettelsesoplevelsen.",
|
||||
"feedbackPrompt": "Del din feedback om karaoke-oprettelsesoplevelsen.",
|
||||
"giveFeedback": "Giv feedback",
|
||||
"createKaraokeVideo": "Opret karaokevideo",
|
||||
"submitTrack": "Indsend nummer",
|
||||
"createDescription": "Gør enhver sang til en karaokevideo med synkroniserede sangtekster",
|
||||
"createDescription": "Forvandl enhver sang til en karaokevideo med synkroniserede sangtekster",
|
||||
"submitDescription": "Upload din mixede lyd og instrumental",
|
||||
"recentJobs": "Seneste job",
|
||||
"recentJobs": "Seneste jobs",
|
||||
"searchPlaceholder": "Søg...",
|
||||
"filterByStatus": "Filtrer efter status",
|
||||
"resultsPerPage": "Resultater pr. side",
|
||||
"allStatuses": "Alle statusser",
|
||||
"active": "Aktiv",
|
||||
"failed": "Fejlet",
|
||||
"completed": "Fuldført",
|
||||
"failed": "Mislykkedes",
|
||||
"completed": "Gennemført",
|
||||
"cancelled": "Annulleret",
|
||||
"awaitingReview": "Afventer gennemgang",
|
||||
"processing": "Behandler",
|
||||
"jobsMatchingFilters": "{count} {count, plural, one {job} other {jobs}} matcher filtrene",
|
||||
"jobsMatchingFilters": "{count} {count, plural, one {job} other {jobs}} matcher filtre",
|
||||
"jobsCount": "{count} {count, plural, one {job} other {jobs}}",
|
||||
"loadingJobs": "Indlæser job...",
|
||||
"noJobsMatchFilters": "Ingen job matcher dine filtre.",
|
||||
"noJobsYet": "Ingen job endnu. Opret et for at komme i gang!",
|
||||
"referrals": "Henvisninger"
|
||||
"loadingJobs": "Indlæser jobs...",
|
||||
"noJobsMatchFilters": "Ingen jobs matcher dine filtre.",
|
||||
"noJobsYet": "Ingen jobs endnu. Opret et for at komme i gang!"
|
||||
},
|
||||
"auth": {
|
||||
"noVerificationToken": "Ingen bekræftelsestoken angivet",
|
||||
@@ -241,21 +240,21 @@
|
||||
"preparingAccount": "Forbereder din konto...",
|
||||
"preparingWait": "Et øjeblik, mens vi gør tingene klar til dig.",
|
||||
"welcomeTitle": "Velkommen til Nomad Karaoke!",
|
||||
"freeCreditsGranted": "{count} gratis credits for at komme i gang",
|
||||
"freeCreditsGranted": "{count} gratis credits til at komme i gang",
|
||||
"freeCreditsExplanation": "Hver credit opretter én professionel karaokevideo.",
|
||||
"freeCreditsRequest": "Disse credits koster os rigtige penge at opfylde, så brug dem fornuftigt og lad os vide, hvad du synes!",
|
||||
"freeCreditsRequest": "Disse credits koster os rigtige penge at levere, så brug dem fornuftigt og lad os vide, hvad du synes!",
|
||||
"startCreating": "Begynd at oprette karaoke",
|
||||
"welcomeBack": "Velkommen tilbage til Nomad Karaoke",
|
||||
"creditsDeniedExplanation": "Vi var ikke i stand til at tildele gratis credits denne gang. Karaokegenerering koster os rigtige penge for hvert job, så vi skal være forsigtige med fordeling af gratis credits.",
|
||||
"creditsDeniedExplanation": "Vi kunne ikke tildele gratis credits denne gang. Karaoke-generering koster os rigtige penge for hvert job, så vi skal være forsigtige med fordelingen af gratis credits.",
|
||||
"creditsDeniedHelp": "Hvis du mener, at dette er en fejl, så tjek din e-mail — vi har sendt dig detaljer om, hvordan du kontakter os for at få dette løst.",
|
||||
"buyCredits": "Køb credits",
|
||||
"goToDashboard": "Gå til betjeningspanel",
|
||||
"goToDashboard": "Gå til kontrolpanel",
|
||||
"creditsPendingTitle": "Velkommen til Nomad Karaoke!",
|
||||
"creditsPendingExplanation": "Vi var ikke i stand til at tildele dine gratis credits automatisk denne gang. Vores team vil gennemgå din tilmelding snarest og tildele credits, hvis vi kan.",
|
||||
"creditsPendingExplanation": "Vi kunne ikke tildele dine gratis credits automatisk denne gang. Vores team vil gennemgå din tilmelding snarest og tildele credits, hvis vi kan.",
|
||||
"creditsPendingHint": "Du kan stadig udforske appen, mens du venter, eller købe credits for at komme i gang med det samme.",
|
||||
"exploreApp": "Udforsk appen",
|
||||
"successSignedIn": "Logget ind med succes!",
|
||||
"welcomeBackUser": "Velkommen tilbage, {email}!",
|
||||
"welcomeBackUser": "Velkommen tilbage{email}!",
|
||||
"redirectingToApp": "Omdirigerer dig til appen...",
|
||||
"signInFailed": "Login mislykkedes",
|
||||
"linkExpiredOrUsed": "Linket kan være udløbet eller allerede brugt.",
|
||||
@@ -265,16 +264,16 @@
|
||||
"dialog": {
|
||||
"title": "Log ind",
|
||||
"emailPrompt": "Indtast din e-mail for at modtage et login-link",
|
||||
"emailPlaceholder": "dig@eksempel.dk",
|
||||
"disposableEmailWarning": "Vi understøtter ikke engangs-e-mailadresser",
|
||||
"disposableEmailExplanation": "Vi vil meget gerne hjælpe dig med at oprette karaokevideoer! Brug venligst din almindelige e-mailadresse, så vi kan sende dig en besked, når din video er klar.",
|
||||
"noSpamPromise": "Vi lover — ingen spam, ingen markedsførings-e-mails, nogensinde. Vi sender dig kun e-mails om dine karaokevideoer.",
|
||||
"emailPlaceholder": "you@example.com",
|
||||
"disposableEmailWarning": "Vi understøtter ikke midlertidige e-mailadresser",
|
||||
"disposableEmailExplanation": "Vi vil meget gerne hjælpe dig med at oprette karaokevideoer! Brug venligst din almindelige e-mailadresse, så vi kan sende dig en notifikation, når din video er klar.",
|
||||
"noSpamPromise": "Vi lover — ingen spam, ingen markedsføringsmails, nogensinde. Vi sender dig kun e-mails om dine karaokevideoer.",
|
||||
"sendSignInLink": "Send login-link",
|
||||
"sending": "Sender...",
|
||||
"useAccessToken": "Brug adgangstoken i stedet",
|
||||
"noAccount": "Ingen konto? Indtast bare din e-mail for at komme i gang.",
|
||||
"noAccount": "Ingen konto? Indtast blot din e-mail for at komme i gang.",
|
||||
"checkEmailTitle": "Tjek din e-mail",
|
||||
"checkEmailSent": "Vi har sendt et login-link til:",
|
||||
"checkEmailSent": "Vi sendte et login-link til:",
|
||||
"checkEmailExpiry": "Klik på linket i e-mailen for at logge ind. Linket udløber om 15 minutter.",
|
||||
"tryDifferentEmail": "Prøv en anden e-mail",
|
||||
"accessTokenTitle": "Adgangstoken",
|
||||
@@ -283,7 +282,7 @@
|
||||
"authenticate": "Godkend",
|
||||
"authenticating": "Godkender...",
|
||||
"backToEmail": "Tilbage til e-mail-login",
|
||||
"contactAdmin": "Kontakt en admin for at få et adgangstoken"
|
||||
"contactAdmin": "Kontakt en administrator for at få et adgangstoken"
|
||||
},
|
||||
"status": {
|
||||
"displayName": "{name}",
|
||||
@@ -291,11 +290,9 @@
|
||||
"creditsAvailable": "{count} credits tilgængelige",
|
||||
"buyMoreCredits": "Køb flere credits",
|
||||
"earnFreeCredit": "Tjen 1 gratis credit",
|
||||
"showTestJobs": "Vis testjob",
|
||||
"showTestJobs": "Vis testjobs",
|
||||
"signOut": "Log ud",
|
||||
"login": "Log ind",
|
||||
"discountActive": "rabat aktiv",
|
||||
"discountActiveHint": "Klik for at vise rabatbanneret"
|
||||
"login": "Log ind"
|
||||
}
|
||||
},
|
||||
"payment": {
|
||||
@@ -307,32 +304,32 @@
|
||||
"confirmationEmail": "En bekræftelses-e-mail er blevet sendt til din e-mailadresse."
|
||||
},
|
||||
"order": {
|
||||
"title": "Ordre bekræftet!",
|
||||
"description": "Tak for din ordre. Vi opretter din tilpassede karaokevideo nu.",
|
||||
"title": "Bestilling bekræftet!",
|
||||
"description": "Tak for din bestilling. Vi opretter din tilpassede karaokevideo nu.",
|
||||
"deliveryTime": "Levering inden for 24 timer",
|
||||
"deliveryNote": "De fleste ordrer fuldføres på blot et par timer",
|
||||
"deliveryNote": "De fleste bestillinger gennemføres på få timer",
|
||||
"checkEmail": "Tjek din e-mail",
|
||||
"checkEmailNote": "Vi sender din video, når den er klar",
|
||||
"backToNomadKaraoke": "Tilbage til Nomad Karaoke",
|
||||
"questionsEmail": "Spørgsmål? Send os en e-mail på help@nomadkaraoke.com"
|
||||
},
|
||||
"header": {
|
||||
"dashboard": "Betjeningspanel",
|
||||
"myJobs": "Mine job",
|
||||
"dashboard": "Kontrolpanel",
|
||||
"myJobs": "Mine jobs",
|
||||
"admin": "Admin",
|
||||
"backToAdmin": "Tilbage til Admin",
|
||||
"needHelp": "Brug for hjælp?",
|
||||
"helpPrompt": "Er der noget, der er forvirrende eller ikke virker? Kontakt os når som helst!",
|
||||
"helpPrompt": "Noget, der er forvirrende eller ikke virker? Kontakt os når som helst!",
|
||||
"credits": "{count} credits",
|
||||
"account": "Konto",
|
||||
"adminRole": "Admin",
|
||||
"userRole": "Bruger",
|
||||
"adminDashboard": "Admin-betjeningspanel",
|
||||
"adminDashboard": "Admin-kontrolpanel",
|
||||
"settings": "Indstillinger",
|
||||
"logout": "Log ud"
|
||||
},
|
||||
"warmingUp": {
|
||||
"title": "Varmer Generator op...",
|
||||
"title": "Varmer generatoren op...",
|
||||
"almostThere": "Næsten der...",
|
||||
"firstLoadNote": "Første indlæsning kan tage op til 30 sekunder"
|
||||
},
|
||||
@@ -341,17 +338,17 @@
|
||||
"processing": "Behandler",
|
||||
"awaitingReview": "Afventer gennemgang",
|
||||
"selectInstrumental": "Vælg instrumental",
|
||||
"completed": "Fuldført",
|
||||
"failed": "Fejlet",
|
||||
"completed": "Gennemført",
|
||||
"failed": "Mislykkedes",
|
||||
"healthy": "Sund",
|
||||
"offline": "Offline",
|
||||
"deployed": "Udrullet {time}",
|
||||
"blueGreenDeployment": "Blå-grøn udrulning",
|
||||
"blueGreenDeployment": "Blue-Green Udrulning",
|
||||
"deploying": "udruller...",
|
||||
"primary": "Primær",
|
||||
"secondaryStopped": "Sekundær (stoppet)",
|
||||
"lastSwap": "Sidste skift: {time}",
|
||||
"activeJobs": "Aktive job: {count}",
|
||||
"activeJobs": "Aktive jobs: {count}",
|
||||
"systemStatus": "Systemstatus",
|
||||
"frontend": "Frontend",
|
||||
"backend": "Backend",
|
||||
@@ -381,7 +378,7 @@
|
||||
"lyricsAccuracy": "Nøjagtighed af sangtekster",
|
||||
"correctionExperience": "Rettelsesoplevelse",
|
||||
"whatWentWell": "Hvad gik godt?",
|
||||
"whatWentWellPlaceholder": "Hvad nød du ved at oprette karaokevideoer?",
|
||||
"whatWentWellPlaceholder": "Hvad kunne du lide ved at lave karaokevideoer?",
|
||||
"whatCouldBeBetter": "Hvad kunne være bedre?",
|
||||
"whatCouldBeBetterPlaceholder": "Hvad ville gøre oplevelsen bedre?",
|
||||
"additionalComments": "Yderligere kommentarer",
|
||||
@@ -417,7 +414,7 @@
|
||||
"addedDate": "Tilføjet {date}",
|
||||
"lastUsedDate": "Sidst brugt {date}",
|
||||
"removeDevice": "Fjern denne enhed",
|
||||
"maxDevicesNote": "Du kan have op til 5 enheder tilmeldt. Tilføjelse af flere vil fjerne den ældste tilmelding.",
|
||||
"maxDevicesNote": "Du kan have op til 5 enheder tilmeldt. Hvis du tilføjer flere, fjernes den ældste tilmelding.",
|
||||
"notAvailable": "Push-notifikationer er ikke tilgængelige på denne server.",
|
||||
"enabled": "Aktiveret",
|
||||
"disabled": "Deaktiveret"
|
||||
@@ -439,19 +436,19 @@
|
||||
"jobCreated": "Job oprettet",
|
||||
"whatsHappensNext": "Hvad sker der nu",
|
||||
"audioProcessing": "Lydbehandling",
|
||||
"audioProcessingDesc": "Vi downloader lyden, adskiller vokalen fra instrumentalen og transskriberer sangteksterne. ~10 minutter",
|
||||
"audioProcessingDesc": "Vi downloader lyden, adskiller vokal fra instrumental og transskriberer sangteksterne. ~10 minutter",
|
||||
"automatic": "Automatisk",
|
||||
"youEditTheAudio": "Du redigerer lyden",
|
||||
"youEditDesc": "Trim, klip eller dæmp sektioner af den downloadede lyd, før behandlingen begynder.",
|
||||
"you": "Dig",
|
||||
"emailChime": "E-mail + pling, når den er klar",
|
||||
"youEditDesc": "Beskær, klip eller dæmp sektioner af den downloadede lyd, før behandlingen begynder.",
|
||||
"you": "Du",
|
||||
"emailChime": "E-mail + lydnotifikation, når den er klar",
|
||||
"youReviewLyrics": "Du gennemgår sangtekster og instrumental",
|
||||
"youReviewDesc": "Tjek sangteksterne og lyt til instrumentalen. Ret eventuelle fejl og godkend.",
|
||||
"videoDelivered": "Video leveret",
|
||||
"videoDeliveredDesc": "Når du har godkendt, renderes din karaokevideo og uploades. ~10 minutter",
|
||||
"emailWithLink": "E-mail med link til at se",
|
||||
"trackProgress": "Følg fremskridt i listen over seneste job. Hold denne fane åben for at høre lyden.",
|
||||
"recentJobs": "Seneste job",
|
||||
"videoDeliveredDesc": "Når du har godkendt, bliver din karaokevideo renderet og uploadet. ~10 minutter",
|
||||
"emailWithLink": "E-mail med link til visning",
|
||||
"trackProgress": "Følg fremskridt i listen Seneste jobs. Hold denne fane åben for at høre lyden.",
|
||||
"recentJobs": "Seneste jobs",
|
||||
"createAnother": "Opret en anden",
|
||||
"noCreditsWarning": "Du har ingen credits tilbage. Køb credits for at oprette nye karaokevideoer.",
|
||||
"buyCredits": "Køb credits",
|
||||
@@ -470,7 +467,7 @@
|
||||
"chooseHowVideoDelivered": "Vælg, hvordan din færdige karaokevideo skal leveres.",
|
||||
"publishShare": "Udgiv og del",
|
||||
"keepPrivate": "Hold privat",
|
||||
"changeVisibilityAnytime": "Du kan ændre synligheden når som helst, efter at videoen er produceret.",
|
||||
"changeVisibilityAnytime": "Du kan ændre synligheden når som helst efter videoen er produceret.",
|
||||
"whatsDifference": "Hvad er forskellen?",
|
||||
"published": "Udgivet",
|
||||
"recommended": "Anbefalet",
|
||||
@@ -487,12 +484,12 @@
|
||||
"customStylingAvailable": "Tilpasset styling tilgængelig — vælg dine egne baggrundsbilleder, farver og tekststile på næste trin.",
|
||||
"confirmArtistTitle": "Bekræft kunstneren og titlen til dit titelkort.",
|
||||
"titleCardPreview": "Forhåndsvisning af titelkort",
|
||||
"titleCardArtist": "Titelkort Kunstner",
|
||||
"titleCardArtist": "Titelkort kunstner",
|
||||
"sameAsAbove": "(samme som ovenfor)",
|
||||
"artistOnTitleCard": "Kunstner på titelkort",
|
||||
"titleCardTitle": "Titelkort Titel",
|
||||
"titleCardTitle": "Titelkort titel",
|
||||
"titleOnTitleCard": "Titel på titelkort",
|
||||
"defaultsToSearchValues": "Disse er som standard dine søgeværdier. Overskriv for soundtracks, covers eller alternativ formatering.",
|
||||
"defaultsToSearchValues": "Disse er som standard dine søgeværdier. Tilsidesæt for soundtracks, covers eller alternativ formatering.",
|
||||
"customVideoStyle": "Tilpasset videostil",
|
||||
"titleCard": "Titelkort",
|
||||
"karaokeVideo": "Karaokevideo",
|
||||
@@ -511,9 +508,9 @@
|
||||
"lyricsTranscriptionDesc": "Vi transskriberer og synkroniserer sangtekster fra din lyd. ~5 minutter",
|
||||
"reviewLyrics": "Gennemgå sangtekster",
|
||||
"reviewLyricsDesc": "Tjek de synkroniserede sangtekster og ret eventuelle fejl.",
|
||||
"emailWhenReady": "E-mail, når den er klar",
|
||||
"afterApproval": "Efter godkendelse renderes og leveres din karaokevideo. ~10 minutter",
|
||||
"trackProgressTenant": "Følg fremskridt i listen over seneste job.",
|
||||
"emailWhenReady": "E-mail når den er klar",
|
||||
"afterApproval": "Efter godkendelse bliver din karaokevideo renderet og leveret. ~10 minutter",
|
||||
"trackProgressTenant": "Følg fremskridt i listen Seneste jobs.",
|
||||
"submitAnother": "Indsend et andet nummer"
|
||||
},
|
||||
"jobStatus": {
|
||||
@@ -536,7 +533,7 @@
|
||||
"reviewLyrics": "Gennemgå sangtekster",
|
||||
"inReview": "Under gennemgang",
|
||||
"startingRender": "Starter rendering",
|
||||
"renderingVideo": "Rendrer video",
|
||||
"renderingVideo": "Render video",
|
||||
"selectInstrumental": "Vælg instrumental",
|
||||
"startingFinalEncode": "Starter endelig kodning",
|
||||
"generatingFinalVideo": "Genererer endelig video",
|
||||
@@ -544,11 +541,11 @@
|
||||
"packagingFiles": "Pakker filer",
|
||||
"uploading": "Uploader",
|
||||
"sendingNotifications": "Sender notifikationer",
|
||||
"complete": "Fuldført",
|
||||
"prepComplete": "Forberedelse fuldført",
|
||||
"failed": "Fejlet",
|
||||
"complete": "Færdig",
|
||||
"prepComplete": "Forberedelse færdig",
|
||||
"failed": "Mislykkedes",
|
||||
"cancelled": "Annulleret",
|
||||
"processingComplete": "Behandling fuldført",
|
||||
"processingComplete": "Behandling færdig",
|
||||
"audio1of2": "Lyd 1/2",
|
||||
"audio2of2": "Lyd 2/2",
|
||||
"audioDone": "Lyd færdig",
|
||||
@@ -579,8 +576,8 @@
|
||||
"jobDeletedDesc": "Jobbet er blevet slettet permanent.",
|
||||
"retryFailed": "Prøv igen mislykkedes",
|
||||
"deleteFailed": "Sletning mislykkedes",
|
||||
"jobRetryStarted": "Jobforsøg startet",
|
||||
"jobRetryStartedDesc": "Jobbet forsøges igen. Opdaterer status..."
|
||||
"jobRetryStarted": "Job prøves igen",
|
||||
"jobRetryStartedDesc": "Jobbet prøves igen. Opdaterer status..."
|
||||
},
|
||||
"jobSubmission": {
|
||||
"search": "Søg",
|
||||
@@ -620,10 +617,10 @@
|
||||
"makingPrivate": "Gør privat...",
|
||||
"email": "E-mail",
|
||||
"admin": "Admin",
|
||||
"sendCompletionEmail": "Send fuldførelses-e-mail",
|
||||
"sendToEmailDesc": "Send jobfuldførelsesbeskeden til en e-mailadresse. E-mailen vil blive CC'et til gen@nomadkaraoke.com.",
|
||||
"sendCompletionEmail": "Send færdiggørelses-e-mail",
|
||||
"sendToEmailDesc": "Send jobfærdiggørelsesbeskeden til en e-mailadresse. E-mailen vil blive CC'et til gen@nomadkaraoke.com.",
|
||||
"emailAddress": "E-mail",
|
||||
"emailPlaceholder": "kunde@eksempel.dk",
|
||||
"emailPlaceholder": "kunde@example.com",
|
||||
"sendEmail": "Send e-mail",
|
||||
"sending": "Sender...",
|
||||
"sent": "Sendt!",
|
||||
@@ -634,19 +631,19 @@
|
||||
"regenerateTitleEndScreens": "Regenerere titel- og slutskærme",
|
||||
"reRenderWithDefault": "Gen-rendere karaokevideoen med standard branding",
|
||||
"publishToAll": "Udgiv til YouTube, Google Drive og Dropbox",
|
||||
"takes15To30Minutes": "Denne proces tager cirka 15-30 minutter. Du modtager en e-mail, når den er fuldført.",
|
||||
"takes15To30Minutes": "Denne proces tager cirka 15-30 minutter. Du modtager en e-mail, når den er færdig.",
|
||||
"customStylingRemoved": "Enhver tilpasset styling, du har anvendt, vil blive fjernet permanent.",
|
||||
"removeFromYoutube": "Fjerne videoen fra YouTube",
|
||||
"removeFromGoogleDrive": "Fjerne filer fra Google Drive",
|
||||
"moveDropboxPrivate": "Flytte Dropbox-filer fra den offentlige mappe til den private mappe",
|
||||
"assignPrivateBrand": "Tildele en ny privat brandkode",
|
||||
"assignPrivateBrand": "Tildele en ny privat brand-kode",
|
||||
"videoContentWontChange": "Videoindholdet ændres ikke. Dette tager normalt omkring 1-2 minutter.",
|
||||
"canChangeBack": "Du kan ændre det tilbage til offentligt senere, men det vil kræve gen-rendering af videoen (~15-30 minutter).",
|
||||
"copyYoutubeUrl": "Kopier YouTube-URL",
|
||||
"youtubeUrlCopied": "YouTube-URL kopieret",
|
||||
"copyDropboxUrl": "Kopier Dropbox-URL",
|
||||
"dropboxUrlCopied": "Dropbox-URL kopieret",
|
||||
"copyCompletionMessage": "Kopier fuldførelsesbesked til udklipsholder",
|
||||
"copyCompletionMessage": "Kopier færdiggørelsesbesked til udklipsholder",
|
||||
"copied": "Kopieret!"
|
||||
},
|
||||
"themeSelector": {
|
||||
@@ -663,8 +660,8 @@
|
||||
"artist": "Kunstner"
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Rediger fuldført nummer",
|
||||
"description": "Dette vil fjerne den aktuelle video fra YouTube, Dropbox og Google Drive.\nNår du har fuldført gennemgangen igen, vil en ny version blive renderet og gen-distribueret.",
|
||||
"title": "Rediger færdigt nummer",
|
||||
"description": "Dette vil fjerne den aktuelle video fra YouTube, Dropbox og Google Drive.\nNår du har gennemført gennemgangen igen, vil en ny version blive renderet og genudgivet.",
|
||||
"updateArtistTitle": "Jeg har brug for at opdatere kunstneren eller titlen",
|
||||
"artist": "Kunstner",
|
||||
"songTitle": "Titel",
|
||||
@@ -672,8 +669,8 @@
|
||||
"cleaningUp": "Rydder op..."
|
||||
},
|
||||
"communityVersion": {
|
||||
"exists": "Der findes allerede en karaokeversion af denne sang!",
|
||||
"checkFirst": "Tjek, om en eksisterende version fungerer for dig, før du bruger en credit.",
|
||||
"exists": "En karaokeversion af denne sang findes allerede!",
|
||||
"checkFirst": "Tjek om en eksisterende version fungerer for dig, før du bruger en credit.",
|
||||
"community": "Fællesskab",
|
||||
"watchOnYoutube": "Se på YouTube",
|
||||
"moreVersions": "+{count} flere {count, plural, one {version} other {versioner}}"
|
||||
@@ -687,15 +684,15 @@
|
||||
"colorOverrides": {
|
||||
"title": "Tilpas farver",
|
||||
"modified": "Ændret",
|
||||
"overrideThemeColors": "Overskriv temafarver (valgfrit)",
|
||||
"overrideThemeColors": "Tilsidesæt temafarver (valgfrit)",
|
||||
"resetAll": "Nulstil alle",
|
||||
"artistColor": "Kunstnerfarve",
|
||||
"artistColorDesc": "Farve til kunstnernavn på titel-/slutskærme",
|
||||
"titleColor": "Titelfarve",
|
||||
"titleColorDesc": "Farve til sangtitel på titel-/slutskærme",
|
||||
"sungLyricsColor": "Farve på sungne sangtekster",
|
||||
"sungLyricsColorDesc": "Farve til sangtekster, der bliver sunget (fremhævet)",
|
||||
"unsungLyricsColor": "Farve på usungne sangtekster",
|
||||
"sungLyricsColor": "Farve på sunget tekst",
|
||||
"sungLyricsColorDesc": "Farve til sangtekster, der synges (fremhævet)",
|
||||
"unsungLyricsColor": "Farve på usunget tekst",
|
||||
"unsungLyricsColorDesc": "Farve til sangtekster, der endnu ikke er sunget",
|
||||
"reset": "Nulstil"
|
||||
},
|
||||
@@ -705,8 +702,8 @@
|
||||
"tipsForChoosing": "Tips til at vælge",
|
||||
"tipFilename": "Tjek, at filnavnet matcher din sangtitel",
|
||||
"tipAvailability": "Grønt tilgængelighedsbadge = mere pålidelig download",
|
||||
"tipStudioAlbum": "Studiealbumversioner giver de bedste karaokeresultater",
|
||||
"tipVinylRips": "Undgå vinyl-rips (overfladestøj påvirker adskillelse)",
|
||||
"tipStudioAlbum": "Studiealbum-versioner giver de bedste karaoke-resultater",
|
||||
"tipVinylRips": "Undgå vinyl-rips (overfladestøj påvirker adskillelsen)",
|
||||
"tipYoutube": "YouTube er en sidste udvej — tabsfrie kilder lyder bedre",
|
||||
"noAudioSources": "Ingen lydkilder fundet",
|
||||
"lossless": "TABSFRIT",
|
||||
@@ -718,15 +715,15 @@
|
||||
"select": "Vælg"
|
||||
},
|
||||
"audioEditor": {
|
||||
"loading": "Indlæser lydredigeringsprogram...",
|
||||
"loading": "Indlæser lydredigering...",
|
||||
"failedToLoad": "Kunne ikke indlæse lyd",
|
||||
"couldNotLoadData": "Kunne ikke indlæse lyddata.",
|
||||
"backToDashboard": "Tilbage til betjeningspanel",
|
||||
"editComplete": "Lydredigering fuldført!",
|
||||
"backToDashboard": "Tilbage til kontrolpanel",
|
||||
"editComplete": "Lydredigering færdig!",
|
||||
"editsWillBeReviewed": "Dine redigeringer vil blive gennemgået, når videoen er færdigbehandlet.",
|
||||
"redirectingIn": "Omdirigerer om {count} sekunder...",
|
||||
"trimStart": "Trim start",
|
||||
"trimEnd": "Trim slut",
|
||||
"trimStart": "Beskær start",
|
||||
"trimEnd": "Beskær slut",
|
||||
"cutSelection": "Klip markering (Delete)",
|
||||
"muteSelection": "Dæmp markering (M)",
|
||||
"undo": "Fortryd (Ctrl+Z)",
|
||||
@@ -745,7 +742,7 @@
|
||||
"original": "Original",
|
||||
"edited": "Redigeret",
|
||||
"submitForReview": "Indsend til gennemgang",
|
||||
"continueWithoutEditing": "Fortsæt uden at redigere",
|
||||
"continueWithoutEditing": "Fortsæt uden redigering",
|
||||
"submitConfirmation": "Indsend dine lydredigeringer til gennemgang?",
|
||||
"mustCompleteEdit": "Du skal fuldføre lydredigeringer før indsendelse.",
|
||||
"editFailed": "Redigering mislykkedes",
|
||||
@@ -758,7 +755,7 @@
|
||||
"title": "Gemte lydredigeringssessioner",
|
||||
"checking": "Tjekker for gemte sessioner...",
|
||||
"editsApplied": "Handlinger anvendt:",
|
||||
"durationChange": "Varighedsændring: {change}",
|
||||
"durationChange": "Ændring af varighed: {change}",
|
||||
"netDuration": "Nettovarighed: {duration}",
|
||||
"selectToPreview": "Vælg en session for at forhåndsvise",
|
||||
"startFresh": "Start forfra",
|
||||
@@ -768,13 +765,13 @@
|
||||
},
|
||||
"lyricsReview": {
|
||||
"header": {
|
||||
"viewOnlyMode": "Kun visning-tilstand",
|
||||
"viewOnlyMode": "Kun visningstilstand",
|
||||
"loadFile": "Indlæs fil",
|
||||
"reviewMode": "Gennemgangstilstand",
|
||||
"reviewOff": "Gennemgang fra",
|
||||
"hideInlineActions": "Skjul indlejrede rettelseshandlinger",
|
||||
"showInlineActions": "Vis indlejrede handlinger på alle rettelser for hurtig gennemgang",
|
||||
"batchActions": "Batch-handlinger ({count} rettelser)",
|
||||
"hideInlineActions": "Skjul indbyggede rettelseshandlinger",
|
||||
"showInlineActions": "Vis indbyggede handlinger på alle rettelser for hurtig gennemgang",
|
||||
"batchActions": "Massehandlinger ({count} rettelser)",
|
||||
"acceptHighConfidence": "Accepter høj tillid ({count})",
|
||||
"acceptAll": "Accepter alle",
|
||||
"revertAll": "Gendan alle",
|
||||
@@ -786,7 +783,7 @@
|
||||
"findReplaceDesc": "Søg efter tekst på tværs af alle sangtekster og erstat den. Nyttigt for et ord, der optræder flere gange.",
|
||||
"editAll": "Rediger alle",
|
||||
"editAllDesc": "Vis og rediger alle sangtekster som almindelig tekst. Nyttigt, når mange linjer skal ændres.",
|
||||
"timingOffset": "Timingforskydning",
|
||||
"timingOffset": "Timing-forskydning",
|
||||
"timingOffsetValue": "{ms}ms",
|
||||
"timingOffsetDesc": "Forskyd alle ordtiminger frem eller tilbage. Brug, hvis sangtekster vises lidt tidligt eller sent i forhåndsvisningen.",
|
||||
"playback": "Afspilning"
|
||||
@@ -798,26 +795,26 @@
|
||||
"matched": "Matchet",
|
||||
"gapsNeedsReview": "Huller (kræver gennemgang)",
|
||||
"corrected": "Rettet",
|
||||
"noReferenceFound": "Der blev ikke fundet nogen referencetekster til dette nummer. Du kan stadig gennemgå transskriptionen og klikke på et hvilket som helst ord for at redigere det. Brug panelet Referencetekster til højre for at søge efter sangtekster med en anden kunstner/titel.",
|
||||
"allMatched": "Alle sangtekster matchede referencen — ingen rettelser nødvendige. Du kan stadig klikke på et hvilket som helst ord for at redigere det.",
|
||||
"noReferenceFound": "Der blev ikke fundet nogen referencetekster til dette nummer. Du kan stadig gennemgå transskriptionen og klikke på et hvilket som helst ord for at redigere. Brug panelet Referencetekster til højre for at søge efter sangtekster med en anden kunstner/titel.",
|
||||
"allMatched": "Alle sangtekster matchede referencen — ingen rettelser nødvendige. Du kan stadig klikke på et hvilket som helst ord for at redigere.",
|
||||
"syncedLyricsOnLeft": "De synkroniserede sangtekster til venstre er det, der vil vises i karaokevideoen.",
|
||||
"orangeHighlightedWords": "De orange fremhævede ord er huller — sektioner, der ikke kunne matches med referenceteksterne og kan indeholde fejl (f.eks. misforståede ord, der lyder ens).",
|
||||
"useNAndP": "Brug N og P til at hoppe mellem huller. For hver enkelt skal du klikke på afspil ved siden af linjen og sammenligne det, du hører, med referenceteksterne til højre, og derefter klikke på et ord for at redigere eller slette det.",
|
||||
"orangeHighlightedWords": "De orange fremhævede ord er huller — sektioner, der ikke kunne matches med referenceteksterne og kan indeholde fejl (f.eks. forkert hørte ord, der lyder ens).",
|
||||
"useNAndP": "Brug N og P til at hoppe mellem huller. For hver enkelt, klik på afspil ved siden af linjen og sammenlign det, du hører, med referenceteksterne til højre, og klik derefter på et ord for at redigere eller slette det.",
|
||||
"watchOutForPhantomWords": "Pas på fantomord som \"og\" i starten eller slutningen af linjer — transskriptionen tilføjer ofte disse.",
|
||||
"tryTimelineView": "Prøv Tidslinje-visningen for at spotte eventuelle usædvanligt lange ord (10+ sekunder), hvilket normalt indikerer et timingproblem.",
|
||||
"watchFullTutorial": "Se fuld vejledning",
|
||||
"tryTimelineView": "Prøv Tidslinje-visningen for at spotte usædvanligt lange ord (10+ sekunder), som normalt indikerer et timingproblem.",
|
||||
"watchFullTutorial": "Se hele vejledningen",
|
||||
"correctionHandlers": "Rettelseshåndterere",
|
||||
"anchorSequences": "Ankersekvenser",
|
||||
"anchorSequencesDesc": "Matchede sektioner mellem transskription og reference",
|
||||
"wordsInAnchors": "Ord i ankre",
|
||||
"multiSourceMatches": "Multi-kilde matches",
|
||||
"correctedGaps": "Rettede huller",
|
||||
"correctedGapsDesc": "Succesfuldt rettede sektioner",
|
||||
"correctedGapsDesc": "Vellykket rettede sektioner",
|
||||
"wordsReplaced": "Ord erstattet",
|
||||
"wordsAddedDeleted": "Ord tilføjet / slettet",
|
||||
"uncorrectedGaps": "Urettede huller",
|
||||
"uncorrectedGapsDesc": "Sektioner, der kan kræve manuel gennemgang",
|
||||
"wordsUncorrected": "Ord ikke rettet",
|
||||
"uncorrectedGapsDesc": "Sektioner, der muligvis kræver manuel gennemgang",
|
||||
"wordsUncorrected": "Ord urettet",
|
||||
"numberOfGaps": "Antal huller"
|
||||
},
|
||||
"transcription": {
|
||||
@@ -841,7 +838,7 @@
|
||||
"removed": "Fjernede \"{before}\", hvorfor?",
|
||||
"added": "Tilføjede \"{after}\", hvorfor?",
|
||||
"editMade": "Redigering foretaget, hvorfor?",
|
||||
"misheardWord": "Misforstået ord",
|
||||
"misheardWord": "Forkert hørt ord",
|
||||
"wrongLyrics": "Forkerte sangtekster",
|
||||
"spellingPunctuation": "Stavning/tegnsætning",
|
||||
"other": "Andet",
|
||||
@@ -866,7 +863,7 @@
|
||||
"modeSelector": {
|
||||
"mode": "Tilstand:",
|
||||
"edit": "Rediger",
|
||||
"editDesc": "Klik på et hvilket som helst ord for at redigere den sangtekstlinje. Standardtilstand til at rette misforståede ord.",
|
||||
"editDesc": "Klik på et hvilket som helst ord for at redigere den sangtekstlinje. Standardtilstand til at rette forkert hørte ord.",
|
||||
"highlight": "Fremhæv",
|
||||
"highlightDesc": "Klik på et hvilket som helst ord for at se, hvor det matcher i referenceteksterne. Genvej: hold SHIFT nede.",
|
||||
"delete": "Slet",
|
||||
@@ -884,18 +881,18 @@
|
||||
"sessionRestore": {
|
||||
"title": "Gemte gennemgangssessioner",
|
||||
"thisJob": "Dette job ({count})",
|
||||
"allJobs": "Alle job",
|
||||
"allJobs": "Alle jobs",
|
||||
"searchPlaceholder": "Søg efter kunstner, titel eller job-ID...",
|
||||
"noSessions": "Ingen gemte sessioner fundet",
|
||||
"searchAcrossAllJobs": "Søg efter sessioner på tværs af alle job",
|
||||
"searchAcrossAllJobs": "Søg efter sessioner på tværs af alle jobs",
|
||||
"selectToPreview": "Vælg en session for at forhåndsvise ændringer",
|
||||
"startFresh": "Start forfra",
|
||||
"restoreSelected": "Gendan valgte",
|
||||
"durationMismatchTitle": "Varighedsuoverensstemmelse",
|
||||
"durationMismatchTitle": "Forskel i varighed",
|
||||
"durationMismatchDesc": "Den valgte session er fra et nummer med en anden varighed:",
|
||||
"thisJobDuration": "Dette job:",
|
||||
"sourceSessionDuration": "Kildesession:",
|
||||
"timingMayNotMatch": "Timingjustering matcher muligvis ikke. Ordtidsstempler fra kildesessionen vil blive bevaret som de er.",
|
||||
"timingMayNotMatch": "Timingjustering matcher muligvis ikke. Ordtidsstempler fra kildesessionen bevares som de er.",
|
||||
"restoreAnyway": "Gendan alligevel",
|
||||
"noWordChanges": "Ingen ændringer på ordniveau registreret i denne session.",
|
||||
"changesAcrossSegments": "{changes} {changes, plural, one {ændring} other {ændringer}} på tværs af {segments} segmenter"
|
||||
@@ -946,7 +943,7 @@
|
||||
"reject": "Afvis",
|
||||
"modify": "Modificer",
|
||||
"finalText": "Endelig tekst",
|
||||
"finalTextPlaceholder": "Indtast den modificerede tekst...",
|
||||
"finalTextPlaceholder": "Indtast den ændrede tekst...",
|
||||
"reason": "Årsag",
|
||||
"aiCorrect": "AI_KORREKT",
|
||||
"aiIncorrect": "AI_FORKERT",
|
||||
@@ -983,57 +980,41 @@
|
||||
"modeSelection": {
|
||||
"title": "Rediger alle sangtekster",
|
||||
"chooseMethod": "Vælg, hvordan du vil redigere sangteksterne:",
|
||||
"resyncTitle": "Gen-synkroniser eksisterende sangtekster",
|
||||
"resyncTitle": "Gensynkroniser eksisterende sangtekster",
|
||||
"resyncDesc": "Behold den aktuelle sangtekst og ret timingproblemer. Brug dette, når sangteksterne er korrekte, men timingen er skredet, især i anden halvdel af sangen.",
|
||||
"resyncRecommended": "Anbefales til at rette timingskred",
|
||||
"replaceSegmentTitle": "Erstat segmentsangtekster",
|
||||
"resyncRecommended": "Anbefales til at rette timing-skred",
|
||||
"replaceSegmentTitle": "Erstat segment-sangtekster",
|
||||
"replaceSegmentDesc": "Rediger eller indsæt nye sangtekster for hver linje. Timingen bevares — kun ordene ændres. Bedst til tilpassede sangtekster, oversættelser eller rettelse af flere linjer på én gang.",
|
||||
"replaceSegmentRecommended": "Anbefales til tilpassede sangtekster",
|
||||
"replaceAllTitle": "Erstat alle sangtekster",
|
||||
"replaceAllDesc": "Indsæt helt nye sangtekster fra udklipsholderen og synkroniser timingen manuelt for alle ord fra bunden.",
|
||||
"replaceAllWarning": "Alle eksisterende timingdata vil gå tabt",
|
||||
"changeCaseDesc": "Konverter hele teksten til STORE BOGSTAVER, små bogstaver, Stort Begyndelsesbogstav eller Sætningsstil. Timingen bevares fuldt ud.",
|
||||
"changeCaseRecommended": "Anbefales for stilmæssig konsistens",
|
||||
"changeCaseTitle": "Skift store/små bogstaver"
|
||||
"replaceAllWarning": "Alle eksisterende timingdata vil gå tabt"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Indsæt dine nye sangtekster nedenfor:",
|
||||
"eachLineNote": "Hver linje bliver til et separat segment. Ord vil blive adskilt af mellemrum.",
|
||||
"eachLineNote": "Hver linje bliver et separat segment. Ord vil blive adskilt af mellemrum.",
|
||||
"pasteFromClipboard": "Indsæt fra udklipsholder",
|
||||
"lineWordCount": "{lines} linjer, {words} ord",
|
||||
"placeholder": "Indsæt dine sangtekster her...\nHver linje bliver til et segment\nOrd vil blive adskilt af mellemrum",
|
||||
"placeholder": "Indsæt dine sangtekster her...\nHver linje bliver et segment\nOrd vil blive adskilt af mellemrum",
|
||||
"continueToSync": "Fortsæt til synkronisering",
|
||||
"replaceAll": "Erstat alle sangtekster",
|
||||
"replaceSegment": "Erstat segmentsangtekster",
|
||||
"editLineByLine": "Rediger sangtekster linje for linje. Hver linje svarer til et tidsindstillet segment. Antallet af linjer skal forblive det samme (i øjeblikket: {count} linjer). Ændrede linjer vil få ny ordtiming estimeret fra segmentets varighed. Uændrede linjer efterlades som de er.",
|
||||
"tooManyLines": "Du har {diff} for mange linjer (forventede {expected}, fik {actual}). Hver linje knyttes til et tidsindstillet segment, så antallet skal matche nøjagtigt.",
|
||||
"tooFewLines": "Du har {diff} for få linjer (forventede {expected}, fik {actual}). Hver linje knyttes til et tidsindstillet segment, så antallet skal matche nøjagtigt.",
|
||||
"replaceSegment": "Erstat segment-sangtekster",
|
||||
"editLineByLine": "Rediger sangtekster linje for linje. Hver linje svarer til et tidsindstillet segment. Antallet af linjer skal forblive det samme (i øjeblikket: {count} linjer). Ændrede linjer får ny ordtiming estimeret ud fra segmentets varighed. Uændrede linjer efterlades som de er.",
|
||||
"tooManyLines": "Du har {diff} for mange linjer (forventet {expected}, fik {actual}). Hver linje knyttes til et tidsindstillet segment, så antallet skal matche nøjagtigt.",
|
||||
"tooFewLines": "Du har {diff} for få linjer (forventet {expected}, fik {actual}). Hver linje knyttes til et tidsindstillet segment, så antallet skal matche nøjagtigt.",
|
||||
"syncNewLyrics": "Synkroniser nye sangtekster",
|
||||
"resyncExisting": "Gen-synkroniser eksisterende sangtekster",
|
||||
"resyncExisting": "Gensynkroniser eksisterende sangtekster",
|
||||
"noLyricsToSync": "Ingen sangtekster at synkronisere",
|
||||
"goBackAndPaste": "Gå tilbage og indsæt nye sangtekster, eller luk denne modal.",
|
||||
"backToSelection": "Tilbage til valg",
|
||||
"caseLower": "små bogstaver",
|
||||
"caseLowerDesc": "alle bogstaver er små",
|
||||
"caseSentence": "Sætningsstil",
|
||||
"caseSentenceDesc": "Første ord i hver linje med stort",
|
||||
"caseTitle": "Stort Begyndelsesbogstav",
|
||||
"caseTitleDesc": "Alle Ord Med Stort",
|
||||
"caseUpper": "STORE BOGSTAVER",
|
||||
"caseUpperDesc": "ALLE BOGSTAVER MED STORT",
|
||||
"changeCase": "Skift store/små bogstaver",
|
||||
"changeCaseApply": "Anvend {case}",
|
||||
"changeCaseNote": "Ordtimingen bevares fuldt ud — kun store/små bogstaver ændres.",
|
||||
"changeCasePreview": "Forhåndsvisning",
|
||||
"changeCasePrompt": "Vælg en stil for store/små bogstaver, der skal anvendes på hele teksten:"
|
||||
"backToSelection": "Tilbage til valg"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Forhåndsvisningsvideo (med vokal)",
|
||||
"noLyricsTitle": "Ingen sangtekster opdaget",
|
||||
"noLyricsTitle": "Ingen sangtekster registreret",
|
||||
"noLyricsDesc": "Der blev ikke fundet nogen sangtekster i lyden. Dette sker normalt, når inputlyden ikke har nogen vokal (f.eks. et karaokenummer eller instrumental).",
|
||||
"noLyricsHint": "Du kan gå tilbage og indsætte sangtekster manuelt ved hjælp af Erstat alle, eller annullere dette job og prøve igen med en lydfil, der indeholder vokal.",
|
||||
"manualCorrectionsDetected": "Manuelle rettelser opdaget. Gennemgå forhåndsvisningen for at sikre, at sangteksterne er synkroniseret korrekt.",
|
||||
"noManualCorrections": "Ingen manuelle rettelser opdaget. Hvis alt ser godt ud i forhåndsvisningen, skal du fortsætte med at vælge din instrumental.",
|
||||
"manualCorrectionsDetected": "Manuelle rettelser registreret. Gennemgå forhåndsvisningen for at sikre, at sangteksterne er synkroniseret korrekt.",
|
||||
"noManualCorrections": "Ingen manuelle rettelser registreret. Hvis alt ser godt ud i forhåndsvisningen, skal du fortsætte med at vælge din instrumental.",
|
||||
"totalSegments": "Samlede segmenter: {count}",
|
||||
"proceedToInstrumental": "Fortsæt til gennemgang af instrumental",
|
||||
"saving": "Gemmer..."
|
||||
@@ -1049,7 +1030,7 @@
|
||||
"searchAgain": "Søg igen",
|
||||
"noMatches": "Ingen matchende sangtekster fundet på tværs af alle udbydere.",
|
||||
"notFound": "Ikke fundet: {sources}",
|
||||
"lowConfidence": "Resultater med lav tillid — vælg en for at gennemtvinge tilføjelse:",
|
||||
"lowConfidence": "Resultater med lav tillid — vælg enhver for at gennemtvinge tilføjelse:",
|
||||
"matched": "Match: {matched}/{total} ord ({relevance}% relevans)",
|
||||
"addSelected": "Tilføj valgte ({count})"
|
||||
},
|
||||
@@ -1057,7 +1038,7 @@
|
||||
"title": "Segment {index} detaljer"
|
||||
},
|
||||
"timingOffset": {
|
||||
"title": "Juster timingforskydning",
|
||||
"title": "Juster timing-forskydning",
|
||||
"offsetLabel": "Forskydning (millisekunder)",
|
||||
"offsetDesc": "Positive værdier forskyder sangtekster senere, negative værdier forskyder dem tidligere.",
|
||||
"currentOffset": "Nuværende forskydning:",
|
||||
@@ -1067,7 +1048,7 @@
|
||||
},
|
||||
"pasteLyrics": {
|
||||
"sourceName": "Kildenavn",
|
||||
"sourceNamePlaceholder": "f.eks., manuel, genius, azlyrics...",
|
||||
"sourceNamePlaceholder": "f.eks., manual, genius, azlyrics...",
|
||||
"lyrics": "Sangtekster",
|
||||
"lyricsPlaceholder": "Indsæt sangtekster her...",
|
||||
"addLyrics": "Tilføj sangtekster",
|
||||
@@ -1088,36 +1069,36 @@
|
||||
"referenceSources": "Konsulterede referencekilder:",
|
||||
"correctionType": "Rettelsestype *",
|
||||
"types": {
|
||||
"soundAlike": "Forvekslede ord (lyder ens)",
|
||||
"soundAlikeDesc": "Homofoner eller enslydende ord (f.eks. \"out\" vs \"now\")",
|
||||
"soundAlike": "Ord der lyder ens",
|
||||
"soundAlikeDesc": "Homofoner eller ord, der lyder ens (f.eks. \"out\" vs \"now\")",
|
||||
"backgroundVocals": "Baggrundsvokal",
|
||||
"backgroundVocalsDesc": "Baggrundsvokal, der skal fjernes fra karaoke",
|
||||
"backgroundVocalsDesc": "Backingvokal, der skal fjernes fra karaoke",
|
||||
"extraFiller": "Ekstra fyldord",
|
||||
"extraFillerDesc": "Transskription tilføjede ord som \"Og\", \"Men\", \"Nå\"",
|
||||
"punctuation": "Kun tegnsætning/stil",
|
||||
"punctuationDesc": "Kun forskelle i tegnsætning eller store/små bogstaver",
|
||||
"repeatedSection": "Gentaget sektion",
|
||||
"repeatedSectionDesc": "Omkvæd eller versgentagelse ikke i kondenserede referencer",
|
||||
"complexMultiError": "Kompleks multi-fejl",
|
||||
"complexMultiError": "Kompleks fejl (flere typer)",
|
||||
"complexMultiErrorDesc": "Flere forskellige fejltyper i én sektion",
|
||||
"ambiguous": "Tvetydig",
|
||||
"ambiguousDesc": "Uklar uden at lytte til lyd",
|
||||
"noError": "Ingen fejl",
|
||||
"noErrorDesc": "Transskription matcher mindst én referencekilde",
|
||||
"manualEdit": "Manuel redigering",
|
||||
"manualEditDesc": "Menneske-initieret rettelse ikke fra opdaget hul"
|
||||
"manualEditDesc": "Menneske-initieret rettelse ikke fra registreret hul"
|
||||
},
|
||||
"confidence": "Tillid til din rettelse *",
|
||||
"confidenceLevels": {
|
||||
"1": "1 - Meget usikker",
|
||||
"2": "2 - Noget usikker",
|
||||
"3": "3 - Neutral",
|
||||
"4": "4 - Ret sikker",
|
||||
"4": "4 - Rimelig sikker",
|
||||
"5": "5 - Meget sikker"
|
||||
},
|
||||
"reasoning": "Ræsonnement *",
|
||||
"reasoningPlaceholder": "Forklar, hvorfor denne rettelse er nødvendig (minimum 10 tegn)...",
|
||||
"minChars": "{count}/10 minimum tegn",
|
||||
"minChars": "{count}/10 minimumstegn",
|
||||
"skip": "Spring over",
|
||||
"saveAndContinue": "Gem og fortsæt"
|
||||
}
|
||||
@@ -1125,14 +1106,14 @@
|
||||
"synchronizer": {
|
||||
"wordsSynced": "{synced} / {total} ord synkroniseret",
|
||||
"remaining": "({remaining} tilbage)",
|
||||
"holdingRelease": "Holder... slip, når ordet slutter",
|
||||
"holdingRelease": "Holder... slip når ordet slutter",
|
||||
"releaseSpacebar": "Slip mellemrumstasten, når ordet er færdigt",
|
||||
"allWordsSynced": "Alle ord synkroniseret!",
|
||||
"clickStopSync": "Klik på \"Stop synkronisering\" og derefter \"Anvend\" for at gemme",
|
||||
"pressSpacebar": "Tryk på MELLEMRUMSTASTEN, når du hører hvert ord",
|
||||
"tapForShort": "Tryk for korte ord, hold for længere ord",
|
||||
"tapForShort": "Tryk for korte ord, hold nede for længere ord",
|
||||
"clickStartSync": "Klik på \"Start synkronisering\" for at begynde at time ord",
|
||||
"audioWillPlay": "Lyden vil spille, og du skal trykke på mellemrumstasten for hvert ord",
|
||||
"audioWillPlay": "Lyden afspilles, og du trykker på mellemrumstasten for hvert ord",
|
||||
"wordsRemaining": "{remaining} ord tilbage at synkronisere",
|
||||
"clickStartContinue": "Klik på \"Start synkronisering\" for at fortsætte, eller \"Fjern synkronisering fra markør\" for at gen-synkronisere fra et punkt",
|
||||
"allSyncedApply": "Alle ord synkroniseret! Klik på \"Anvend\" for at gemme ændringer, eller foretag justeringer først",
|
||||
@@ -1141,7 +1122,7 @@
|
||||
"saveAndResetTiming": "Gem og nulstil timing",
|
||||
"editWord": "Rediger ord",
|
||||
"editWordDesc": "Rediger ordteksten. Indtast flere ord adskilt af mellemrum for at dele.",
|
||||
"editWordPlaceholder": "Indtast den modificerede tekst...",
|
||||
"editWordPlaceholder": "Indtast den ændrede tekst...",
|
||||
"controls": {
|
||||
"play": "Afspil",
|
||||
"stop": "Stop",
|
||||
@@ -1162,7 +1143,7 @@
|
||||
},
|
||||
"instrumentalReview": {
|
||||
"separationInProgress": "Lydadskillelse i gang",
|
||||
"separationInProgressDesc": "Lydsporene bliver stadig adskilt. Dette tager normalt et par minutter. Denne side opdateres automatisk, når adskillelsen er fuldført.",
|
||||
"separationInProgressDesc": "Lydstems bliver stadig adskilt. Dette tager normalt et par minutter. Denne side opdateres automatisk, når adskillelsen er færdig.",
|
||||
"loadingAnalysis": "Indlæser instrumentalanalyse...",
|
||||
"review": "Gennemgå",
|
||||
"title": "Gennemgang af instrumental",
|
||||
@@ -1179,26 +1160,26 @@
|
||||
"redirecting": "Omdirigerer...",
|
||||
"selectionSubmitted": "Valg indsendt",
|
||||
"youSelected": "Du valgte: {label}",
|
||||
"backToDashboard": "Tilbage til betjeningspanel",
|
||||
"backToDashboard": "Tilbage til kontrolpanel",
|
||||
"shiftDrag": "Shift+træk",
|
||||
"space": "Mellemrum",
|
||||
"loadingAudio": "Indlæser lyd...",
|
||||
"noOptionsAvailable": "Ingen instrumentalmuligheder tilgængelige.",
|
||||
"selectTrack": "Vælg instrumentalnummer",
|
||||
"required": "Påkrævet",
|
||||
"backingVocalsDetected": "{percentage}% baggrundsvokal opdaget",
|
||||
"backingVocalsDetected": "{percentage}% baggrundsvokal registreret",
|
||||
"segmentsCount": "({count} segmenter)",
|
||||
"backingVocalsIncluded": "Inkluderer baggrundsvokal fra originalen",
|
||||
"cleanDescription": "Ingen baggrundsvokal - ren instrumental",
|
||||
"guidance": {
|
||||
"chooseBackingTrack": "Vælg dit karaoke-backing track. AI'en adskilte vokalen fra musikken — vælg nu, hvilken version der lyder bedst.",
|
||||
"chooseBackingTrack": "Vælg dit karaoke-backingtrack. AI'en adskilte vokalen fra musikken — vælg nu, hvilken version der lyder bedst.",
|
||||
"littleBackingVocals": "Dette nummer har meget lidt baggrundsvokalindhold ({percentage}%). Vi anbefaler den rene instrumental — bekræft blot nedenfor for at fortsætte.",
|
||||
"hearDifference": "Vil du høre forskellen? Brug lydknapperne ovenfor til at sammenligne, eller klik på de lyserøde sektioner i bølgeformen for at lytte til baggrundsvokalen.",
|
||||
"watchFullTutorial": "Se fuld vejledning",
|
||||
"backingVocalsExplanation": "Baggrundsvokal er harmoni-/omkvædsstemmerne, der synger med på leadvokalen. Nogle karaokesangere foretrækker at beholde dem som vejledning, andre foretrækker en ren instrumental.",
|
||||
"watchFullTutorial": "Se hele vejledningen",
|
||||
"backingVocalsExplanation": "Baggrundsvokal er harmoni-/omkvædsstemmerne, der synger med på hovedvokalen. Nogle karaokesangere foretrækker at beholde dem som vejledning, andre foretrækker en ren instrumental.",
|
||||
"step1": "Trin 1: Klik på de lyserøde sektioner i bølgeformen for at høre baggrundsvokalen{segments}.",
|
||||
"step2": "Trin 2: Beslut — behold dem eller brug den rene instrumental? Brug lydskifteknapperne ovenfor til at sammenligne.",
|
||||
"step3": "Trin 3 (hvis nødvendigt): Hvis du vil have baggrundsvokal, men nogle sektioner har uønsket leadvokal-bleed, skal du bruge Shift+træk på bølgeformen for at markere disse sektioner og derefter klikke på Opret tilpasset.",
|
||||
"step2": "Trin 2: Beslut dig — behold dem eller brug den rene instrumental? Brug lydskifteknapperne ovenfor til at sammenligne.",
|
||||
"step3": "Trin 3 (hvis nødvendigt): Hvis du vil have baggrundsvokal, men nogle sektioner har uønsket hovedvokal-bleed, skal du Shift+trække på bølgeformen for at markere disse sektioner og derefter klikke på Opret tilpasset.",
|
||||
"showTips": "Vis tips",
|
||||
"dismissTip": "Afvis tip"
|
||||
},
|
||||
@@ -1209,13 +1190,13 @@
|
||||
"withBackingVocals": "Med baggrundsvokal",
|
||||
"allBackingVocalsIncluded": "Al baggrundsvokal inkluderet",
|
||||
"originalAudio": "Original lyd",
|
||||
"fullOriginalWithVocals": "Fuld original med leadvokal",
|
||||
"fullOriginalWithVocals": "Fuld original med hovedvokal",
|
||||
"custom": "Tilpasset",
|
||||
"customRegionsMuted": "{count} {count, plural, one {region} other {regioner}} dæmpet",
|
||||
"uploaded": "Uploadet",
|
||||
"customFile": "Tilpasset instrumentalfil",
|
||||
"recommended": "Anbefalet",
|
||||
"veryFewVocals": "Meget få baggrundsvokaler opdaget ({percentage}%)",
|
||||
"veryFewVocals": "Meget få baggrundsvokaler registreret ({percentage}%)",
|
||||
"significantVocals": "Betydelig baggrundsvokal ({percentage}%) — kan forbedre karaokeoplevelsen"
|
||||
},
|
||||
"stemComparison": {
|
||||
@@ -1236,134 +1217,10 @@
|
||||
"clear": "Ryd",
|
||||
"createCustom": "Opret tilpasset",
|
||||
"creating": "Opretter...",
|
||||
"explanation": "Vil du have baggrundsvokal, men hører leadvokal-bleed i nogle sektioner? Dæmp disse sektioner for at oprette et tilpasset mix.",
|
||||
"explanation": "Vil du have baggrundsvokal, men hører hovedvokal-bleed i nogle sektioner? Dæmp disse sektioner for at oprette et tilpasset mix.",
|
||||
"clickSegment": "Klik på et segment nedenfor for at dæmpe det, eller Shift+træk på bølgeformen for at markere en tilpasset region.",
|
||||
"noBackingDetected": "Ingen baggrundsvokal opdaget — ren instrumental anbefales.",
|
||||
"noBackingDetected": "Ingen baggrundsvokal registreret — ren instrumental anbefales.",
|
||||
"addToMuteRegions": "Tilføj til dæmpede regioner"
|
||||
}
|
||||
},
|
||||
"referrals": {
|
||||
"title": "Henvisninger",
|
||||
"backToDashboard": "Tilbage til betjeningspanel",
|
||||
"howItWorksTitle": "Sådan fungerer det",
|
||||
"howItWorksIntro": "Tjen penge ved at dele Nomad Karaoke med dine venner, dit publikum eller dit fællesskab. Det er simpelt — del dit unikke link, og når folk tilmelder sig og foretager køb, drager I begge fordel af det.",
|
||||
"howStep1Title": "Del dit link",
|
||||
"howStep1Desc": "Send dit unikke henvisningslink til venner eller del det på sociale medier, din hjemmeside eller til begivenheder.",
|
||||
"howStep2Title": "De får rabat",
|
||||
"howStep2Desc": "Alle, der tilmelder sig via dit link, får {discount}% rabat på alle creditkøb i {days} dage.",
|
||||
"howStep3Title": "Du tjener penge",
|
||||
"howStep3Desc": "Du tjener {kickback}% af hvert køb, de foretager inden for {days} dage efter tilmelding.",
|
||||
"howPayoutTitle": "Hvornår får jeg betaling?",
|
||||
"howPayoutDesc": "Indtjening akkumuleres på din saldo. Når du når $20 og har forbundet din bankkonto via Stripe, sendes udbetalinger automatisk. Du kan spore alt lige her på denne side.",
|
||||
"yourLink": "Dit henvisningslink",
|
||||
"copyLink": "Kopier link",
|
||||
"copied": "Kopieret!",
|
||||
"vanityRequest": "Vil du have en tilpasset URL? Anmod om et personligt link",
|
||||
"vanityPlaceholder": "dit-navn",
|
||||
"vanitySubmit": "Anmod",
|
||||
"vanityRequested": "Anmodning sendt! Vi vender tilbage til dig snart.",
|
||||
"displayName": "Visningsnavn",
|
||||
"customMessage": "Tilpasset besked",
|
||||
"customMessagePlaceholder": "Fortæl dine venner, hvorfor de skal prøve Nomad Karaoke...",
|
||||
"save": "Gem",
|
||||
"stats": "Statistik",
|
||||
"clicks": "Klik",
|
||||
"signups": "Tilmeldinger",
|
||||
"purchases": "Køb",
|
||||
"earnings": "Indtjening",
|
||||
"pendingBalance": "Afventende saldo",
|
||||
"totalEarned": "Samlet indtjent",
|
||||
"totalPaid": "Samlet udbetalt",
|
||||
"termDiscount": "Rabat for henvisninger",
|
||||
"termDiscountWindow": "Rabatvindue",
|
||||
"termKickback": "Din provision",
|
||||
"termEarningWindow": "Indtjeningsvindue",
|
||||
"recentEarnings": "Seneste indtjening",
|
||||
"recentPayouts": "Seneste udbetalinger",
|
||||
"noEarnings": "Ingen indtjening endnu. Del dit link for at begynde at tjene!",
|
||||
"noPayouts": "Ingen udbetalinger endnu.",
|
||||
"connectBank": "Forbind bankkonto",
|
||||
"connectDescription": "Forbind din bankkonto via Stripe for at modtage henvisningsudbetalinger, når din saldo når $20.",
|
||||
"connectComplete": "Bankkonto forbundet!",
|
||||
"payoutThreshold": "Udbetalinger sendes automatisk, når din saldo når $20.",
|
||||
"interstitialTitle": "Du er blevet henvist!",
|
||||
"interstitialReferred": "Henvist af {name}",
|
||||
"interstitialDiscount": "Nyd {percent}% rabat på alle creditkøb i {days} dage",
|
||||
"interstitialCta": "Kom i gang",
|
||||
"discountBadge": "{percent}% henvisningsrabat",
|
||||
"discountActive": "Henvisningsrabat aktiv — {percent}% rabat i {days} dage mere",
|
||||
"cancel": "Annuller",
|
||||
"editProfile": "Rediger visningsnavn og besked",
|
||||
"qrCode": "QR-kode",
|
||||
"qrOrFlyer": "QR-kode / Flyer",
|
||||
"qrTitle": "QR-kodegenerator",
|
||||
"qrDotStyle": "Prikstil",
|
||||
"qrCornerFrame": "Hjørneramme",
|
||||
"qrCornerDot": "Hjørneprik",
|
||||
"qrColors": "Farver",
|
||||
"qrForeground": "Forgrund",
|
||||
"qrBackground": "Baggrund",
|
||||
"qrLogo": "Centerlogo",
|
||||
"qrLogoNone": "Ingen",
|
||||
"qrLogoNomad": "NK Logo",
|
||||
"qrLogoEmoji": "Emoji",
|
||||
"qrDownloadPng": "Download PNG",
|
||||
"qrDownloadSvg": "Download SVG",
|
||||
"qrStyleSquare": "Firkantet",
|
||||
"qrStyleRounded": "Afrundet",
|
||||
"qrStyleDots": "Prikker",
|
||||
"qrStyleClassy": "Stilfuld",
|
||||
"qrStyleClassyRounded": "Stilfuld afrundet",
|
||||
"qrStyleExtraRounded": "Ekstra afrundet",
|
||||
"qrStyleDot": "Prik",
|
||||
"flyerTheme": "Flyer-tema",
|
||||
"flyerThemeLight": "Lyst",
|
||||
"flyerThemeDark": "Mørkt",
|
||||
"flyerGenerate": "Generer flyer",
|
||||
"flyerGenerating": "Genererer...",
|
||||
"appliedAtCheckout": "Anvendes automatisk ved kassen",
|
||||
"expires": "Udløber {date}",
|
||||
"referredBy": "Henvist af {name}",
|
||||
"usingCode": "Kode: {code}",
|
||||
"connectBankLoading": "Gør klar...",
|
||||
"connectDetailsNeeded": "Stripe har brug for yderligere oplysninger for at aktivere udbetalinger. Klik på \"Opdater bankkonto\" nedenfor for at fuldføre opsætningen.",
|
||||
"connectRefresh": "Det ser ud til, at du ikke blev færdig med at opsætte din bankkonto. Klik nedenfor for at prøve igen.",
|
||||
"connectStatusActive": "Udbetalinger aktiveret",
|
||||
"connectStatusPending": "Opsætning i gang",
|
||||
"connectStripeNote": "Du vil blive viderestillet til Stripes sikre side for at indtaste dine bankoplysninger. Det tager normalt et par minutter.",
|
||||
"flyerAccentColor": "Accentfarve",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Farver",
|
||||
"flyerDownloadHtml": "Download HTML",
|
||||
"flyerDownloadPdf": "Download PDF",
|
||||
"flyerDownloadPng": "Download PNG",
|
||||
"flyerEditQr": "Rediger QR-stil",
|
||||
"flyerExporting": "Eksporterer...",
|
||||
"flyerHeadlineGradient": "Overskriftsgradient",
|
||||
"flyerHeadlineSubColor": "Underoverskrift",
|
||||
"flyerMargins": "Sidemargener",
|
||||
"flyerPerPage": "Flyers pr. side",
|
||||
"flyerPresetCustom": "Brugerdefineret",
|
||||
"flyerPresetName": "Navn på forudindstilling",
|
||||
"flyerPresetSave": "Gem forudindstilling",
|
||||
"flyerPrintLayout": "Udskriftslayout",
|
||||
"flyerSections": "Sektioner",
|
||||
"flyerSubtextColor": "Undertekst",
|
||||
"flyerTextColor": "Tekst",
|
||||
"flyerTextOverrides": "Tilpasning af tekst",
|
||||
"flyerToggleDivider": "Skillelinje",
|
||||
"flyerToggleFeatures": "Funktioner i bunden",
|
||||
"flyerToggleSteps": "Trin til 'Sådan fungerer det'",
|
||||
"flyerToggleSubtitle": "Undertitel",
|
||||
"flyerToggleTagline": "Slogan i bunden",
|
||||
"flyerUploadLogo": "Upload logo",
|
||||
"managePayouts": "Administrer udbetalinger",
|
||||
"payoutTitle": "Udbetalinger & bankkonto",
|
||||
"tabFlyer": "Udskriftsvenlig flyer",
|
||||
"tabQrCode": "QR-kode",
|
||||
"toolsTitle": "QR-kode & Flyer Generator",
|
||||
"updateBankAccount": "Opdater bankkonto",
|
||||
"connectFailed": "Noget gik galt. Prøv venligst igen.",
|
||||
"flyerRemoveLogo": "Fjern"
|
||||
}
|
||||
}
|
||||
+260
-403
File diff suppressed because it is too large.
Load diff
+224
-367
File diff suppressed because it is too large.
Load diff
@@ -292,8 +292,6 @@
|
||||
"buyMoreCredits": "Buy More Credits",
|
||||
"earnFreeCredit": "Earn 1 Free Credit",
|
||||
"showTestJobs": "Show Test Jobs",
|
||||
"discountActive": "discount active",
|
||||
"discountActiveHint": "Click to show discount banner",
|
||||
"signOut": "Sign Out",
|
||||
"login": "Login"
|
||||
}
|
||||
@@ -991,10 +989,7 @@
|
||||
"replaceSegmentRecommended": "Recommended for custom lyrics",
|
||||
"replaceAllTitle": "Replace All Lyrics",
|
||||
"replaceAllDesc": "Paste completely new lyrics from clipboard and manually sync timing for all words from scratch.",
|
||||
"replaceAllWarning": "All existing timing data will be lost",
|
||||
"changeCaseTitle": "Change Case",
|
||||
"changeCaseDesc": "Convert all lyrics to UPPERCASE, lowercase, Title Case, or Sentence case. Timing is fully preserved.",
|
||||
"changeCaseRecommended": "Recommended for style consistency"
|
||||
"replaceAllWarning": "All existing timing data will be lost"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Paste your new lyrics below:",
|
||||
@@ -1012,20 +1007,7 @@
|
||||
"resyncExisting": "Re-sync Existing Lyrics",
|
||||
"noLyricsToSync": "No lyrics to sync",
|
||||
"goBackAndPaste": "Go back and paste new lyrics, or close this modal.",
|
||||
"backToSelection": "Back to Selection",
|
||||
"changeCase": "Change Case",
|
||||
"changeCasePrompt": "Choose a case style to apply to all lyrics:",
|
||||
"changeCaseNote": "Word timing is fully preserved — only letter case changes.",
|
||||
"caseUpper": "UPPERCASE",
|
||||
"caseLower": "lowercase",
|
||||
"caseTitle": "Title Case",
|
||||
"caseSentence": "Sentence case",
|
||||
"caseUpperDesc": "ALL LETTERS CAPITALIZED",
|
||||
"caseLowerDesc": "all letters lowercase",
|
||||
"caseTitleDesc": "Every Word Capitalized",
|
||||
"caseSentenceDesc": "First word of each line capitalized",
|
||||
"changeCasePreview": "Preview",
|
||||
"changeCaseApply": "Apply {case}"
|
||||
"backToSelection": "Back to Selection"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Preview Video (With Vocals)",
|
||||
@@ -1244,24 +1226,9 @@
|
||||
},
|
||||
"referrals": {
|
||||
"title": "Referrals",
|
||||
"backToDashboard": "Back to Dashboard",
|
||||
"howItWorksTitle": "How It Works",
|
||||
"howItWorksIntro": "Earn money by sharing Nomad Karaoke with your friends, audience, or community. It's simple — share your unique link, and when people sign up and make purchases, you both benefit.",
|
||||
"howStep1Title": "Share your link",
|
||||
"howStep1Desc": "Send your unique referral link to friends or share it on social media, your website, or at events.",
|
||||
"howStep2Title": "They get a discount",
|
||||
"howStep2Desc": "Anyone who signs up through your link gets {discount}% off all credit purchases for {days} days.",
|
||||
"howStep3Title": "You earn cash",
|
||||
"howStep3Desc": "You earn {kickback}% of every purchase they make within {days} days of signing up.",
|
||||
"howPayoutTitle": "When do I get paid?",
|
||||
"howPayoutDesc": "Earnings accumulate in your balance. Once you reach $20 and have connected your bank account via Stripe, payouts are sent automatically. You can track everything right here on this page.",
|
||||
"yourLink": "Your Referral Link",
|
||||
"copyLink": "Copy Link",
|
||||
"copied": "Copied!",
|
||||
"vanityRequest": "Want a custom URL? Request a vanity link",
|
||||
"vanityPlaceholder": "your-name",
|
||||
"vanitySubmit": "Request",
|
||||
"vanityRequested": "Request sent! We'll get back to you soon.",
|
||||
"displayName": "Display Name",
|
||||
"customMessage": "Custom Message",
|
||||
"customMessagePlaceholder": "Tell your friends why they should try Nomad Karaoke...",
|
||||
@@ -1274,42 +1241,23 @@
|
||||
"pendingBalance": "Pending Balance",
|
||||
"totalEarned": "Total Earned",
|
||||
"totalPaid": "Total Paid Out",
|
||||
"termDiscount": "Discount for referrals",
|
||||
"termDiscountWindow": "Discount window",
|
||||
"termKickback": "Your kickback",
|
||||
"termEarningWindow": "Earning window",
|
||||
"recentEarnings": "Recent Earnings",
|
||||
"recentPayouts": "Recent Payouts",
|
||||
"noEarnings": "No earnings yet. Share your link to start earning!",
|
||||
"noPayouts": "No payouts yet.",
|
||||
"payoutTitle": "Payouts & Bank Account",
|
||||
"connectBank": "Connect Bank Account",
|
||||
"connectBankLoading": "Setting up...",
|
||||
"connectDescription": "Connect your bank account via Stripe to receive referral payouts when your balance reaches $20.",
|
||||
"connectStripeNote": "You'll be redirected to Stripe's secure site to enter your bank details. This usually takes a couple of minutes.",
|
||||
"connectFailed": "Something went wrong. Please try again.",
|
||||
"connectComplete": "Stripe Connect setup complete! Your bank account is now linked for payouts.",
|
||||
"connectRefresh": "It looks like you didn't finish setting up your bank account. Click below to try again.",
|
||||
"connectStatusActive": "Payouts enabled",
|
||||
"connectStatusPending": "Setup in progress",
|
||||
"connectDetailsNeeded": "Stripe needs additional information to enable payouts. Click \"Update Bank Account\" below to complete setup.",
|
||||
"managePayouts": "Manage Payouts",
|
||||
"updateBankAccount": "Update Bank Account",
|
||||
"connectComplete": "Bank account connected!",
|
||||
"payoutThreshold": "Payouts are automatically sent when your balance reaches $20.",
|
||||
"interstitialTitle": "You've been referred!",
|
||||
"interstitialReferred": "Referred by {name}",
|
||||
"interstitialDiscount": "Enjoy {percent}% off all credit purchases for {days} days",
|
||||
"interstitialCta": "Get Started",
|
||||
"discountBadge": "{percent}% referral discount",
|
||||
"referredBy": "Referred by {name}",
|
||||
"usingCode": "Code: {code}",
|
||||
"appliedAtCheckout": "Applied automatically at checkout",
|
||||
"expires": "Expires {date}",
|
||||
"discountActive": "Referral discount active — {percent}% off for {days} more days",
|
||||
"cancel": "Cancel",
|
||||
"editProfile": "Edit display name & message",
|
||||
"qrCode": "QR Code",
|
||||
"qrOrFlyer": "QR Code / Flyer",
|
||||
"qrTitle": "QR Code Generator",
|
||||
"qrDotStyle": "Dot Style",
|
||||
"qrCornerFrame": "Corner Frame",
|
||||
@@ -1319,8 +1267,9 @@
|
||||
"qrBackground": "Background",
|
||||
"qrLogo": "Center Logo",
|
||||
"qrLogoNone": "None",
|
||||
"qrLogoNomad": "NK Logo",
|
||||
"qrLogoEmoji": "Emoji",
|
||||
"qrLogoNomad": "Nomad Karaoke",
|
||||
"qrLogoMic": "Microphone",
|
||||
"qrLogoMusic": "Music",
|
||||
"qrDownloadPng": "Download PNG",
|
||||
"qrDownloadSvg": "Download SVG",
|
||||
"qrStyleSquare": "Square",
|
||||
@@ -1329,41 +1278,6 @@
|
||||
"qrStyleClassy": "Classy",
|
||||
"qrStyleClassyRounded": "Classy Rounded",
|
||||
"qrStyleExtraRounded": "Extra Rounded",
|
||||
"qrStyleDot": "Dot",
|
||||
"flyerTheme": "Flyer Theme",
|
||||
"flyerThemeLight": "Light",
|
||||
"flyerThemeDark": "Dark",
|
||||
"flyerGenerate": "Generate Flyer",
|
||||
"flyerGenerating": "Generating...",
|
||||
"toolsTitle": "QR Code & Flyer Generator",
|
||||
"tabQrCode": "QR Code",
|
||||
"tabFlyer": "Printable Flyer",
|
||||
"flyerPresetCustom": "Custom",
|
||||
"flyerPresetName": "Preset name",
|
||||
"flyerPresetSave": "Save Preset",
|
||||
"flyerColors": "Colors",
|
||||
"flyerHeadlineGradient": "Headline Gradient",
|
||||
"flyerHeadlineSubColor": "Headline Sub",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerSubtextColor": "Subtext",
|
||||
"flyerAccentColor": "Accent",
|
||||
"flyerTextOverrides": "Text Overrides",
|
||||
"flyerSections": "Sections",
|
||||
"flyerToggleSubtitle": "Subtitle",
|
||||
"flyerToggleSteps": "How It Works Steps",
|
||||
"flyerToggleDivider": "Divider",
|
||||
"flyerToggleFeatures": "Bottom Features",
|
||||
"flyerToggleTagline": "Bottom Tagline",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerUploadLogo": "Upload Logo",
|
||||
"flyerRemoveLogo": "Remove",
|
||||
"flyerPrintLayout": "Print Layout",
|
||||
"flyerPerPage": "Flyers Per Page",
|
||||
"flyerMargins": "Page Margins",
|
||||
"flyerEditQr": "Edit QR Style",
|
||||
"flyerDownloadPdf": "Download PDF",
|
||||
"flyerDownloadHtml": "Download HTML",
|
||||
"flyerDownloadPng": "Download PNG",
|
||||
"flyerExporting": "Exporting..."
|
||||
"qrStyleDot": "Dot"
|
||||
}
|
||||
}
|
||||
+144
-287
@@ -57,38 +57,38 @@
|
||||
"heroCTA": {
|
||||
"createYourself": "Créalo tú mismo",
|
||||
"createYourselfPrice": "$10",
|
||||
"createYourselfNote": "1 crédito gratis incluido - no requiere pago",
|
||||
"makeForYou": "Lo hacemos por ti",
|
||||
"createYourselfNote": "1 crédito gratis incluido - sin necesidad de pago",
|
||||
"makeForYou": "Lo haremos por ti",
|
||||
"makeForYouPrice": "$50",
|
||||
"makeForYouNote": "Nos encargamos de todo, entregado en 24h"
|
||||
},
|
||||
"demoVideo": {
|
||||
"title": "Demo de Nomad Karaoke"
|
||||
"title": "Demostración de Nomad Karaoke"
|
||||
},
|
||||
"howItWorks": {
|
||||
"title": "Cómo funciona",
|
||||
"step1Title": "Elige una canción",
|
||||
"step1Desc": "Busca, pega un enlace de YouTube o sube audio",
|
||||
"step1Desc": "Busca, pega un enlace de YouTube o sube un audio",
|
||||
"step2Title": "Hacemos el trabajo pesado",
|
||||
"step2Desc": "Voces eliminadas, letras transcritas y sincronizadas",
|
||||
"step2Desc": "Voz principal eliminada, letras transcritas y sincronizadas",
|
||||
"step3Title": "Revisa y corrige",
|
||||
"step3Desc": "Corrige cualquier error de transcripción (usualmente 5-10 min)",
|
||||
"step4Title": "Obtén tu video",
|
||||
"step4Desc": "Descarga archivos o míralo en nuestro YouTube",
|
||||
"step4Desc": "Descarga los archivos o míralo en nuestro YouTube",
|
||||
"tutorialTitle": "¿Quieres un recorrido más detallado?",
|
||||
"tutorialDesc": "Mira el tutorial completo para ver cada paso en detalle — desde crear un trabajo hasta descargar tu video terminado.",
|
||||
"tutorialDesc": "Mira el tutorial completo para ver cada paso en detalle — desde la creación de un trabajo hasta la descarga de tu video terminado.",
|
||||
"tutorialVideoTitle": "Tutorial completo de Nomad Karaoke"
|
||||
},
|
||||
"features": {
|
||||
"title": "Lo que obtienes",
|
||||
"feature1Title": "Instrumentales reales",
|
||||
"feature1Desc": "Usa el instrumental real de tu canción, no una banda de covers o recreación MIDI.",
|
||||
"feature1Desc": "Usa el instrumental real de tu canción, no una banda de covers ni una recreación MIDI.",
|
||||
"feature2Title": "Sincronización de letras precisa",
|
||||
"feature2Desc": "Sincronización palabra por palabra que resalta exactamente cuándo cantar. Tú haces la revisión de letras para mayor precisión.",
|
||||
"feature2Desc": "Sincronización palabra por palabra que resalta exactamente cuándo cantar. Tú realizas la revisión de letras para asegurar la precisión.",
|
||||
"feature3Title": "Mantén o elimina los coros",
|
||||
"feature3Desc": "Elige un instrumental limpio o uno que conserve los coros para un sonido más completo.",
|
||||
"feature4Title": "Video 4K + Múltiples formatos",
|
||||
"feature4Desc": "Obtén un video de karaoke en 4K, una versión para cantar junto con voces, y CDG+MP3 para sistemas más antiguos.",
|
||||
"feature4Desc": "Obtén un video de karaoke en 4K, una versión para cantar junto con las voces, y CDG+MP3 para sistemas más antiguos.",
|
||||
"feature5Title": "Publicado en YouTube",
|
||||
"feature5Desc": "Cada video se publica automáticamente en nuestro canal de YouTube para compartirlo fácilmente.",
|
||||
"feature6Title": "Control total antes de exportar",
|
||||
@@ -99,7 +99,7 @@
|
||||
"subtitle": "Así es como se ve el proceso en cada paso",
|
||||
"jobCreationAlt": "Flujo guiado de creación de trabajo con entrada de artista y título",
|
||||
"jobCreationTitle": "Crea tu video",
|
||||
"jobCreationDesc": "Ingresa cualquier canción y encontramos el mejor audio automáticamente",
|
||||
"jobCreationDesc": "Ingresa cualquier canción y encontraremos el mejor audio automáticamente",
|
||||
"lyricsReviewAlt": "Revisión de letras con letras sincronizadas junto a letras de referencia para corrección",
|
||||
"lyricsReviewTitle": "Revisión de letras",
|
||||
"lyricsReviewDesc": "Compara las letras sincronizadas con las referencias y corrige cualquier error",
|
||||
@@ -108,7 +108,7 @@
|
||||
"instrumentalReviewDesc": "Escucha las opciones de audio y elige la mejor pista de acompañamiento",
|
||||
"exampleOutputAlt": "Trabajo de karaoke completado con opciones de descarga para 4K, 720p, CDG y más",
|
||||
"exampleOutputTitle": "Descarga y comparte",
|
||||
"exampleOutputDesc": "Obtén tu video 4K, 720p, CDG y más en minutos"
|
||||
"exampleOutputDesc": "Obtén tu video en 4K, 720p, CDG y más en minutos"
|
||||
},
|
||||
"pricing": {
|
||||
"title": "Precios simples",
|
||||
@@ -124,7 +124,7 @@
|
||||
"continuePayment": "Continuar al pago",
|
||||
"redirecting": "Redirigiendo...",
|
||||
"secureCheckout": "Pago seguro",
|
||||
"poweredByStripe": "desarrollado por Stripe",
|
||||
"poweredByStripe": "impulsado por Stripe",
|
||||
"creditUnit": "crédito",
|
||||
"creditsUnit": "créditos",
|
||||
"perVideo": "/video",
|
||||
@@ -133,24 +133,24 @@
|
||||
},
|
||||
"madeForYou": {
|
||||
"badgeLabel": "Opción de servicio completo",
|
||||
"title": "Lo hacemos por ti",
|
||||
"subtitle": "¿No quieres usar el Generator y hacer la revisión de letras tú mismo? No hay problema. Dinos la canción, paga $50 y te entregaremos tu video de karaoke en 24 horas.",
|
||||
"title": "Lo haremos por ti",
|
||||
"subtitle": "¿No quieres usar el Generator y realizar la revisión de letras tú mismo? No hay problema. Dinos la canción, paga $50 y te entregaremos tu video de karaoke en 24 horas.",
|
||||
"secondarySubtitle": "¿No quieres pasar 10 minutos revisando letras? Por solo $10 más que hacerlo tú mismo, nos encargamos de todo.",
|
||||
"benefitsTitle": "Lo que obtienes",
|
||||
"benefit1Title": "Video 4K profesional",
|
||||
"benefit1Desc": "Video de karaoke de alta calidad con letras perfectamente sincronizadas",
|
||||
"benefit1Desc": "Video de karaoke de alta calidad con letras sincronizadas perfectamente",
|
||||
"benefit2Title": "Entrega en 24 horas",
|
||||
"benefit2Desc": "Nos encargamos de todo — solo espera a que llegue tu video",
|
||||
"benefit3Title": "Todos los formatos incluidos",
|
||||
"benefit3Desc": "Video MP4, CDG+MP3 para máquinas de karaoke, pistas de audio",
|
||||
"benefit4Title": "Más de 1000 ejemplos reales en YouTube",
|
||||
"benefit4Desc": "Explora nuestro canal de YouTube para ver exactamente lo que obtendrás",
|
||||
"benefit4Desc": "Navega por nuestro canal de YouTube para ver exactamente lo que obtendrás",
|
||||
"deliveryIncludesTitle": "Tu entrega incluye:",
|
||||
"delivery1": "Video MP4 4K sin pérdida con pantalla de título",
|
||||
"delivery2": "Versión 720p optimizada para web",
|
||||
"delivery3": "CDG+MP3 para máquinas de karaoke",
|
||||
"delivery4": "Audio instrumental (con o sin coros)",
|
||||
"delivery5": "Versión para \"cantar junto\" con voces originales",
|
||||
"delivery5": "Versión para cantar junto con las voces originales",
|
||||
"orderFormTitle": "Pedir un video",
|
||||
"orderPrice": "$50",
|
||||
"artistLabel": "Artista",
|
||||
@@ -160,7 +160,7 @@
|
||||
"audioSourceLabel": "Fuente de audio",
|
||||
"autoSearchLabel": "Búsqueda automática",
|
||||
"youtubeUrlLabel": "URL de YouTube",
|
||||
"fileUploadLabel": "Subida de archivo",
|
||||
"fileUploadLabel": "Subir archivo",
|
||||
"autoSearchHint": "Encontraremos automáticamente el audio de mejor calidad para tu canción.",
|
||||
"youtubeUrlHint": "Proporciona un enlace de YouTube a la canción que deseas.",
|
||||
"fileUploadHint": "Sube tu propio archivo de audio (contáctanos después de hacer el pedido).",
|
||||
@@ -169,31 +169,31 @@
|
||||
"emailLabel2": "Tu correo electrónico",
|
||||
"emailPlaceholder2": "tu@ejemplo.com",
|
||||
"emailHint2": "Enviaremos tus archivos de video a esta dirección",
|
||||
"notesLabel": "Peticiones especiales",
|
||||
"notesLabel": "Solicitudes especiales",
|
||||
"notesOptional": "(opcional)",
|
||||
"notesPlaceholder": "Cualquier petición especial o nota sobre la canción...",
|
||||
"notesPlaceholder": "Cualquier solicitud especial o nota sobre la canción...",
|
||||
"submitButton": "Pagar $50 y pedir",
|
||||
"processing": "Procesando...",
|
||||
"paymentDisclaimer": "Pago seguro vía Stripe. Entrega garantizada en 24 horas o te devolvemos tu dinero.",
|
||||
"paymentDisclaimer": "Pago seguro a través de Stripe. Entrega en 24 horas garantizada o te devolvemos tu dinero.",
|
||||
"requiredField": "*",
|
||||
"artistRequired": "Por favor ingresa el nombre del artista",
|
||||
"titleRequired": "Por favor ingresa el título de la canción",
|
||||
"emailRequired": "Por favor ingresa tu correo electrónico",
|
||||
"youtubeUrlRequired": "Por favor ingresa una URL de YouTube",
|
||||
"submitError": "Algo salió mal. Por favor intenta de nuevo."
|
||||
"submitError": "Algo salió mal. Por favor, inténtalo de nuevo."
|
||||
},
|
||||
"faq": {
|
||||
"title": "¿Preguntas?",
|
||||
"faq1Question": "¿Cómo funciona?",
|
||||
"faq1Answer": "Ingresa un artista y título de canción (o pega un enlace de YouTube, o sube tu propio archivo de audio). Nuestro sistema encuentra el audio, separa las voces del instrumental, transcribe las letras y las sincroniza con la música. Luego revisas y corriges cualquier error de transcripción antes de que generemos tu video de karaoke final.",
|
||||
"faq1Answer": "Ingresa un artista y el título de la canción (o pega un enlace de YouTube, o sube tu propio archivo de audio). Nuestro sistema encuentra el audio, separa la voz principal del instrumental, transcribe las letras y las sincroniza con la música. Luego realizas la revisión de letras y corriges cualquier error de transcripción antes de que generemos tu video de karaoke final.",
|
||||
"faq2Question": "¿Qué canciones puedo usar?",
|
||||
"faq2Answer": "¡Cualquier canción! Busca por artista y título, pega una URL de YouTube o sube tu propio archivo de audio. Si puedes conseguir el audio, podemos convertirlo en karaoke.",
|
||||
"faq3Question": "¿En qué formato es la salida?",
|
||||
"faq3Answer": "Obtienes múltiples archivos: un video de karaoke MP4 en 4K, una versión \"Con voces\" para practicar y cantar junto, y un ZIP con CDG+MP3 para sistemas de karaoke más antiguos. Todos los videos también se publican en nuestro canal de YouTube para compartirlos fácilmente.",
|
||||
"faq4Question": "¿Necesito hacer algo, o es completamente automático?",
|
||||
"faq4Answer": "La transcripción de letras es muy precisa, pero tendrás que revisarla y corregir cualquier palabra mal escuchada antes de que se genere el video final. Para canciones con voces claras, puede que haya pocas o ninguna corrección necesaria. Para canciones complejas, espera pasar de 5 a 10 minutos arreglando errores. La sincronización de tiempo de las palabras se maneja automáticamente y es muy precisa.",
|
||||
"faq5Question": "¿Los créditos expiran?",
|
||||
"faq5Answer": "¡No! Tus créditos nunca expiran. Úsalos cuando quieras."
|
||||
"faq4Question": "¿Necesito hacer algo o es completamente automático?",
|
||||
"faq4Answer": "La transcripción de letras es muy precisa, pero tendrás que revisarla y corregir cualquier palabra mal escuchada antes de que se genere el video final. Para canciones con voces claras, es posible que se necesiten pocas o ninguna corrección. Para canciones complejas, espera pasar de 5 a 10 minutos arreglando errores. El tiempo/sincronización de las palabras se maneja automáticamente y es muy preciso.",
|
||||
"faq5Question": "¿Los créditos caducan?",
|
||||
"faq5Answer": "¡No! Tus créditos nunca caducan. Úsalos cuando quieras."
|
||||
},
|
||||
"footer": {
|
||||
"logo": "Nomad Karaoke",
|
||||
@@ -207,8 +207,8 @@
|
||||
"refresh": "Actualizar",
|
||||
"hideAdminControls": "Ocultar controles de administrador",
|
||||
"showAdminControls": "Mostrar controles de administrador",
|
||||
"switchToLightMode": "Cambiar a modo claro",
|
||||
"switchToDarkMode": "Cambiar a modo oscuro",
|
||||
"switchToLightMode": "Cambiar al modo claro",
|
||||
"switchToDarkMode": "Cambiar al modo oscuro",
|
||||
"earnFreeCredit": "¡Gana 1 crédito gratis!",
|
||||
"feedbackPrompt": "Comparte tus comentarios sobre la experiencia de creación de karaoke.",
|
||||
"giveFeedback": "Dar comentarios",
|
||||
@@ -231,8 +231,7 @@
|
||||
"jobsCount": "{count} {count, plural, one {trabajo} other {trabajos}}",
|
||||
"loadingJobs": "Cargando trabajos...",
|
||||
"noJobsMatchFilters": "Ningún trabajo coincide con tus filtros.",
|
||||
"noJobsYet": "Aún no hay trabajos. ¡Crea uno para empezar!",
|
||||
"referrals": "Referencias"
|
||||
"noJobsYet": "Aún no hay trabajos. ¡Crea uno para empezar!"
|
||||
},
|
||||
"auth": {
|
||||
"noVerificationToken": "No se proporcionó token de verificación",
|
||||
@@ -243,11 +242,11 @@
|
||||
"welcomeTitle": "¡Bienvenido a Nomad Karaoke!",
|
||||
"freeCreditsGranted": "{count} créditos gratis para empezar",
|
||||
"freeCreditsExplanation": "Cada crédito crea un video de karaoke profesional.",
|
||||
"freeCreditsRequest": "Estos créditos nos cuestan dinero real, así que úsalos sabiamente y cuéntanos qué te parece.",
|
||||
"freeCreditsRequest": "Estos créditos nos cuestan dinero real, así que por favor úsalos sabiamente y cuéntanos qué te parece.",
|
||||
"startCreating": "Empezar a crear karaoke",
|
||||
"welcomeBack": "Bienvenido de nuevo a Nomad Karaoke",
|
||||
"creditsDeniedExplanation": "No pudimos otorgar créditos gratis esta vez. La generación de karaoke nos cuesta dinero real por cada trabajo, por lo que debemos tener cuidado con la distribución de créditos gratis.",
|
||||
"creditsDeniedHelp": "Si crees que esto es un error, revisa tu correo — te hemos enviado detalles sobre cómo contactarnos para resolverlo.",
|
||||
"creditsDeniedExplanation": "No pudimos otorgar créditos gratis esta vez. La generación de karaoke nos cuesta dinero real por cada trabajo, por lo que debemos tener cuidado con la distribución de créditos gratuitos.",
|
||||
"creditsDeniedHelp": "Si crees que esto es un error, revisa tu correo electrónico — te hemos enviado detalles sobre cómo contactarnos para resolver esto.",
|
||||
"buyCredits": "Comprar créditos",
|
||||
"goToDashboard": "Ir al panel",
|
||||
"creditsPendingTitle": "¡Bienvenido a Nomad Karaoke!",
|
||||
@@ -255,28 +254,28 @@
|
||||
"creditsPendingHint": "Aún puedes explorar la aplicación mientras esperas, o comprar créditos para empezar de inmediato.",
|
||||
"exploreApp": "Explorar la aplicación",
|
||||
"successSignedIn": "¡Sesión iniciada con éxito!",
|
||||
"welcomeBackUser": "¡Bienvenido de nuevo{email}!",
|
||||
"welcomeBackUser": "¡Bienvenido de nuevo, {email}!",
|
||||
"redirectingToApp": "Redirigiéndote a la aplicación...",
|
||||
"signInFailed": "Error al iniciar sesión",
|
||||
"linkExpiredOrUsed": "El enlace puede haber expirado o ya haber sido usado.",
|
||||
"linkExpiredOrUsed": "El enlace puede haber caducado o ya haber sido usado.",
|
||||
"goToApp": "Ir a la aplicación",
|
||||
"requestNewLink": "Puedes solicitar un nuevo enlace de inicio de sesión desde la aplicación.",
|
||||
"pleaseWait": "Por favor espera.",
|
||||
"dialog": {
|
||||
"title": "Iniciar sesión",
|
||||
"emailPrompt": "Ingresa tu correo para recibir un enlace de inicio de sesión",
|
||||
"emailPrompt": "Ingresa tu correo electrónico para recibir un enlace de inicio de sesión",
|
||||
"emailPlaceholder": "tu@ejemplo.com",
|
||||
"disposableEmailWarning": "No admitimos direcciones de correo desechables",
|
||||
"disposableEmailExplanation": "¡Nos encantaría ayudarte a crear videos de karaoke! Por favor usa tu dirección de correo habitual para que podamos enviarte una notificación cuando tu video esté listo.",
|
||||
"noSpamPromise": "Lo prometemos — nada de spam ni correos de marketing, nunca. Solo te enviaremos correos sobre tus videos de karaoke.",
|
||||
"disposableEmailWarning": "No admitimos direcciones de correo electrónico desechables",
|
||||
"disposableEmailExplanation": "¡Nos encantaría ayudarte a crear videos de karaoke! Por favor usa tu dirección de correo electrónico habitual para que podamos enviarte una notificación cuando tu video esté listo.",
|
||||
"noSpamPromise": "Lo prometemos — sin spam, sin correos de marketing, nunca. Solo te enviaremos correos sobre tus videos de karaoke.",
|
||||
"sendSignInLink": "Enviar enlace de inicio de sesión",
|
||||
"sending": "Enviando...",
|
||||
"useAccessToken": "Usar token de acceso en su lugar",
|
||||
"noAccount": "¿No tienes cuenta? Solo ingresa tu correo para empezar.",
|
||||
"checkEmailTitle": "Revisa tu correo",
|
||||
"noAccount": "¿No tienes cuenta? Solo ingresa tu correo electrónico para empezar.",
|
||||
"checkEmailTitle": "Revisa tu correo electrónico",
|
||||
"checkEmailSent": "Enviamos un enlace de inicio de sesión a:",
|
||||
"checkEmailExpiry": "Haz clic en el enlace del correo para iniciar sesión. El enlace expira en 15 minutos.",
|
||||
"tryDifferentEmail": "Intentar con un correo diferente",
|
||||
"checkEmailExpiry": "Haz clic en el enlace del correo para iniciar sesión. El enlace caduca en 15 minutos.",
|
||||
"tryDifferentEmail": "Probar con un correo diferente",
|
||||
"accessTokenTitle": "Token de acceso",
|
||||
"accessTokenPrompt": "Ingresa tu token de acceso para autenticarte",
|
||||
"accessTokenPlaceholder": "Ingresar token de acceso",
|
||||
@@ -293,14 +292,12 @@
|
||||
"earnFreeCredit": "Gana 1 crédito gratis",
|
||||
"showTestJobs": "Mostrar trabajos de prueba",
|
||||
"signOut": "Cerrar sesión",
|
||||
"login": "Iniciar sesión",
|
||||
"discountActive": "descuento activo",
|
||||
"discountActiveHint": "Haz clic para mostrar el banner de descuento"
|
||||
"login": "Iniciar sesión"
|
||||
}
|
||||
},
|
||||
"payment": {
|
||||
"title": "¡Pago exitoso!",
|
||||
"description": "Gracias por tu compra. Tus créditos han sido añadidos a tu cuenta.",
|
||||
"description": "Gracias por tu compra. Tus créditos han sido agregados a tu cuenta.",
|
||||
"loadingBalance": "Cargando tu saldo...",
|
||||
"creditsAvailable": "créditos disponibles",
|
||||
"startCreating": "Empezar a crear karaoke",
|
||||
@@ -310,8 +307,8 @@
|
||||
"title": "¡Pedido confirmado!",
|
||||
"description": "Gracias por tu pedido. Estamos creando tu video de karaoke personalizado ahora.",
|
||||
"deliveryTime": "Entrega en 24 horas",
|
||||
"deliveryNote": "La mayoría de los pedidos se completan en solo unas pocas horas",
|
||||
"checkEmail": "Revisa tu correo",
|
||||
"deliveryNote": "La mayoría de los pedidos se completan en solo unas horas",
|
||||
"checkEmail": "Revisa tu correo electrónico",
|
||||
"checkEmailNote": "Te enviaremos tu video cuando esté listo",
|
||||
"backToNomadKaraoke": "Volver a Nomad Karaoke",
|
||||
"questionsEmail": "¿Preguntas? Envíanos un correo a help@nomadkaraoke.com"
|
||||
@@ -372,10 +369,10 @@
|
||||
"feedback": {
|
||||
"thankYou": "¡Gracias!",
|
||||
"thankYouDesc": "Tus comentarios nos ayudan a mejorar Nomad Karaoke para todos.",
|
||||
"creditsAdded": "{count} créditos añadidos a tu cuenta",
|
||||
"creditsAdded": "{count} créditos agregados a tu cuenta",
|
||||
"done": "Hecho",
|
||||
"title": "Comparte tus comentarios — Gana 1 crédito gratis",
|
||||
"description": "Cuéntanos sobre tu experiencia creando videos de karaoke. Tus comentarios dan forma directamente a lo que construiremos a continuación.",
|
||||
"description": "Cuéntanos sobre tu experiencia creando videos de karaoke. Tus comentarios dan forma directamente a lo que construimos a continuación.",
|
||||
"overallExperience": "Experiencia general",
|
||||
"easeOfUse": "Facilidad de uso",
|
||||
"lyricsAccuracy": "Precisión de las letras",
|
||||
@@ -414,10 +411,10 @@
|
||||
"refresh": "Actualizar",
|
||||
"noDevicesSubscribed": "No hay dispositivos suscritos a las notificaciones push.",
|
||||
"deviceLabel": "Dispositivo {index}",
|
||||
"addedDate": "Añadido el {date}",
|
||||
"lastUsedDate": "Último uso el {date}",
|
||||
"addedDate": "Agregado {date}",
|
||||
"lastUsedDate": "Último uso {date}",
|
||||
"removeDevice": "Eliminar este dispositivo",
|
||||
"maxDevicesNote": "Puedes tener hasta 5 dispositivos suscritos. Añadir más eliminará la suscripción más antigua.",
|
||||
"maxDevicesNote": "Puedes tener hasta 5 dispositivos suscritos. Agregar más eliminará la suscripción más antigua.",
|
||||
"notAvailable": "Las notificaciones push no están disponibles en este servidor.",
|
||||
"enabled": "Habilitado",
|
||||
"disabled": "Deshabilitado"
|
||||
@@ -427,7 +424,7 @@
|
||||
"description": "Crea videos de karaoke profesionales con instrumentales reales, sincronización de letras precisa y salida en 4K.",
|
||||
"signIn": "Iniciar sesión",
|
||||
"signInWithDomain": "Inicia sesión con tu correo de {domains}",
|
||||
"poweredBy": "Desarrollado por Nomad Karaoke"
|
||||
"poweredBy": "Impulsado por Nomad Karaoke"
|
||||
},
|
||||
"jobFlow": {
|
||||
"stepLabels": {
|
||||
@@ -437,15 +434,15 @@
|
||||
"customizeCreate": "Personalizar y crear"
|
||||
},
|
||||
"jobCreated": "Trabajo creado",
|
||||
"whatsHappensNext": "Qué pasa después",
|
||||
"whatsHappensNext": "Qué pasa a continuación",
|
||||
"audioProcessing": "Procesamiento de audio",
|
||||
"audioProcessingDesc": "Descargamos el audio, separamos las voces del instrumental y transcribimos las letras. ~10 minutos",
|
||||
"audioProcessingDesc": "Descargamos el audio, separamos la voz principal del instrumental y transcribimos las letras. ~10 minutos",
|
||||
"automatic": "Automático",
|
||||
"youEditTheAudio": "Tú editas el audio",
|
||||
"youEditDesc": "Recorta, corta o silencia secciones del audio descargado antes de que comience el procesamiento.",
|
||||
"you": "Tú",
|
||||
"emailChime": "Correo + sonido cuando esté listo",
|
||||
"youReviewLyrics": "Tú revisas las letras y el instrumental",
|
||||
"youReviewLyrics": "Tú realizas la revisión de letras y del instrumental",
|
||||
"youReviewDesc": "Revisa las letras y escucha el instrumental. Corrige cualquier error y aprueba.",
|
||||
"videoDelivered": "Video entregado",
|
||||
"videoDeliveredDesc": "Después de que apruebes, tu video de karaoke se renderiza y se sube. ~10 minutos",
|
||||
@@ -464,8 +461,8 @@
|
||||
"title": "Título",
|
||||
"titlePlaceholder": "ej. Bohemian Rhapsody",
|
||||
"tipCallout": "¿Buscas una versión específica (en vivo, cover, remix)? Incluye esos detalles en el título - ej. \"Bohemian Rhapsody - Live at Wembley\".\nSi no podemos encontrar el audio correcto, puedes proporcionar una URL de YouTube o subir un archivo en la página siguiente.",
|
||||
"customLyricsNote": "¿Haciendo un video con letras personalizadas? Empieza con el artista/título de la canción original aquí - puedes cambiar la pantalla de título y las letras más tarde.",
|
||||
"unreleasedNote": "¿Tienes una canción inédita o tu propio archivo de audio? Ingresa el artista y título aquí de todos modos — puedes subir tu archivo en el paso 2, y marcarlo como privado en el paso 3 si no estás listo para publicarlo.",
|
||||
"customLyricsNote": "¿Haciendo un video con letras personalizadas? Comienza con el artista/título de la canción original aquí - puedes cambiar la pantalla de título y las letras más tarde.",
|
||||
"unreleasedNote": "¿Tienes una canción inédita o tu propio archivo de audio? Ingresa el artista y el título aquí de todos modos — puedes subir tu archivo en el paso 2 y marcarlo como privado en el paso 3 si no estás listo para publicarlo.",
|
||||
"howShouldVideoBeShared": "¿Cómo debería compartirse tu video?",
|
||||
"chooseHowVideoDelivered": "Elige cómo se entregará tu video de karaoke terminado.",
|
||||
"publishShare": "Publicar y compartir",
|
||||
@@ -475,13 +472,13 @@
|
||||
"published": "Publicado",
|
||||
"recommended": "Recomendado",
|
||||
"videoSharedWithWorld": "Tu video de karaoke se compartirá con el mundo:",
|
||||
"uploadedToYoutube": "Subido a YouTube en el canal de Nomad Karaoke - la forma más fácil para ti (y cualquier otra persona) de cantar esta canción en cualquier momento",
|
||||
"uploadedToYoutube": "Subido a YouTube en el canal de Nomad Karaoke - la forma más fácil para ti (y para cualquier otra persona) de cantar esta canción en cualquier momento",
|
||||
"sharedWithVenues": "Compartido con lugares de karaoke a través de Google Drive — tu canción estará disponible para cantar en bares y lugares de todo el mundo",
|
||||
"sourceFilesDelivered": "Archivos fuente entregados a ti a través de Dropbox — todas las pistas de audio, formatos de la más alta calidad, listos para descargar",
|
||||
"publishingHelpFans": "Al publicar, estás ayudando a otros fans de esta canción a descubrirla y disfrutarla en noches de karaoke en todas partes. ¡Comparte la alegría!",
|
||||
"private": "Privado",
|
||||
"videoStaysWithYou": "Tu video de karaoke se queda solo contigo:",
|
||||
"deliveredViaDropboxOnly": "Entregado solo a través de Dropbox — sin subida a YouTube, sin compartir en Google Drive. Descarga y úsalo como mejor te parezca.",
|
||||
"deliveredViaDropboxOnly": "Entregado solo a través de Dropbox — sin subida a YouTube, sin compartir en Google Drive. Descarga y usa como mejor te parezca.",
|
||||
"venueUseUpToYou": "El uso en lugares depende de ti — si quieres interpretar esta pista en un lugar, tendrás que proporcionar los archivos al anfitrión tú mismo.",
|
||||
"youtubeUploadOwn": "Subida propia a YouTube — puedes subirlo a tu propio canal, pero la monetización es poco probable ya que los derechos de autor de las canciones suelen estar en manos de las discográficas.",
|
||||
"customStylingAvailable": "Estilo personalizado disponible — elige tus propias imágenes de fondo, colores y estilos de texto en el siguiente paso.",
|
||||
@@ -492,7 +489,7 @@
|
||||
"artistOnTitleCard": "Artista en la tarjeta de título",
|
||||
"titleCardTitle": "Título de la tarjeta de título",
|
||||
"titleOnTitleCard": "Título en la tarjeta de título",
|
||||
"defaultsToSearchValues": "Estos valores predeterminados son los de tu búsqueda. Anúlalos para bandas sonoras, covers o formato alternativo.",
|
||||
"defaultsToSearchValues": "Estos valores predeterminados son los de tu búsqueda. Sobrescríbelos para bandas sonoras, covers o formatos alternativos.",
|
||||
"customVideoStyle": "Estilo de video personalizado",
|
||||
"titleCard": "Tarjeta de título",
|
||||
"karaokeVideo": "Video de karaoke",
|
||||
@@ -503,9 +500,9 @@
|
||||
"leaveColorsBlank": "Deja los colores en blanco para usar el tema predeterminado de Nomad. Las vistas previas son aproximadas — el renderizado final puede diferir ligeramente.",
|
||||
"createKaraokeVideo": "Crear video de karaoke",
|
||||
"creating": "Creando...",
|
||||
"missingAudioSource": "Falta la fuente de audio. Por favor vuelve atrás e inténtalo de nuevo.",
|
||||
"searchExpired": "Tus resultados de búsqueda expiraron. Por favor busca de nuevo — la información de tu canción aún está guardada.",
|
||||
"failedToStartProcessing": "Error al iniciar el procesamiento. Por favor intenta de nuevo.",
|
||||
"missingAudioSource": "Falta la fuente de audio. Por favor, vuelve atrás e inténtalo de nuevo.",
|
||||
"searchExpired": "Tus resultados de búsqueda caducaron. Por favor busca de nuevo — la información de tu canción aún está guardada.",
|
||||
"failedToStartProcessing": "Error al iniciar el procesamiento. Por favor, inténtalo de nuevo.",
|
||||
"trackSubmitted": "Pista enviada",
|
||||
"lyricsTranscription": "Transcripción de letras",
|
||||
"lyricsTranscriptionDesc": "Transcribimos y sincronizamos las letras de tu audio. ~5 minutos",
|
||||
@@ -551,11 +548,11 @@
|
||||
"processingComplete": "Procesamiento completo",
|
||||
"audio1of2": "Audio 1/2",
|
||||
"audio2of2": "Audio 2/2",
|
||||
"audioDone": "Audio terminado",
|
||||
"audioDone": "Audio listo",
|
||||
"audio": "Audio",
|
||||
"transcribing": "Transcribiendo",
|
||||
"correcting": "Corrigiendo",
|
||||
"lyricsDone": "Letras terminadas",
|
||||
"lyricsDone": "Letras listas",
|
||||
"lyrics": "Letras"
|
||||
},
|
||||
"jobCard": {
|
||||
@@ -564,10 +561,10 @@
|
||||
"editAudio": "Editar audio",
|
||||
"selectAudio": "Seleccionar audio",
|
||||
"selectInstrumental": "Seleccionar instrumental",
|
||||
"autoAccept": "Aceptará automáticamente",
|
||||
"autoSelect": "Seleccionará automáticamente",
|
||||
"willAutoSelectFirst": "Seleccionará automáticamente el primero",
|
||||
"noOutputsAvailable": "No hay salidas disponibles aún"
|
||||
"autoAccept": "Se aceptará automáticamente",
|
||||
"autoSelect": "Se seleccionará automáticamente",
|
||||
"willAutoSelectFirst": "Se seleccionará automáticamente el primero",
|
||||
"noOutputsAvailable": "Aún no hay salidas disponibles"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Eliminar",
|
||||
@@ -588,14 +585,14 @@
|
||||
"url": "URL",
|
||||
"audioFile": "Archivo de audio",
|
||||
"clickToUpload": "Haz clic para subir",
|
||||
"supportedFormats": "MP3, WAV, FLAC, M4A, u OGG",
|
||||
"supportedFormats": "MP3, WAV, FLAC, M4A u OGG",
|
||||
"youtubeUrlLabel": "URL de YouTube",
|
||||
"youtubeUrlPlaceholder": "https://youtube.com/watch?v=...",
|
||||
"artistTip": "Empieza a escribir y selecciona de las sugerencias para el formato correcto, o escribe libremente.",
|
||||
"artistTip": "Empieza a escribir y selecciona de las sugerencias para un formato correcto, o escribe libremente.",
|
||||
"privateNoYoutubeUpload": "Privado (sin subida a YouTube)",
|
||||
"filesDropboxOnly": "Archivos entregados solo a través de Dropbox. Sin subida a YouTube o Google Drive.",
|
||||
"searchForAudioOnline": "Buscar audio en línea",
|
||||
"useDisplayAs": "Usar un artista/título diferente para la pantalla de título",
|
||||
"useDisplayAs": "Usar artista/título diferente para la pantalla de título",
|
||||
"displayArtist": "Mostrar artista",
|
||||
"displayArtistPlaceholder": "ej., Footloose (Broadway Cast)",
|
||||
"displayTitle": "Mostrar título",
|
||||
@@ -634,14 +631,14 @@
|
||||
"regenerateTitleEndScreens": "Regenerar pantallas de título y final",
|
||||
"reRenderWithDefault": "Volver a renderizar el video de karaoke con la marca predeterminada",
|
||||
"publishToAll": "Publicar en YouTube, Google Drive y Dropbox",
|
||||
"takes15To30Minutes": "Este proceso tarda aproximadamente 15-30 minutos. Recibirás un correo cuando esté completo.",
|
||||
"takes15To30Minutes": "Este proceso tarda aproximadamente 15-30 minutos. Recibirás un correo electrónico cuando esté completo.",
|
||||
"customStylingRemoved": "Cualquier estilo personalizado que hayas aplicado se eliminará permanentemente.",
|
||||
"removeFromYoutube": "Eliminar el video de YouTube",
|
||||
"removeFromGoogleDrive": "Eliminar archivos de Google Drive",
|
||||
"moveDropboxPrivate": "Mover archivos de Dropbox de la carpeta pública a la carpeta privada",
|
||||
"assignPrivateBrand": "Asignar un nuevo código de marca privado",
|
||||
"videoContentWontChange": "El contenido del video no cambiará. Esto suele tardar entre 1 y 2 minutos.",
|
||||
"canChangeBack": "Puedes volver a hacerlo público más tarde, pero eso requerirá volver a renderizar el video (~15-30 minutos).",
|
||||
"assignPrivateBrand": "Asignar un nuevo código de marca privada",
|
||||
"videoContentWontChange": "El contenido del video no cambiará. Esto usualmente toma alrededor de 1-2 minutos.",
|
||||
"canChangeBack": "Puedes volver a cambiarlo a público más tarde, pero eso requerirá volver a renderizar el video (~15-30 minutos).",
|
||||
"copyYoutubeUrl": "Copiar URL de YouTube",
|
||||
"youtubeUrlCopied": "URL de YouTube copiada",
|
||||
"copyDropboxUrl": "Copiar URL de Dropbox",
|
||||
@@ -664,7 +661,7 @@
|
||||
},
|
||||
"editTrack": {
|
||||
"title": "Editar pista completada",
|
||||
"description": "Esto eliminará el video actual de YouTube, Dropbox y Google Drive.\nDespués de que completes la revisión de nuevo, se renderizará y redistribuirá una nueva versión.",
|
||||
"description": "Esto eliminará el video actual de YouTube, Dropbox y Google Drive.\nDespués de que completes la revisión nuevamente, se hará el renderizado de una nueva versión y se redistribuirá.",
|
||||
"updateArtistTitle": "Necesito actualizar el artista o el título",
|
||||
"artist": "Artista",
|
||||
"songTitle": "Título",
|
||||
@@ -682,12 +679,12 @@
|
||||
"onlyPngJpg": "Solo se permiten imágenes PNG y JPG.",
|
||||
"fileTooLarge": "Archivo demasiado grande ({size}). El máximo es 10 MB.",
|
||||
"dropOrBrowse": "Suelta una imagen aquí o explora",
|
||||
"maxSize": "PNG o JPG, máx 10 MB"
|
||||
"maxSize": "PNG o JPG, máx. 10 MB"
|
||||
},
|
||||
"colorOverrides": {
|
||||
"title": "Personalizar colores",
|
||||
"modified": "Modificado",
|
||||
"overrideThemeColors": "Anular colores del tema (opcional)",
|
||||
"overrideThemeColors": "Sobrescribir colores del tema (opcional)",
|
||||
"resetAll": "Restablecer todo",
|
||||
"artistColor": "Color del artista",
|
||||
"artistColorDesc": "Color para el nombre del artista en las pantallas de título/final",
|
||||
@@ -727,19 +724,19 @@
|
||||
"redirectingIn": "Redirigiendo en {count} segundos...",
|
||||
"trimStart": "Recortar inicio",
|
||||
"trimEnd": "Recortar final",
|
||||
"cutSelection": "Cortar selección (Suprimir)",
|
||||
"cutSelection": "Cortar selección (Eliminar)",
|
||||
"muteSelection": "Silenciar selección (M)",
|
||||
"undo": "Deshacer (Ctrl+Z)",
|
||||
"redo": "Rehacer (Ctrl+Shift+Z)",
|
||||
"playPause": "Reproducir/Pausar (Espacio)",
|
||||
"addToStart": "Añadir al inicio",
|
||||
"addToEnd": "Añadir al final",
|
||||
"addToStart": "Agregar al inicio",
|
||||
"addToEnd": "Agregar al final",
|
||||
"autoSaved": "Tus ediciones se guardan automáticamente mientras trabajas.",
|
||||
"keyboardShortcuts": "Atajos de teclado:",
|
||||
"shortcutSpace": "Espacio: Reproducir/Pausar",
|
||||
"shortcutUndo": "Ctrl+Z: Deshacer",
|
||||
"shortcutRedo": "Ctrl+Shift+Z: Rehacer",
|
||||
"shortcutDelete": "Suprimir/Retroceso: Eliminar selección",
|
||||
"shortcutDelete": "Eliminar/Retroceso: Eliminar selección",
|
||||
"shortcutMute": "M: Silenciar selección",
|
||||
"dismissGuidance": "Entendido",
|
||||
"original": "Original",
|
||||
@@ -751,7 +748,7 @@
|
||||
"editFailed": "Error al editar",
|
||||
"undoFailed": "Error al deshacer",
|
||||
"redoFailed": "Error al rehacer",
|
||||
"restoreFailed": "Error al restaurar — algunas ediciones pueden no haberse aplicado",
|
||||
"restoreFailed": "Error al restaurar — es posible que algunas ediciones no se hayan aplicado",
|
||||
"submitFailed": "Error al enviar"
|
||||
},
|
||||
"audioEditRestore": {
|
||||
@@ -761,24 +758,24 @@
|
||||
"durationChange": "Cambio de duración: {change}",
|
||||
"netDuration": "Duración neta: {duration}",
|
||||
"selectToPreview": "Selecciona una sesión para previsualizar",
|
||||
"startFresh": "Empezar de cero",
|
||||
"startFresh": "Empezar de nuevo",
|
||||
"restoreSelected": "Restaurar seleccionada",
|
||||
"restoring": "Restaurando...",
|
||||
"latest": "[Más reciente]"
|
||||
"latest": "[Última]"
|
||||
},
|
||||
"lyricsReview": {
|
||||
"header": {
|
||||
"viewOnlyMode": "Modo de solo lectura",
|
||||
"loadFile": "Cargar archivo",
|
||||
"reviewMode": "Modo de revisión",
|
||||
"reviewOff": "Revisión desactivada",
|
||||
"reviewOff": "Revisión apagada",
|
||||
"hideInlineActions": "Ocultar acciones de corrección en línea",
|
||||
"showInlineActions": "Mostrar acciones en línea en todas las correcciones para una revisión rápida",
|
||||
"batchActions": "Acciones por lotes ({count} correcciones)",
|
||||
"acceptHighConfidence": "Aceptar alta confianza ({count})",
|
||||
"acceptAll": "Aceptar todo",
|
||||
"revertAll": "Revertir todo",
|
||||
"undoAll": "Deshacer todo",
|
||||
"acceptAll": "Aceptar todas",
|
||||
"revertAll": "Revertir todas",
|
||||
"undoAll": "Deshacer todas",
|
||||
"resetAllChanges": "Restablecer todos los cambios a las letras originales corregidas por IA",
|
||||
"undo": "Deshacer",
|
||||
"redo": "Rehacer",
|
||||
@@ -788,7 +785,7 @@
|
||||
"editAllDesc": "Ver y editar todas las letras como texto sin formato. Útil cuando muchas líneas necesitan cambios.",
|
||||
"timingOffset": "Desplazamiento de tiempo",
|
||||
"timingOffsetValue": "{ms}ms",
|
||||
"timingOffsetDesc": "Desplaza todos los tiempos de las palabras hacia adelante o hacia atrás. Úsalo si las letras aparecen un poco antes o después en la vista previa.",
|
||||
"timingOffsetDesc": "Desplaza todos los tiempos de las palabras hacia adelante o hacia atrás. Úsalo si las letras aparecen un poco temprano o tarde en la vista previa.",
|
||||
"playback": "Reproducción"
|
||||
},
|
||||
"guidance": {
|
||||
@@ -798,26 +795,26 @@
|
||||
"matched": "Coincidentes",
|
||||
"gapsNeedsReview": "Huecos (necesita revisión)",
|
||||
"corrected": "Corregido",
|
||||
"noReferenceFound": "No se encontraron letras de referencia para esta pista. Aún puedes revisar la transcripción y hacer clic en cualquier palabra para editarla. Usa el panel de Letras de referencia a la derecha para buscar letras con un artista/título diferente.",
|
||||
"noReferenceFound": "No se encontraron letras de referencia para esta pista. Aún puedes revisar la transcripción y hacer clic en cualquier palabra para editarla. Usa el panel de letras de referencia a la derecha para buscar letras con un artista/título diferente.",
|
||||
"allMatched": "Todas las letras coincidieron con la referencia — no se necesitan correcciones. Aún puedes hacer clic en cualquier palabra para editarla.",
|
||||
"syncedLyricsOnLeft": "Las letras sincronizadas a la izquierda son las que aparecerán en el video de karaoke.",
|
||||
"orangeHighlightedWords": "Las palabras resaltadas en naranja son huecos — secciones que no se pudieron emparejar con las letras de referencia y pueden contener errores (ej. palabras mal escuchadas que suenan similar).",
|
||||
"useNAndP": "Usa N y P para saltar entre huecos. Para cada uno, haz clic en reproducir junto a la línea y compara lo que escuchas con las letras de referencia a la derecha, luego haz clic en una palabra para editarla o eliminarla.",
|
||||
"watchOutForPhantomWords": "Cuidado con las palabras fantasma como \"and\" al principio o al final de las líneas — la transcripción a menudo las añade.",
|
||||
"tryTimelineView": "Prueba la vista de Línea de tiempo para detectar cualquier palabra inusualmente larga (10+ segundos), que generalmente indica un problema de tiempo.",
|
||||
"watchOutForPhantomWords": "Cuidado con las palabras fantasma como \"y\" al principio o al final de las líneas — la transcripción a menudo las agrega.",
|
||||
"tryTimelineView": "Prueba la vista de Línea de tiempo para detectar palabras inusualmente largas (10+ segundos), que generalmente indican un problema de tiempo.",
|
||||
"watchFullTutorial": "Ver tutorial completo",
|
||||
"correctionHandlers": "Manejadores de corrección",
|
||||
"anchorSequences": "Secuencias de anclaje",
|
||||
"anchorSequencesDesc": "Secciones coincidentes entre la transcripción y la referencia",
|
||||
"anchorSequencesDesc": "Secciones emparejadas entre la transcripción y la referencia",
|
||||
"wordsInAnchors": "Palabras en anclajes",
|
||||
"multiSourceMatches": "Coincidencias de múltiples fuentes",
|
||||
"correctedGaps": "Huecos corregidos",
|
||||
"correctedGapsDesc": "Secciones corregidas con éxito",
|
||||
"wordsReplaced": "Palabras reemplazadas",
|
||||
"wordsAddedDeleted": "Palabras añadidas / eliminadas",
|
||||
"uncorrectedGaps": "Huecos sin corregir",
|
||||
"wordsAddedDeleted": "Palabras agregadas / eliminadas",
|
||||
"uncorrectedGaps": "Huecos no corregidos",
|
||||
"uncorrectedGapsDesc": "Secciones que pueden necesitar revisión manual",
|
||||
"wordsUncorrected": "Palabras sin corregir",
|
||||
"wordsUncorrected": "Palabras no corregidas",
|
||||
"numberOfGaps": "Número de huecos"
|
||||
},
|
||||
"transcription": {
|
||||
@@ -837,9 +834,9 @@
|
||||
"save": "Guardar"
|
||||
},
|
||||
"editFeedback": {
|
||||
"changed": "Cambió \"{before}\" → \"{after}\", ¿por qué?",
|
||||
"removed": "Eliminó \"{before}\", ¿por qué?",
|
||||
"added": "Añadió \"{after}\", ¿por qué?",
|
||||
"changed": "Se cambió \"{before}\" → \"{after}\", ¿por qué?",
|
||||
"removed": "Se eliminó \"{before}\", ¿por qué?",
|
||||
"added": "Se agregó \"{after}\", ¿por qué?",
|
||||
"editMade": "Edición realizada, ¿por qué?",
|
||||
"misheardWord": "Palabra mal escuchada",
|
||||
"wrongLyrics": "Letras incorrectas",
|
||||
@@ -870,7 +867,7 @@
|
||||
"highlight": "Resaltar",
|
||||
"highlightDesc": "Haz clic en cualquier palabra para ver dónde coincide en las letras de referencia. Atajo: mantén presionado SHIFT.",
|
||||
"delete": "Eliminar",
|
||||
"deleteDesc": "Haz clic en cualquier palabra para eliminarla al instante. Ideal para eliminar palabras fantasma como \"And\" durante secciones instrumentales. Atajo: mantén presionado CTRL."
|
||||
"deleteDesc": "Haz clic en cualquier palabra para eliminarla instantáneamente. Ideal para eliminar una palabra fantasma como \"Y\" durante secciones instrumentales. Atajo: mantén presionado CTRL."
|
||||
},
|
||||
"reference": {
|
||||
"title": "Letras de referencia",
|
||||
@@ -889,7 +886,7 @@
|
||||
"noSessions": "No se encontraron sesiones guardadas",
|
||||
"searchAcrossAllJobs": "Buscar sesiones en todos los trabajos",
|
||||
"selectToPreview": "Selecciona una sesión para previsualizar los cambios",
|
||||
"startFresh": "Empezar de cero",
|
||||
"startFresh": "Empezar de nuevo",
|
||||
"restoreSelected": "Restaurar seleccionada",
|
||||
"durationMismatchTitle": "Discrepancia de duración",
|
||||
"durationMismatchDesc": "La sesión seleccionada es de una pista con una duración diferente:",
|
||||
@@ -902,7 +899,7 @@
|
||||
},
|
||||
"previewVideo": {
|
||||
"generating": "Generando video de vista previa...",
|
||||
"startingEncoder": "Iniciando trabajador de codificación... Esto suele tardar alrededor de un minuto.",
|
||||
"startingEncoder": "Iniciando trabajador de codificación... Esto usualmente toma alrededor de un minuto.",
|
||||
"failed": "Error al generar el video de vista previa",
|
||||
"unsupportedBrowser": "Tu navegador no soporta la etiqueta de video."
|
||||
},
|
||||
@@ -935,7 +932,7 @@
|
||||
},
|
||||
"modals": {
|
||||
"addLyrics": {
|
||||
"title": "Añadir letras de referencia",
|
||||
"title": "Agregar letras de referencia",
|
||||
"search": "Buscar",
|
||||
"paste": "Pegar"
|
||||
},
|
||||
@@ -948,11 +945,11 @@
|
||||
"finalText": "Texto final",
|
||||
"finalTextPlaceholder": "Ingresa el texto modificado...",
|
||||
"reason": "Razón",
|
||||
"aiCorrect": "IA_CORRECTA",
|
||||
"aiIncorrect": "IA_INCORRECTA",
|
||||
"aiSuboptimal": "IA_SUBÓPTIMA",
|
||||
"contextNeeded": "SE_NECESITA_CONTEXTO",
|
||||
"subjectivePreference": "PREFERENCIA_SUBJETIVA",
|
||||
"aiCorrect": "AI_CORRECT",
|
||||
"aiIncorrect": "AI_INCORRECT",
|
||||
"aiSuboptimal": "AI_SUBOPTIMAL",
|
||||
"contextNeeded": "CONTEXT_NEEDED",
|
||||
"subjectivePreference": "SUBJECTIVE_PREFERENCE",
|
||||
"details": "Detalles",
|
||||
"detailsPlaceholder": "Detalles adicionales...",
|
||||
"submit": "Enviar"
|
||||
@@ -975,9 +972,9 @@
|
||||
"useRegex": "Usar regex",
|
||||
"fullTextMode": "Modo de texto completo",
|
||||
"preview": "Vista previa",
|
||||
"emptyWordsWarning": "Algunos reemplazos darán como resultado palabras vacías, que serán eliminadas.",
|
||||
"emptyWordsWarning": "Algunos reemplazos resultarán en palabras vacías, que serán eliminadas.",
|
||||
"noMatches": "No se encontraron coincidencias",
|
||||
"matchesFound": "{count} {count, plural, one {coincidencia encontrada} other {coincidencias encontradas}}",
|
||||
"matchesFound": "{count} {count, plural, one {coincidencia} other {coincidencias}} encontradas",
|
||||
"replaceAll": "Reemplazar todo ({count})"
|
||||
},
|
||||
"modeSelection": {
|
||||
@@ -987,14 +984,11 @@
|
||||
"resyncDesc": "Mantén el texto de las letras actuales y corrige los problemas de tiempo. Úsalo cuando las letras sean correctas pero el tiempo se haya desviado, especialmente en la segunda mitad de la canción.",
|
||||
"resyncRecommended": "Recomendado para corregir la desviación de tiempo",
|
||||
"replaceSegmentTitle": "Reemplazar letras del segmento",
|
||||
"replaceSegmentDesc": "Edita o pega nuevas letras para cada línea. El tiempo se conserva — solo cambian las palabras. Ideal para letras personalizadas, traducciones o corregir varias líneas a la vez.",
|
||||
"replaceSegmentDesc": "Edita o pega nuevas letras para cada línea. El tiempo se conserva — solo cambian las palabras. Ideal para letras personalizadas, traducciones o para arreglar varias líneas a la vez.",
|
||||
"replaceSegmentRecommended": "Recomendado para letras personalizadas",
|
||||
"replaceAllTitle": "Reemplazar todas las letras",
|
||||
"replaceAllDesc": "Pega letras completamente nuevas desde el portapapeles y sincroniza manualmente el tiempo de todas las palabras desde cero.",
|
||||
"replaceAllWarning": "Todos los datos de tiempo existentes se perderán",
|
||||
"changeCaseDesc": "Convierte todas las letras a MAYÚSCULAS, minúsculas, Tipo Título o Tipo oración. La sincronización se conserva por completo.",
|
||||
"changeCaseRecommended": "Recomendado para mantener un estilo consistente",
|
||||
"changeCaseTitle": "Cambiar mayúsculas y minúsculas"
|
||||
"replaceAllWarning": "Todos los datos de tiempo existentes se perderán"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Pega tus nuevas letras a continuación:",
|
||||
@@ -1005,34 +999,21 @@
|
||||
"continueToSync": "Continuar a sincronizar",
|
||||
"replaceAll": "Reemplazar todas las letras",
|
||||
"replaceSegment": "Reemplazar letras del segmento",
|
||||
"editLineByLine": "Edita las letras línea por línea. Cada línea corresponde a un segmento cronometrado. El número de líneas debe ser el mismo (actualmente: {count} líneas). Las líneas cambiadas obtendrán un nuevo tiempo de palabra estimado a partir de la duración del segmento. Las líneas sin cambios se dejan tal cual.",
|
||||
"editLineByLine": "Edita las letras línea por línea. Cada línea corresponde a un segmento cronometrado. El número de líneas debe permanecer igual (actualmente: {count} líneas). Las líneas cambiadas obtendrán un nuevo tiempo de palabra estimado a partir de la duración del segmento. Las líneas sin cambios se dejan tal cual.",
|
||||
"tooManyLines": "Tienes {diff} líneas de más (se esperaban {expected}, obtuviste {actual}). Cada línea se asigna a un segmento cronometrado, por lo que el recuento debe coincidir exactamente.",
|
||||
"tooFewLines": "Tienes {diff} líneas de menos (se esperaban {expected}, obtuviste {actual}). Cada línea se asigna a un segmento cronometrado, por lo que el recuento debe coincidir exactamente.",
|
||||
"syncNewLyrics": "Sincronizar nuevas letras",
|
||||
"resyncExisting": "Re-sincronizar letras existentes",
|
||||
"noLyricsToSync": "No hay letras para sincronizar",
|
||||
"goBackAndPaste": "Vuelve atrás y pega nuevas letras, o cierra este modal.",
|
||||
"backToSelection": "Volver a la selección",
|
||||
"caseLower": "minúsculas",
|
||||
"caseLowerDesc": "todas las letras en minúsculas",
|
||||
"caseSentence": "Tipo oración",
|
||||
"caseSentenceDesc": "Primera palabra de cada línea en mayúscula",
|
||||
"caseTitle": "Tipo Título",
|
||||
"caseTitleDesc": "Cada Palabra En Mayúscula",
|
||||
"caseUpper": "MAYÚSCULAS",
|
||||
"caseUpperDesc": "TODAS LAS LETRAS EN MAYÚSCULAS",
|
||||
"changeCase": "Cambiar mayúsculas y minúsculas",
|
||||
"changeCaseApply": "Aplicar {case}",
|
||||
"changeCaseNote": "La sincronización de las palabras se conserva por completo — solo cambian las mayúsculas y minúsculas.",
|
||||
"changeCasePreview": "Vista previa",
|
||||
"changeCasePrompt": "Elige un estilo de mayúsculas y minúsculas para aplicar a todas las letras:"
|
||||
"backToSelection": "Volver a la selección"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Video de vista previa (Con voces)",
|
||||
"previewWithVocals": "Vista previa del video (Con voces)",
|
||||
"noLyricsTitle": "No se detectaron letras",
|
||||
"noLyricsDesc": "No se encontraron letras en el audio. Esto suele suceder cuando el audio de entrada no tiene voces (ej. una pista de karaoke o instrumental).",
|
||||
"noLyricsHint": "Puedes volver atrás y pegar letras manualmente usando Reemplazar todo, o cancelar este trabajo e intentarlo de nuevo con un archivo de audio que contenga voces.",
|
||||
"manualCorrectionsDetected": "Se detectaron correcciones manuales. Revisa la vista previa para asegurarte de que las letras estén sincronizadas correctamente.",
|
||||
"noLyricsHint": "Puedes volver atrás y pegar las letras manualmente usando Reemplazar todo, o cancelar este trabajo e intentarlo de nuevo con un archivo de audio que contenga voces.",
|
||||
"manualCorrectionsDetected": "Correcciones manuales detectadas. Revisa la vista previa para asegurarte de que las letras estén sincronizadas correctamente.",
|
||||
"noManualCorrections": "No se detectaron correcciones manuales. Si todo se ve bien en la vista previa, procede a seleccionar tu instrumental.",
|
||||
"totalSegments": "Total de segmentos: {count}",
|
||||
"proceedToInstrumental": "Proceder a la revisión instrumental",
|
||||
@@ -1043,7 +1024,7 @@
|
||||
"artistPlaceholder": "Nombre del artista",
|
||||
"title": "Título",
|
||||
"titlePlaceholder": "Título de la canción",
|
||||
"searchDesc": "Busca en todos los proveedores de letras configurados (Genius, AZLyrics, etc.) y añade cualquier resultado que sea una coincidencia cercana a esta canción.",
|
||||
"searchDesc": "Busca en todos los proveedores de letras configurados (Genius, AZLyrics, etc.) y agrega cualquier resultado que sea una coincidencia cercana a esta canción.",
|
||||
"searchAll": "Buscar en todos los proveedores",
|
||||
"searching": "Buscando...",
|
||||
"searchAgain": "Buscar de nuevo",
|
||||
@@ -1051,7 +1032,7 @@
|
||||
"notFound": "No encontrado: {sources}",
|
||||
"lowConfidence": "Resultados de baja confianza — selecciona cualquiera para forzar su adición:",
|
||||
"matched": "Coincidencia: {matched}/{total} palabras ({relevance}% relevancia)",
|
||||
"addSelected": "Añadir seleccionados ({count})"
|
||||
"addSelected": "Agregar seleccionados ({count})"
|
||||
},
|
||||
"segmentDetails": {
|
||||
"title": "Detalles del segmento {index}"
|
||||
@@ -1059,7 +1040,7 @@
|
||||
"timingOffset": {
|
||||
"title": "Ajustar desplazamiento de tiempo",
|
||||
"offsetLabel": "Desplazamiento (milisegundos)",
|
||||
"offsetDesc": "Los valores positivos desplazan las letras más tarde, los valores negativos las desplazan antes.",
|
||||
"offsetDesc": "Los valores positivos desplazan las letras más tarde, los valores negativos las desplazan más temprano.",
|
||||
"currentOffset": "Desplazamiento actual:",
|
||||
"newOffset": "Nuevo desplazamiento:",
|
||||
"change": "Cambio:",
|
||||
@@ -1070,8 +1051,8 @@
|
||||
"sourceNamePlaceholder": "ej., manual, genius, azlyrics...",
|
||||
"lyrics": "Letras",
|
||||
"lyricsPlaceholder": "Pega las letras aquí...",
|
||||
"addLyrics": "Añadir letras",
|
||||
"adding": "Añadiendo..."
|
||||
"addLyrics": "Agregar letras",
|
||||
"adding": "Agregando..."
|
||||
},
|
||||
"correctionAnnotation": {
|
||||
"title": "Anota tu corrección",
|
||||
@@ -1091,13 +1072,13 @@
|
||||
"soundAlike": "Error de sonido similar",
|
||||
"soundAlikeDesc": "Homófonos o palabras que suenan similar (ej., \"out\" vs \"now\")",
|
||||
"backgroundVocals": "Coros",
|
||||
"backgroundVocalsDesc": "Coros que deben eliminarse del karaoke",
|
||||
"backgroundVocalsDesc": "Coros que deberían eliminarse del karaoke",
|
||||
"extraFiller": "Palabras de relleno adicionales",
|
||||
"extraFillerDesc": "La transcripción añadió palabras como \"And\", \"But\", \"Well\"",
|
||||
"extraFillerDesc": "La transcripción agregó palabras como \"Y\", \"Pero\", \"Bueno\"",
|
||||
"punctuation": "Solo puntuación/estilo",
|
||||
"punctuationDesc": "Solo diferencias de puntuación o capitalización",
|
||||
"repeatedSection": "Sección repetida",
|
||||
"repeatedSectionDesc": "Repetición de coro o verso que no está en las referencias condensadas",
|
||||
"repeatedSectionDesc": "Repetición de coro o verso no en referencias condensadas",
|
||||
"complexMultiError": "Error múltiple complejo",
|
||||
"complexMultiErrorDesc": "Múltiples tipos de errores diferentes en una sección",
|
||||
"ambiguous": "Ambiguo",
|
||||
@@ -1105,12 +1086,12 @@
|
||||
"noError": "Sin error",
|
||||
"noErrorDesc": "La transcripción coincide con al menos una fuente de referencia",
|
||||
"manualEdit": "Edición manual",
|
||||
"manualEditDesc": "Corrección iniciada por humanos no desde un hueco detectado"
|
||||
"manualEditDesc": "Corrección iniciada por humanos no de un hueco detectado"
|
||||
},
|
||||
"confidence": "Confianza en tu corrección *",
|
||||
"confidenceLevels": {
|
||||
"1": "1 - Muy inseguro",
|
||||
"2": "2 - Algo inseguro",
|
||||
"1": "1 - Muy incierto",
|
||||
"2": "2 - Algo incierto",
|
||||
"3": "3 - Neutral",
|
||||
"4": "4 - Bastante seguro",
|
||||
"5": "5 - Muy seguro"
|
||||
@@ -1130,17 +1111,17 @@
|
||||
"allWordsSynced": "¡Todas las palabras sincronizadas!",
|
||||
"clickStopSync": "Haz clic en \"Detener sincronización\" y luego en \"Aplicar\" para guardar",
|
||||
"pressSpacebar": "Presiona la BARRA ESPACIADORA cuando escuches cada palabra",
|
||||
"tapForShort": "Toca para palabras cortas, mantén presionado para palabras más largas",
|
||||
"clickStartSync": "Haz clic en \"Iniciar sincronización\" para empezar a cronometrar palabras",
|
||||
"tapForShort": "Toca para palabras cortas, mantén para palabras más largas",
|
||||
"clickStartSync": "Haz clic en \"Iniciar sincronización\" para comenzar a cronometrar palabras",
|
||||
"audioWillPlay": "El audio se reproducirá y tocarás la barra espaciadora para cada palabra",
|
||||
"wordsRemaining": "Quedan {remaining} palabras por sincronizar",
|
||||
"clickStartContinue": "Haz clic en \"Iniciar sincronización\" para continuar, o en \"Desincronizar desde el cursor\" para volver a sincronizar desde un punto",
|
||||
"wordsRemaining": "{remaining} palabras restantes para sincronizar",
|
||||
"clickStartContinue": "Haz clic en \"Iniciar sincronización\" para continuar, o \"Desincronizar desde el cursor\" para re-sincronizar desde un punto",
|
||||
"allSyncedApply": "¡Todas las palabras sincronizadas! Haz clic en \"Aplicar\" para guardar los cambios, o haz ajustes primero",
|
||||
"editingResetsWarning": "Editar las letras restablecerá todos los datos de tiempo. Tendrás que volver a sincronizar toda la canción.",
|
||||
"editingResetsWarning": "La edición de letras restablecerá todos los datos de tiempo. Tendrás que re-sincronizar toda la canción.",
|
||||
"lyricsPlaceholder": "Ingresa las letras, una línea por segmento...",
|
||||
"saveAndResetTiming": "Guardar y restablecer tiempo",
|
||||
"editWord": "Editar palabra",
|
||||
"editWordDesc": "Edita el texto de la palabra. Ingresa varias palabras separadas por espacios para dividir.",
|
||||
"editWordDesc": "Edita el texto de la palabra. Ingresa múltiples palabras separadas por espacios para dividir.",
|
||||
"editWordPlaceholder": "Ingresa el texto modificado...",
|
||||
"controls": {
|
||||
"play": "Reproducir",
|
||||
@@ -1162,9 +1143,9 @@
|
||||
},
|
||||
"instrumentalReview": {
|
||||
"separationInProgress": "Separación de audio en progreso",
|
||||
"separationInProgressDesc": "Las pistas de audio aún se están separando. Esto suele tardar unos minutos. Esta página se actualizará automáticamente cuando se complete la separación.",
|
||||
"separationInProgressDesc": "Las pistas de audio aún se están separando. Esto usualmente toma unos minutos. Esta página se actualizará automáticamente cuando la separación esté completa.",
|
||||
"loadingAnalysis": "Cargando análisis instrumental...",
|
||||
"review": "Revisión",
|
||||
"review": "Revisar",
|
||||
"title": "Revisión instrumental",
|
||||
"cleanRecommended": "Limpio recomendado",
|
||||
"reviewBackingVocals": "Revisar coros",
|
||||
@@ -1192,11 +1173,11 @@
|
||||
"cleanDescription": "Sin coros - instrumental puro",
|
||||
"guidance": {
|
||||
"chooseBackingTrack": "Elige tu pista de acompañamiento de karaoke. La IA separó las voces de la música — ahora elige qué versión suena mejor.",
|
||||
"littleBackingVocals": "Esta pista tiene muy poco contenido de coros ({percentage}%). Recomendamos el instrumental limpio — solo confirma a continuación para proceder.",
|
||||
"hearDifference": "¿Quieres escuchar la diferencia? Usa los botones de audio de arriba para comparar, o haz clic en las secciones rosas de la forma de onda para escuchar los coros.",
|
||||
"littleBackingVocals": "Esta pista tiene muy poco contenido de coros ({percentage}%). Recomendamos el instrumental limpio — solo confirma a continuación para continuar.",
|
||||
"hearDifference": "¿Quieres escuchar la diferencia? Usa los botones de audio de arriba para comparar, o haz clic en las secciones rosas en la forma de onda para escuchar los coros.",
|
||||
"watchFullTutorial": "Ver tutorial completo",
|
||||
"backingVocalsExplanation": "Los coros son las voces de armonía/coro que cantan junto con la voz principal. Algunos cantantes de karaoke prefieren mantenerlos como guía, otros prefieren un instrumental limpio.",
|
||||
"step1": "Paso 1: Haz clic en las secciones rosas de la forma de onda para escuchar los coros{segments}.",
|
||||
"step1": "Paso 1: Haz clic en las secciones rosas en la forma de onda para escuchar los coros{segments}.",
|
||||
"step2": "Paso 2: Decide — ¿mantenerlos o usar el instrumental limpio? Usa los botones de alternancia de audio de arriba para comparar.",
|
||||
"step3": "Paso 3 (si es necesario): Si quieres coros pero algunas secciones tienen sangrado de voz principal no deseado, haz Shift+arrastrar en la forma de onda para marcar esas secciones, luego haz clic en Crear personalizado.",
|
||||
"showTips": "Mostrar consejos",
|
||||
@@ -1239,131 +1220,7 @@
|
||||
"explanation": "¿Quieres coros pero escuchas sangrado de voz principal en algunas secciones? Silencia esas secciones para crear una mezcla personalizada.",
|
||||
"clickSegment": "Haz clic en un segmento a continuación para silenciarlo, o haz Shift+arrastrar en la forma de onda para marcar una región personalizada.",
|
||||
"noBackingDetected": "No se detectaron coros — se recomienda instrumental limpio.",
|
||||
"addToMuteRegions": "Añadir a regiones silenciadas"
|
||||
"addToMuteRegions": "Agregar a regiones silenciadas"
|
||||
}
|
||||
},
|
||||
"referrals": {
|
||||
"title": "Referencias",
|
||||
"backToDashboard": "Volver al panel",
|
||||
"howItWorksTitle": "Cómo funciona",
|
||||
"howItWorksIntro": "Gana dinero compartiendo Nomad Karaoke con tus amigos, audiencia o comunidad. Es simple — comparte tu enlace único, y cuando las personas se registren y hagan compras, ambos se benefician.",
|
||||
"howStep1Title": "Comparte tu enlace",
|
||||
"howStep1Desc": "Envía tu enlace de referencia único a amigos o compártelo en redes sociales, tu sitio web o en eventos.",
|
||||
"howStep2Title": "Ellos obtienen un descuento",
|
||||
"howStep2Desc": "Cualquiera que se registre a través de tu enlace obtiene un {discount}% de descuento en todas las compras de créditos durante {days} días.",
|
||||
"howStep3Title": "Tú ganas dinero",
|
||||
"howStep3Desc": "Ganas el {kickback}% de cada compra que hagan dentro de los {days} días posteriores a registrarse.",
|
||||
"howPayoutTitle": "¿Cuándo me pagan?",
|
||||
"howPayoutDesc": "Las ganancias se acumulan en tu saldo. Una vez que alcances los $20 y hayas conectado tu cuenta bancaria a través de Stripe, los pagos se envían automáticamente. Puedes hacer un seguimiento de todo aquí en esta página.",
|
||||
"yourLink": "Tu enlace de referencia",
|
||||
"copyLink": "Copiar enlace",
|
||||
"copied": "¡Copiado!",
|
||||
"vanityRequest": "¿Quieres una URL personalizada? Solicita un enlace personalizado",
|
||||
"vanityPlaceholder": "tu-nombre",
|
||||
"vanitySubmit": "Solicitar",
|
||||
"vanityRequested": "¡Solicitud enviada! Nos pondremos en contacto contigo pronto.",
|
||||
"displayName": "Nombre para mostrar",
|
||||
"customMessage": "Mensaje personalizado",
|
||||
"customMessagePlaceholder": "Dile a tus amigos por qué deberían probar Nomad Karaoke...",
|
||||
"save": "Guardar",
|
||||
"stats": "Estadísticas",
|
||||
"clicks": "Clics",
|
||||
"signups": "Registros",
|
||||
"purchases": "Compras",
|
||||
"earnings": "Ganancias",
|
||||
"pendingBalance": "Saldo pendiente",
|
||||
"totalEarned": "Total ganado",
|
||||
"totalPaid": "Total pagado",
|
||||
"termDiscount": "Descuento por referencias",
|
||||
"termDiscountWindow": "Ventana de descuento",
|
||||
"termKickback": "Tu comisión",
|
||||
"termEarningWindow": "Ventana de ganancias",
|
||||
"recentEarnings": "Ganancias recientes",
|
||||
"recentPayouts": "Pagos recientes",
|
||||
"noEarnings": "Aún no hay ganancias. ¡Comparte tu enlace para empezar a ganar!",
|
||||
"noPayouts": "Aún no hay pagos.",
|
||||
"connectBank": "Conectar cuenta bancaria",
|
||||
"connectDescription": "Conecta tu cuenta bancaria a través de Stripe para recibir pagos por referencias cuando tu saldo alcance los $20.",
|
||||
"connectComplete": "¡Cuenta bancaria conectada!",
|
||||
"payoutThreshold": "Los pagos se envían automáticamente cuando tu saldo alcanza los $20.",
|
||||
"interstitialTitle": "¡Has sido referido!",
|
||||
"interstitialReferred": "Referido por {name}",
|
||||
"interstitialDiscount": "Disfruta de un {percent}% de descuento en todas las compras de créditos durante {days} días",
|
||||
"interstitialCta": "Empezar",
|
||||
"discountBadge": "{percent}% de descuento por referencia",
|
||||
"discountActive": "Descuento por referencia activo — {percent}% de descuento por {days} días más",
|
||||
"cancel": "Cancelar",
|
||||
"editProfile": "Editar nombre para mostrar y mensaje",
|
||||
"qrCode": "Código QR",
|
||||
"qrOrFlyer": "Código QR / Folleto",
|
||||
"qrTitle": "Generador de códigos QR",
|
||||
"qrDotStyle": "Estilo de punto",
|
||||
"qrCornerFrame": "Marco de esquina",
|
||||
"qrCornerDot": "Punto de esquina",
|
||||
"qrColors": "Colores",
|
||||
"qrForeground": "Primer plano",
|
||||
"qrBackground": "Fondo",
|
||||
"qrLogo": "Logo central",
|
||||
"qrLogoNone": "Ninguno",
|
||||
"qrLogoNomad": "Logo NK",
|
||||
"qrLogoEmoji": "Emoji",
|
||||
"qrDownloadPng": "Descargar PNG",
|
||||
"qrDownloadSvg": "Descargar SVG",
|
||||
"qrStyleSquare": "Cuadrado",
|
||||
"qrStyleRounded": "Redondeado",
|
||||
"qrStyleDots": "Puntos",
|
||||
"qrStyleClassy": "Elegante",
|
||||
"qrStyleClassyRounded": "Elegante redondeado",
|
||||
"qrStyleExtraRounded": "Extra redondeado",
|
||||
"qrStyleDot": "Punto",
|
||||
"flyerTheme": "Tema del folleto",
|
||||
"flyerThemeLight": "Claro",
|
||||
"flyerThemeDark": "Oscuro",
|
||||
"flyerGenerate": "Generar folleto",
|
||||
"flyerGenerating": "Generando...",
|
||||
"appliedAtCheckout": "Aplicado automáticamente al finalizar la compra",
|
||||
"expires": "Expira {date}",
|
||||
"referredBy": "Referido por {name}",
|
||||
"usingCode": "Código: {code}",
|
||||
"connectBankLoading": "Configurando...",
|
||||
"connectDetailsNeeded": "Stripe necesita información adicional para habilitar los pagos. Haz clic en \"Actualizar cuenta bancaria\" a continuación para completar la configuración.",
|
||||
"connectRefresh": "Parece que no terminaste de configurar tu cuenta bancaria. Haz clic abajo para intentarlo de nuevo.",
|
||||
"connectStatusActive": "Pagos habilitados",
|
||||
"connectStatusPending": "Configuración en curso",
|
||||
"connectStripeNote": "Serás redirigido al sitio seguro de Stripe para ingresar tus datos bancarios. Esto generalmente toma un par de minutos.",
|
||||
"flyerAccentColor": "Acento",
|
||||
"flyerBranding": "Marca",
|
||||
"flyerColors": "Colores",
|
||||
"flyerDownloadHtml": "Descargar HTML",
|
||||
"flyerDownloadPdf": "Descargar PDF",
|
||||
"flyerDownloadPng": "Descargar PNG",
|
||||
"flyerEditQr": "Editar estilo del QR",
|
||||
"flyerExporting": "Exportando...",
|
||||
"flyerHeadlineGradient": "Degradado del titular",
|
||||
"flyerHeadlineSubColor": "Subtítulo del titular",
|
||||
"flyerMargins": "Márgenes de página",
|
||||
"flyerPerPage": "Folletos por página",
|
||||
"flyerPresetCustom": "Personalizado",
|
||||
"flyerPresetName": "Nombre del preset",
|
||||
"flyerPresetSave": "Guardar preset",
|
||||
"flyerPrintLayout": "Diseño de impresión",
|
||||
"flyerSections": "Secciones",
|
||||
"flyerSubtextColor": "Subtexto",
|
||||
"flyerTextColor": "Texto",
|
||||
"flyerTextOverrides": "Modificaciones de texto",
|
||||
"flyerToggleDivider": "Separador",
|
||||
"flyerToggleFeatures": "Características inferiores",
|
||||
"flyerToggleSteps": "Pasos de 'Cómo funciona'",
|
||||
"flyerToggleSubtitle": "Subtítulo",
|
||||
"flyerToggleTagline": "Eslogan inferior",
|
||||
"flyerUploadLogo": "Subir logo",
|
||||
"managePayouts": "Gestionar pagos",
|
||||
"payoutTitle": "Pagos y cuenta bancaria",
|
||||
"tabFlyer": "Folleto imprimible",
|
||||
"tabQrCode": "Código QR",
|
||||
"toolsTitle": "Generator de código QR y folletos",
|
||||
"updateBankAccount": "Actualizar cuenta bancaria",
|
||||
"connectFailed": "Algo salió mal. Por favor, inténtalo de nuevo.",
|
||||
"flyerRemoveLogo": "Quitar"
|
||||
}
|
||||
}
|
||||
+214
-357
File diff suppressed because it is too large.
Load diff
+179
-322
File diff suppressed because it is too large.
Load diff
+203
-346
File diff suppressed because it is too large.
Load diff
+405
-548
File diff suppressed because it is too large.
Load diff
+255
-398
File diff suppressed because it is too large.
Load diff
+332
-475
File diff suppressed because it is too large.
Load diff
+175
-318
File diff suppressed because it is too large.
Load diff
+137
-280
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"languageSwitcher": {
|
||||
"label": "Seleziona lingua"
|
||||
"label": "Seleziona la lingua"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Caricamento...",
|
||||
@@ -36,7 +36,7 @@
|
||||
"showMore": "Mostra di più",
|
||||
"showLess": "Mostra di meno",
|
||||
"required": "Obbligatorio",
|
||||
"optional": "Opzionale",
|
||||
"optional": "Facoltativo",
|
||||
"uploading": "Caricamento in corso...",
|
||||
"processing": "Elaborazione...",
|
||||
"free": "Gratis",
|
||||
@@ -52,7 +52,7 @@
|
||||
"hero": {
|
||||
"title": "Crea un video karaoke per qualsiasi canzone",
|
||||
"titleGradient": "Video Karaoke",
|
||||
"subtitle": "Crea video karaoke professionali in meno di 30 minuti. Strumentali reali dalla canzone originale, sincronizzazione precisa del testo e output video in 4K."
|
||||
"subtitle": "Crea video karaoke professionali in meno di 30 minuti. Basi strumentali reali dalla canzone originale, sincronizzazione precisa del testo e output video in 4K."
|
||||
},
|
||||
"heroCTA": {
|
||||
"createYourself": "Crealo tu stesso",
|
||||
@@ -68,7 +68,7 @@
|
||||
"howItWorks": {
|
||||
"title": "Come funziona",
|
||||
"step1Title": "Scegli una canzone",
|
||||
"step1Desc": "Cerca, incolla un link di YouTube o carica l'audio",
|
||||
"step1Desc": "Cerca, incolla un link di YouTube o carica un file audio",
|
||||
"step2Title": "Facciamo noi il lavoro pesante",
|
||||
"step2Desc": "Voci rimosse, testo trascritto e sincronizzato",
|
||||
"step3Title": "Rivedi e correggi",
|
||||
@@ -76,39 +76,39 @@
|
||||
"step4Title": "Ottieni il tuo video",
|
||||
"step4Desc": "Scarica i file o guardalo sul nostro YouTube",
|
||||
"tutorialTitle": "Vuoi una guida più dettagliata?",
|
||||
"tutorialDesc": "Guarda il tutorial completo per vedere ogni passaggio nel dettaglio — dalla creazione di un lavoro al download del tuo video finito.",
|
||||
"tutorialDesc": "Guarda il tutorial completo per vedere ogni passaggio nel dettaglio — dalla creazione di un progetto al download del tuo video finito.",
|
||||
"tutorialVideoTitle": "Tutorial completo di Nomad Karaoke"
|
||||
},
|
||||
"features": {
|
||||
"title": "Cosa ottieni",
|
||||
"feature1Title": "Strumentali reali",
|
||||
"feature1Title": "Basi strumentali reali",
|
||||
"feature1Desc": "Usa la vera base strumentale della tua canzone, non una cover band o una ricreazione MIDI.",
|
||||
"feature2Title": "Sincronizzazione precisa del testo",
|
||||
"feature2Desc": "Tempismo parola per parola che evidenzia esattamente quando cantare. Rivedi il testo per garantirne l'accuratezza.",
|
||||
"feature3Title": "Mantieni o rimuovi i cori",
|
||||
"feature3Desc": "Scegli una base strumentale pulita o una che preserva i cori per un suono più pieno.",
|
||||
"feature4Title": "Video 4K + Formati multipli",
|
||||
"feature4Desc": "Ottieni un video karaoke in 4K, una versione da cantare con la voce e CDG+MP3 per i sistemi più vecchi.",
|
||||
"feature4Desc": "Ottieni un video karaoke in 4K, una versione da cantare con la voce originale e CDG+MP3 per i sistemi più vecchi.",
|
||||
"feature5Title": "Pubblicato su YouTube",
|
||||
"feature5Desc": "Ogni video viene pubblicato automaticamente sul nostro canale YouTube per una facile condivisione.",
|
||||
"feature6Title": "Controllo totale prima dell'esportazione",
|
||||
"feature6Title": "Controllo completo prima dell'esportazione",
|
||||
"feature6Desc": "Rivedi e correggi eventuali errori di trascrizione prima che venga generato il video finale."
|
||||
},
|
||||
"screenshots": {
|
||||
"title": "Guardalo in azione",
|
||||
"subtitle": "Ecco come appare il processo in ogni fase",
|
||||
"jobCreationAlt": "Flusso guidato di creazione del lavoro con inserimento di artista e titolo",
|
||||
"jobCreationAlt": "Flusso guidato di creazione del progetto con inserimento di artista e titolo",
|
||||
"jobCreationTitle": "Crea il tuo video",
|
||||
"jobCreationDesc": "Inserisci qualsiasi canzone e troviamo automaticamente il miglior audio",
|
||||
"lyricsReviewAlt": "Revisione del testo con testo sincronizzato accanto al testo di riferimento per la correzione",
|
||||
"jobCreationDesc": "Inserisci qualsiasi canzone e troviamo automaticamente l'audio migliore",
|
||||
"lyricsReviewAlt": "Revisione del testo con testi sincronizzati accanto ai testi di riferimento per la correzione",
|
||||
"lyricsReviewTitle": "Rivedi il testo",
|
||||
"lyricsReviewDesc": "Confronta il testo sincronizzato con i riferimenti e correggi eventuali errori",
|
||||
"instrumentalReviewAlt": "Revisione strumentale con visualizzazione della forma d'onda e opzioni per i cori",
|
||||
"instrumentalReviewTitle": "Scegli la tua base strumentale",
|
||||
"instrumentalReviewDesc": "Ascolta le opzioni audio e scegli la migliore base musicale",
|
||||
"exampleOutputAlt": "Lavoro karaoke completato con opzioni di download per 4K, 720p, CDG e altro",
|
||||
"instrumentalReviewDesc": "Ascolta le opzioni audio e scegli la base migliore",
|
||||
"exampleOutputAlt": "Progetto karaoke completato con opzioni di download per 4K, 720p, CDG e altro",
|
||||
"exampleOutputTitle": "Scarica e condividi",
|
||||
"exampleOutputDesc": "Ottieni il tuo video 4K, 720p, CDG e altro in pochi minuti"
|
||||
"exampleOutputDesc": "Ottieni il tuo video in 4K, 720p, CDG e altro in pochi minuti"
|
||||
},
|
||||
"pricing": {
|
||||
"title": "Prezzi semplici",
|
||||
@@ -124,7 +124,7 @@
|
||||
"continuePayment": "Continua al pagamento",
|
||||
"redirecting": "Reindirizzamento...",
|
||||
"secureCheckout": "Pagamento sicuro",
|
||||
"poweredByStripe": "basato su Stripe",
|
||||
"poweredByStripe": "powered by Stripe",
|
||||
"creditUnit": "credito",
|
||||
"creditsUnit": "crediti",
|
||||
"perVideo": "/video",
|
||||
@@ -132,7 +132,7 @@
|
||||
"saveFmt": "Risparmia il {savings}%"
|
||||
},
|
||||
"madeForYou": {
|
||||
"badgeLabel": "Opzione servizio completo",
|
||||
"badgeLabel": "Opzione Full-Service",
|
||||
"title": "Lo facciamo noi per te",
|
||||
"subtitle": "Non vuoi usare il Generator e rivedere il testo da solo? Nessun problema. Dicci la canzone, paga $50 e ti consegneremo il tuo video karaoke entro 24 ore.",
|
||||
"secondarySubtitle": "Non vuoi passare 10 minuti a rivedere il testo? Per soli $10 in più rispetto al fai-da-te, gestiamo tutto noi.",
|
||||
@@ -150,7 +150,7 @@
|
||||
"delivery2": "Versione ottimizzata per il web a 720p",
|
||||
"delivery3": "CDG+MP3 per macchine karaoke",
|
||||
"delivery4": "Audio strumentale (con o senza cori)",
|
||||
"delivery5": "Versione \"canta insieme\" con voce originale",
|
||||
"delivery5": "Versione \"da cantare\" con voci originali",
|
||||
"orderFormTitle": "Ordina un video",
|
||||
"orderPrice": "$50",
|
||||
"artistLabel": "Artista",
|
||||
@@ -168,7 +168,7 @@
|
||||
"youtubeUrlPlaceholder": "https://youtube.com/watch?v=...",
|
||||
"emailLabel2": "La tua email",
|
||||
"emailPlaceholder2": "tu@esempio.com",
|
||||
"emailHint2": "Invieremo i tuoi file video a questo indirizzo",
|
||||
"emailHint2": "Invieremo i file del tuo video a questo indirizzo",
|
||||
"notesLabel": "Richieste speciali",
|
||||
"notesOptional": "(opzionale)",
|
||||
"notesPlaceholder": "Eventuali richieste speciali o note sulla canzone...",
|
||||
@@ -185,13 +185,13 @@
|
||||
"faq": {
|
||||
"title": "Domande?",
|
||||
"faq1Question": "Come funziona?",
|
||||
"faq1Answer": "Inserisci un artista e il titolo di una canzone (oppure incolla un link di YouTube o carica il tuo file audio). Il nostro sistema trova l'audio, separa la voce dalla base strumentale, trascrive il testo e lo sincronizza con la musica. Successivamente, rivedi e correggi eventuali errori di trascrizione prima che generiamo il tuo video karaoke finale.",
|
||||
"faq1Answer": "Inserisci un artista e il titolo della canzone (o incolla un link di YouTube, o carica il tuo file audio). Il nostro sistema trova l'audio, separa le voci dalla base strumentale, trascrive il testo e lo sincronizza con la musica. Successivamente rivedi e correggi eventuali errori di trascrizione prima che generiamo il tuo video karaoke finale.",
|
||||
"faq2Question": "Quali canzoni posso usare?",
|
||||
"faq2Answer": "Qualsiasi canzone! Cerca per artista e titolo, incolla un URL di YouTube o carica il tuo file audio. Se riesci a ottenere l'audio, possiamo trasformarlo in karaoke.",
|
||||
"faq3Question": "Qual è il formato di output?",
|
||||
"faq3Answer": "Ottieni più file: un video karaoke MP4 in 4K, una versione \"Con voce\" per fare pratica e uno ZIP CDG+MP3 per i vecchi sistemi karaoke. Tutti i video vengono anche pubblicati sul nostro canale YouTube per una facile condivisione.",
|
||||
"faq3Answer": "Ottieni più file: un video karaoke MP4 in 4K, una versione \"Con voce\" per esercitarti a cantare e uno ZIP CDG+MP3 per i sistemi karaoke più vecchi. Tutti i video vengono anche pubblicati sul nostro canale YouTube per una facile condivisione.",
|
||||
"faq4Question": "Devo fare qualcosa o è completamente automatico?",
|
||||
"faq4Answer": "La trascrizione del testo è molto accurata, ma dovrai rivederla e correggere eventuali parole fraintese prima che venga generato il video finale. Per le canzoni con voci chiare, potrebbero essere necessarie poche o nessuna correzione. Per le canzoni complesse, aspettati di dedicare 5-10 minuti alla correzione degli errori. Il tempismo/sincronizzazione delle parole è gestito automaticamente ed è molto preciso.",
|
||||
"faq4Answer": "La trascrizione del testo è molto accurata, ma dovrai rivederla e correggere eventuali parole fraintese prima che venga generato il video finale. Per le canzoni con voci chiare, potrebbero essere necessarie poche o nessuna correzione. Per canzoni complesse, aspettati di dedicare 5-10 minuti a correggere gli errori. Il tempismo/sincronizzazione delle parole è gestito automaticamente ed è molto preciso.",
|
||||
"faq5Question": "I crediti scadono?",
|
||||
"faq5Answer": "No! I tuoi crediti non scadono mai. Usali quando vuoi."
|
||||
},
|
||||
@@ -209,7 +209,7 @@
|
||||
"showAdminControls": "Mostra controlli admin",
|
||||
"switchToLightMode": "Passa alla modalità chiara",
|
||||
"switchToDarkMode": "Passa alla modalità scura",
|
||||
"earnFreeCredit": "Guadagna 1 credito gratuito!",
|
||||
"earnFreeCredit": "Guadagna 1 credito gratis!",
|
||||
"feedbackPrompt": "Condividi il tuo feedback sull'esperienza di creazione del karaoke.",
|
||||
"giveFeedback": "Lascia un feedback",
|
||||
"createKaraokeVideo": "Crea video karaoke",
|
||||
@@ -231,8 +231,7 @@
|
||||
"jobsCount": "{count} {count, plural, one {lavoro} other {lavori}}",
|
||||
"loadingJobs": "Caricamento lavori...",
|
||||
"noJobsMatchFilters": "Nessun lavoro corrisponde ai tuoi filtri.",
|
||||
"noJobsYet": "Ancora nessun lavoro. Creane uno per iniziare!",
|
||||
"referrals": "Inviti"
|
||||
"noJobsYet": "Ancora nessun lavoro. Creane uno per iniziare!"
|
||||
},
|
||||
"auth": {
|
||||
"noVerificationToken": "Nessun token di verifica fornito",
|
||||
@@ -243,19 +242,19 @@
|
||||
"welcomeTitle": "Benvenuto su Nomad Karaoke!",
|
||||
"freeCreditsGranted": "{count} crediti gratuiti per iniziare",
|
||||
"freeCreditsExplanation": "Ogni credito crea un video karaoke professionale.",
|
||||
"freeCreditsRequest": "Questi crediti ci costano soldi veri, quindi usali saggiamente e facci sapere cosa ne pensi!",
|
||||
"freeCreditsRequest": "Questi crediti ci costano soldi veri per essere erogati, quindi usali saggiamente e facci sapere cosa ne pensi!",
|
||||
"startCreating": "Inizia a creare karaoke",
|
||||
"welcomeBack": "Bentornato su Nomad Karaoke",
|
||||
"creditsDeniedExplanation": "Non siamo riusciti a concedere crediti gratuiti questa volta. La generazione di karaoke ci costa soldi veri per ogni lavoro, quindi dobbiamo stare attenti alla distribuzione di crediti gratuiti.",
|
||||
"creditsDeniedHelp": "Se pensi che si tratti di un errore, controlla la tua email — ti abbiamo inviato i dettagli su come contattarci per risolvere il problema.",
|
||||
"creditsDeniedHelp": "Se pensi che sia un errore, controlla la tua email — ti abbiamo inviato i dettagli su come contattarci per risolvere il problema.",
|
||||
"buyCredits": "Acquista crediti",
|
||||
"goToDashboard": "Vai alla Dashboard",
|
||||
"creditsPendingTitle": "Benvenuto su Nomad Karaoke!",
|
||||
"creditsPendingExplanation": "Non siamo riusciti ad assegnare automaticamente i tuoi crediti gratuiti questa volta. Il nostro team esaminerà a breve la tua registrazione e assegnerà i crediti se possibile.",
|
||||
"creditsPendingExplanation": "Non siamo riusciti ad assegnare i tuoi crediti gratuiti automaticamente questa volta. Il nostro team esaminerà a breve la tua registrazione e assegnerà i crediti se possibile.",
|
||||
"creditsPendingHint": "Puoi comunque esplorare l'app mentre aspetti, o acquistare crediti per iniziare subito.",
|
||||
"exploreApp": "Esplora l'app",
|
||||
"successSignedIn": "Accesso effettuato con successo!",
|
||||
"welcomeBackUser": "Bentornato{email}!",
|
||||
"welcomeBackUser": "Bentornato {email}!",
|
||||
"redirectingToApp": "Reindirizzamento all'app...",
|
||||
"signInFailed": "Accesso fallito",
|
||||
"linkExpiredOrUsed": "Il link potrebbe essere scaduto o già stato utilizzato.",
|
||||
@@ -266,12 +265,12 @@
|
||||
"title": "Accedi",
|
||||
"emailPrompt": "Inserisci la tua email per ricevere un link di accesso",
|
||||
"emailPlaceholder": "tu@esempio.com",
|
||||
"disposableEmailWarning": "Non supportiamo indirizzi email temporanei",
|
||||
"disposableEmailWarning": "Non supportiamo indirizzi email usa e getta",
|
||||
"disposableEmailExplanation": "Ci piacerebbe aiutarti a creare video karaoke! Usa il tuo indirizzo email normale così possiamo inviarti una notifica quando il tuo video è pronto.",
|
||||
"noSpamPromise": "Te lo promettiamo: niente spam, niente email di marketing, mai. Ti scriveremo solo riguardo ai tuoi video karaoke.",
|
||||
"noSpamPromise": "Promettiamo — niente spam, niente email di marketing, mai. Ti invieremo email solo riguardo ai tuoi video karaoke.",
|
||||
"sendSignInLink": "Invia link di accesso",
|
||||
"sending": "Invio...",
|
||||
"useAccessToken": "Usa invece il token di accesso",
|
||||
"sending": "Invio in corso...",
|
||||
"useAccessToken": "Usa invece un token di accesso",
|
||||
"noAccount": "Nessun account? Inserisci semplicemente la tua email per iniziare.",
|
||||
"checkEmailTitle": "Controlla la tua email",
|
||||
"checkEmailSent": "Abbiamo inviato un link di accesso a:",
|
||||
@@ -290,16 +289,14 @@
|
||||
"defaultName": "Fan del Karaoke",
|
||||
"creditsAvailable": "{count} crediti disponibili",
|
||||
"buyMoreCredits": "Acquista altri crediti",
|
||||
"earnFreeCredit": "Guadagna 1 credito gratuito",
|
||||
"earnFreeCredit": "Guadagna 1 credito gratis",
|
||||
"showTestJobs": "Mostra lavori di test",
|
||||
"signOut": "Esci",
|
||||
"login": "Accedi",
|
||||
"discountActive": "sconto attivo",
|
||||
"discountActiveHint": "Clicca per mostrare il banner dello sconto"
|
||||
"login": "Accedi"
|
||||
}
|
||||
},
|
||||
"payment": {
|
||||
"title": "Pagamento riuscito!",
|
||||
"title": "Pagamento completato!",
|
||||
"description": "Grazie per il tuo acquisto. I tuoi crediti sono stati aggiunti al tuo account.",
|
||||
"loadingBalance": "Caricamento del tuo saldo...",
|
||||
"creditsAvailable": "crediti disponibili",
|
||||
@@ -333,17 +330,17 @@
|
||||
},
|
||||
"warmingUp": {
|
||||
"title": "Riscaldamento del Generator...",
|
||||
"almostThere": "Quasi pronto...",
|
||||
"almostThere": "Ci siamo quasi...",
|
||||
"firstLoadNote": "Il primo caricamento può richiedere fino a 30 secondi"
|
||||
},
|
||||
"status": {
|
||||
"queued": "In coda",
|
||||
"processing": "In elaborazione",
|
||||
"awaitingReview": "In attesa di revisione",
|
||||
"selectInstrumental": "Seleziona strumentale",
|
||||
"selectInstrumental": "Seleziona base strumentale",
|
||||
"completed": "Completato",
|
||||
"failed": "Fallito",
|
||||
"healthy": "In salute",
|
||||
"healthy": "Operativo",
|
||||
"offline": "Offline",
|
||||
"deployed": "Distribuito {time}",
|
||||
"blueGreenDeployment": "Distribuzione Blue-Green",
|
||||
@@ -374,34 +371,34 @@
|
||||
"thankYouDesc": "Il tuo feedback ci aiuta a migliorare Nomad Karaoke per tutti.",
|
||||
"creditsAdded": "{count} crediti aggiunti al tuo account",
|
||||
"done": "Fatto",
|
||||
"title": "Condividi il tuo feedback — Guadagna 1 credito gratuito",
|
||||
"title": "Condividi il tuo feedback — Guadagna 1 credito gratis",
|
||||
"description": "Raccontaci la tua esperienza nella creazione di video karaoke. Il tuo feedback modella direttamente ciò che costruiremo in futuro.",
|
||||
"overallExperience": "Esperienza generale",
|
||||
"easeOfUse": "Facilità d'uso",
|
||||
"lyricsAccuracy": "Accuratezza del testo",
|
||||
"correctionExperience": "Esperienza di correzione",
|
||||
"whatWentWell": "Cosa è andato bene?",
|
||||
"whatWentWellPlaceholder": "Cosa ti è piaciuto della creazione dei video karaoke?",
|
||||
"whatWentWellPlaceholder": "Cosa ti è piaciuto della creazione di video karaoke?",
|
||||
"whatCouldBeBetter": "Cosa potrebbe essere migliorato?",
|
||||
"whatCouldBeBetterPlaceholder": "Cosa renderebbe l'esperienza migliore?",
|
||||
"additionalComments": "Commenti aggiuntivi",
|
||||
"additionalCommentsPlaceholder": "C'è qualcos'altro che vorresti farci sapere?",
|
||||
"minCharsWarning": "Scrivi almeno 50 caratteri in uno dei campi sopra ({count}/50)",
|
||||
"minCharsWarning": "Scrivi almeno 50 caratteri in uno dei campi qui sopra ({count}/50)",
|
||||
"wouldRecommend": "Consiglierei Nomad Karaoke ad altri",
|
||||
"wouldUseAgain": "Userei di nuovo Nomad Karaoke",
|
||||
"submitting": "Invio...",
|
||||
"submitting": "Invio in corso...",
|
||||
"submitButton": "Invia feedback e guadagna 1 credito"
|
||||
},
|
||||
"push": {
|
||||
"iosTitle": "Ricevi notifiche sul tuo iPhone",
|
||||
"iosInstructions": "Per ricevere notifiche push su iOS, installa questa app nella tua schermata iniziale:",
|
||||
"iosInstructions": "Per ricevere notifiche push su iOS, installa questa app nella tua schermata Home:",
|
||||
"iosStep1": "Tocca il pulsante Condividi in Safari",
|
||||
"iosStep2": "Scorri verso il basso e tocca \"Aggiungi alla schermata Home\"",
|
||||
"iosStep3": "Apri l'app dalla tua schermata iniziale",
|
||||
"iosStep3": "Apri l'app dalla tua schermata Home",
|
||||
"iosNote": "iOS richiede che le app siano installate affinché le notifiche push funzionino.",
|
||||
"promptTitle": "Ricevi una notifica quando il tuo video è pronto",
|
||||
"promptDescription": "Ti invieremo una notifica quando il tuo video karaoke richiede attenzione o è pronto per il download.",
|
||||
"enabling": "Abilitazione...",
|
||||
"enabling": "Abilitazione in corso...",
|
||||
"enable": "Abilita notifiche",
|
||||
"notNow": "Non ora",
|
||||
"dontAskAgain": "Non chiederlo più",
|
||||
@@ -419,12 +416,12 @@
|
||||
"removeDevice": "Rimuovi questo dispositivo",
|
||||
"maxDevicesNote": "Puoi avere fino a 5 dispositivi iscritti. Aggiungerne altri rimuoverà l'iscrizione più vecchia.",
|
||||
"notAvailable": "Le notifiche push non sono disponibili su questo server.",
|
||||
"enabled": "Abilitate",
|
||||
"disabled": "Disabilitate"
|
||||
"enabled": "Abilitato",
|
||||
"disabled": "Disabilitato"
|
||||
},
|
||||
"tenant": {
|
||||
"title": "Karaoke Generator per {tenantName}",
|
||||
"description": "Crea video karaoke professionali con strumentali reali, sincronizzazione precisa del testo e output in 4K.",
|
||||
"description": "Crea video karaoke professionali con basi strumentali reali, sincronizzazione precisa del testo e output in 4K.",
|
||||
"signIn": "Accedi",
|
||||
"signInWithDomain": "Accedi con la tua email {domains}",
|
||||
"poweredBy": "Basato su Nomad Karaoke"
|
||||
@@ -436,15 +433,15 @@
|
||||
"visibility": "Visibilità",
|
||||
"customizeCreate": "Personalizza e crea"
|
||||
},
|
||||
"jobCreated": "Lavoro creato",
|
||||
"jobCreated": "Progetto creato",
|
||||
"whatsHappensNext": "Cosa succede dopo",
|
||||
"audioProcessing": "Elaborazione audio",
|
||||
"audioProcessingDesc": "Scarichiamo l'audio, separiamo la voce dalla base strumentale e trascriviamo il testo. ~10 minuti",
|
||||
"audioProcessingDesc": "Scarichiamo l'audio, separiamo le voci dalla base strumentale e trascriviamo il testo. ~10 minuti",
|
||||
"automatic": "Automatico",
|
||||
"youEditTheAudio": "Tu modifichi l'audio",
|
||||
"youEditDesc": "Taglia, riduci o silenzia sezioni dell'audio scaricato prima che inizi l'elaborazione.",
|
||||
"youEditDesc": "Taglia, accorcia o silenzia sezioni dell'audio scaricato prima che inizi l'elaborazione.",
|
||||
"you": "Tu",
|
||||
"emailChime": "Email + notifica sonora quando è pronto",
|
||||
"emailChime": "Email + suono quando pronto",
|
||||
"youReviewLyrics": "Tu rivedi il testo e la base strumentale",
|
||||
"youReviewDesc": "Controlla il testo e ascolta la base strumentale. Correggi eventuali errori e approva.",
|
||||
"videoDelivered": "Video consegnato",
|
||||
@@ -455,7 +452,7 @@
|
||||
"createAnother": "Creane un altro",
|
||||
"noCreditsWarning": "Non hai crediti rimanenti. Acquista crediti per creare nuovi video karaoke.",
|
||||
"buyCredits": "Acquista crediti",
|
||||
"weFindBestAudio": "Troviamo il miglior audio",
|
||||
"weFindBestAudio": "Troviamo l'audio migliore",
|
||||
"uploadAFile": "carica un file",
|
||||
"youtubeUrl": "URL di YouTube",
|
||||
"onNextPage": "(nella pagina successiva)",
|
||||
@@ -464,7 +461,7 @@
|
||||
"title": "Titolo",
|
||||
"titlePlaceholder": "es. Bohemian Rhapsody",
|
||||
"tipCallout": "Cerchi una versione specifica (live, cover, remix)? Includi quei dettagli nel titolo - es. \"Bohemian Rhapsody - Live at Wembley\".\nSe non riusciamo a trovare l'audio giusto, puoi fornire un URL di YouTube o caricare un file nella pagina successiva.",
|
||||
"customLyricsNote": "Stai creando un video con testo personalizzato? Inizia con l'artista/titolo della canzone originale qui - potrai cambiare la schermata del titolo e il testo in seguito.",
|
||||
"customLyricsNote": "Stai facendo un video con un testo personalizzato? Inizia con l'artista/titolo della canzone originale qui - potrai cambiare la schermata del titolo e il testo in seguito.",
|
||||
"unreleasedNote": "Hai una canzone inedita o un tuo file audio? Inserisci comunque l'artista e il titolo qui — potrai caricare il tuo file nel passaggio 2 e contrassegnarlo come privato nel passaggio 3 se non sei pronto a pubblicarlo.",
|
||||
"howShouldVideoBeShared": "Come dovrebbe essere condiviso il tuo video?",
|
||||
"chooseHowVideoDelivered": "Scegli come verrà consegnato il tuo video karaoke finito.",
|
||||
@@ -483,16 +480,16 @@
|
||||
"videoStaysWithYou": "Il tuo video karaoke rimane solo con te:",
|
||||
"deliveredViaDropboxOnly": "Consegnato solo tramite Dropbox — nessun caricamento su YouTube, nessuna condivisione su Google Drive. Scarica e usa come ritieni opportuno.",
|
||||
"venueUseUpToYou": "L'uso nei locali dipende da te — se vuoi esibirti con questa traccia in un locale, dovrai fornire tu stesso i file al presentatore.",
|
||||
"youtubeUploadOwn": "Caricamento autonomo su YouTube — puoi caricarlo sul tuo canale, ma la monetizzazione è improbabile poiché i diritti d'autore delle canzoni sono solitamente detenuti dalle etichette discografiche.",
|
||||
"youtubeUploadOwn": "Caricamento autonomo su YouTube — puoi caricarlo sul tuo canale, ma la monetizzazione è improbabile poiché i diritti d'autore delle canzoni sono tipicamente detenuti dalle etichette discografiche.",
|
||||
"customStylingAvailable": "Stile personalizzato disponibile — scegli le tue immagini di sfondo, i colori e gli stili di testo nel passaggio successivo.",
|
||||
"confirmArtistTitle": "Conferma l'artista e il titolo per la tua schermata del titolo.",
|
||||
"confirmArtistTitle": "Conferma l'artista e il titolo per la tua schermata iniziale.",
|
||||
"titleCardPreview": "Anteprima schermata del titolo",
|
||||
"titleCardArtist": "Artista sulla schermata del titolo",
|
||||
"sameAsAbove": "(uguale a sopra)",
|
||||
"artistOnTitleCard": "Artista sulla schermata del titolo",
|
||||
"titleCardTitle": "Titolo sulla schermata del titolo",
|
||||
"titleOnTitleCard": "Titolo sulla schermata del titolo",
|
||||
"defaultsToSearchValues": "Questi sono predefiniti ai tuoi valori di ricerca. Sostituiscili per colonne sonore, cover o formattazioni alternative.",
|
||||
"defaultsToSearchValues": "Questi valori predefiniti corrispondono alla tua ricerca. Modificali per colonne sonore, cover o formattazioni alternative.",
|
||||
"customVideoStyle": "Stile video personalizzato",
|
||||
"titleCard": "Schermata del titolo",
|
||||
"karaokeVideo": "Video Karaoke",
|
||||
@@ -537,11 +534,11 @@
|
||||
"inReview": "In revisione",
|
||||
"startingRender": "Avvio rendering",
|
||||
"renderingVideo": "Rendering video",
|
||||
"selectInstrumental": "Seleziona strumentale",
|
||||
"selectInstrumental": "Seleziona base strumentale",
|
||||
"startingFinalEncode": "Avvio codifica finale",
|
||||
"generatingFinalVideo": "Generazione video finale",
|
||||
"encodingVideo": "Codifica video",
|
||||
"packagingFiles": "Confezionamento file",
|
||||
"packagingFiles": "Preparazione file",
|
||||
"uploading": "Caricamento",
|
||||
"sendingNotifications": "Invio notifiche",
|
||||
"complete": "Completato",
|
||||
@@ -563,7 +560,7 @@
|
||||
"reviewLyrics": "Rivedi testo",
|
||||
"editAudio": "Modifica audio",
|
||||
"selectAudio": "Seleziona audio",
|
||||
"selectInstrumental": "Seleziona strumentale",
|
||||
"selectInstrumental": "Seleziona base strumentale",
|
||||
"autoAccept": "Accetterà automaticamente",
|
||||
"autoSelect": "Selezionerà automaticamente",
|
||||
"willAutoSelectFirst": "Selezionerà automaticamente il primo",
|
||||
@@ -591,17 +588,17 @@
|
||||
"supportedFormats": "MP3, WAV, FLAC, M4A o OGG",
|
||||
"youtubeUrlLabel": "URL di YouTube",
|
||||
"youtubeUrlPlaceholder": "https://youtube.com/watch?v=...",
|
||||
"artistTip": "Inizia a digitare e seleziona dai suggerimenti per una formattazione corretta, o digita liberamente.",
|
||||
"artistTip": "Inizia a digitare e seleziona dai suggerimenti per una formattazione corretta, oppure digita liberamente.",
|
||||
"privateNoYoutubeUpload": "Privato (nessun caricamento su YouTube)",
|
||||
"filesDropboxOnly": "File consegnati solo tramite Dropbox. Nessun caricamento su YouTube o Google Drive.",
|
||||
"searchForAudioOnline": "Cerca audio online",
|
||||
"useDisplayAs": "Usa artista/titolo diverso per la schermata del titolo",
|
||||
"displayArtist": "Artista visualizzato",
|
||||
"useDisplayAs": "Usa un artista/titolo diverso per la schermata del titolo",
|
||||
"displayArtist": "Artista da visualizzare",
|
||||
"displayArtistPlaceholder": "es., Footloose (Broadway Cast)",
|
||||
"displayTitle": "Titolo visualizzato",
|
||||
"displayTitle": "Titolo da visualizzare",
|
||||
"displayTitlePlaceholder": "es., I Can't Stand Still",
|
||||
"creatingJob": "Creazione lavoro...",
|
||||
"searching": "Ricerca...",
|
||||
"searching": "Ricerca in corso...",
|
||||
"searchCreateJob": "Cerca e crea lavoro",
|
||||
"outOfCredits": "Hai esaurito i crediti. Acquistane altri per continuare a creare video karaoke.",
|
||||
"failedToCreateJob": "Impossibile creare il lavoro"
|
||||
@@ -616,30 +613,30 @@
|
||||
"txt": "TXT",
|
||||
"makePublic": "Rendi pubblico",
|
||||
"makePrivate": "Rendi privato",
|
||||
"makingPublic": "Rendo pubblico...",
|
||||
"makingPrivate": "Rendo privato...",
|
||||
"makingPublic": "Rendendo pubblico...",
|
||||
"makingPrivate": "Rendendo privato...",
|
||||
"email": "Email",
|
||||
"admin": "Admin",
|
||||
"sendCompletionEmail": "Invia email di completamento",
|
||||
"sendToEmailDesc": "Invia il messaggio di completamento del lavoro a un indirizzo email. L'email sarà inviata in CC a gen@nomadkaraoke.com.",
|
||||
"sendToEmailDesc": "Invia il messaggio di completamento del lavoro a un indirizzo email. L'email sarà in CC a gen@nomadkaraoke.com.",
|
||||
"emailAddress": "Email",
|
||||
"emailPlaceholder": "cliente@esempio.com",
|
||||
"sendEmail": "Invia email",
|
||||
"sending": "Invio...",
|
||||
"sending": "Invio in corso...",
|
||||
"sent": "Inviato!",
|
||||
"makePublicTitle": "Rendere pubblica questa traccia?",
|
||||
"makePrivateTitle": "Rendere privata questa traccia?",
|
||||
"thisWill": "Questo comporterà:",
|
||||
"removeCustomStyling": "Rimuovi qualsiasi stile personalizzato (sfondi, colori) e ripristina il tema standard di Nomad Karaoke",
|
||||
"regenerateTitleEndScreens": "Rigenera le schermate del titolo e finali",
|
||||
"reRenderWithDefault": "Esegui nuovamente il rendering del video karaoke con il branding predefinito",
|
||||
"publishToAll": "Pubblica su YouTube, Google Drive e Dropbox",
|
||||
"removeCustomStyling": "Rimuovere qualsiasi stile personalizzato (sfondi, colori) e ripristinare il tema standard di Nomad Karaoke",
|
||||
"regenerateTitleEndScreens": "Rigenerare le schermate del titolo e finali",
|
||||
"reRenderWithDefault": "Eseguire nuovamente il rendering del video karaoke con il branding predefinito",
|
||||
"publishToAll": "Pubblicare su YouTube, Google Drive e Dropbox",
|
||||
"takes15To30Minutes": "Questo processo richiede circa 15-30 minuti. Riceverai un'email quando sarà completato.",
|
||||
"customStylingRemoved": "Qualsiasi stile personalizzato applicato verrà rimosso definitivamente.",
|
||||
"removeFromYoutube": "Rimuovi il video da YouTube",
|
||||
"removeFromGoogleDrive": "Rimuovi i file da Google Drive",
|
||||
"moveDropboxPrivate": "Sposta i file Dropbox dalla cartella pubblica alla cartella privata",
|
||||
"assignPrivateBrand": "Assegna un nuovo codice brand privato",
|
||||
"removeFromYoutube": "Rimuovere il video da YouTube",
|
||||
"removeFromGoogleDrive": "Rimuovere i file da Google Drive",
|
||||
"moveDropboxPrivate": "Spostare i file Dropbox dalla cartella pubblica alla cartella privata",
|
||||
"assignPrivateBrand": "Assegnare un nuovo codice brand privato",
|
||||
"videoContentWontChange": "Il contenuto del video non cambierà. Questo di solito richiede circa 1-2 minuti.",
|
||||
"canChangeBack": "Puoi renderlo di nuovo pubblico in seguito, ma ciò richiederà un nuovo rendering del video (~15-30 minuti).",
|
||||
"copyYoutubeUrl": "Copia URL di YouTube",
|
||||
@@ -690,9 +687,9 @@
|
||||
"overrideThemeColors": "Sostituisci i colori del tema (opzionale)",
|
||||
"resetAll": "Reimposta tutto",
|
||||
"artistColor": "Colore artista",
|
||||
"artistColorDesc": "Colore per il nome dell'artista sulle schermate del titolo/finali",
|
||||
"artistColorDesc": "Colore per il nome dell'artista nelle schermate del titolo/finali",
|
||||
"titleColor": "Colore titolo",
|
||||
"titleColorDesc": "Colore per il titolo della canzone sulle schermate del titolo/finali",
|
||||
"titleColorDesc": "Colore per il titolo della canzone nelle schermate del titolo/finali",
|
||||
"sungLyricsColor": "Colore testo cantato",
|
||||
"sungLyricsColorDesc": "Colore per il testo che viene cantato (evidenziato)",
|
||||
"unsungLyricsColor": "Colore testo non cantato",
|
||||
@@ -705,7 +702,7 @@
|
||||
"tipsForChoosing": "Suggerimenti per la scelta",
|
||||
"tipFilename": "Controlla che il nome del file corrisponda al titolo della tua canzone",
|
||||
"tipAvailability": "Badge di disponibilità verde = download più affidabile",
|
||||
"tipStudioAlbum": "Le versioni da album in studio producono i migliori risultati karaoke",
|
||||
"tipStudioAlbum": "Le versioni degli album in studio producono i migliori risultati karaoke",
|
||||
"tipVinylRips": "Evita i rip da vinile (il rumore di superficie influisce sulla separazione)",
|
||||
"tipYoutube": "YouTube è l'ultima risorsa — le sorgenti lossless suonano meglio",
|
||||
"noAudioSources": "Nessuna sorgente audio trovata",
|
||||
@@ -723,7 +720,7 @@
|
||||
"couldNotLoadData": "Impossibile caricare i dati audio.",
|
||||
"backToDashboard": "Torna alla dashboard",
|
||||
"editComplete": "Modifica audio completata!",
|
||||
"editsWillBeReviewed": "Le tue modifiche verranno riviste dopo che il video avrà terminato l'elaborazione.",
|
||||
"editsWillBeReviewed": "Le tue modifiche verranno esaminate dopo che il video avrà terminato l'elaborazione.",
|
||||
"redirectingIn": "Reindirizzamento in {count} secondi...",
|
||||
"trimStart": "Taglia inizio",
|
||||
"trimEnd": "Taglia fine",
|
||||
@@ -763,12 +760,12 @@
|
||||
"selectToPreview": "Seleziona una sessione per l'anteprima",
|
||||
"startFresh": "Inizia da zero",
|
||||
"restoreSelected": "Ripristina selezionata",
|
||||
"restoring": "Ripristino...",
|
||||
"latest": "[Ultima]"
|
||||
"restoring": "Ripristino in corso...",
|
||||
"latest": "[Più recente]"
|
||||
},
|
||||
"lyricsReview": {
|
||||
"header": {
|
||||
"viewOnlyMode": "Modalità solo visualizzazione",
|
||||
"viewOnlyMode": "Modalità di sola visualizzazione",
|
||||
"loadFile": "Carica file",
|
||||
"reviewMode": "Modalità revisione",
|
||||
"reviewOff": "Revisione disattivata",
|
||||
@@ -785,10 +782,10 @@
|
||||
"findReplace": "Trova/Sostituisci",
|
||||
"findReplaceDesc": "Cerca del testo in tutto il testo della canzone e sostituiscilo. Utile per una parola che appare più volte.",
|
||||
"editAll": "Modifica tutto",
|
||||
"editAllDesc": "Visualizza e modifica tutto il testo come testo normale. Utile quando molte righe devono essere modificate.",
|
||||
"editAllDesc": "Visualizza e modifica tutto il testo come testo normale. Utile quando molte righe devono essere cambiate.",
|
||||
"timingOffset": "Offset temporale",
|
||||
"timingOffsetValue": "{ms}ms",
|
||||
"timingOffsetDesc": "Sposta tutti i tempi delle parole in avanti o all'indietro. Usalo se il testo appare leggermente in anticipo o in ritardo nell'anteprima.",
|
||||
"timingOffsetDesc": "Sposta il tempismo di tutte le parole in avanti o all'indietro. Usalo se il testo appare leggermente in anticipo o in ritardo nell'anteprima.",
|
||||
"playback": "Riproduzione"
|
||||
},
|
||||
"guidance": {
|
||||
@@ -798,13 +795,13 @@
|
||||
"matched": "Corrispondenti",
|
||||
"gapsNeedsReview": "Lacune (da rivedere)",
|
||||
"corrected": "Corretti",
|
||||
"noReferenceFound": "Nessun testo di riferimento è stato trovato per questa traccia. Puoi comunque rivedere la trascrizione e cliccare su qualsiasi parola per modificarla. Usa il pannello Testo di riferimento a destra per cercare il testo con un artista/titolo diverso.",
|
||||
"noReferenceFound": "Nessun testo di riferimento trovato per questa traccia. Puoi comunque rivedere la trascrizione e cliccare su qualsiasi parola per modificarla. Usa il pannello Testo di riferimento a destra per cercare il testo con un artista/titolo diverso.",
|
||||
"allMatched": "Tutto il testo corrisponde al riferimento — nessuna correzione necessaria. Puoi comunque cliccare su qualsiasi parola per modificarla.",
|
||||
"syncedLyricsOnLeft": "Il testo sincronizzato a sinistra è quello che apparirà nel video karaoke.",
|
||||
"orangeHighlightedWords": "Le parole evidenziate in arancione sono lacune — sezioni che non è stato possibile abbinare al testo di riferimento e potrebbero contenere errori (es. parole fraintese che suonano in modo simile).",
|
||||
"syncedLyricsOnLeft": "Il Testo sincronizzato a sinistra è quello che apparirà nel video karaoke.",
|
||||
"orangeHighlightedWords": "Le parole evidenziate in arancione sono lacune — sezioni che non è stato possibile abbinare al testo di riferimento e che potrebbero contenere errori (es. parole fraintese che suonano in modo simile).",
|
||||
"useNAndP": "Usa N e P per saltare tra le lacune. Per ognuna, clicca su play accanto alla riga e confronta ciò che senti con il testo di riferimento a destra, poi clicca su una parola per modificarla o eliminarla.",
|
||||
"watchOutForPhantomWords": "Fai attenzione alle parole fantasma come \"and\" all'inizio o alla fine delle righe — la trascrizione spesso le aggiunge.",
|
||||
"tryTimelineView": "Prova la vista Timeline per individuare eventuali parole insolitamente lunghe (10+ secondi), che di solito indicano un problema di tempismo.",
|
||||
"tryTimelineView": "Prova la visualizzazione Timeline per individuare eventuali parole insolitamente lunghe (10+ secondi), che di solito indicano un problema di tempismo.",
|
||||
"watchFullTutorial": "Guarda il tutorial completo",
|
||||
"correctionHandlers": "Gestori di correzione",
|
||||
"anchorSequences": "Sequenze di ancoraggio",
|
||||
@@ -822,7 +819,7 @@
|
||||
},
|
||||
"transcription": {
|
||||
"syncedLyrics": "Testo sincronizzato",
|
||||
"advanced": "Avanzate",
|
||||
"advanced": "Avanzato",
|
||||
"simple": "Semplice",
|
||||
"text": "Testo",
|
||||
"timeline": "Timeline",
|
||||
@@ -877,7 +874,7 @@
|
||||
"copyAll": "Copia tutto il testo di riferimento"
|
||||
},
|
||||
"referenceEmpty": {
|
||||
"noReferenceFound": "Nessun testo di riferimento è stato trovato per questa canzone. Cerca in tutti i provider di testi configurati o incolla il testo manualmente per abilitare la correzione delle lacune.",
|
||||
"noReferenceFound": "Nessun testo di riferimento trovato per questa canzone. Cerca in tutti i provider di testi configurati o incolla il testo manualmente per abilitare la correzione delle lacune.",
|
||||
"search": "Cerca",
|
||||
"paste": "Incolla"
|
||||
},
|
||||
@@ -888,7 +885,7 @@
|
||||
"searchPlaceholder": "Cerca per artista, titolo o ID lavoro...",
|
||||
"noSessions": "Nessuna sessione salvata trovata",
|
||||
"searchAcrossAllJobs": "Cerca sessioni in tutti i lavori",
|
||||
"selectToPreview": "Seleziona una sessione per visualizzare in anteprima le modifiche",
|
||||
"selectToPreview": "Seleziona una sessione per visualizzare l'anteprima delle modifiche",
|
||||
"startFresh": "Inizia da zero",
|
||||
"restoreSelected": "Ripristina selezionata",
|
||||
"durationMismatchTitle": "Mancata corrispondenza della durata",
|
||||
@@ -902,7 +899,7 @@
|
||||
},
|
||||
"previewVideo": {
|
||||
"generating": "Generazione video di anteprima...",
|
||||
"startingEncoder": "Avvio del worker di codifica... Questo di solito richiede circa un minuto.",
|
||||
"startingEncoder": "Avvio del worker di codifica... Di solito richiede circa un minuto.",
|
||||
"failed": "Impossibile generare il video di anteprima",
|
||||
"unsupportedBrowser": "Il tuo browser non supporta il tag video."
|
||||
},
|
||||
@@ -920,7 +917,7 @@
|
||||
"metadata": "Metadati",
|
||||
"handler": "Gestore: {handler}",
|
||||
"source": "Sorgente: {source}",
|
||||
"revertToOriginal": "Ripristina all'originale",
|
||||
"revertToOriginal": "Ripristina originale",
|
||||
"editCorrection": "Modifica correzione",
|
||||
"markAsCorrect": "Segna come corretto"
|
||||
},
|
||||
@@ -930,7 +927,7 @@
|
||||
"avgConfidence": "Affidabilità media:",
|
||||
"low": "Bassa (<60%):",
|
||||
"high": "Alta (≥80%):",
|
||||
"byCategory": "Per categoria",
|
||||
"byCategory": "Per Categoria",
|
||||
"noCorrections": "Nessuna correzione agentica"
|
||||
},
|
||||
"modals": {
|
||||
@@ -970,12 +967,12 @@
|
||||
"find": "Trova",
|
||||
"findPlaceholder": "Testo da trovare...",
|
||||
"replaceWith": "Sostituisci con",
|
||||
"replacePlaceholder": "Testo di sostituzione...",
|
||||
"replacePlaceholder": "Testo sostitutivo...",
|
||||
"caseSensitive": "Maiuscole/minuscole",
|
||||
"useRegex": "Usa regex",
|
||||
"fullTextMode": "Modalità testo completo",
|
||||
"preview": "Anteprima",
|
||||
"emptyWordsWarning": "Alcune sostituzioni risulteranno in parole vuote, che verranno rimosse.",
|
||||
"emptyWordsWarning": "Alcune sostituzioni produrranno parole vuote, che verranno rimosse.",
|
||||
"noMatches": "Nessuna corrispondenza trovata",
|
||||
"matchesFound": "{count} {count, plural, one {corrispondenza trovata} other {corrispondenze trovate}}",
|
||||
"replaceAll": "Sostituisci tutto ({count})"
|
||||
@@ -991,10 +988,7 @@
|
||||
"replaceSegmentRecommended": "Consigliato per testi personalizzati",
|
||||
"replaceAllTitle": "Sostituisci tutto il testo",
|
||||
"replaceAllDesc": "Incolla un testo completamente nuovo dagli appunti e sincronizza manualmente il tempismo per tutte le parole da zero.",
|
||||
"replaceAllWarning": "Tutti i dati di tempismo esistenti andranno persi",
|
||||
"changeCaseDesc": "Converti tutto il testo in MAIUSCOLO, minuscolo, Iniziali Maiuscole o Maiuscolo a inizio frase. La sincronizzazione rimane inalterata.",
|
||||
"changeCaseRecommended": "Consigliato per la coerenza dello stile",
|
||||
"changeCaseTitle": "Cambia maiuscole/minuscole"
|
||||
"replaceAllWarning": "Tutti i dati di tempismo esistenti andranno persi"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Incolla il tuo nuovo testo qui sotto:",
|
||||
@@ -1002,40 +996,27 @@
|
||||
"pasteFromClipboard": "Incolla dagli appunti",
|
||||
"lineWordCount": "{lines} righe, {words} parole",
|
||||
"placeholder": "Incolla il tuo testo qui...\nOgni riga diventerà un segmento\nLe parole saranno separate da spazi",
|
||||
"continueToSync": "Continua alla sincronizzazione",
|
||||
"continueToSync": "Continua per sincronizzare",
|
||||
"replaceAll": "Sostituisci tutto il testo",
|
||||
"replaceSegment": "Sostituisci il testo del segmento",
|
||||
"editLineByLine": "Modifica il testo riga per riga. Ogni riga corrisponde a un segmento temporizzato. Il numero di righe deve rimanere lo stesso (attualmente: {count} righe). Le righe modificate otterranno un nuovo tempismo delle parole stimato dalla durata del segmento. Le righe non modificate vengono lasciate così come sono.",
|
||||
"tooManyLines": "Hai {diff} righe di troppo (attese {expected}, ottenute {actual}). Ogni riga è mappata a un segmento temporizzato, quindi il conteggio deve corrispondere esattamente.",
|
||||
"tooFewLines": "Hai {diff} righe in meno (attese {expected}, ottenute {actual}). Ogni riga è mappata a un segmento temporizzato, quindi il conteggio deve corrispondere esattamente.",
|
||||
"tooManyLines": "Hai {diff} righe di troppo (previste {expected}, ottenute {actual}). Ogni riga è mappata a un segmento temporizzato, quindi il conteggio deve corrispondere esattamente.",
|
||||
"tooFewLines": "Hai {diff} righe in meno (previste {expected}, ottenute {actual}). Ogni riga è mappata a un segmento temporizzato, quindi il conteggio deve corrispondere esattamente.",
|
||||
"syncNewLyrics": "Sincronizza nuovo testo",
|
||||
"resyncExisting": "Risincronizza il testo esistente",
|
||||
"resyncExisting": "Risincronizza testo esistente",
|
||||
"noLyricsToSync": "Nessun testo da sincronizzare",
|
||||
"goBackAndPaste": "Torna indietro e incolla un nuovo testo, oppure chiudi questo modale.",
|
||||
"backToSelection": "Torna alla selezione",
|
||||
"caseLower": "minuscolo",
|
||||
"caseLowerDesc": "tutte le lettere minuscole",
|
||||
"caseSentence": "Maiuscolo a inizio frase",
|
||||
"caseSentenceDesc": "Prima parola di ogni riga in maiuscolo",
|
||||
"caseTitle": "Iniziali Maiuscole",
|
||||
"caseTitleDesc": "Ogni Parola In Maiuscolo",
|
||||
"caseUpper": "MAIUSCOLO",
|
||||
"caseUpperDesc": "TUTTE LE LETTERE IN MAIUSCOLO",
|
||||
"changeCase": "Cambia maiuscole/minuscole",
|
||||
"changeCaseApply": "Applica {case}",
|
||||
"changeCaseNote": "La sincronizzazione delle parole rimane inalterata — cambiano solo le maiuscole/minuscole.",
|
||||
"changeCasePreview": "Anteprima",
|
||||
"changeCasePrompt": "Scegli uno stile di maiuscole/minuscole da applicare a tutto il testo:"
|
||||
"backToSelection": "Torna alla selezione"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Anteprima video (Con voce)",
|
||||
"noLyricsTitle": "Nessun testo rilevato",
|
||||
"noLyricsDesc": "Nessun testo è stato trovato nell'audio. Questo di solito accade quando l'audio di input non ha voce (es. una traccia karaoke o strumentale).",
|
||||
"noLyricsHint": "Puoi tornare indietro e incollare il testo manualmente usando Sostituisci tutto, oppure annullare questo lavoro e riprovare con un file audio che contiene la voce.",
|
||||
"manualCorrectionsDetected": "Correzioni manuali rilevate. Rivedi l'anteprima per assicurarti che il testo sia sincronizzato correttamente.",
|
||||
"noManualCorrections": "Nessuna correzione manuale rilevata. Se tutto sembra a posto nell'anteprima, procedi alla selezione della tua base strumentale.",
|
||||
"manualCorrectionsDetected": "Rilevate correzioni manuali. Rivedi l'anteprima per assicurarti che il testo sia sincronizzato correttamente.",
|
||||
"noManualCorrections": "Nessuna correzione manuale rilevata. Se tutto sembra a posto nell'anteprima, procedi a selezionare la tua base strumentale.",
|
||||
"totalSegments": "Segmenti totali: {count}",
|
||||
"proceedToInstrumental": "Procedi alla revisione strumentale",
|
||||
"proceedToInstrumental": "Procedi alla revisione della base strumentale",
|
||||
"saving": "Salvataggio..."
|
||||
},
|
||||
"searchLyrics": {
|
||||
@@ -1043,13 +1024,13 @@
|
||||
"artistPlaceholder": "Nome dell'artista",
|
||||
"title": "Titolo",
|
||||
"titlePlaceholder": "Titolo della canzone",
|
||||
"searchDesc": "Cerca in tutti i provider di testi configurati (Genius, AZLyrics, ecc.) e aggiunge eventuali risultati che corrispondono strettamente a questa canzone.",
|
||||
"searchDesc": "Cerca in tutti i provider di testi configurati (Genius, AZLyrics, ecc.) e aggiunge eventuali risultati che corrispondono bene a questa canzone.",
|
||||
"searchAll": "Cerca in tutti i provider",
|
||||
"searching": "Ricerca...",
|
||||
"searching": "Ricerca in corso...",
|
||||
"searchAgain": "Cerca di nuovo",
|
||||
"noMatches": "Nessun testo corrispondente trovato in tutti i provider.",
|
||||
"notFound": "Non trovato: {sources}",
|
||||
"lowConfidence": "Risultati a bassa affidabilità — seleziona per forzare l'aggiunta:",
|
||||
"lowConfidence": "Risultati a bassa affidabilità — selezionane uno per forzare l'aggiunta:",
|
||||
"matched": "Corrispondenza: {matched}/{total} parole ({relevance}% rilevanza)",
|
||||
"addSelected": "Aggiungi selezionati ({count})"
|
||||
},
|
||||
@@ -1059,7 +1040,7 @@
|
||||
"timingOffset": {
|
||||
"title": "Regola offset temporale",
|
||||
"offsetLabel": "Offset (millisecondi)",
|
||||
"offsetDesc": "I valori positivi spostano il testo in ritardo, i valori negativi lo spostano in anticipo.",
|
||||
"offsetDesc": "I valori positivi spostano il testo più tardi, i valori negativi lo spostano prima.",
|
||||
"currentOffset": "Offset attuale:",
|
||||
"newOffset": "Nuovo offset:",
|
||||
"change": "Variazione:",
|
||||
@@ -1071,7 +1052,7 @@
|
||||
"lyrics": "Testo",
|
||||
"lyricsPlaceholder": "Incolla il testo qui...",
|
||||
"addLyrics": "Aggiungi testo",
|
||||
"adding": "Aggiunta..."
|
||||
"adding": "Aggiunta in corso..."
|
||||
},
|
||||
"correctionAnnotation": {
|
||||
"title": "Annota la tua correzione",
|
||||
@@ -1089,8 +1070,8 @@
|
||||
"correctionType": "Tipo di correzione *",
|
||||
"types": {
|
||||
"soundAlike": "Errore di suono simile",
|
||||
"soundAlikeDesc": "Omofoni o parole dal suono simile (es., \"out\" vs \"now\")",
|
||||
"backgroundVocals": "Cori",
|
||||
"soundAlikeDesc": "Omofoni o parole dal suono simile (es. \"out\" vs \"now\")",
|
||||
"backgroundVocals": "Cori di sottofondo",
|
||||
"backgroundVocalsDesc": "Cori che dovrebbero essere rimossi dal karaoke",
|
||||
"extraFiller": "Parole riempitive extra",
|
||||
"extraFillerDesc": "La trascrizione ha aggiunto parole come \"And\", \"But\", \"Well\"",
|
||||
@@ -1107,11 +1088,11 @@
|
||||
"manualEdit": "Modifica manuale",
|
||||
"manualEditDesc": "Correzione avviata dall'uomo non da una lacuna rilevata"
|
||||
},
|
||||
"confidence": "Affidabilità nella tua correzione *",
|
||||
"confidence": "Fiducia nella tua correzione *",
|
||||
"confidenceLevels": {
|
||||
"1": "1 - Molto incerto",
|
||||
"2": "2 - Abbastanza incerto",
|
||||
"3": "3 - Neutro",
|
||||
"3": "3 - Neutrale",
|
||||
"4": "4 - Abbastanza sicuro",
|
||||
"5": "5 - Molto sicuro"
|
||||
},
|
||||
@@ -1130,12 +1111,12 @@
|
||||
"allWordsSynced": "Tutte le parole sincronizzate!",
|
||||
"clickStopSync": "Clicca \"Ferma sincronizzazione\" poi \"Applica\" per salvare",
|
||||
"pressSpacebar": "Premi la BARRA SPAZIATRICE quando senti ogni parola",
|
||||
"tapForShort": "Tocca per le parole brevi, tieni premuto per le parole più lunghe",
|
||||
"tapForShort": "Tocca per parole brevi, tieni premuto per parole più lunghe",
|
||||
"clickStartSync": "Clicca \"Avvia sincronizzazione\" per iniziare a temporizzare le parole",
|
||||
"audioWillPlay": "L'audio verrà riprodotto e tu toccherai la barra spaziatrice per ogni parola",
|
||||
"wordsRemaining": "{remaining} parole rimanenti da sincronizzare",
|
||||
"clickStartContinue": "Clicca \"Avvia sincronizzazione\" per continuare, o \"Annulla sincronizzazione dal cursore\" per risincronizzare da un punto",
|
||||
"allSyncedApply": "Tutte le parole sincronizzate! Clicca \"Applica\" per salvare le modifiche, o fai prima degli aggiustamenti",
|
||||
"clickStartContinue": "Clicca \"Avvia sincronizzazione\" per continuare, o \"Desincronizza dal cursore\" per risincronizzare da un punto",
|
||||
"allSyncedApply": "Tutte le parole sincronizzate! Clicca \"Applica\" per salvare le modifiche, o fai prima delle regolazioni",
|
||||
"editingResetsWarning": "La modifica del testo ripristinerà tutti i dati di tempismo. Dovrai risincronizzare l'intera canzone.",
|
||||
"lyricsPlaceholder": "Inserisci il testo, una riga per segmento...",
|
||||
"saveAndResetTiming": "Salva e reimposta tempismo",
|
||||
@@ -1153,7 +1134,7 @@
|
||||
"release": "Rilascia",
|
||||
"clearSync": "Cancella sincronizzazione",
|
||||
"editLyrics": "Modifica testo",
|
||||
"unsyncFromCursor": "Annulla sincronizzazione dal cursore",
|
||||
"unsyncFromCursor": "Desincronizza dal cursore",
|
||||
"editWord": "Modifica parola",
|
||||
"deleteCount": "Elimina ({count})"
|
||||
},
|
||||
@@ -1162,16 +1143,16 @@
|
||||
},
|
||||
"instrumentalReview": {
|
||||
"separationInProgress": "Separazione audio in corso",
|
||||
"separationInProgressDesc": "Le tracce audio separate sono ancora in fase di elaborazione. Questo di solito richiede alcuni minuti. Questa pagina si aggiornerà automaticamente quando la separazione sarà completata.",
|
||||
"separationInProgressDesc": "Le tracce audio sono ancora in fase di separazione. Questo di solito richiede alcuni minuti. Questa pagina si aggiornerà automaticamente quando la separazione sarà completata.",
|
||||
"loadingAnalysis": "Caricamento analisi strumentale...",
|
||||
"review": "Revisione",
|
||||
"title": "Revisione strumentale",
|
||||
"title": "Revisione base strumentale",
|
||||
"cleanRecommended": "Pulita consigliata",
|
||||
"reviewBackingVocals": "Rivedi i cori",
|
||||
"alternateInstrumental": "Strumentale alternativa",
|
||||
"alternateInstrumental": "Base strumentale alternativa",
|
||||
"uploadYourOwn": "Hai la tua traccia strumentale? Caricala qui. Il file deve avere la stessa durata dell'audio originale ({duration}) in modo che il testo sincronizzato rimanga allineato.",
|
||||
"usingFile": "In uso: {filename}",
|
||||
"submitting": "Invio...",
|
||||
"submitting": "Invio in corso...",
|
||||
"confirmContinue": "Conferma e continua",
|
||||
"closingIn": "Chiusura in {countdown}s...",
|
||||
"redirectingIn": "Reindirizzamento in {countdown}s...",
|
||||
@@ -1189,27 +1170,27 @@
|
||||
"backingVocalsDetected": "{percentage}% di cori rilevati",
|
||||
"segmentsCount": "({count} segmenti)",
|
||||
"backingVocalsIncluded": "Include i cori dall'originale",
|
||||
"cleanDescription": "Nessun coro - puramente strumentale",
|
||||
"cleanDescription": "Nessun coro - base strumentale pura",
|
||||
"guidance": {
|
||||
"chooseBackingTrack": "Scegli la tua base karaoke. L'IA ha separato la voce dalla musica — ora scegli quale versione suona meglio.",
|
||||
"littleBackingVocals": "Questa traccia ha pochissimi cori ({percentage}%). Consigliamo la Strumentale pulita — conferma qui sotto per procedere.",
|
||||
"hearDifference": "Vuoi sentire la differenza? Usa i pulsanti audio sopra per confrontare, o clicca sulle sezioni rosa nella forma d'onda per ascoltare i cori.",
|
||||
"chooseBackingTrack": "Scegli la tua base karaoke. L'IA ha separato le voci dalla musica — ora scegli quale versione suona meglio.",
|
||||
"littleBackingVocals": "Questa traccia ha pochissimo contenuto di cori ({percentage}%). Consigliamo la Base strumentale pulita — basta confermare qui sotto per procedere.",
|
||||
"hearDifference": "Vuoi sentire la differenza? Usa i pulsanti audio qui sopra per confrontare, o clicca sulle sezioni rosa nella forma d'onda per ascoltare i cori.",
|
||||
"watchFullTutorial": "Guarda il tutorial completo",
|
||||
"backingVocalsExplanation": "I cori sono le voci di armonia/ritornello che cantano insieme alla voce principale. Alcuni cantanti di karaoke preferiscono mantenerli come guida, altri preferiscono una base strumentale pulita.",
|
||||
"step1": "Passaggio 1: Clicca sulle sezioni rosa nella forma d'onda per ascoltare i cori{segments}.",
|
||||
"step2": "Passaggio 2: Decidi — mantenerli o usare la base strumentale pulita? Usa i pulsanti di attivazione/disattivazione audio sopra per confrontare.",
|
||||
"step3": "Passaggio 3 (se necessario): Se vuoi i cori ma alcune sezioni hanno sbavature indesiderate della voce principale, Shift+trascina sulla forma d'onda per contrassegnare quelle sezioni, quindi clicca su Crea personalizzato.",
|
||||
"step2": "Passaggio 2: Decidi — mantenerli o usare la base strumentale pulita? Usa i pulsanti di attivazione audio qui sopra per confrontare.",
|
||||
"step3": "Passaggio 3 (se necessario): Se vuoi i cori ma alcune sezioni hanno un indesiderato rientro della voce principale, Shift+trascina sulla forma d'onda per contrassegnare quelle sezioni, quindi clicca su Crea personalizzato.",
|
||||
"showTips": "Mostra suggerimenti",
|
||||
"dismissTip": "Nascondi suggerimento"
|
||||
},
|
||||
"options": {
|
||||
"finalSelection": "Selezione finale",
|
||||
"cleanInstrumental": "Strumentale pulita",
|
||||
"cleanInstrumental": "Base strumentale pulita",
|
||||
"noBackingVocals": "Nessun coro",
|
||||
"withBackingVocals": "Con cori",
|
||||
"allBackingVocalsIncluded": "Tutti i cori inclusi",
|
||||
"originalAudio": "Audio originale",
|
||||
"fullOriginalWithVocals": "Originale completo con voce principale",
|
||||
"fullOriginalWithVocals": "Originale completo con voci principali",
|
||||
"custom": "Personalizzato",
|
||||
"customRegionsMuted": "{count} {count, plural, one {regione silenziata} other {regioni silenziate}}",
|
||||
"uploaded": "Caricato",
|
||||
@@ -1221,149 +1202,25 @@
|
||||
"stemComparison": {
|
||||
"original": "Originale",
|
||||
"backingVocalsOnly": "Solo cori",
|
||||
"pureInstrumental": "Puramente strumentale",
|
||||
"pureInstrumental": "Strumentale pura",
|
||||
"instrumentalPlusBacking": "Strumentale + Cori",
|
||||
"custom": "Personalizzato",
|
||||
"uploaded": "Caricato"
|
||||
},
|
||||
"customUpload": {
|
||||
"uploading": "Caricamento...",
|
||||
"uploading": "Caricamento in corso...",
|
||||
"upload": "Carica"
|
||||
},
|
||||
"muteRegion": {
|
||||
"title": "Mix personalizzato",
|
||||
"titleWithCount": "Mix personalizzato ({count} silenziati)",
|
||||
"clear": "Pulisci",
|
||||
"clear": "Cancella",
|
||||
"createCustom": "Crea personalizzato",
|
||||
"creating": "Creazione...",
|
||||
"explanation": "Vuoi i cori ma senti sbavature della voce principale in alcune sezioni? Silenzia quelle sezioni per creare un mix personalizzato.",
|
||||
"creating": "Creazione in corso...",
|
||||
"explanation": "Vuoi i cori ma senti il rientro della voce principale in alcune sezioni? Silenzia quelle sezioni per creare un mix personalizzato.",
|
||||
"clickSegment": "Clicca su un segmento qui sotto per silenziarlo, o Shift+trascina sulla forma d'onda per contrassegnare una regione personalizzata.",
|
||||
"noBackingDetected": "Nessun coro rilevato — consigliata strumentale pulita.",
|
||||
"noBackingDetected": "Nessun coro rilevato — consigliata base strumentale pulita.",
|
||||
"addToMuteRegions": "Aggiungi alle regioni da silenziare"
|
||||
}
|
||||
},
|
||||
"referrals": {
|
||||
"title": "Inviti",
|
||||
"backToDashboard": "Torna alla Dashboard",
|
||||
"howItWorksTitle": "Come funziona",
|
||||
"howItWorksIntro": "Guadagna denaro condividendo Nomad Karaoke con i tuoi amici, il tuo pubblico o la tua community. È semplice — condividi il tuo link univoco e quando le persone si iscrivono e fanno acquisti, ne traete vantaggio entrambi.",
|
||||
"howStep1Title": "Condividi il tuo link",
|
||||
"howStep1Desc": "Invia il tuo link di invito univoco agli amici o condividilo sui social media, sul tuo sito web o agli eventi.",
|
||||
"howStep2Title": "Loro ottengono uno sconto",
|
||||
"howStep2Desc": "Chiunque si iscriva tramite il tuo link ottiene il {discount}% di sconto su tutti gli acquisti di crediti per {days} giorni.",
|
||||
"howStep3Title": "Tu guadagni contanti",
|
||||
"howStep3Desc": "Guadagni il {kickback}% di ogni acquisto che effettuano entro {days} giorni dall'iscrizione.",
|
||||
"howPayoutTitle": "Quando vengo pagato?",
|
||||
"howPayoutDesc": "I guadagni si accumulano nel tuo saldo. Una volta raggiunti i $20 e aver collegato il tuo conto bancario tramite Stripe, i pagamenti vengono inviati automaticamente. Puoi monitorare tutto proprio qui su questa pagina.",
|
||||
"yourLink": "Il tuo link di invito",
|
||||
"copyLink": "Copia link",
|
||||
"copied": "Copiato!",
|
||||
"vanityRequest": "Vuoi un URL personalizzato? Richiedi un link personalizzato",
|
||||
"vanityPlaceholder": "il-tuo-nome",
|
||||
"vanitySubmit": "Richiedi",
|
||||
"vanityRequested": "Richiesta inviata! Ti risponderemo presto.",
|
||||
"displayName": "Nome visualizzato",
|
||||
"customMessage": "Messaggio personalizzato",
|
||||
"customMessagePlaceholder": "Dì ai tuoi amici perché dovrebbero provare Nomad Karaoke...",
|
||||
"save": "Salva",
|
||||
"stats": "Statistiche",
|
||||
"clicks": "Clic",
|
||||
"signups": "Iscrizioni",
|
||||
"purchases": "Acquisti",
|
||||
"earnings": "Guadagni",
|
||||
"pendingBalance": "Saldo in sospeso",
|
||||
"totalEarned": "Totale guadagnato",
|
||||
"totalPaid": "Totale pagato",
|
||||
"termDiscount": "Sconto per inviti",
|
||||
"termDiscountWindow": "Finestra di sconto",
|
||||
"termKickback": "La tua ricompensa",
|
||||
"termEarningWindow": "Finestra di guadagno",
|
||||
"recentEarnings": "Guadagni recenti",
|
||||
"recentPayouts": "Pagamenti recenti",
|
||||
"noEarnings": "Ancora nessun guadagno. Condividi il tuo link per iniziare a guadagnare!",
|
||||
"noPayouts": "Ancora nessun pagamento.",
|
||||
"connectBank": "Collega conto bancario",
|
||||
"connectDescription": "Collega il tuo conto bancario tramite Stripe per ricevere i pagamenti degli inviti quando il tuo saldo raggiunge i $20.",
|
||||
"connectComplete": "Conto bancario collegato!",
|
||||
"payoutThreshold": "I pagamenti vengono inviati automaticamente quando il tuo saldo raggiunge i $20.",
|
||||
"interstitialTitle": "Sei stato invitato!",
|
||||
"interstitialReferred": "Invitato da {name}",
|
||||
"interstitialDiscount": "Goditi il {percent}% di sconto su tutti gli acquisti di crediti per {days} giorni",
|
||||
"interstitialCta": "Inizia",
|
||||
"discountBadge": "{percent}% di sconto invito",
|
||||
"discountActive": "Sconto invito attivo — {percent}% di sconto per altri {days} giorni",
|
||||
"cancel": "Annulla",
|
||||
"editProfile": "Modifica nome visualizzato e messaggio",
|
||||
"qrCode": "Codice QR",
|
||||
"qrOrFlyer": "Codice QR / Volantino",
|
||||
"qrTitle": "Generatore di codici QR",
|
||||
"qrDotStyle": "Stile punti",
|
||||
"qrCornerFrame": "Cornice angolo",
|
||||
"qrCornerDot": "Punto angolo",
|
||||
"qrColors": "Colori",
|
||||
"qrForeground": "Primo piano",
|
||||
"qrBackground": "Sfondo",
|
||||
"qrLogo": "Logo centrale",
|
||||
"qrLogoNone": "Nessuno",
|
||||
"qrLogoNomad": "Logo NK",
|
||||
"qrLogoEmoji": "Emoji",
|
||||
"qrDownloadPng": "Scarica PNG",
|
||||
"qrDownloadSvg": "Scarica SVG",
|
||||
"qrStyleSquare": "Quadrato",
|
||||
"qrStyleRounded": "Arrotondato",
|
||||
"qrStyleDots": "Punti",
|
||||
"qrStyleClassy": "Elegante",
|
||||
"qrStyleClassyRounded": "Elegante arrotondato",
|
||||
"qrStyleExtraRounded": "Extra arrotondato",
|
||||
"qrStyleDot": "Punto",
|
||||
"flyerTheme": "Tema volantino",
|
||||
"flyerThemeLight": "Chiaro",
|
||||
"flyerThemeDark": "Scuro",
|
||||
"flyerGenerate": "Genera volantino",
|
||||
"flyerGenerating": "Generazione...",
|
||||
"appliedAtCheckout": "Applicato automaticamente al checkout",
|
||||
"expires": "Scade {date}",
|
||||
"referredBy": "Invitato da {name}",
|
||||
"usingCode": "Codice: {code}",
|
||||
"connectBankLoading": "Configurazione in corso...",
|
||||
"connectDetailsNeeded": "Stripe ha bisogno di ulteriori informazioni per abilitare gli accrediti. Clicca su \"Aggiorna conto bancario\" qui sotto per completare la configurazione.",
|
||||
"connectRefresh": "Sembra che tu non abbia finito di configurare il tuo conto bancario. Clicca qui sotto per riprovare.",
|
||||
"connectStatusActive": "Accrediti abilitati",
|
||||
"connectStatusPending": "Configurazione in corso",
|
||||
"connectStripeNote": "Verrai reindirizzato al sito sicuro di Stripe per inserire i tuoi dati bancari. Di solito ci vogliono un paio di minuti.",
|
||||
"flyerAccentColor": "Accento",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Colori",
|
||||
"flyerDownloadHtml": "Scarica HTML",
|
||||
"flyerDownloadPdf": "Scarica PDF",
|
||||
"flyerDownloadPng": "Scarica PNG",
|
||||
"flyerEditQr": "Modifica stile QR",
|
||||
"flyerExporting": "Esportazione in corso...",
|
||||
"flyerHeadlineGradient": "Sfumatura titolo",
|
||||
"flyerHeadlineSubColor": "Sottotitolo",
|
||||
"flyerMargins": "Margini pagina",
|
||||
"flyerPerPage": "Volantini per pagina",
|
||||
"flyerPresetCustom": "Personalizzato",
|
||||
"flyerPresetName": "Nome preset",
|
||||
"flyerPresetSave": "Salva preset",
|
||||
"flyerPrintLayout": "Layout di stampa",
|
||||
"flyerSections": "Sezioni",
|
||||
"flyerSubtextColor": "Sottotesto",
|
||||
"flyerTextColor": "Testo",
|
||||
"flyerTextOverrides": "Sostituzioni testo",
|
||||
"flyerToggleDivider": "Separatore",
|
||||
"flyerToggleFeatures": "Funzionalità in basso",
|
||||
"flyerToggleSteps": "Passaggi 'Come funziona'",
|
||||
"flyerToggleSubtitle": "Sottotitolo",
|
||||
"flyerToggleTagline": "Slogan in basso",
|
||||
"flyerUploadLogo": "Carica logo",
|
||||
"managePayouts": "Gestisci accrediti",
|
||||
"payoutTitle": "Accrediti e conto bancario",
|
||||
"tabFlyer": "Volantino stampabile",
|
||||
"tabQrCode": "Codice QR",
|
||||
"toolsTitle": "Generator di codici QR e volantini",
|
||||
"updateBankAccount": "Aggiorna conto bancario",
|
||||
"connectFailed": "Qualcosa è andato storto. Riprova.",
|
||||
"flyerRemoveLogo": "Rimuovi"
|
||||
}
|
||||
}
|
||||
+336
-479
File diff suppressed because it is too large.
Load diff
+270
-413
File diff suppressed because it is too large.
Load diff
+216
-359
File diff suppressed because it is too large.
Load diff
Loaded 100 of 136 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user