mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 01:26:07 +09:00
Compare commits
No files matched your search
+26
-5
@@ -1,9 +1,30 @@
|
||||
#!/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
|
||||
#!/usr/bin/env bash
|
||||
# Nomad Karaoke pre-commit hook (karaoke-gen variant)
|
||||
# 1. Gitleaks secret scan (fail fast)
|
||||
# 2. i18n auto-translation when en.json changes
|
||||
# Enable: git config core.hooksPath .githooks
|
||||
set -eu
|
||||
|
||||
set -e
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Gitleaks secret scan
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
if command -v gitleaks >/dev/null 2>&1; then
|
||||
if ! gitleaks protect --staged --redact --no-banner; then
|
||||
printf '\n\033[31m✗ gitleaks detected a potential secret in staged changes.\033[0m\n' >&2
|
||||
printf ' • If real: remove it, rotate the credential, then re-commit.\n' >&2
|
||||
printf ' • If false positive: add an allowlist entry to .gitleaks.toml.\n' >&2
|
||||
printf ' • Emergency override (not recommended): git commit --no-verify\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
printf '\033[33mwarn:\033[0m gitleaks not installed — skipping secret scan\n' >&2
|
||||
printf ' install: brew install gitleaks\n' >&2
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. i18n auto-translation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
STAGED_EN=$(git diff --cached --name-only --diff-filter=ACM | grep -E '(messages|translations)/en\.json$' || true)
|
||||
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
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 }}
|
||||
@@ -1,196 +0,0 @@
|
||||
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
|
||||
@@ -0,0 +1,10 @@
|
||||
name: Security
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
gitleaks:
|
||||
uses: nomadkaraoke/.github/.github/workflows/gitleaks.yml@main
|
||||
@@ -0,0 +1,60 @@
|
||||
# Nomad Karaoke shared gitleaks config.
|
||||
# Extends the default ruleset with one custom rule for Discord webhooks
|
||||
# and an allowlist covering known false-positive paths.
|
||||
|
||||
title = "Nomad Karaoke"
|
||||
|
||||
[extend]
|
||||
useDefault = true
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Custom rules
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
[[rules]]
|
||||
id = "discord-webhook-url"
|
||||
description = "Discord webhook URL (token embedded in URL)"
|
||||
regex = '''https://(?:discord|discordapp)\.com/api/webhooks/\d{17,20}/[A-Za-z0-9_-]{60,}'''
|
||||
tags = ["discord", "webhook", "secret"]
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Global allowlist
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
[allowlist]
|
||||
description = "Paths and patterns that are known false positives"
|
||||
|
||||
paths = [
|
||||
'''(?i)\.(jpg|jpeg|png|gif|bmp|svg|webp|pdf|ico|mp3|mp4|wav|flac|m4a)$''',
|
||||
'''(^|/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Podfile\.lock|Cargo\.lock|go\.sum|composer\.lock|Gemfile\.lock|uv\.lock)$''',
|
||||
'''(^|/)node_modules/''',
|
||||
'''(^|/)vendor/''',
|
||||
'''(^|/)wp-content/''',
|
||||
'''(^|/)\.dart_tool/''',
|
||||
'''(^|/)\.venv/''',
|
||||
'''(^|/)\.next/''',
|
||||
'''(^|/)build/''',
|
||||
'''(^|/)dist/''',
|
||||
'''(^|/)\.flutter-plugins''',
|
||||
'''(^|/)test[-_]?fixtures?/''',
|
||||
'''(^|/)tests?/.*conftest\.py$''',
|
||||
'''(^|/)tests?/.*test_[^/]+\.py$''',
|
||||
'''(^|/)tests?/.*_test\.py$''',
|
||||
'''(^|/).*\.(test|spec)\.(js|mjs|cjs|ts|tsx|jsx)$''',
|
||||
'''(^|/).*\.test\.local\.(js|mjs|cjs|ts|tsx|jsx|py)$''',
|
||||
'''(^|/).*\.local\.(js|mjs|cjs|ts|tsx|jsx|py)$''',
|
||||
]
|
||||
|
||||
regexes = [
|
||||
# Explicit placeholder patterns
|
||||
'''YOUR_[A-Z_]{2,}''',
|
||||
'''EXAMPLE_[A-Z_]{2,}''',
|
||||
'''PLACEHOLDER_[A-Z_]{2,}''',
|
||||
'''CHANGE[_-]?ME''',
|
||||
'''<[A-Z_]{2,}>''',
|
||||
'''\$\{[A-Z_]{2,}\}''',
|
||||
|
||||
# Firebase / GCP client API keys — public by design (identify the project,
|
||||
# access is gated by Firebase Security Rules).
|
||||
'''AIzaSy[A-Za-z0-9_-]{33}''',
|
||||
]
|
||||
@@ -0,0 +1,92 @@
|
||||
"""POST /api/client-errors — ingest frontend crash reports.
|
||||
|
||||
Unauthenticated (logged-out users' crashes still matter). Deduped and alerted
|
||||
via the existing error-monitor pipeline — see
|
||||
``backend/services/error_monitor``.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Request, HTTPException
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from backend.services.error_monitor.firestore_adapter import ErrorPatternsAdapter
|
||||
from backend.services.error_monitor.frontend_ingestion import (
|
||||
FrontendErrorReport,
|
||||
RateLimiter,
|
||||
build_pattern_data,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/client-errors", tags=["client-errors"])
|
||||
|
||||
_limiter = RateLimiter(max_per_minute=60)
|
||||
_adapter_singleton: ErrorPatternsAdapter | None = None
|
||||
|
||||
|
||||
def _get_adapter() -> ErrorPatternsAdapter:
|
||||
global _adapter_singleton
|
||||
if _adapter_singleton is None:
|
||||
_adapter_singleton = ErrorPatternsAdapter()
|
||||
return _adapter_singleton
|
||||
|
||||
|
||||
class ClientErrorPayload(BaseModel):
|
||||
message: str = Field(..., min_length=1, max_length=4000)
|
||||
stack: Optional[str] = Field(None, max_length=1_000_000)
|
||||
url: str = Field("", max_length=2048)
|
||||
user_agent: str = Field("", max_length=1024)
|
||||
release: str = Field("", max_length=64)
|
||||
user_email: Optional[str] = Field(None, max_length=320)
|
||||
viewport: Optional[dict] = None
|
||||
locale: str = Field("en", max_length=10)
|
||||
source: str = Field("unknown", max_length=64)
|
||||
# optional free-form extra for debugging. Capped server-side.
|
||||
extra: Optional[dict] = None
|
||||
|
||||
@field_validator("message", "url", "user_agent", "locale", "source")
|
||||
@classmethod
|
||||
def strip(cls, v: str) -> str:
|
||||
return (v or "").strip()
|
||||
|
||||
|
||||
class ClientErrorResponse(BaseModel):
|
||||
pattern_id: str
|
||||
is_new: bool
|
||||
|
||||
|
||||
@router.post("", response_model=ClientErrorResponse, status_code=202)
|
||||
def report_client_error(payload: ClientErrorPayload, request: Request) -> ClientErrorResponse:
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
if not _limiter.allow(client_ip, time.monotonic()):
|
||||
raise HTTPException(status_code=429, detail="too many reports")
|
||||
|
||||
report = FrontendErrorReport(
|
||||
message=payload.message,
|
||||
stack=payload.stack,
|
||||
url=payload.url,
|
||||
user_agent=payload.user_agent,
|
||||
release=payload.release,
|
||||
user_email=payload.user_email,
|
||||
viewport=payload.viewport,
|
||||
locale=payload.locale,
|
||||
extra=payload.extra,
|
||||
)
|
||||
pattern_data = build_pattern_data(report)
|
||||
|
||||
try:
|
||||
result = _get_adapter().upsert_pattern(pattern_data)
|
||||
except Exception: # pragma: no cover - Firestore transient errors
|
||||
logger.exception("Failed to upsert frontend error pattern")
|
||||
raise HTTPException(status_code=503, detail="storage unavailable")
|
||||
|
||||
logger.info(
|
||||
"frontend_crash_reported pattern_id=%s is_new=%s source=%s",
|
||||
result.pattern_id,
|
||||
result.is_new,
|
||||
payload.source,
|
||||
)
|
||||
return ClientErrorResponse(pattern_id=result.pattern_id, is_new=result.is_new)
|
||||
@@ -127,6 +127,38 @@ 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-]+$")
|
||||
|
||||
|
||||
+2
-1
@@ -7,7 +7,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -165,6 +165,7 @@ app.include_router(admin.router, prefix="/api") # Admin dashboard and managemen
|
||||
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
|
||||
app.include_router(push.router, prefix="/api") # Push notification subscription management
|
||||
app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Production error monitoring service for Nomad Karaoke."""
|
||||
@@ -0,0 +1,177 @@
|
||||
"""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"
|
||||
@@ -0,0 +1,323 @@
|
||||
"""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
|
||||
@@ -0,0 +1,489 @@
|
||||
"""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,
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Frontend error ingestion helpers.
|
||||
|
||||
Converts an inbound browser crash report into a ``PatternData`` suitable for
|
||||
the shared ``ErrorPatternsAdapter``. The adapter + existing error-monitor
|
||||
Cloud Run Job handle all alerting / Discord plumbing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
from backend.services.error_monitor.firestore_adapter import PatternData
|
||||
from backend.services.error_monitor.normalizer import (
|
||||
compute_pattern_hash,
|
||||
normalize_message,
|
||||
)
|
||||
|
||||
MAX_SAMPLE_MESSAGE_CHARS = 4000
|
||||
MAX_URL_CHARS = 512
|
||||
|
||||
|
||||
@dataclass
|
||||
class FrontendErrorReport:
|
||||
"""In-memory representation of an inbound crash report."""
|
||||
|
||||
message: str
|
||||
stack: str | None
|
||||
url: str
|
||||
user_agent: str
|
||||
release: str
|
||||
user_email: str | None
|
||||
viewport: dict | None
|
||||
locale: str
|
||||
extra: dict | None
|
||||
|
||||
|
||||
def sanitize_url(url: str) -> str:
|
||||
"""Strip query and fragment from a URL; cap length; tolerate junk."""
|
||||
if not url:
|
||||
return ""
|
||||
try:
|
||||
parts = urlsplit(url)
|
||||
if not parts.scheme:
|
||||
return url[:MAX_URL_CHARS]
|
||||
cleaned = urlunsplit((parts.scheme, parts.netloc, parts.path, "", ""))
|
||||
return cleaned[:MAX_URL_CHARS]
|
||||
except ValueError:
|
||||
return url[:MAX_URL_CHARS]
|
||||
|
||||
|
||||
def _stack_for_hashing(report: FrontendErrorReport) -> str:
|
||||
"""Pick the most stable signal we have for pattern dedup.
|
||||
|
||||
Prefer the stack (stable across invocations) over the message (sometimes
|
||||
has interpolated values). Falls back to message if no stack.
|
||||
"""
|
||||
if report.stack:
|
||||
return report.stack
|
||||
return report.message
|
||||
|
||||
|
||||
def build_pattern_data(
|
||||
report: FrontendErrorReport, now: datetime | None = None
|
||||
) -> PatternData:
|
||||
"""Convert an inbound report to a PatternData ready for upsert."""
|
||||
if now is None:
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
|
||||
raw = _stack_for_hashing(report)
|
||||
normalized = normalize_message(raw)
|
||||
pattern_id = compute_pattern_hash("frontend", normalized)
|
||||
|
||||
# sample_message is human-readable context. Keep the error message plus a
|
||||
# trimmed stack + sanitized URL so the Discord alert is self-contained.
|
||||
sample_parts: list[str] = []
|
||||
if report.message:
|
||||
sample_parts.append(report.message.strip())
|
||||
if report.stack and report.stack.strip() != (report.message or "").strip():
|
||||
sample_parts.append(report.stack.strip())
|
||||
clean_url = sanitize_url(report.url)
|
||||
if clean_url:
|
||||
sample_parts.append(f"URL: {clean_url}")
|
||||
if report.user_agent:
|
||||
sample_parts.append(f"UA: {report.user_agent[:200]}")
|
||||
if report.release:
|
||||
sample_parts.append(f"Build: {report.release}")
|
||||
sample_message = "\n".join(sample_parts)[:MAX_SAMPLE_MESSAGE_CHARS]
|
||||
|
||||
return PatternData(
|
||||
pattern_id=pattern_id,
|
||||
service="frontend",
|
||||
resource_type="browser",
|
||||
normalized_message=normalized,
|
||||
sample_message=sample_message,
|
||||
count=1,
|
||||
timestamp=now,
|
||||
)
|
||||
|
||||
|
||||
class RateLimiter:
|
||||
"""In-memory sliding-window limiter. One instance per process is enough —
|
||||
this runs inside Cloud Run which scales to multiple instances, so the
|
||||
effective limit is (per_ip_per_minute * num_instances). That's fine for our
|
||||
threat model (non-malicious browsers reporting their own crashes).
|
||||
"""
|
||||
|
||||
def __init__(self, max_per_minute: int = 60) -> None:
|
||||
self._max = max_per_minute
|
||||
self._hits: dict[str, list[float]] = {}
|
||||
|
||||
def allow(self, ip: str, now_ts: float) -> bool:
|
||||
cutoff = now_ts - 60.0
|
||||
hits = [t for t in self._hits.get(ip, []) if t >= cutoff]
|
||||
if len(hits) >= self._max:
|
||||
self._hits[ip] = hits
|
||||
return False
|
||||
hits.append(now_ts)
|
||||
self._hits[ip] = hits
|
||||
# simple cleanup: if the map gets huge, drop stale keys
|
||||
if len(self._hits) > 10_000:
|
||||
self._hits = {
|
||||
k: [t for t in v if t >= cutoff]
|
||||
for k, v in self._hits.items()
|
||||
if any(t >= cutoff for t in v)
|
||||
}
|
||||
return True
|
||||
@@ -0,0 +1,106 @@
|
||||
"""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
|
||||
@@ -0,0 +1,429 @@
|
||||
"""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
|
||||
@@ -0,0 +1,641 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,137 @@
|
||||
"""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()
|
||||
@@ -339,6 +339,24 @@ 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 = (
|
||||
@@ -425,11 +443,17 @@ class ReferralService:
|
||||
# total_paid = total_earned - pending (since total_earned tracks all time)
|
||||
total_paid = total_earned - pending_balance
|
||||
|
||||
# Check Connect status
|
||||
# Check Connect status and fetch account details
|
||||
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,
|
||||
@@ -467,6 +491,7 @@ 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,6 +6,7 @@ Handles:
|
||||
- Processing webhook events
|
||||
- Managing customer records
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from typing import Optional, Dict, Any, Tuple
|
||||
@@ -290,7 +291,10 @@ class StripeService:
|
||||
event = stripe.Webhook.construct_event(
|
||||
payload, signature, self.webhook_secret
|
||||
)
|
||||
return True, event, "Webhook verified"
|
||||
# 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"
|
||||
except stripe.error.SignatureVerificationError as e:
|
||||
logger.error(f"Invalid webhook signature: {e}")
|
||||
return False, None, "Invalid signature"
|
||||
@@ -392,8 +396,8 @@ class StripeService:
|
||||
)
|
||||
account_link = stripe.AccountLink.create(
|
||||
account=account.id,
|
||||
refresh_url=f"{self.frontend_url}/app?tab=referrals&connect=refresh",
|
||||
return_url=f"{self.frontend_url}/app?tab=referrals&connect=complete",
|
||||
refresh_url=f"{self.frontend_url}/app/referrals?connect=refresh",
|
||||
return_url=f"{self.frontend_url}/app/referrals?connect=complete",
|
||||
type="account_onboarding",
|
||||
)
|
||||
logger.info(f"Created Connect account {account.id} for {email}")
|
||||
@@ -402,6 +406,50 @@ 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,6 +13,7 @@ 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
|
||||
@@ -531,6 +532,7 @@ 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
|
||||
@@ -562,6 +564,7 @@ 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
|
||||
@@ -999,7 +1002,7 @@ class UserService:
|
||||
'amount': amount,
|
||||
'processed_at': datetime.utcnow()
|
||||
})
|
||||
except Exception:
|
||||
except google_exceptions.AlreadyExists:
|
||||
# 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"
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,92 @@
|
||||
"""API tests for POST /api/client-errors."""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes.client_errors import router as client_errors_router
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
# reset the module-level limiter between tests
|
||||
import backend.api.routes.client_errors as mod
|
||||
mod._limiter = mod.RateLimiter(max_per_minute=60)
|
||||
|
||||
fake_adapter = MagicMock()
|
||||
fake_adapter.upsert_pattern.return_value = MagicMock(
|
||||
pattern_id="deadbeef", is_new=True, previous_status=None
|
||||
)
|
||||
monkeypatch.setattr(mod, "_get_adapter", lambda: fake_adapter)
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(client_errors_router, prefix="/api")
|
||||
client = TestClient(app)
|
||||
client.fake_adapter = fake_adapter # type: ignore[attr-defined]
|
||||
return client
|
||||
|
||||
|
||||
def _payload(**overrides):
|
||||
base = {
|
||||
"message": "TypeError: Cannot read properties of null",
|
||||
"stack": "TypeError: Cannot read properties of null\n at x (app.js:1:2)",
|
||||
"url": "https://gen.nomadkaraoke.com/en/app/jobs/#/abc/review",
|
||||
"user_agent": "Mozilla/5.0 (Android 14; Mobile; rv:138.0) Gecko/138.0 Firefox/138.0",
|
||||
"release": "abc1234",
|
||||
"user_email": None,
|
||||
"viewport": {"w": 412, "h": 915},
|
||||
"locale": "en",
|
||||
"source": "window.onerror",
|
||||
}
|
||||
base.update(overrides)
|
||||
return base
|
||||
|
||||
|
||||
def test_accepts_valid_report_and_upserts(client):
|
||||
resp = client.post("/api/client-errors", json=_payload())
|
||||
assert resp.status_code == 202
|
||||
assert resp.json()["pattern_id"] == "deadbeef"
|
||||
client.fake_adapter.upsert_pattern.assert_called_once()
|
||||
(pd,), _ = client.fake_adapter.upsert_pattern.call_args
|
||||
assert pd.service == "frontend"
|
||||
assert pd.resource_type == "browser"
|
||||
|
||||
|
||||
def test_rejects_missing_message(client):
|
||||
resp = client.post("/api/client-errors", json=_payload(message=""))
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
def test_caps_oversized_payload(client):
|
||||
huge = "x" * 200_000
|
||||
resp = client.post("/api/client-errors", json=_payload(stack=huge))
|
||||
# server accepts but truncates — sample_message must be <= MAX
|
||||
assert resp.status_code == 202
|
||||
(pd,), _ = client.fake_adapter.upsert_pattern.call_args
|
||||
from backend.services.error_monitor.frontend_ingestion import (
|
||||
MAX_SAMPLE_MESSAGE_CHARS,
|
||||
)
|
||||
assert len(pd.sample_message) <= MAX_SAMPLE_MESSAGE_CHARS
|
||||
|
||||
|
||||
def test_rate_limit_returns_429(client, monkeypatch):
|
||||
import backend.api.routes.client_errors as mod
|
||||
mod._limiter = mod.RateLimiter(max_per_minute=2)
|
||||
assert client.post("/api/client-errors", json=_payload()).status_code == 202
|
||||
assert client.post("/api/client-errors", json=_payload()).status_code == 202
|
||||
r3 = client.post("/api/client-errors", json=_payload())
|
||||
assert r3.status_code == 429
|
||||
|
||||
|
||||
def test_strips_sensitive_query_string(client):
|
||||
resp = client.post(
|
||||
"/api/client-errors",
|
||||
json=_payload(url="https://gen.nomadkaraoke.com/en/app/jobs/?token=SECRET#/abc/review"),
|
||||
)
|
||||
assert resp.status_code == 202
|
||||
(pd,), _ = client.fake_adapter.upsert_pattern.call_args
|
||||
assert "SECRET" not in pd.sample_message
|
||||
assert "token=" not in pd.sample_message
|
||||
@@ -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.stream.return_value = mock_docs
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.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.stream.return_value = mock_docs
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.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.stream.return_value = mock_docs
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.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.stream.return_value = mock_docs
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.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.stream = stream_side_effect
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.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.stream.return_value = []
|
||||
mock_db.collection.return_value.where.return_value.where.return_value.order_by.return_value.stream.return_value = []
|
||||
|
||||
from backend.services.user_service import UserService
|
||||
service = UserService()
|
||||
|
||||
+19
-1
@@ -1894,7 +1894,25 @@ 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.
|
||||
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.
|
||||
|
||||
### Create Vanity Link (Admin)
|
||||
|
||||
|
||||
@@ -36,6 +36,31 @@
|
||||
Uses immutable deployment pattern - see infrastructure/encoding-worker/README.md.
|
||||
```
|
||||
|
||||
### Error Monitor
|
||||
|
||||
```text
|
||||
Cloud Logging (all services) ──→ Error Monitor (Cloud Run Job, */15 min)
|
||||
Frontend clients ───────────────→ POST /api/client-errors ──→ Firestore
|
||||
│
|
||||
├─ 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
|
||||
Frontend crash reporting: docs/archive/2026-04-19-frontend-crash-reporting-plan.md
|
||||
```
|
||||
|
||||
Frontend crashes are captured via `window.onerror`, `unhandledrejection`, Next.js
|
||||
`error.tsx`, and a `CrashReportBoundary` around the review UIs. They POST to
|
||||
`/api/client-errors`, which normalises and upserts into the same `error_patterns`
|
||||
collection with `service="frontend"` so they flow through the existing
|
||||
Discord-alerting pipeline. `ChunkLoadError` after deploy triggers an automatic
|
||||
hard reload; the `CrashReport` card also checks `/version.json` and shows an
|
||||
"Update now" CTA when the running bundle is stale.
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
```text
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
| **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
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ curl -X POST "https://nomadkaraoke--karaoke-generator-webapp-api-endpoint.modal.
|
||||
"organised_dir_rclone_root": "andrewdropboxfull:Tracks-Organized",
|
||||
"public_share_dir": "/output/public-share",
|
||||
"rclone_destination": "googledrive:Nomad Karaoke",
|
||||
"discord_webhook_url": "https://discord.com/api/webhooks/1313902611421724734/QcQXuvFpa5E3-PA8QXkeG-3mGJVHXXfbbVYWSmT9a7DoSnE-oOXeSWQpMntmIaw9yqPG"
|
||||
"discord_webhook_url": "https://discord.com/api/webhooks/YOUR_WEBHOOK_ID/YOUR_WEBHOOK_TOKEN"
|
||||
}'
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# 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
|
||||
@@ -0,0 +1,199 @@
|
||||
# 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 |
|
||||
@@ -0,0 +1,183 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,407 @@
|
||||
# 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
@@ -0,0 +1,888 @@
|
||||
# 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"
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -20,3 +20,6 @@ e2e/fixtures/data/search-results/*.json
|
||||
|
||||
# Translation snapshot for incremental delta mode
|
||||
messages/.en-snapshot.json
|
||||
|
||||
# Generated at build time by scripts/write-version.mjs
|
||||
public/version.json
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React from 'react'
|
||||
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
|
||||
import { NextIntlClientProvider } from 'next-intl'
|
||||
import messages from '@/messages/en.json'
|
||||
import CrashReport from '@/components/CrashReport'
|
||||
|
||||
jest.mock('@/lib/crash-reporter', () => ({
|
||||
reportClientError: jest.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
import { reportClientError } from '@/lib/crash-reporter'
|
||||
|
||||
jest.mock('@/lib/version-check', () => ({
|
||||
isStale: jest.fn().mockResolvedValue({ stale: false, latestSha: 'aaa', currentSha: 'aaa' }),
|
||||
hardReload: jest.fn(),
|
||||
}))
|
||||
import { isStale, hardReload } from '@/lib/version-check'
|
||||
|
||||
function wrap(ui: React.ReactElement) {
|
||||
return (
|
||||
<NextIntlClientProvider locale="en" messages={messages as any}>
|
||||
{ui}
|
||||
</NextIntlClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('CrashReport', () => {
|
||||
beforeEach(() => {
|
||||
;(reportClientError as jest.Mock).mockClear()
|
||||
;(reportClientError as jest.Mock).mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('renders title and auto-sends on mount', async () => {
|
||||
const err = new Error('boom')
|
||||
render(wrap(<CrashReport error={err} source="test" />))
|
||||
expect(screen.getByText(/Something went wrong/i)).toBeInTheDocument()
|
||||
await waitFor(() => expect(reportClientError).toHaveBeenCalled())
|
||||
const [[args]] = (reportClientError as jest.Mock).mock.calls
|
||||
expect(args.source).toBe('test')
|
||||
})
|
||||
|
||||
it('shows a success indicator after successful send', async () => {
|
||||
render(wrap(<CrashReport error={new Error('x')} source="test" />))
|
||||
expect(await screen.findByText(/Crash report sent/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('copies debug info to clipboard on click', async () => {
|
||||
const writeText = jest.fn().mockResolvedValue(undefined)
|
||||
Object.assign(navigator, { clipboard: { writeText } })
|
||||
render(wrap(<CrashReport error={new Error('copy me')} source="test" />))
|
||||
fireEvent.click(screen.getByRole('button', { name: /Copy debug info/i }))
|
||||
await waitFor(() => expect(writeText).toHaveBeenCalled())
|
||||
expect(writeText.mock.calls[0][0]).toContain('copy me')
|
||||
})
|
||||
|
||||
it('calls onReset when Try again is clicked', () => {
|
||||
const reset = jest.fn()
|
||||
render(wrap(<CrashReport error={new Error('x')} source="test" onReset={reset} />))
|
||||
fireEvent.click(screen.getByRole('button', { name: /Try again/i }))
|
||||
expect(reset).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('CrashReport stale-version banner', () => {
|
||||
beforeEach(() => {
|
||||
;(isStale as jest.Mock).mockReset()
|
||||
;(hardReload as jest.Mock).mockReset()
|
||||
})
|
||||
|
||||
it('renders banner + Update now button when stale', async () => {
|
||||
;(isStale as jest.Mock).mockResolvedValue({ stale: true, latestSha: 'bbb', currentSha: 'aaa' })
|
||||
render(wrap(<CrashReport error={new Error('x')} source="test" />))
|
||||
expect(await screen.findByTestId('crash-report-stale-banner')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: /Update now/i }))
|
||||
expect(hardReload).toHaveBeenCalledWith('bbb')
|
||||
})
|
||||
|
||||
it('does not render banner when not stale', async () => {
|
||||
;(isStale as jest.Mock).mockResolvedValue({ stale: false, latestSha: 'aaa', currentSha: 'aaa' })
|
||||
render(wrap(<CrashReport error={new Error('x')} source="test" />))
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
expect(screen.queryByTestId('crash-report-stale-banner')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React from 'react'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { NextIntlClientProvider } from 'next-intl'
|
||||
import messages from '@/messages/en.json'
|
||||
import CrashReportBoundary from '@/components/CrashReportBoundary'
|
||||
|
||||
jest.mock('@/lib/crash-reporter', () => ({
|
||||
reportClientError: jest.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
function Bomb(): React.ReactElement {
|
||||
throw new Error('KABOOM')
|
||||
}
|
||||
|
||||
function wrap(ui: React.ReactElement) {
|
||||
return (
|
||||
<NextIntlClientProvider locale="en" messages={messages as any}>
|
||||
{ui}
|
||||
</NextIntlClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('CrashReportBoundary', () => {
|
||||
const origError = console.error
|
||||
beforeAll(() => {
|
||||
// Silence React's expected error noise in tests
|
||||
console.error = jest.fn()
|
||||
})
|
||||
afterAll(() => {
|
||||
console.error = origError
|
||||
})
|
||||
|
||||
it('catches a child error and renders CrashReport', () => {
|
||||
render(wrap(
|
||||
<CrashReportBoundary source="test">
|
||||
<Bomb />
|
||||
</CrashReportBoundary>
|
||||
))
|
||||
expect(screen.getByText(/Something went wrong/i)).toBeInTheDocument()
|
||||
expect(screen.getByTestId('crash-report-message').textContent).toContain('KABOOM')
|
||||
})
|
||||
|
||||
it('renders children normally when no error', () => {
|
||||
render(wrap(
|
||||
<CrashReportBoundary source="test">
|
||||
<div>hello</div>
|
||||
</CrashReportBoundary>
|
||||
))
|
||||
expect(screen.getByText('hello')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { collectContext, reportClientError, __resetForTest } from '@/lib/crash-reporter'
|
||||
|
||||
describe('crash-reporter.collectContext', () => {
|
||||
beforeEach(() => {
|
||||
__resetForTest()
|
||||
})
|
||||
|
||||
it('sanitizes url by dropping query + fragment', () => {
|
||||
const ctx = collectContext({
|
||||
href: 'https://gen.nomadkaraoke.com/en/app/jobs/?token=abc#/x/review',
|
||||
userAgent: 'Mozilla/5.0 Firefox/138.0',
|
||||
})
|
||||
expect(ctx.url).toBe('https://gen.nomadkaraoke.com/en/app/jobs/')
|
||||
})
|
||||
|
||||
it('captures viewport dimensions', () => {
|
||||
const ctx = collectContext({
|
||||
href: 'https://x.example/',
|
||||
userAgent: 'ua',
|
||||
innerWidth: 412,
|
||||
innerHeight: 915,
|
||||
})
|
||||
expect(ctx.viewport).toEqual({ w: 412, h: 915 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('crash-reporter.reportClientError', () => {
|
||||
const fetchMock = jest.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
__resetForTest()
|
||||
fetchMock.mockReset()
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ pattern_id: 'p', is_new: true }) })
|
||||
;(global as any).fetch = fetchMock
|
||||
})
|
||||
|
||||
it('POSTs sanitized payload to /api/client-errors', async () => {
|
||||
await reportClientError({
|
||||
error: new TypeError('boom'),
|
||||
source: 'test',
|
||||
context: { href: 'https://gen.nomadkaraoke.com/en/app/', userAgent: 'ua' },
|
||||
})
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toMatch(/\/api\/client-errors$/)
|
||||
expect(init.method).toBe('POST')
|
||||
expect(init.keepalive).toBe(true)
|
||||
const body = JSON.parse(init.body)
|
||||
expect(body.message).toBe('TypeError: boom')
|
||||
expect(body.stack).toContain('TypeError')
|
||||
expect(body.source).toBe('test')
|
||||
expect(body.url).toBe('https://gen.nomadkaraoke.com/en/app/')
|
||||
})
|
||||
|
||||
it('dedupes identical errors within the window', async () => {
|
||||
const err = new Error('same')
|
||||
await reportClientError({ error: err, source: 'a', context: { href: '', userAgent: '' } })
|
||||
await reportClientError({ error: err, source: 'a', context: { href: '', userAgent: '' } })
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('does not throw on fetch failure', async () => {
|
||||
fetchMock.mockRejectedValueOnce(new Error('offline'))
|
||||
await expect(
|
||||
reportClientError({
|
||||
error: new Error('x'),
|
||||
source: 'test',
|
||||
context: { href: '', userAgent: '' },
|
||||
})
|
||||
).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { isStale, hardReload, __resetForTest, __setBuildShaForTest } from '@/lib/version-check'
|
||||
|
||||
describe('version-check.isStale', () => {
|
||||
const fetchMock = jest.fn()
|
||||
beforeEach(() => {
|
||||
__resetForTest()
|
||||
__setBuildShaForTest('aaa')
|
||||
fetchMock.mockReset()
|
||||
;(global as any).fetch = fetchMock
|
||||
})
|
||||
|
||||
it('returns stale=false when SHAs match', async () => {
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ build_sha: 'aaa' }) })
|
||||
const r = await isStale()
|
||||
expect(r.stale).toBe(false)
|
||||
expect(r.latestSha).toBe('aaa')
|
||||
})
|
||||
|
||||
it('returns stale=true when SHAs differ', async () => {
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ build_sha: 'bbb' }) })
|
||||
const r = await isStale()
|
||||
expect(r.stale).toBe(true)
|
||||
expect(r.latestSha).toBe('bbb')
|
||||
})
|
||||
|
||||
it('fetches with cache: no-store', async () => {
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ build_sha: 'aaa' }) })
|
||||
await isStale()
|
||||
const [, init] = fetchMock.mock.calls[0]
|
||||
expect(init.cache).toBe('no-store')
|
||||
})
|
||||
|
||||
it('treats fetch failures as not-stale (fail-safe)', async () => {
|
||||
fetchMock.mockRejectedValue(new Error('offline'))
|
||||
const r = await isStale()
|
||||
expect(r.stale).toBe(false)
|
||||
})
|
||||
|
||||
it('treats "dev" build_sha as not-stale (local dev)', async () => {
|
||||
__setBuildShaForTest('dev')
|
||||
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ build_sha: 'bbb' }) })
|
||||
const r = await isStale()
|
||||
expect(r.stale).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('version-check.hardReload circuit breaker', () => {
|
||||
const assignMock = jest.fn()
|
||||
let originalLocation: Location
|
||||
|
||||
beforeEach(() => {
|
||||
__resetForTest()
|
||||
assignMock.mockReset()
|
||||
originalLocation = window.location
|
||||
// @ts-expect-error — overwriting readonly for test
|
||||
delete window.location
|
||||
// @ts-expect-error — mock location
|
||||
window.location = {
|
||||
pathname: '/en/app/jobs/',
|
||||
assign: assignMock,
|
||||
reload: jest.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
// @ts-expect-error — restore
|
||||
window.location = originalLocation
|
||||
})
|
||||
|
||||
it('navigates with _v cache-buster on first call', () => {
|
||||
hardReload('bbb')
|
||||
expect(assignMock).toHaveBeenCalledTimes(1)
|
||||
expect(assignMock.mock.calls[0][0]).toContain('_v=bbb')
|
||||
expect(assignMock.mock.calls[0][0]).toContain('/en/app/jobs/')
|
||||
})
|
||||
|
||||
it('refuses to reload twice within 60s (circuit breaker)', () => {
|
||||
hardReload('bbb')
|
||||
hardReload('ccc')
|
||||
expect(assignMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -11,6 +11,7 @@ import { LyricsAnalyzer } from "@/components/lyrics-review"
|
||||
import { InstrumentalSelector } from "@/components/instrumental-review"
|
||||
import { AudioEditor } from "@/components/audio-editor/AudioEditor"
|
||||
import { ThemeToggle } from "@/components/ThemeToggle"
|
||||
import CrashReportBoundary from "@/components/CrashReportBoundary"
|
||||
import type { CorrectionData } from "@/lib/lyrics-review/types"
|
||||
import { isLocalMode, createLocalModeJob } from "@/lib/local-mode"
|
||||
|
||||
@@ -313,10 +314,18 @@ export function JobRouterClient() {
|
||||
}
|
||||
|
||||
if (currentRouteType === "instrumental") {
|
||||
return <InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} />
|
||||
return (
|
||||
<CrashReportBoundary source="instrumental-review" backHref="/app">
|
||||
<InstrumentalReviewWrapper job={job} isLocalMode={inLocalMode} />
|
||||
</CrashReportBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
return <LyricsReviewWrapper job={job} isLocalMode={inLocalMode} />
|
||||
return (
|
||||
<CrashReportBoundary source="lyrics-review" backHref="/app">
|
||||
<LyricsReviewWrapper job={job} isLocalMode={inLocalMode} />
|
||||
</CrashReportBoundary>
|
||||
)
|
||||
}
|
||||
|
||||
// Lyrics Review Component Wrapper
|
||||
|
||||
@@ -221,8 +221,8 @@ function AppPageContent() {
|
||||
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>
|
||||
<RefreshCw className={`w-4 h-4 me-1.5 ${isLoadingJobs ? 'animate-spin' : ''}`} />
|
||||
<span className="text-sm">{t('refresh')}</span>
|
||||
</Button>
|
||||
{isAdmin && (
|
||||
<TooltipProvider>
|
||||
@@ -256,7 +256,7 @@ function AppPageContent() {
|
||||
onClose={() => setShowFeedbackDialog(false)}
|
||||
/>
|
||||
|
||||
<main className="px-4 pt-24 pb-8 space-y-6">
|
||||
<main className="px-4 pt-28 sm:pt-24 pb-8 space-y-6">
|
||||
{/* Push notification prompt - shows once when appropriate */}
|
||||
<PushNotificationPrompt />
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
'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 } from 'lucide-react';
|
||||
import { ChevronLeft, Loader2 } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
export default function ReferralsPage() {
|
||||
@@ -12,7 +13,7 @@ export default function ReferralsPage() {
|
||||
return (
|
||||
<div className="min-h-screen" style={{ backgroundColor: 'var(--background)' }}>
|
||||
<AppHeader />
|
||||
<main className="container mx-auto max-w-4xl px-4 pt-20 pb-6">
|
||||
<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"
|
||||
@@ -21,7 +22,9 @@ export default function ReferralsPage() {
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
{t('backToDashboard')}
|
||||
</Link>
|
||||
<ReferralDashboard />
|
||||
<Suspense fallback={<Loader2 className="w-6 h-6 animate-spin mx-auto mt-8" style={{ color: 'var(--text-muted)' }} />}>
|
||||
<ReferralDashboard />
|
||||
</Suspense>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
import CrashReport from '@/components/CrashReport'
|
||||
|
||||
interface Props {
|
||||
error: Error & { digest?: string }
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
export default function LocaleError({ error, reset }: Props) {
|
||||
useEffect(() => {
|
||||
// The CrashReport component also auto-sends on mount; this log is just for
|
||||
// local dev visibility.
|
||||
if (typeof console !== 'undefined') {
|
||||
console.error('[error.tsx]', error)
|
||||
}
|
||||
}, [error])
|
||||
|
||||
return <CrashReport error={error} source="error.tsx" digest={error.digest} onReset={reset} />
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
import { reportClientError } from '@/lib/crash-reporter'
|
||||
|
||||
interface Props {
|
||||
error: Error & { digest?: string }
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
export default function GlobalError({ error, reset }: Props) {
|
||||
useEffect(() => {
|
||||
void reportClientError({
|
||||
error,
|
||||
source: 'global-error.tsx',
|
||||
context: {
|
||||
href: typeof window !== 'undefined' ? window.location.href : '',
|
||||
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
|
||||
innerWidth: typeof window !== 'undefined' ? window.innerWidth : undefined,
|
||||
innerHeight: typeof window !== 'undefined' ? window.innerHeight : undefined,
|
||||
userEmail: null,
|
||||
},
|
||||
extra: { digest: error.digest },
|
||||
})
|
||||
}, [error])
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>
|
||||
<div style={{ minHeight: '60vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, fontFamily: 'system-ui, sans-serif' }}>
|
||||
<div style={{ maxWidth: 560 }}>
|
||||
<h1 style={{ fontSize: 20, marginBottom: 8 }}>Something went wrong</h1>
|
||||
<p style={{ color: '#666', fontSize: 14 }}>
|
||||
The app hit an unexpected error. We've been notified automatically.
|
||||
</p>
|
||||
<pre style={{ marginTop: 12, padding: 12, background: '#f4f4f4', border: '1px solid #e5e5e5', borderRadius: 6, fontSize: 11, overflow: 'auto' }}>
|
||||
{error.name}: {error.message}
|
||||
{error.digest ? `\nDigest: ${error.digest}` : ''}
|
||||
</pre>
|
||||
<button onClick={reset} style={{ marginTop: 12, padding: '8px 16px', border: '1px solid #ddd', borderRadius: 6, background: '#fff', cursor: 'pointer' }}>
|
||||
Try again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { hasLocale } from 'next-intl';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { routing } from '@/i18n/routing';
|
||||
import { ReferralCapture } from '@/components/ReferralCapture';
|
||||
import ClientErrorInit from '@/components/ClientErrorInit';
|
||||
|
||||
export function generateStaticParams() {
|
||||
return routing.locales.map((locale) => ({ locale }));
|
||||
@@ -34,6 +35,7 @@ export default async function LocaleLayout({
|
||||
__html: `document.documentElement.lang="${locale}";document.documentElement.dir="${['ar', 'he'].includes(locale) ? 'rtl' : 'ltr'}";`,
|
||||
}}
|
||||
/>
|
||||
<ClientErrorInit locale={locale} />
|
||||
<Suspense fallback={null}>
|
||||
<ReferralCapture />
|
||||
</Suspense>
|
||||
|
||||
@@ -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 } from '@/lib/api';
|
||||
import { getAccessToken, clearAccessToken, API_BASE_URL } from '@/lib/api';
|
||||
import type { ReferralInterstitial } from '@/lib/types';
|
||||
import { Gift, ArrowRight, Mail, CheckCircle, Loader2 } from 'lucide-react';
|
||||
|
||||
@@ -34,9 +34,23 @@ export function ReferralInterstitialClient() {
|
||||
// Store referral code immediately
|
||||
setReferralCode(code);
|
||||
|
||||
// Check if already logged in
|
||||
if (getAccessToken()) {
|
||||
setIsLoggedIn(true);
|
||||
// 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
|
||||
});
|
||||
}
|
||||
|
||||
getReferralInterstitial(code)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
export default function CrashTestPage() {
|
||||
const [mode, setMode] = useState<"sync" | "async" | "render" | null>(null)
|
||||
|
||||
if (mode === "render") {
|
||||
throw new Error("synthetic render crash")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">Crash test</h1>
|
||||
<p className="text-muted-foreground mt-1">
|
||||
Fires intentional client-side errors to exercise the crash-reporting pipeline end-to-end.
|
||||
Each button triggers a different error flavour so you can verify Discord alerts fire and
|
||||
patterns land in Firestore with <code className="font-mono text-xs">service=frontend</code>.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setTimeout(() => {
|
||||
throw new Error("synthetic async crash")
|
||||
}, 0)
|
||||
}}
|
||||
>
|
||||
Async throw (setTimeout)
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
void Promise.reject(new Error("synthetic unhandled rejection"))
|
||||
}}
|
||||
>
|
||||
Unhandled rejection
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={() => setMode("render")}>
|
||||
Render-time throw
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
After clicking, check the browser console and the Discord error channel. The async and
|
||||
rejection variants should NOT show a visible error UI (they're caught by the global
|
||||
handlers). The render-time throw should render the <code>CrashReport</code> card via the
|
||||
Next.js <code>error.tsx</code> boundary.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
Share2, Link as LinkIcon, Users, MousePointerClick, DollarSign,
|
||||
Plus, Copy, Check, RefreshCw, Loader2, ToggleLeft, ToggleRight, Pencil, QrCode,
|
||||
} from "lucide-react"
|
||||
import QRCodeDialog from "@/components/referrals/QRCodeDialog"
|
||||
import ReferralToolsDialog from "@/components/referrals/ReferralToolsDialog"
|
||||
import { NextIntlClientProvider } from "next-intl"
|
||||
import enMessages from "@/messages/en.json"
|
||||
|
||||
@@ -498,12 +498,12 @@ export default function ReferralsPage() {
|
||||
{/* QR Code / Flyer Dialog */}
|
||||
{qrDialogCode && (
|
||||
<NextIntlClientProvider locale="en" messages={enMessages}>
|
||||
<QRCodeDialog
|
||||
<ReferralToolsDialog
|
||||
referralUrl={`https://nomadkaraoke.com/r/${qrDialogCode}`}
|
||||
open={!!qrDialogCode}
|
||||
onOpenChange={(open) => { if (!open) setQrDialogCode(null) }}
|
||||
onGenerateFlyer={(theme, qrDataUrl) => adminApi.generateFlyer(qrDialogCode, theme, qrDataUrl)}
|
||||
flyerFilename={`nomad-karaoke-flyer-${qrDialogCode}.pdf`}
|
||||
flyerFilename={`nomad-karaoke-flyer-${qrDialogCode}`}
|
||||
referralCode={qrDialogCode}
|
||||
/>
|
||||
</NextIntlClientProvider>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { LocaleRedirect } from "@/components/LocaleRedirect"
|
||||
|
||||
export default function ReferralsRedirect() {
|
||||
return <LocaleRedirect />
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { installGlobalErrorHandlers } from '@/lib/client-error-setup'
|
||||
|
||||
interface Props {
|
||||
locale: string
|
||||
}
|
||||
|
||||
export default function ClientErrorInit({ locale }: Props) {
|
||||
const user = useAuth((s) => s.user)
|
||||
useEffect(() => {
|
||||
installGlobalErrorHandlers(() => user?.email ?? null, locale)
|
||||
}, [locale, user])
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { AlertCircle, Check, Clipboard, RefreshCw, Send } from 'lucide-react'
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useAuth } from '@/lib/auth'
|
||||
import { reportClientError } from '@/lib/crash-reporter'
|
||||
import { hardReload, isStale } from '@/lib/version-check'
|
||||
|
||||
type SendState = 'sending' | 'sent' | 'failed' | 'idle'
|
||||
|
||||
interface Props {
|
||||
error: unknown
|
||||
source: string
|
||||
/** Optional Next.js error digest (present for errors in server components) */
|
||||
digest?: string
|
||||
/** Optional reset handler (present for Next.js error.tsx boundaries) */
|
||||
onReset?: () => void
|
||||
/** Optional "back" URL for the in-boundary version */
|
||||
backHref?: string
|
||||
}
|
||||
|
||||
function errorText(error: unknown): { name: string; message: string; stack: string } {
|
||||
if (error instanceof Error) {
|
||||
return { name: error.name, message: error.message, stack: error.stack ?? '' }
|
||||
}
|
||||
if (typeof error === 'string') return { name: 'Error', message: error, stack: '' }
|
||||
try {
|
||||
return { name: 'Error', message: JSON.stringify(error), stack: '' }
|
||||
} catch {
|
||||
return { name: 'Error', message: String(error), stack: '' }
|
||||
}
|
||||
}
|
||||
|
||||
export default function CrashReport({ error, source, digest, onReset, backHref }: Props) {
|
||||
const t = useTranslations('crashReport')
|
||||
const user = useAuth((s) => s.user)
|
||||
const [state, setState] = useState<SendState>('idle')
|
||||
const [copied, setCopied] = useState(false)
|
||||
const [showStack, setShowStack] = useState(false)
|
||||
const [staleInfo, setStaleInfo] = useState<{ latestSha: string } | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
void isStale().then((r) => {
|
||||
if (!cancelled && r.stale) setStaleInfo({ latestSha: r.latestSha })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
|
||||
const info = useMemo(() => errorText(error), [error])
|
||||
|
||||
const debugText = useMemo(() => {
|
||||
const lines = [
|
||||
`${info.name}: ${info.message}`,
|
||||
digest ? `Digest: ${digest}` : null,
|
||||
`Source: ${source}`,
|
||||
`URL: ${typeof window !== 'undefined' ? window.location.href : ''}`,
|
||||
`UA: ${typeof navigator !== 'undefined' ? navigator.userAgent : ''}`,
|
||||
`Build: ${process.env.NEXT_PUBLIC_COMMIT_SHA || '(dev)'}`,
|
||||
`When: ${new Date().toISOString()}`,
|
||||
'',
|
||||
info.stack || '(no stack)',
|
||||
].filter(Boolean) as string[]
|
||||
return lines.join('\n')
|
||||
}, [info, source, digest])
|
||||
|
||||
async function send() {
|
||||
setState('sending')
|
||||
try {
|
||||
await reportClientError({
|
||||
error,
|
||||
source,
|
||||
context: {
|
||||
href: typeof window !== 'undefined' ? window.location.href : '',
|
||||
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
|
||||
innerWidth: typeof window !== 'undefined' ? window.innerWidth : undefined,
|
||||
innerHeight: typeof window !== 'undefined' ? window.innerHeight : undefined,
|
||||
userEmail: user?.email ?? null,
|
||||
},
|
||||
extra: { digest, interactive: state === 'idle' ? 'auto' : 'manual', latest_sha: staleInfo?.latestSha ?? null },
|
||||
})
|
||||
setState('sent')
|
||||
} catch {
|
||||
setState('failed')
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// auto-send once on mount
|
||||
void send()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(debugText)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-[60vh] items-center justify-center p-4">
|
||||
<div className="w-full max-w-xl rounded-xl border bg-card p-6 shadow-sm">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertCircle className="mt-0.5 h-6 w-6 shrink-0 text-destructive" />
|
||||
<div className="flex-1 space-y-1">
|
||||
<h1 className="text-lg font-semibold">{t('title')}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t('subtitle')}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{staleInfo && (
|
||||
<div className="mt-4 rounded-md border border-amber-400/60 bg-amber-400/10 p-3 text-sm" data-testid="crash-report-stale-banner">
|
||||
<strong className="font-medium">{t('updateAvailable')}</strong>
|
||||
<p className="mt-1 text-xs text-muted-foreground">{t('updateAvailableSubtitle')}</p>
|
||||
<Button
|
||||
size="sm"
|
||||
className="mt-2 min-h-[40px]"
|
||||
onClick={() => hardReload(staleInfo.latestSha)}
|
||||
>
|
||||
{t('updateNow')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="mt-4 rounded-md border bg-muted/40 p-3 text-xs font-mono break-words"
|
||||
data-testid="crash-report-message"
|
||||
>
|
||||
<strong>{info.name}:</strong> {info.message}
|
||||
</div>
|
||||
|
||||
<div className="mt-3">
|
||||
<button
|
||||
type="button"
|
||||
className="text-xs text-muted-foreground underline"
|
||||
onClick={() => setShowStack((v) => !v)}
|
||||
>
|
||||
{showStack ? t('hideStack') : t('toggleStack')}
|
||||
</button>
|
||||
{showStack && (
|
||||
<pre className="mt-2 max-h-64 overflow-auto rounded-md border bg-muted/40 p-3 text-[10px] leading-tight">
|
||||
{debugText}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="mt-4 text-xs"
|
||||
role="status"
|
||||
data-testid="crash-report-status"
|
||||
>
|
||||
{state === 'sending' && <span>{t('reportSending')}</span>}
|
||||
{state === 'sent' && (
|
||||
<span className="inline-flex items-center gap-1 text-emerald-600">
|
||||
<Check className="h-3.5 w-3.5" />
|
||||
{t('reportSent')}
|
||||
</span>
|
||||
)}
|
||||
{state === 'failed' && (
|
||||
<span className="text-destructive">{t('reportFailed')}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
<Button variant="outline" size="sm" onClick={copy} className="min-h-[40px]">
|
||||
<Clipboard className="mr-1.5 h-4 w-4" />
|
||||
{copied ? t('copied') : t('copyDebug')}
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={send} disabled={state === 'sending'} className="min-h-[40px]">
|
||||
<Send className="mr-1.5 h-4 w-4" />
|
||||
{t('sendReport')}
|
||||
</Button>
|
||||
{onReset && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={staleInfo ? 'outline' : 'default'}
|
||||
onClick={onReset}
|
||||
className="min-h-[40px]"
|
||||
>
|
||||
<RefreshCw className="mr-1.5 h-4 w-4" />
|
||||
{t('retry')}
|
||||
</Button>
|
||||
)}
|
||||
{backHref && (
|
||||
<Button variant="ghost" size="sm" asChild className="min-h-[40px]">
|
||||
<a href={backHref}>{t('backToDashboard')}</a>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
'use client'
|
||||
|
||||
import React from 'react'
|
||||
import CrashReport from './CrashReport'
|
||||
|
||||
interface Props {
|
||||
children: React.ReactNode
|
||||
source: string
|
||||
backHref?: string
|
||||
}
|
||||
|
||||
interface State {
|
||||
error: Error | null
|
||||
key: number
|
||||
}
|
||||
|
||||
export default class CrashReportBoundary extends React.Component<Props, State> {
|
||||
state: State = { error: null, key: 0 }
|
||||
|
||||
static getDerivedStateFromError(error: Error): Partial<State> {
|
||||
return { error }
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: React.ErrorInfo) {
|
||||
if (typeof console !== 'undefined') {
|
||||
console.error('[CrashReportBoundary]', error, info.componentStack)
|
||||
}
|
||||
}
|
||||
|
||||
reset = () => {
|
||||
this.setState((s) => ({ error: null, key: s.key + 1 }))
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
return (
|
||||
<CrashReport
|
||||
error={this.state.error}
|
||||
source={this.props.source}
|
||||
onReset={this.reset}
|
||||
backHref={this.props.backHref}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return <React.Fragment key={this.state.key}>{this.props.children}</React.Fragment>
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
export default function LanguageSwitcher({ showLabel }: { showLabel?: boolean } = {}) {
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
@@ -87,7 +87,7 @@ export default function LanguageSwitcher() {
|
||||
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="hidden sm:inline">{current.native}</span>
|
||||
<span className={showLabel ? '' : 'hidden sm:inline'}>{current.native}</span>
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
|
||||
@@ -30,11 +30,14 @@ import { ReactNode, useState, useEffect } from "react"
|
||||
* 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, isDefaultTenant } = useTenant()
|
||||
const { branding, isDefault: isDefaultTenant } = useTenant()
|
||||
const { isDarkMode, toggleTheme } = useTheme()
|
||||
const [mounted, setMounted] = useState(false)
|
||||
|
||||
@@ -42,86 +45,132 @@ export function AppHeader({ children }: { children?: ReactNode }) {
|
||||
|
||||
return (
|
||||
<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">
|
||||
{/* 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-8 sm:h-10 shrink-0" />
|
||||
<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-base sm:text-xl font-bold truncate block" style={{ color: 'var(--text)' }}>
|
||||
<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-1 sm:gap-2 shrink-0">
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{children}
|
||||
<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" />
|
||||
</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>
|
||||
<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)' }}>
|
||||
<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 className="hidden sm:inline">{t('referrals')}</span>
|
||||
<span>{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>
|
||||
)}
|
||||
{mounted && <ThemeToggle isDarkMode={isDarkMode} toggleTheme={toggleTheme} t={t} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 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>
|
||||
</Link>
|
||||
<LanguageSwitcher showLabel />
|
||||
{mounted && <ThemeToggle isDarkMode={isDarkMode} toggleTheme={toggleTheme} t={t} />}
|
||||
</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>
|
||||
)
|
||||
}
|
||||
@@ -207,6 +207,33 @@ 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])
|
||||
@@ -1115,15 +1142,20 @@ export default function LyricsAnalyzer({
|
||||
}, [])
|
||||
|
||||
const handleSaveReplaceAllLyrics = useCallback(
|
||||
(newSegments: LyricsSegment[]) => {
|
||||
addEditEntry(editLog, 'replace_all_lyrics', {
|
||||
details: {
|
||||
(
|
||||
newSegments: LyricsSegment[],
|
||||
meta?: { operation: 'replace_all_lyrics' | 'change_case'; details?: Record<string, unknown> }
|
||||
) => {
|
||||
const operation = meta?.operation ?? 'replace_all_lyrics'
|
||||
const details =
|
||||
meta?.details ?? {
|
||||
segments_before: data.corrected_segments.length,
|
||||
segments_after: newSegments.length,
|
||||
},
|
||||
})
|
||||
}
|
||||
addEditEntry(editLog, operation, { details })
|
||||
const newData = { ...data, corrected_segments: newSegments }
|
||||
updateDataWithHistory(newData, 'replace all lyrics')
|
||||
const historyLabel = operation === 'change_case' ? 'change case' : 'replace all lyrics'
|
||||
updateDataWithHistory(newData, historyLabel)
|
||||
setIsReplaceAllLyricsModalOpen(false)
|
||||
},
|
||||
[data, updateDataWithHistory, editLog]
|
||||
@@ -1254,6 +1286,7 @@ export default function LyricsAnalyzer({
|
||||
activeGapWordIds={activeGapWordIds}
|
||||
advancedMode={advancedMode}
|
||||
onAdvancedModeToggle={handleAdvancedModeToggle}
|
||||
editedWordIds={editedWordIds}
|
||||
/>
|
||||
<ReferenceView
|
||||
referenceSources={data.reference_lyrics}
|
||||
|
||||
@@ -33,6 +33,7 @@ export default function TranscriptionView({
|
||||
activeGapWordIds,
|
||||
advancedMode = false,
|
||||
onAdvancedModeToggle,
|
||||
editedWordIds,
|
||||
}: TranscriptionViewProps) {
|
||||
const t = useTranslations('lyricsReview.transcription')
|
||||
const [selectedSegmentIndex, setSelectedSegmentIndex] = useState<number | null>(null)
|
||||
@@ -201,6 +202,7 @@ export default function TranscriptionView({
|
||||
onEditCorrection={onEditCorrection}
|
||||
onAcceptCorrection={onAcceptCorrection}
|
||||
onShowCorrectionDetail={onShowCorrectionDetail}
|
||||
editedWordIds={editedWordIds}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -187,6 +187,51 @@ describe('Replace Segments Mode', () => {
|
||||
expect(savedSegments[2].words[0].text).toBe('Third')
|
||||
})
|
||||
|
||||
it('preserves per-word timing when word count is unchanged (e.g. case-only edit)', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openReplaceSegmentsMode()
|
||||
|
||||
// Lowercase the second segment only — same word count (2 words)
|
||||
const textarea = screen.getByRole('textbox')
|
||||
await user.clear(textarea)
|
||||
await user.type(textarea, 'Hello world\ngoodbye moon\nThird line here')
|
||||
|
||||
const applyButton = screen.getByRole('button', { name: 'Apply' })
|
||||
await user.click(applyButton)
|
||||
|
||||
const savedSegments = defaultProps.onSave.mock.calls[0][0]
|
||||
|
||||
// Changed segment — text updated, but original word-level timing + IDs preserved
|
||||
expect(savedSegments[1].text).toBe('goodbye moon')
|
||||
expect(savedSegments[1].words).toHaveLength(2)
|
||||
expect(savedSegments[1].words[0].text).toBe('goodbye')
|
||||
expect(savedSegments[1].words[0].id).toBe('w3')
|
||||
expect(savedSegments[1].words[0].start_time).toBe(3)
|
||||
expect(savedSegments[1].words[0].end_time).toBe(4)
|
||||
expect(savedSegments[1].words[1].text).toBe('moon')
|
||||
expect(savedSegments[1].words[1].id).toBe('w4')
|
||||
expect(savedSegments[1].words[1].start_time).toBe(4)
|
||||
expect(savedSegments[1].words[1].end_time).toBe(5)
|
||||
})
|
||||
|
||||
it('preserves word confidence when word count is unchanged', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openReplaceSegmentsMode()
|
||||
|
||||
const textarea = screen.getByRole('textbox')
|
||||
await user.clear(textarea)
|
||||
// Change one word in third segment, same count (3 words)
|
||||
await user.type(textarea, 'Hello world\nGoodbye moon\nThird lane here')
|
||||
|
||||
const applyButton = screen.getByRole('button', { name: 'Apply' })
|
||||
await user.click(applyButton)
|
||||
|
||||
const savedSegments = defaultProps.onSave.mock.calls[0][0]
|
||||
expect(savedSegments[2].words[1].text).toBe('lane')
|
||||
expect(savedSegments[2].words[1].confidence).toBe(0.9)
|
||||
expect(savedSegments[2].words[1].id).toBe('w6')
|
||||
})
|
||||
|
||||
it('preserves segment id and timing for changed lines', async () => {
|
||||
const user = userEvent.setup()
|
||||
await openReplaceSegmentsMode()
|
||||
|
||||
@@ -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, X } from 'lucide-react'
|
||||
import { RefreshCw, ClipboardPaste, TextCursorInput, CaseSensitive, X, type LucideIcon } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface ModeSelectionModalProps {
|
||||
@@ -12,21 +12,76 @@ interface ModeSelectionModalProps {
|
||||
onSelectReplace: () => void
|
||||
onSelectResync: () => void
|
||||
onSelectReplaceSegments: () => void
|
||||
onSelectChangeCase: () => void
|
||||
hasExistingLyrics: boolean
|
||||
}
|
||||
|
||||
type ModeOption = {
|
||||
key: string
|
||||
icon: LucideIcon
|
||||
title: string
|
||||
desc: string
|
||||
tag?: string
|
||||
tagTone?: 'positive' | 'caution'
|
||||
primary?: boolean
|
||||
onSelect: () => void
|
||||
}
|
||||
|
||||
export default function ModeSelectionModal({
|
||||
open,
|
||||
onClose,
|
||||
onSelectReplace,
|
||||
onSelectResync,
|
||||
onSelectReplaceSegments,
|
||||
onSelectChangeCase,
|
||||
hasExistingLyrics,
|
||||
}: ModeSelectionModalProps) {
|
||||
const t = useTranslations('lyricsReview.modals.modeSelection')
|
||||
const tCommon = useTranslations('common')
|
||||
|
||||
const options: ModeOption[] = [
|
||||
hasExistingLyrics && {
|
||||
key: 'resync',
|
||||
icon: RefreshCw,
|
||||
title: t('resyncTitle'),
|
||||
desc: t('resyncDesc'),
|
||||
tag: t('resyncRecommended'),
|
||||
tagTone: 'positive' as const,
|
||||
primary: true,
|
||||
onSelect: onSelectResync,
|
||||
},
|
||||
hasExistingLyrics && {
|
||||
key: 'replaceSegments',
|
||||
icon: TextCursorInput,
|
||||
title: t('replaceSegmentTitle'),
|
||||
desc: t('replaceSegmentDesc'),
|
||||
tag: t('replaceSegmentRecommended'),
|
||||
tagTone: 'positive' as const,
|
||||
onSelect: onSelectReplaceSegments,
|
||||
},
|
||||
hasExistingLyrics && {
|
||||
key: 'changeCase',
|
||||
icon: CaseSensitive,
|
||||
title: t('changeCaseTitle'),
|
||||
desc: t('changeCaseDesc'),
|
||||
tag: t('changeCaseRecommended'),
|
||||
tagTone: 'positive' as const,
|
||||
onSelect: onSelectChangeCase,
|
||||
},
|
||||
{
|
||||
key: 'replaceAll',
|
||||
icon: ClipboardPaste,
|
||||
title: t('replaceAllTitle'),
|
||||
desc: t('replaceAllDesc'),
|
||||
tag: t('replaceAllWarning'),
|
||||
tagTone: 'caution' as const,
|
||||
onSelect: onSelectReplace,
|
||||
},
|
||||
].filter((opt): opt is ModeOption => Boolean(opt))
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogContent className="max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center justify-between">
|
||||
<span>{t('title')}</span>
|
||||
@@ -36,81 +91,61 @@ export default function ModeSelectionModal({
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">{t('chooseMethod')}</p>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
{/* Re-sync Existing option - only show if there are existing lyrics */}
|
||||
{hasExistingLyrics && (
|
||||
<div
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||
{options.map(({ key, icon: Icon, title, desc, tag, tagTone, primary, onSelect }) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
'p-4 border-2 border-primary rounded-lg cursor-pointer',
|
||||
'hover:bg-primary/10 transition-colors'
|
||||
'p-3 rounded-lg border text-left transition-colors',
|
||||
'flex gap-3 items-start',
|
||||
'focus:outline-none focus-visible:ring-2 focus-visible:ring-primary',
|
||||
primary
|
||||
? 'border-2 border-primary hover:bg-primary/10'
|
||||
: 'hover:bg-muted/30 hover:border-muted-foreground'
|
||||
)}
|
||||
onClick={onSelectResync}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<RefreshCw className="h-10 w-10 text-primary mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h3 className="text-lg font-semibold text-primary">{t('resyncTitle')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('resyncDesc')}
|
||||
</p>
|
||||
<p className="text-xs text-green-500 mt-2">{t('resyncRecommended')}</p>
|
||||
<Icon
|
||||
className={cn(
|
||||
'h-7 w-7 shrink-0 mt-0.5',
|
||||
primary ? 'text-primary' : 'text-muted-foreground'
|
||||
)}
|
||||
/>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
|
||||
<h3
|
||||
className={cn(
|
||||
'text-sm font-semibold leading-tight',
|
||||
primary && 'text-primary'
|
||||
)}
|
||||
>
|
||||
{title}
|
||||
</h3>
|
||||
{tag && (
|
||||
<span
|
||||
className={cn(
|
||||
'text-[11px] font-medium leading-tight',
|
||||
tagTone === 'caution' ? 'text-yellow-500' : 'text-green-500'
|
||||
)}
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-1 line-clamp-2">{desc}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Replace Segment Lyrics 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={onSelectReplaceSegments}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<TextCursorInput className="h-10 w-10 text-muted-foreground mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h3 className="text-lg font-semibold">{t('replaceSegmentTitle')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('replaceSegmentDesc')}
|
||||
</p>
|
||||
<p className="text-xs text-green-500 mt-2">{t('replaceSegmentRecommended')}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Replace All option */}
|
||||
<div
|
||||
className={cn(
|
||||
'p-4 border rounded-lg cursor-pointer',
|
||||
'hover:bg-muted/30 hover:border-muted-foreground transition-colors'
|
||||
)}
|
||||
onClick={onSelectReplace}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<ClipboardPaste className="h-10 w-10 text-muted-foreground mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h3 className="text-lg font-semibold">{t('replaceAllTitle')}</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{t('replaceAllDesc')}
|
||||
</p>
|
||||
<p className="text-xs text-yellow-500 mt-2">
|
||||
{t('replaceAllWarning')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
Cancel
|
||||
{tCommon('cancel')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
|
||||
@@ -9,6 +9,7 @@ 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'
|
||||
|
||||
@@ -20,12 +21,19 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
type ModalMode = 'selection' | 'replace' | 'resync' | 'replaceSegments'
|
||||
type ModalMode = 'selection' | 'replace' | 'resync' | 'replaceSegments' | 'changeCase'
|
||||
|
||||
export type ReplaceAllOperation = 'replace_all_lyrics' | 'change_case'
|
||||
|
||||
export interface ReplaceAllSaveMeta {
|
||||
operation: ReplaceAllOperation
|
||||
details?: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface ReplaceAllLyricsModalProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
onSave: (newSegments: LyricsSegment[]) => void
|
||||
onSave: (newSegments: LyricsSegment[], meta?: ReplaceAllSaveMeta) => void
|
||||
onPlaySegment?: (startTime: number) => void
|
||||
currentTime?: number
|
||||
setModalSpacebarHandler: (handler: ((e: KeyboardEvent) => void) | undefined) => void
|
||||
@@ -45,6 +53,7 @@ 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(() => {
|
||||
@@ -52,6 +61,7 @@ export default function ReplaceAllLyricsModal({
|
||||
setMode('selection')
|
||||
setInputText('')
|
||||
setNewSegments([])
|
||||
setSelectedCase('upper')
|
||||
}
|
||||
}, [open])
|
||||
|
||||
@@ -135,7 +145,9 @@ export default function ReplaceAllLyricsModal({
|
||||
onClose()
|
||||
}, [onClose])
|
||||
|
||||
// Apply replace segments: build updated segments with new words for changed lines
|
||||
// Apply replace segments: build updated segments with new words for changed lines.
|
||||
// When a line changed but the word count is the same, preserve per-word timing/IDs
|
||||
// and only update the word text — so case-only or single-word edits don't drop timing.
|
||||
const handleApplyReplaceSegments = useCallback(() => {
|
||||
const newLines = inputText.split('\n')
|
||||
const updatedSegments: LyricsSegment[] = existingSegments.map((segment, i) => {
|
||||
@@ -147,7 +159,22 @@ export default function ReplaceAllLyricsModal({
|
||||
return JSON.parse(JSON.stringify(segment))
|
||||
}
|
||||
|
||||
// Changed — create new words with distributed timing
|
||||
const newWordTexts = newLineText.split(/\s+/).filter((w) => w.length > 0)
|
||||
|
||||
// Same word count — preserve timing, only swap text per word
|
||||
if (newWordTexts.length === segment.words.length && newWordTexts.length > 0) {
|
||||
const updatedWords = segment.words.map((word, idx) => ({
|
||||
...word,
|
||||
text: newWordTexts[idx],
|
||||
}))
|
||||
return {
|
||||
...segment,
|
||||
text: newLineText,
|
||||
words: updatedWords,
|
||||
}
|
||||
}
|
||||
|
||||
// Word count changed — distribute timing across new words
|
||||
const newWords = createWordsWithDistributedTiming(
|
||||
newLineText,
|
||||
segment.start_time,
|
||||
@@ -188,6 +215,33 @@ 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')
|
||||
@@ -211,6 +265,7 @@ export default function ReplaceAllLyricsModal({
|
||||
onSelectReplace={handleSelectReplace}
|
||||
onSelectResync={handleSelectResync}
|
||||
onSelectReplaceSegments={handleSelectReplaceSegments}
|
||||
onSelectChangeCase={handleSelectChangeCase}
|
||||
hasExistingLyrics={hasExistingLyrics}
|
||||
/>
|
||||
|
||||
@@ -343,6 +398,68 @@ 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,6 +49,8 @@ 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({
|
||||
@@ -76,6 +78,7 @@ export function HighlightedText({
|
||||
onEditCorrection,
|
||||
onAcceptCorrection,
|
||||
onShowCorrectionDetail,
|
||||
editedWordIds,
|
||||
}: HighlightedTextProps) {
|
||||
const { handleWordClick } = useWordClick({
|
||||
mode,
|
||||
@@ -242,6 +245,7 @@ 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(
|
||||
@@ -348,6 +352,7 @@ 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,6 +14,7 @@ export const WordComponent = React.memo(function Word({
|
||||
isUncorrectedGap,
|
||||
isCurrentlyPlaying,
|
||||
isActiveGap,
|
||||
isUserEdited,
|
||||
padding = 'px-[3px] py-[1px]',
|
||||
onClick,
|
||||
id,
|
||||
@@ -24,15 +25,18 @@ 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
|
||||
: isCorrectedGap
|
||||
? HIGHLIGHT_CLASSES.corrected
|
||||
: isUncorrectedGap
|
||||
? HIGHLIGHT_CLASSES.uncorrectedGap
|
||||
: ''
|
||||
: isUserEdited
|
||||
? HIGHLIGHT_CLASSES.userEdited
|
||||
: isCorrectedGap
|
||||
? HIGHLIGHT_CLASSES.corrected
|
||||
: isUncorrectedGap
|
||||
? HIGHLIGHT_CLASSES.uncorrectedGap
|
||||
: ''
|
||||
|
||||
const wordElement = (
|
||||
<span
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
'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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
'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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
'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>
|
||||
);
|
||||
}
|
||||
@@ -1,461 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState, useCallback } from 'react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { QrCode, Download } from 'lucide-react';
|
||||
import { generateFlyer } from '@/lib/api';
|
||||
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' | 'emoji';
|
||||
|
||||
interface QRStylePrefs {
|
||||
dotStyle: DotStyle;
|
||||
cornerSquareStyle: CornerSquareStyle;
|
||||
cornerDotStyle: CornerDotStyle;
|
||||
fgColor: string;
|
||||
bgColor: string;
|
||||
logo: LogoOption;
|
||||
logoEmoji: string;
|
||||
}
|
||||
|
||||
const DEFAULT_PREFS: QRStylePrefs = {
|
||||
dotStyle: 'square',
|
||||
cornerSquareStyle: 'square',
|
||||
cornerDotStyle: 'square',
|
||||
fgColor: '#000000',
|
||||
bgColor: '#ffffff',
|
||||
logo: 'none',
|
||||
logoEmoji: '🎤',
|
||||
};
|
||||
|
||||
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 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 QRCodeDialogProps {
|
||||
referralUrl: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** Override the flyer generator (e.g. admin endpoint). Receives theme + QR data URL, returns PDF blob. */
|
||||
onGenerateFlyer?: (theme: 'light' | 'dark', qrDataUrl: string) => Promise<Blob>;
|
||||
/** Override the download filename */
|
||||
flyerFilename?: string;
|
||||
}
|
||||
|
||||
export default function QRCodeDialog({ referralUrl, open, onOpenChange, onGenerateFlyer, flyerFilename }: 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);
|
||||
const [flyerTheme, setFlyerTheme] = useState<'light' | 'dark'>('light');
|
||||
const [flyerLoading, setFlyerLoading] = useState(false);
|
||||
const [flyerError, setFlyerError] = useState('');
|
||||
|
||||
// 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 === '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 (!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]);
|
||||
|
||||
// Clean up debounce timer on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
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 handleGenerateFlyer = async () => {
|
||||
setFlyerLoading(true);
|
||||
setFlyerError('');
|
||||
try {
|
||||
let qrDataUrl: string;
|
||||
if (qrRef.current) {
|
||||
const blob = await qrRef.current.getRawData('svg');
|
||||
if (blob) {
|
||||
qrDataUrl = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => resolve(reader.result as string);
|
||||
reader.onerror = () => reject(new Error('Failed to read QR code data'));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
} else {
|
||||
throw new Error('Failed to generate QR code image');
|
||||
}
|
||||
} else {
|
||||
throw new Error('QR code not initialized');
|
||||
}
|
||||
|
||||
const flyerFn = onGenerateFlyer || generateFlyer;
|
||||
const pdfBlob = await flyerFn(flyerTheme, qrDataUrl);
|
||||
const url = URL.createObjectURL(pdfBlob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = flyerFilename || 'nomad-karaoke-referral-flyer.pdf';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Failed to generate flyer';
|
||||
setFlyerError(message);
|
||||
console.error('Failed to generate flyer:', err);
|
||||
} finally {
|
||||
setFlyerLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
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="flex gap-1.5 mt-1">
|
||||
{(['none', 'nomad', 'emoji'] as LogoOption[]).map(option => {
|
||||
const labelKeys: Record<LogoOption, string> = {
|
||||
none: 'qrLogoNone',
|
||||
nomad: 'qrLogoNomad',
|
||||
emoji: 'qrLogoEmoji',
|
||||
};
|
||||
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) => {
|
||||
// Take only the last entered character/emoji
|
||||
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>
|
||||
|
||||
<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>
|
||||
{flyerError && (
|
||||
<p className="text-xs text-destructive">{flyerError}</p>
|
||||
)}
|
||||
{/* 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>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
'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,16 +1,22 @@
|
||||
'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, Gift, DollarSign, Users, Clock, Share2, Sparkles, ExternalLink } from 'lucide-react';
|
||||
import QRCodeDialog from './QRCodeDialog';
|
||||
import {
|
||||
QrCode, Sparkles, ExternalLink, CheckCircle, AlertCircle,
|
||||
Loader2, Banknote, Settings,
|
||||
} from 'lucide-react';
|
||||
import ReferralToolsDialog from './ReferralToolsDialog';
|
||||
|
||||
function formatCents(cents: number): string {
|
||||
return `$${(cents / 100).toFixed(2)}`;
|
||||
@@ -18,6 +24,7 @@ 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);
|
||||
@@ -30,6 +37,11 @@ export default function ReferralDashboard() {
|
||||
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 {
|
||||
@@ -48,6 +60,18 @@ 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}`;
|
||||
@@ -67,11 +91,42 @@ 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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -100,6 +155,8 @@ export default function ReferralDashboard() {
|
||||
|
||||
if (!data) return null;
|
||||
|
||||
const connectAccount = data.stripe_connect_account;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<h2 className="text-xl font-bold">{t('title')}</h2>
|
||||
@@ -300,25 +357,122 @@ export default function ReferralDashboard() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Payout section */}
|
||||
<div className="rounded-lg p-4 space-y-3" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
|
||||
{/* Payout & Bank Account section */}
|
||||
<div className="rounded-lg p-4 space-y-4" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
|
||||
<div className="flex justify-between items-center">
|
||||
<h3 className="font-semibold">{t('earnings')}</h3>
|
||||
<h3 className="font-semibold flex items-center gap-2">
|
||||
<Banknote className="w-5 h-5" style={{ color: 'var(--text-muted)' }} />
|
||||
{t('payoutTitle')}
|
||||
</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>
|
||||
|
||||
{!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>
|
||||
{/* 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>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('payoutThreshold')}</p>
|
||||
/* 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>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -359,10 +513,12 @@ export default function ReferralDashboard() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<QRCodeDialog
|
||||
<ReferralToolsDialog
|
||||
referralUrl={`https://nomadkaraoke.com/r/${data.link.code}`}
|
||||
open={qrOpen}
|
||||
onOpenChange={setQrOpen}
|
||||
referralCode={data.link.code}
|
||||
discountPercent={data.link.discount_percent}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
'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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,145 +0,0 @@
|
||||
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('NK Logo')).toBeInTheDocument();
|
||||
expect(screen.getByText('Emoji')).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',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
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',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
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 {}
|
||||
}
|
||||
@@ -160,8 +160,17 @@ export async function createEmailHelper(): Promise<EmailHelper> {
|
||||
url.searchParams.set('livequery', 'true');
|
||||
url.searchParams.set('wait', waitSeconds.toString());
|
||||
|
||||
// Node fetch has no default timeout — if testmail.app hangs (e.g. during a
|
||||
// quota-exceeded redirect loop) the call would block until Playwright's
|
||||
// per-test timeout (10+ min) instead of the intended waitForEmail timeout.
|
||||
const controller = new AbortController();
|
||||
const abortTimer = setTimeout(() => controller.abort(), (waitSeconds + 5) * 1000);
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString());
|
||||
const response = await fetch(url.toString(), {
|
||||
signal: controller.signal,
|
||||
redirect: 'error',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`testmail.app API error: ${response.status} ${response.statusText}`);
|
||||
@@ -189,10 +198,12 @@ export async function createEmailHelper(): Promise<EmailHelper> {
|
||||
} catch (error) {
|
||||
// If it's a timeout or network error, continue polling
|
||||
if (Date.now() - startTime < timeout) {
|
||||
console.log(`Polling for email... (${Math.round((Date.now() - startTime) / 1000)}s elapsed)`);
|
||||
console.log(`Polling for email... (${Math.round((Date.now() - startTime) / 1000)}s elapsed): ${error instanceof Error ? error.message : String(error)}`);
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(abortTimer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,8 +318,14 @@ export async function createEmailHelper(): Promise<EmailHelper> {
|
||||
url.searchParams.set('livequery', 'true');
|
||||
url.searchParams.set('wait', waitSeconds.toString());
|
||||
|
||||
const controller = new AbortController();
|
||||
const abortTimer = setTimeout(() => controller.abort(), (waitSeconds + 5) * 1000);
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString());
|
||||
const response = await fetch(url.toString(), {
|
||||
signal: controller.signal,
|
||||
redirect: 'error',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`testmail.app API error: ${response.status} ${response.statusText}`);
|
||||
@@ -361,10 +378,12 @@ export async function createEmailHelper(): Promise<EmailHelper> {
|
||||
}
|
||||
} catch (error) {
|
||||
if (Date.now() - startTime < timeout) {
|
||||
console.log(`Polling for completion email... (${Math.round((Date.now() - startTime) / 1000)}s elapsed)`);
|
||||
console.log(`Polling for completion email... (${Math.round((Date.now() - startTime) / 1000)}s elapsed): ${error instanceof Error ? error.message : String(error)}`);
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
clearTimeout(abortTimer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
// 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)`);
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
// 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,7 +1,8 @@
|
||||
/**
|
||||
* Tests for auth store's fetchUser() behavior, specifically:
|
||||
* - Abort errors (from page navigation) should NOT clear auth
|
||||
* - Other errors (expired session) SHOULD clear auth
|
||||
* - 401 errors (expired session) SHOULD clear auth
|
||||
* - Network errors (fetch failures) should NOT clear auth
|
||||
*/
|
||||
|
||||
// Mock api module before importing auth
|
||||
@@ -50,18 +51,31 @@ describe('fetchUser', () => {
|
||||
expect(useAuth.getState().isLoading).toBe(false)
|
||||
})
|
||||
|
||||
it('clears auth state when API returns a non-abort error (expired session)', async () => {
|
||||
mockGetCurrentUser.mockRejectedValueOnce(new Error('Unauthorized'))
|
||||
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)
|
||||
|
||||
const result = await useAuth.getState().fetchUser()
|
||||
|
||||
expect(result).toBe(false)
|
||||
// Auth SHOULD be cleared
|
||||
// Auth SHOULD be cleared on explicit 401
|
||||
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: {
|
||||
|
||||
@@ -3584,6 +3584,24 @@ 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',
|
||||
|
||||
@@ -152,9 +152,14 @@ export const useAuth = create<AuthStore>()(
|
||||
set({ isLoading: false })
|
||||
return false
|
||||
}
|
||||
// Session may have expired
|
||||
clearAccessToken()
|
||||
set({ user: null, isLoading: 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 })
|
||||
}
|
||||
return false
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
'use client'
|
||||
|
||||
import { reportClientError } from '@/lib/crash-reporter'
|
||||
import { hardReload, isChunkLoadError, isStale, startAmbientVersionPoll } from '@/lib/version-check'
|
||||
|
||||
let installed = false
|
||||
|
||||
function buildContext(userEmail: string | null, locale: string) {
|
||||
return {
|
||||
href: typeof window !== 'undefined' ? window.location.href : '',
|
||||
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
|
||||
innerWidth: typeof window !== 'undefined' ? window.innerWidth : undefined,
|
||||
innerHeight: typeof window !== 'undefined' ? window.innerHeight : undefined,
|
||||
locale,
|
||||
userEmail,
|
||||
}
|
||||
}
|
||||
|
||||
export function installGlobalErrorHandlers(getUserEmail: () => string | null, locale: string) {
|
||||
if (installed) return
|
||||
if (typeof window === 'undefined') return
|
||||
installed = true
|
||||
|
||||
const maybeReloadForChunkError = async (err: unknown): Promise<boolean> => {
|
||||
if (!isChunkLoadError(err)) return false
|
||||
const staleResult = await isStale().catch(() => null)
|
||||
// If the bundle is stale OR we can't verify, still reload — ChunkLoadError
|
||||
// by itself is strong signal of post-deploy mismatch.
|
||||
const triggered = hardReload(staleResult?.latestSha)
|
||||
return triggered
|
||||
}
|
||||
|
||||
window.addEventListener('error', (event) => {
|
||||
const err = event.error ?? new Error(event.message || 'Unknown window error')
|
||||
void (async () => {
|
||||
const reloaded = await maybeReloadForChunkError(err)
|
||||
if (reloaded) return
|
||||
void reportClientError({
|
||||
error: err,
|
||||
source: 'window.onerror',
|
||||
context: buildContext(getUserEmail(), locale),
|
||||
extra: {
|
||||
filename: event.filename,
|
||||
lineno: event.lineno,
|
||||
colno: event.colno,
|
||||
},
|
||||
})
|
||||
})()
|
||||
})
|
||||
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
const err = event.reason instanceof Error ? event.reason : new Error(String(event.reason))
|
||||
void (async () => {
|
||||
const reloaded = await maybeReloadForChunkError(err)
|
||||
if (reloaded) return
|
||||
void reportClientError({
|
||||
error: err,
|
||||
source: 'unhandledrejection',
|
||||
context: buildContext(getUserEmail(), locale),
|
||||
})
|
||||
})()
|
||||
})
|
||||
|
||||
// Ambient poll: every 10 min, if stale, stash info for UI to pick up via
|
||||
// a CustomEvent. We do NOT auto-reload here — that's reserved for crashes.
|
||||
startAmbientVersionPoll((r) => {
|
||||
try {
|
||||
sessionStorage.setItem('karaoke_latest_sha', r.latestSha)
|
||||
window.dispatchEvent(new CustomEvent('karaoke:stale-version', { detail: r }))
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/**
|
||||
* Frontend crash reporter.
|
||||
*
|
||||
* - Call `reportClientError(...)` from React error boundaries and global listeners.
|
||||
* - Dedupes identical errors within a short window to avoid spamming the API.
|
||||
* - Never throws; any failure to report is swallowed and logged to the console.
|
||||
*/
|
||||
|
||||
import { API_BASE_URL } from '@/lib/api'
|
||||
|
||||
export interface ClientErrorContext {
|
||||
href: string
|
||||
userAgent: string
|
||||
innerWidth?: number
|
||||
innerHeight?: number
|
||||
locale?: string
|
||||
release?: string
|
||||
userEmail?: string | null
|
||||
}
|
||||
|
||||
export interface CollectedContext {
|
||||
url: string
|
||||
userAgent: string
|
||||
locale: string
|
||||
release: string
|
||||
viewport: { w: number; h: number } | undefined
|
||||
userEmail: string | null
|
||||
}
|
||||
|
||||
export interface ReportArgs {
|
||||
error: unknown
|
||||
/** Where the error was caught. e.g. 'window.onerror', 'error.tsx', 'CrashReportBoundary' */
|
||||
source: string
|
||||
context: ClientErrorContext
|
||||
extra?: Record<string, unknown>
|
||||
}
|
||||
|
||||
const DEDUP_WINDOW_MS = 5_000
|
||||
const recentSignatures = new Map<string, number>()
|
||||
|
||||
export function __resetForTest() {
|
||||
recentSignatures.clear()
|
||||
}
|
||||
|
||||
function sanitizeUrl(href: string): string {
|
||||
if (!href) return ''
|
||||
try {
|
||||
const u = new URL(href)
|
||||
u.search = ''
|
||||
u.hash = ''
|
||||
return u.toString()
|
||||
} catch {
|
||||
return href.slice(0, 512)
|
||||
}
|
||||
}
|
||||
|
||||
export function collectContext(ctx: ClientErrorContext): CollectedContext {
|
||||
const viewport =
|
||||
typeof ctx.innerWidth === 'number' && typeof ctx.innerHeight === 'number'
|
||||
? { w: ctx.innerWidth, h: ctx.innerHeight }
|
||||
: undefined
|
||||
return {
|
||||
url: sanitizeUrl(ctx.href),
|
||||
userAgent: ctx.userAgent || '',
|
||||
locale: ctx.locale || 'en',
|
||||
release: ctx.release || process.env.NEXT_PUBLIC_COMMIT_SHA || '',
|
||||
viewport,
|
||||
userEmail: ctx.userEmail ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeError(e: unknown): { message: string; stack: string | null } {
|
||||
if (e instanceof Error) {
|
||||
return {
|
||||
message: `${e.name}: ${e.message}`,
|
||||
stack: e.stack ?? null,
|
||||
}
|
||||
}
|
||||
if (typeof e === 'string') {
|
||||
return { message: e, stack: null }
|
||||
}
|
||||
try {
|
||||
return { message: JSON.stringify(e).slice(0, 4000), stack: null }
|
||||
} catch {
|
||||
return { message: String(e).slice(0, 4000), stack: null }
|
||||
}
|
||||
}
|
||||
|
||||
function signatureFor(message: string, stack: string | null, source: string): string {
|
||||
return `${source}|${stack?.slice(0, 500) ?? message.slice(0, 500)}`
|
||||
}
|
||||
|
||||
export async function reportClientError(args: ReportArgs): Promise<void> {
|
||||
try {
|
||||
const { message, stack } = normalizeError(args.error)
|
||||
const sig = signatureFor(message, stack, args.source)
|
||||
const now = Date.now()
|
||||
const last = recentSignatures.get(sig)
|
||||
if (last && now - last < DEDUP_WINDOW_MS) return
|
||||
recentSignatures.set(sig, now)
|
||||
// simple cleanup
|
||||
if (recentSignatures.size > 200) {
|
||||
for (const [k, t] of recentSignatures) {
|
||||
if (now - t > DEDUP_WINDOW_MS * 4) recentSignatures.delete(k)
|
||||
}
|
||||
}
|
||||
|
||||
const ctx = collectContext(args.context)
|
||||
const body = {
|
||||
message,
|
||||
stack,
|
||||
url: ctx.url,
|
||||
user_agent: ctx.userAgent,
|
||||
release: ctx.release,
|
||||
user_email: ctx.userEmail,
|
||||
viewport: ctx.viewport ?? null,
|
||||
locale: ctx.locale,
|
||||
source: args.source,
|
||||
extra: args.extra ?? null,
|
||||
}
|
||||
|
||||
await fetch(`${API_BASE_URL}/api/client-errors`, {
|
||||
method: 'POST',
|
||||
keepalive: true,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}).catch(() => {
|
||||
/* swallow — never surface reporter errors to callers */
|
||||
})
|
||||
} catch (err) {
|
||||
if (typeof console !== 'undefined') {
|
||||
console.warn('[crash-reporter] failed:', err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ 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'
|
||||
| 'find_replace' | 'replace_all_lyrics' | 'change_case'
|
||||
| 'timing_change' | 'revert_correction' | 'revert_all'
|
||||
|
||||
export type EditFeedbackReason =
|
||||
@@ -337,6 +337,7 @@ export interface WordProps {
|
||||
isUncorrectedGap?: boolean
|
||||
isCurrentlyPlaying?: boolean
|
||||
isActiveGap?: boolean
|
||||
isUserEdited?: boolean
|
||||
padding?: string
|
||||
onClick?: () => void
|
||||
id?: string
|
||||
@@ -381,6 +382,7 @@ export interface TranscriptionViewProps {
|
||||
onShowCorrectionDetail?: (wordId: string) => void
|
||||
advancedMode?: boolean
|
||||
onAdvancedModeToggle?: (enabled: boolean) => void
|
||||
editedWordIds?: Set<string>
|
||||
}
|
||||
|
||||
export interface ReferenceViewProps extends BaseViewProps {
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
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 !@#')
|
||||
})
|
||||
|
||||
it('capitalizes the first accented letter correctly', () => {
|
||||
expect(convertCase('über alles', 'sentence')).toBe('Über alles')
|
||||
})
|
||||
})
|
||||
|
||||
describe('unicode handling', () => {
|
||||
it('title-cases accented Latin characters', () => {
|
||||
expect(convertCase('über alles éclair', 'title')).toBe('Über Alles Éclair')
|
||||
})
|
||||
|
||||
it('lowercases Cyrillic correctly', () => {
|
||||
expect(convertCase('ПРИВЕТ мир', 'lower')).toBe('привет мир')
|
||||
})
|
||||
|
||||
it('title-cases Cyrillic correctly', () => {
|
||||
expect(convertCase('привет мир', 'title')).toBe('Привет Мир')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
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',
|
||||
'find_replace', 'replace_all_lyrics', 'change_case',
|
||||
'timing_change', 'revert_correction', 'revert_all',
|
||||
] as const
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
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 capitalizeFirstLetter(text: string): string {
|
||||
const firstLetter = text.search(/\p{L}/u)
|
||||
if (firstLetter === -1) return text
|
||||
return (
|
||||
text.slice(0, firstLetter) +
|
||||
text.charAt(firstLetter).toUpperCase() +
|
||||
text.slice(firstLetter + 1)
|
||||
)
|
||||
}
|
||||
|
||||
function toTitleCase(text: string): string {
|
||||
return text.replace(/\S+/gu, (word) => capitalizeFirstLetter(word.toLowerCase()))
|
||||
}
|
||||
|
||||
function toSentenceCase(text: string): string {
|
||||
return capitalizeFirstLetter(text.toLowerCase())
|
||||
}
|
||||
|
||||
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 Unicode letter — so a
|
||||
// leading punctuation-only token doesn't steal the capitalization.
|
||||
const firstCasedIndex = perLine
|
||||
? segment.words.findIndex((w) => /\p{L}/u.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,6 +113,14 @@ 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;
|
||||
@@ -121,6 +129,7 @@ export interface ReferralDashboard {
|
||||
recent_earnings: ReferralEarning[];
|
||||
recent_payouts: ReferralPayout[];
|
||||
stripe_connect_configured: boolean;
|
||||
stripe_connect_account: StripeConnectAccount | null;
|
||||
}
|
||||
|
||||
export interface ReferralInterstitial {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
'use client'
|
||||
|
||||
/**
|
||||
* Version-awareness for cache-busting.
|
||||
*
|
||||
* - isStale() — compares the compiled NEXT_PUBLIC_COMMIT_SHA against /version.json.
|
||||
* - hardReload() — unregisters SWs, clears caches, navigates to url?_v=<sha>.
|
||||
* Includes a 60s circuit breaker to prevent reload loops.
|
||||
* - handleChunkLoadError() — pattern-matches common chunk errors and reloads.
|
||||
*/
|
||||
|
||||
const STORAGE_KEY = 'karaoke_last_hard_reload'
|
||||
const CIRCUIT_BREAKER_MS = 60_000
|
||||
|
||||
let _buildShaOverride: string | null = null
|
||||
|
||||
export function __resetForTest() {
|
||||
_buildShaOverride = null
|
||||
if (typeof sessionStorage !== 'undefined') {
|
||||
sessionStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
}
|
||||
|
||||
export function __setBuildShaForTest(sha: string) {
|
||||
_buildShaOverride = sha
|
||||
}
|
||||
|
||||
function currentBuildSha(): string {
|
||||
if (_buildShaOverride !== null) return _buildShaOverride
|
||||
return process.env.NEXT_PUBLIC_COMMIT_SHA || 'dev'
|
||||
}
|
||||
|
||||
export interface StaleResult {
|
||||
stale: boolean
|
||||
latestSha: string
|
||||
currentSha: string
|
||||
}
|
||||
|
||||
export async function isStale(): Promise<StaleResult> {
|
||||
const current = currentBuildSha()
|
||||
// 'dev' means local — never surface a stale warning in dev
|
||||
if (current === 'dev' || current === '') {
|
||||
return { stale: false, latestSha: current, currentSha: current }
|
||||
}
|
||||
try {
|
||||
const res = await fetch('/version.json', { cache: 'no-store' })
|
||||
if (!res.ok) throw new Error(`status ${res.status}`)
|
||||
const data = (await res.json()) as { build_sha?: string }
|
||||
const latest = data?.build_sha ?? current
|
||||
return { stale: latest !== current, latestSha: latest, currentSha: current }
|
||||
} catch {
|
||||
// Fail-safe: if we can't check, don't claim stale (would spam users).
|
||||
return { stale: false, latestSha: current, currentSha: current }
|
||||
}
|
||||
}
|
||||
|
||||
function withinCircuitBreaker(): boolean {
|
||||
if (typeof sessionStorage === 'undefined') return false
|
||||
const last = sessionStorage.getItem(STORAGE_KEY)
|
||||
if (!last) return false
|
||||
const ts = Number(last)
|
||||
if (!Number.isFinite(ts)) return false
|
||||
return Date.now() - ts < CIRCUIT_BREAKER_MS
|
||||
}
|
||||
|
||||
function markReload() {
|
||||
try {
|
||||
sessionStorage.setItem(STORAGE_KEY, String(Date.now()))
|
||||
} catch {
|
||||
/* private mode — ok */
|
||||
}
|
||||
}
|
||||
|
||||
export function hardReload(latestSha?: string): boolean {
|
||||
if (typeof window === 'undefined') return false
|
||||
if (withinCircuitBreaker()) {
|
||||
if (typeof console !== 'undefined') {
|
||||
console.warn('[version-check] hardReload suppressed by circuit breaker')
|
||||
}
|
||||
return false
|
||||
}
|
||||
markReload()
|
||||
|
||||
// Best-effort cache-busting before reload. These are fire-and-forget —
|
||||
// if they're slow, the navigation still proceeds.
|
||||
try {
|
||||
if ('serviceWorker' in navigator) {
|
||||
void navigator.serviceWorker
|
||||
.getRegistrations()
|
||||
.then((regs) => regs.forEach((r) => r.unregister()))
|
||||
.catch(() => {})
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
if (typeof caches !== 'undefined') {
|
||||
void caches
|
||||
.keys()
|
||||
.then((keys) => keys.forEach((k) => caches.delete(k)))
|
||||
.catch(() => {})
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
const sep = window.location.pathname.includes('?') ? '&' : '?'
|
||||
const buster = latestSha && latestSha !== 'dev' ? latestSha : String(Date.now())
|
||||
window.location.assign(`${window.location.pathname}${sep}_v=${encodeURIComponent(buster)}`)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if `err` looks like a chunk-load error from a post-deploy
|
||||
* mismatch. Next.js surfaces these as `ChunkLoadError` or messages mentioning
|
||||
* "Loading chunk" / "dynamically imported module".
|
||||
*/
|
||||
export function isChunkLoadError(err: unknown): boolean {
|
||||
if (!err) return false
|
||||
const e = err as { name?: string; message?: string }
|
||||
if (e.name === 'ChunkLoadError') return true
|
||||
const msg = typeof e.message === 'string' ? e.message : ''
|
||||
return (
|
||||
/ChunkLoadError/i.test(msg) ||
|
||||
/Loading chunk [\w-]+ failed/i.test(msg) ||
|
||||
/Failed to fetch dynamically imported module/i.test(msg) ||
|
||||
/Importing a module script failed/i.test(msg)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Ambient poll every 10 minutes. Only installs one poller per tab.
|
||||
*/
|
||||
let pollHandle: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
export function startAmbientVersionPoll(
|
||||
onStale: (r: StaleResult) => void,
|
||||
intervalMs = 10 * 60 * 1000,
|
||||
) {
|
||||
if (typeof window === 'undefined') return () => {}
|
||||
if (pollHandle !== null) return () => {}
|
||||
const tick = async () => {
|
||||
const r = await isStale()
|
||||
if (r.stale) onStale(r)
|
||||
}
|
||||
pollHandle = setInterval(() => void tick(), intervalMs)
|
||||
return () => {
|
||||
if (pollHandle !== null) {
|
||||
clearInterval(pollHandle)
|
||||
pollHandle = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"replaceSegmentRecommended": "موصى به للكلمات المخصصة",
|
||||
"replaceAllTitle": "استبدال جميع الكلمات",
|
||||
"replaceAllDesc": "الصق كلمات جديدة تماماً من الحافظة وقم بمزامنة التوقيت يدوياً لجميع الكلمات من الصفر.",
|
||||
"replaceAllWarning": "سيتم فقدان جميع بيانات التوقيت الحالية"
|
||||
"replaceAllWarning": "سيتم فقدان جميع بيانات التوقيت الحالية",
|
||||
"changeCaseDesc": "حوّل جميع الكلمات إلى أحرف كبيرة، أو أحرف صغيرة، أو حالة العنوان، أو حالة الجملة. يتم الحفاظ على التوقيت بالكامل.",
|
||||
"changeCaseRecommended": "موصى به لتناسق الأسلوب",
|
||||
"changeCaseTitle": "تغيير حالة الأحرف"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "الصق كلماتك الجديدة أدناه:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"resyncExisting": "إعادة مزامنة الكلمات الحالية",
|
||||
"noLyricsToSync": "لا توجد كلمات لمزامنتها",
|
||||
"goBackAndPaste": "ارجع والصق كلمات جديدة، أو أغلق هذه النافذة.",
|
||||
"backToSelection": "العودة إلى التحديد"
|
||||
"backToSelection": "العودة إلى التحديد",
|
||||
"caseLower": "أحرف صغيرة",
|
||||
"caseLowerDesc": "جميع الأحرف صغيرة",
|
||||
"caseSentence": "حالة الجملة",
|
||||
"caseSentenceDesc": "تكبير الحرف الأول من كل سطر",
|
||||
"caseTitle": "حالة العنوان",
|
||||
"caseTitleDesc": "تكبير الحرف الأول من كل كلمة",
|
||||
"caseUpper": "أحرف كبيرة",
|
||||
"caseUpperDesc": "جميع الأحرف كبيرة",
|
||||
"changeCase": "تغيير حالة الأحرف",
|
||||
"changeCaseApply": "تطبيق {case}",
|
||||
"changeCaseNote": "يتم الحفاظ على توقيت الكلمات بالكامل — تتغير حالة الأحرف فقط.",
|
||||
"changeCasePreview": "معاينة",
|
||||
"changeCasePrompt": "اختر نمط حالة الأحرف لتطبيقه على جميع الكلمات:"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "معاينة الفيديو (مع الغناء)",
|
||||
@@ -1308,6 +1324,63 @@
|
||||
"appliedAtCheckout": "يُطبق تلقائياً عند الدفع",
|
||||
"expires": "ينتهي في {date}",
|
||||
"referredBy": "بإحالة من {name}",
|
||||
"usingCode": "الرمز: {code}"
|
||||
"usingCode": "الرمز: {code}",
|
||||
"connectBankLoading": "جاري الإعداد...",
|
||||
"connectDetailsNeeded": "تحتاج Stripe إلى معلومات إضافية لتمكين المدفوعات. انقر على \"تحديث الحساب البنكي\" أدناه لإكمال الإعداد.",
|
||||
"connectRefresh": "يبدو أنك لم تكمل إعداد حسابك البنكي. انقر أدناه للمحاولة مرة أخرى.",
|
||||
"connectStatusActive": "تم تمكين المدفوعات",
|
||||
"connectStatusPending": "الإعداد قيد التقدم",
|
||||
"connectStripeNote": "ستتم إعادة توجيهك إلى موقع Stripe الآمن لإدخال تفاصيل حسابك البنكي. يستغرق هذا عادةً بضع دقائق.",
|
||||
"flyerAccentColor": "لون التمييز",
|
||||
"flyerBranding": "العلامة التجارية",
|
||||
"flyerColors": "الألوان",
|
||||
"flyerDownloadHtml": "تنزيل HTML",
|
||||
"flyerDownloadPdf": "تنزيل PDF",
|
||||
"flyerDownloadPng": "تنزيل PNG",
|
||||
"flyerEditQr": "تعديل نمط QR",
|
||||
"flyerExporting": "جاري التصدير...",
|
||||
"flyerHeadlineGradient": "تدرج العنوان",
|
||||
"flyerHeadlineSubColor": "لون العنوان الفرعي",
|
||||
"flyerMargins": "هوامش الصفحة",
|
||||
"flyerPerPage": "عدد النشرات في الصفحة",
|
||||
"flyerPresetCustom": "مخصص",
|
||||
"flyerPresetName": "اسم الإعداد المسبق",
|
||||
"flyerPresetSave": "حفظ الإعداد المسبق",
|
||||
"flyerPrintLayout": "تخطيط الطباعة",
|
||||
"flyerSections": "الأقسام",
|
||||
"flyerSubtextColor": "النص الفرعي",
|
||||
"flyerTextColor": "النص",
|
||||
"flyerTextOverrides": "تعديلات النص",
|
||||
"flyerToggleDivider": "الفاصل",
|
||||
"flyerToggleFeatures": "الميزات السفلية",
|
||||
"flyerToggleSteps": "خطوات الاستخدام",
|
||||
"flyerToggleSubtitle": "العنوان الفرعي",
|
||||
"flyerToggleTagline": "العبارة الترويجية السفلية",
|
||||
"flyerUploadLogo": "رفع الشعار",
|
||||
"managePayouts": "إدارة المدفوعات",
|
||||
"payoutTitle": "المدفوعات والحساب البنكي",
|
||||
"tabFlyer": "نشرة إعلانية قابلة للطباعة",
|
||||
"tabQrCode": "رمز QR",
|
||||
"toolsTitle": "Generator رمز QR والنشرات الإعلانية",
|
||||
"updateBankAccount": "تحديث الحساب البنكي",
|
||||
"connectFailed": "حدث خطأ ما. يرجى المحاولة مرة أخرى.",
|
||||
"flyerRemoveLogo": "إزالة"
|
||||
},
|
||||
"crashReport": {
|
||||
"backToDashboard": "العودة إلى لوحة التحكم",
|
||||
"copied": "تم النسخ!",
|
||||
"copyDebug": "نسخ معلومات تصحيح الأخطاء",
|
||||
"hideStack": "إخفاء التفاصيل الفنية",
|
||||
"reportFailed": "لم نتمكن من إرسال تقرير العطل تلقائياً. يرجى نسخ التفاصيل ومراسلة الدعم.",
|
||||
"reportSending": "جارٍ إرسال تقرير العطل…",
|
||||
"reportSent": "تم إرسال تقرير العطل — لقد تم إبلاغنا.",
|
||||
"sendReport": "إرسال تقرير العطل مرة أخرى",
|
||||
"subtitle": "واجه التطبيق خطأً غير متوقع. يمكنك نسخ التفاصيل أو العودة إلى لوحة التحكم.",
|
||||
"title": "حدث خطأ ما",
|
||||
"toggleStack": "إظهار التفاصيل الفنية",
|
||||
"updateAvailable": "يتوفر إصدار أحدث — قد يحل هذه المشكلة.",
|
||||
"updateAvailableSubtitle": "سنقوم بتحديث الصفحة وتحميل أحدث كود.",
|
||||
"updateNow": "التحديث الآن",
|
||||
"retry": "حاول مرة أخرى"
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"replaceSegmentRecommended": "Recomanat per a lletres personalitzades",
|
||||
"replaceAllTitle": "Reemplaça totes les lletres",
|
||||
"replaceAllDesc": "Enganxa lletres completament noves des del porta-retalls i sincronitza manualment el temps de totes les paraules des de zero.",
|
||||
"replaceAllWarning": "Es perdran totes les dades de temps existents"
|
||||
"replaceAllWarning": "Es perdran totes les dades de temps existents",
|
||||
"changeCaseDesc": "Converteix tota la lletra a MAJÚSCULES, minúscules, Tipus títol o Tipus oració. La sincronització es conserva completament.",
|
||||
"changeCaseRecommended": "Recomanat per a la coherència d'estil",
|
||||
"changeCaseTitle": "Canvia majúscules/minúscules"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Enganxa les teves noves lletres a continuació:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"resyncExisting": "Ressincronitza les lletres existents",
|
||||
"noLyricsToSync": "No hi ha lletres per sincronitzar",
|
||||
"goBackAndPaste": "Torna enrere i enganxa noves lletres, o tanca aquest modal.",
|
||||
"backToSelection": "Torna a la selecció"
|
||||
"backToSelection": "Torna a la selecció",
|
||||
"caseLower": "minúscules",
|
||||
"caseLowerDesc": "totes les lletres en minúscula",
|
||||
"caseSentence": "Tipus oració",
|
||||
"caseSentenceDesc": "La primera paraula de cada línia en majúscula",
|
||||
"caseTitle": "Tipus títol",
|
||||
"caseTitleDesc": "Cada Paraula En Majúscula",
|
||||
"caseUpper": "MAJÚSCULES",
|
||||
"caseUpperDesc": "TOTES LES LLETRES EN MAJÚSCULA",
|
||||
"changeCase": "Canvia majúscules/minúscules",
|
||||
"changeCaseApply": "Aplica {case}",
|
||||
"changeCaseNote": "La sincronització de les paraules es conserva completament — només canvien les majúscules i minúscules.",
|
||||
"changeCasePreview": "Previsualització",
|
||||
"changeCasePrompt": "Tria un estil de majúscules/minúscules per aplicar a tota la lletra:"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Previsualitza el vídeo (Amb veus)",
|
||||
@@ -1308,6 +1324,63 @@
|
||||
"appliedAtCheckout": "S'aplica automàticament en finalitzar la compra",
|
||||
"expires": "Caduca el {date}",
|
||||
"referredBy": "Recomanat per {name}",
|
||||
"usingCode": "Codi: {code}"
|
||||
"usingCode": "Codi: {code}",
|
||||
"connectBankLoading": "Configurant...",
|
||||
"connectDetailsNeeded": "Stripe necessita informació addicional per activar els pagaments. Fes clic a \"Actualitza el compte bancari\" a continuació per completar la configuració.",
|
||||
"connectRefresh": "Sembla que no has acabat de configurar el teu compte bancari. Fes clic a continuació per tornar-ho a provar.",
|
||||
"connectStatusActive": "Pagaments activats",
|
||||
"connectStatusPending": "Configuració en curs",
|
||||
"connectStripeNote": "Se't redirigirà al lloc segur de Stripe per introduir les teves dades bancàries. Això sol trigar un parell de minuts.",
|
||||
"flyerAccentColor": "Color d'accent",
|
||||
"flyerBranding": "Marca",
|
||||
"flyerColors": "Colors",
|
||||
"flyerDownloadHtml": "Descarrega HTML",
|
||||
"flyerDownloadPdf": "Descarrega PDF",
|
||||
"flyerDownloadPng": "Descarrega PNG",
|
||||
"flyerEditQr": "Edita l'estil del QR",
|
||||
"flyerExporting": "Exportant...",
|
||||
"flyerHeadlineGradient": "Degradat del titular",
|
||||
"flyerHeadlineSubColor": "Subtitular",
|
||||
"flyerMargins": "Marges de la pàgina",
|
||||
"flyerPerPage": "Fullets per pàgina",
|
||||
"flyerPresetCustom": "Personalitzat",
|
||||
"flyerPresetName": "Nom del preajust",
|
||||
"flyerPresetSave": "Desa el preajust",
|
||||
"flyerPrintLayout": "Disposició d'impressió",
|
||||
"flyerSections": "Seccions",
|
||||
"flyerSubtextColor": "Subtext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Substitucions de text",
|
||||
"flyerToggleDivider": "Separador",
|
||||
"flyerToggleFeatures": "Característiques inferiors",
|
||||
"flyerToggleSteps": "Passos de com funciona",
|
||||
"flyerToggleSubtitle": "Subtítol",
|
||||
"flyerToggleTagline": "Eslògan inferior",
|
||||
"flyerUploadLogo": "Puja el logotip",
|
||||
"managePayouts": "Gestiona els pagaments",
|
||||
"payoutTitle": "Pagaments i compte bancari",
|
||||
"tabFlyer": "Fullet imprimible",
|
||||
"tabQrCode": "Codi QR",
|
||||
"toolsTitle": "Generator de codis QR i fullets",
|
||||
"updateBankAccount": "Actualitza el compte bancari",
|
||||
"connectFailed": "Alguna cosa ha anat malament. Torna-ho a provar.",
|
||||
"flyerRemoveLogo": "Elimina"
|
||||
},
|
||||
"crashReport": {
|
||||
"backToDashboard": "Torna al tauler",
|
||||
"copied": "Copiat!",
|
||||
"copyDebug": "Copia la informació de depuració",
|
||||
"hideStack": "Amaga els detalls tècnics",
|
||||
"reportFailed": "No hem pogut enviar l'informe d'error automàticament. Si us plau, copia els detalls i envia un missatge a suport.",
|
||||
"reportSending": "S'està enviant l'informe d'error…",
|
||||
"reportSent": "Informe d'error enviat — hem rebut l'avís.",
|
||||
"sendReport": "Torna a enviar l'informe d'error",
|
||||
"subtitle": "L'aplicació ha trobat un error inesperat. Pots copiar els detalls o tornar al tauler.",
|
||||
"title": "Hi ha hagut un problema",
|
||||
"toggleStack": "Mostra els detalls tècnics",
|
||||
"updateAvailable": "Hi ha una versió més nova disponible — podria solucionar aquest problema.",
|
||||
"updateAvailableSubtitle": "Actualitzarem la pàgina i carregarem el codi més recent.",
|
||||
"updateNow": "Actualitza ara",
|
||||
"retry": "Torna-ho a provar"
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"replaceSegmentRecommended": "Doporučeno pro vlastní texty",
|
||||
"replaceAllTitle": "Nahradit veškerý text",
|
||||
"replaceAllDesc": "Vlož úplně nový text ze schránky a manuálně synchronizuj časování pro všechna slova od začátku.",
|
||||
"replaceAllWarning": "Všechna existující data časování budou ztracena"
|
||||
"replaceAllWarning": "Všechna existující data časování budou ztracena",
|
||||
"changeCaseDesc": "Převeď celý text na VELKÁ PÍSMENA, malá písmena, Velká první písmena nebo Velké počáteční písmeno. Časování zůstane plně zachováno.",
|
||||
"changeCaseRecommended": "Doporučeno pro sjednocení stylu",
|
||||
"changeCaseTitle": "Změnit velikost písmen"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Vlož svůj nový text níže:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"resyncExisting": "Znovu synchronizovat existující text",
|
||||
"noLyricsToSync": "Žádný text k synchronizaci",
|
||||
"goBackAndPaste": "Vrať se zpět a vlož nový text, nebo zavři toto okno.",
|
||||
"backToSelection": "Zpět na výběr"
|
||||
"backToSelection": "Zpět na výběr",
|
||||
"caseLower": "malá písmena",
|
||||
"caseLowerDesc": "všechna písmena malá",
|
||||
"caseSentence": "Velké počáteční písmeno",
|
||||
"caseSentenceDesc": "První slovo každého řádku začíná velkým písmenem",
|
||||
"caseTitle": "Velká první písmena",
|
||||
"caseTitleDesc": "Každé Slovo Začíná Velkým Písmenem",
|
||||
"caseUpper": "VELKÁ PÍSMENA",
|
||||
"caseUpperDesc": "VŠECHNA PÍSMENA VELKÁ",
|
||||
"changeCase": "Změnit velikost písmen",
|
||||
"changeCaseApply": "Použít {case}",
|
||||
"changeCaseNote": "Časování slov zůstává plně zachováno — mění se pouze velikost písmen.",
|
||||
"changeCasePreview": "Náhled",
|
||||
"changeCasePrompt": "Vyber styl velikosti písmen, který se použije na celý text:"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Náhled videa (S vokály)",
|
||||
@@ -1308,6 +1324,63 @@
|
||||
"appliedAtCheckout": "Automaticky uplatněno při platbě",
|
||||
"expires": "Platnost do {date}",
|
||||
"referredBy": "Doporučil/a {name}",
|
||||
"usingCode": "Kód: {code}"
|
||||
"usingCode": "Kód: {code}",
|
||||
"connectBankLoading": "Nastavování...",
|
||||
"connectDetailsNeeded": "Stripe potřebuje další informace k povolení výplat. Klikni níže na „Aktualizovat bankovní účet“ a dokonči nastavení.",
|
||||
"connectRefresh": "Vypadá to, že nemáš dokončené nastavení svého bankovního účtu. Klikni níže a zkus to znovu.",
|
||||
"connectStatusActive": "Výplaty povoleny",
|
||||
"connectStatusPending": "Probíhá nastavení",
|
||||
"connectStripeNote": "Přesměrujeme tě na zabezpečenou stránku Stripe, kde zadáš své bankovní údaje. Obvykle to trvá jen pár minut.",
|
||||
"flyerAccentColor": "Akcentní barva",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Barvy",
|
||||
"flyerDownloadHtml": "Stáhnout HTML",
|
||||
"flyerDownloadPdf": "Stáhnout PDF",
|
||||
"flyerDownloadPng": "Stáhnout PNG",
|
||||
"flyerEditQr": "Upravit styl QR",
|
||||
"flyerExporting": "Probíhá export...",
|
||||
"flyerHeadlineGradient": "Přechod nadpisu",
|
||||
"flyerHeadlineSubColor": "Podnadpis",
|
||||
"flyerMargins": "Okraje stránky",
|
||||
"flyerPerPage": "Letáků na stránku",
|
||||
"flyerPresetCustom": "Vlastní",
|
||||
"flyerPresetName": "Název předvolby",
|
||||
"flyerPresetSave": "Uložit předvolbu",
|
||||
"flyerPrintLayout": "Rozvržení tisku",
|
||||
"flyerSections": "Sekce",
|
||||
"flyerSubtextColor": "Podtext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Vlastní texty",
|
||||
"flyerToggleDivider": "Oddělovač",
|
||||
"flyerToggleFeatures": "Funkce v dolní části",
|
||||
"flyerToggleSteps": "Kroky „Jak to funguje“",
|
||||
"flyerToggleSubtitle": "Podtitul",
|
||||
"flyerToggleTagline": "Spodní slogan",
|
||||
"flyerUploadLogo": "Nahrát logo",
|
||||
"managePayouts": "Spravovat výplaty",
|
||||
"payoutTitle": "Výplaty a bankovní účet",
|
||||
"tabFlyer": "Leták k tisku",
|
||||
"tabQrCode": "QR kód",
|
||||
"toolsTitle": "Generator QR kódů a letáků",
|
||||
"updateBankAccount": "Aktualizovat bankovní účet",
|
||||
"connectFailed": "Něco se pokazilo. Zkus to prosím znovu.",
|
||||
"flyerRemoveLogo": "Odstranit"
|
||||
},
|
||||
"crashReport": {
|
||||
"backToDashboard": "Zpět na přehled",
|
||||
"copied": "Zkopírováno!",
|
||||
"copyDebug": "Zkopírovat ladicí informace",
|
||||
"hideStack": "Skrýt technické detaily",
|
||||
"reportFailed": "Nepodařilo se nám automaticky odeslat zprávu o chybě. Zkopíruj prosím detaily a napiš na podporu.",
|
||||
"reportSending": "Odesílání zprávy o chybě…",
|
||||
"reportSent": "Zpráva o chybě byla odeslána — už o tom víme.",
|
||||
"sendReport": "Odeslat zprávu o chybě znovu",
|
||||
"subtitle": "Aplikace narazila na neočekávanou chybu. Můžeš zkopírovat detaily nebo se vrátit na přehled.",
|
||||
"title": "Něco se pokazilo",
|
||||
"toggleStack": "Zobrazit technické detaily",
|
||||
"updateAvailable": "Je k dispozici novější verze — možná tento problém vyřeší.",
|
||||
"updateAvailableSubtitle": "Obnovíme stránku a načteme nejnovější kód.",
|
||||
"updateNow": "Aktualizovat nyní",
|
||||
"retry": "Zkusit znovu"
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"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"
|
||||
"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"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Indsæt dine nye sangtekster nedenfor:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"resyncExisting": "Gen-synkroniser eksisterende sangtekster",
|
||||
"noLyricsToSync": "Ingen sangtekster at synkronisere",
|
||||
"goBackAndPaste": "Gå tilbage og indsæt nye sangtekster, eller luk denne modal.",
|
||||
"backToSelection": "Tilbage til valg"
|
||||
"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:"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Forhåndsvisningsvideo (med vokal)",
|
||||
@@ -1308,6 +1324,63 @@
|
||||
"appliedAtCheckout": "Anvendes automatisk ved kassen",
|
||||
"expires": "Udløber {date}",
|
||||
"referredBy": "Henvist af {name}",
|
||||
"usingCode": "Kode: {code}"
|
||||
"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"
|
||||
},
|
||||
"crashReport": {
|
||||
"backToDashboard": "Tilbage til dashboard",
|
||||
"copied": "Kopieret!",
|
||||
"copyDebug": "Kopiér debug-info",
|
||||
"hideStack": "Skjul tekniske detaljer",
|
||||
"reportFailed": "Vi kunne ikke sende fejlrapporten automatisk. Kopiér detaljerne og send en besked til support.",
|
||||
"reportSending": "Sender fejlrapport…",
|
||||
"reportSent": "Fejlrapport sendt — vi har fået besked.",
|
||||
"sendReport": "Send fejlrapport igen",
|
||||
"subtitle": "Appen stødte på en uventet fejl. Du kan kopiere detaljerne eller gå tilbage til dashboardet.",
|
||||
"title": "Noget gik galt",
|
||||
"toggleStack": "Vis tekniske detaljer",
|
||||
"updateAvailable": "En nyere version er tilgængelig — den løser muligvis dette problem.",
|
||||
"updateAvailableSubtitle": "Vi genindlæser siden og henter den nyeste kode.",
|
||||
"updateNow": "Opdatér nu",
|
||||
"retry": "Prøv igen"
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"replaceSegmentRecommended": "Empfohlen für eigenen Text",
|
||||
"replaceAllTitle": "Gesamten Text ersetzen",
|
||||
"replaceAllDesc": "Füge komplett neuen Text aus der Zwischenablage ein und synchronisiere das Timing für alle Wörter manuell von Grund auf neu.",
|
||||
"replaceAllWarning": "Alle bestehenden Timing-Daten gehen verloren"
|
||||
"replaceAllWarning": "Alle bestehenden Timing-Daten gehen verloren",
|
||||
"changeCaseDesc": "Konvertiere den gesamten Text in GROSSBUCHSTABEN, Kleinbuchstaben, Wortanfang groß oder Satzanfang groß. Das Timing bleibt vollständig erhalten.",
|
||||
"changeCaseRecommended": "Empfohlen für einen einheitlichen Stil",
|
||||
"changeCaseTitle": "Groß-/Kleinschreibung ändern"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Füge deinen neuen Text unten ein:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"resyncExisting": "Bestehenden Text neu synchronisieren",
|
||||
"noLyricsToSync": "Kein Text zum Synchronisieren",
|
||||
"goBackAndPaste": "Gehe zurück und füge neuen Text ein, oder schließe dieses Modal.",
|
||||
"backToSelection": "Zurück zur Auswahl"
|
||||
"backToSelection": "Zurück zur Auswahl",
|
||||
"caseLower": "Kleinbuchstaben",
|
||||
"caseLowerDesc": "alle Buchstaben klein",
|
||||
"caseSentence": "Satzanfang groß",
|
||||
"caseSentenceDesc": "Erstes Wort jeder Zeile großgeschrieben",
|
||||
"caseTitle": "Wortanfang groß",
|
||||
"caseTitleDesc": "Jedes Wort großgeschrieben",
|
||||
"caseUpper": "GROSSBUCHSTABEN",
|
||||
"caseUpperDesc": "ALLE BUCHSTABEN GROSSGESCHRIEBEN",
|
||||
"changeCase": "Groß-/Kleinschreibung ändern",
|
||||
"changeCaseApply": "{case} anwenden",
|
||||
"changeCaseNote": "Das Wort-Timing bleibt vollständig erhalten — nur die Groß-/Kleinschreibung ändert sich.",
|
||||
"changeCasePreview": "Vorschau",
|
||||
"changeCasePrompt": "Wähle einen Stil für die Groß-/Kleinschreibung, der auf den gesamten Text angewendet werden soll:"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Vorschau-Video (Mit Gesang)",
|
||||
@@ -1308,6 +1324,63 @@
|
||||
"appliedAtCheckout": "Wird an der Kasse automatisch angewendet",
|
||||
"expires": "Läuft am {date} ab",
|
||||
"referredBy": "Empfohlen von {name}",
|
||||
"usingCode": "Code: {code}"
|
||||
"usingCode": "Code: {code}",
|
||||
"connectBankLoading": "Wird eingerichtet...",
|
||||
"connectDetailsNeeded": "Stripe benötigt zusätzliche Informationen, um Auszahlungen zu aktivieren. Klicke unten auf \"Bankkonto aktualisieren\", um die Einrichtung abzuschließen.",
|
||||
"connectRefresh": "Es sieht so aus, als hättest du die Einrichtung deines Bankkontos nicht abgeschlossen. Klicke unten, um es erneut zu versuchen.",
|
||||
"connectStatusActive": "Auszahlungen aktiviert",
|
||||
"connectStatusPending": "Einrichtung läuft",
|
||||
"connectStripeNote": "Du wirst zur sicheren Website von Stripe weitergeleitet, um deine Bankdaten einzugeben. Dies dauert normalerweise ein paar Minuten.",
|
||||
"flyerAccentColor": "Akzentfarbe",
|
||||
"flyerBranding": "Branding",
|
||||
"flyerColors": "Farben",
|
||||
"flyerDownloadHtml": "HTML herunterladen",
|
||||
"flyerDownloadPdf": "PDF herunterladen",
|
||||
"flyerDownloadPng": "PNG herunterladen",
|
||||
"flyerEditQr": "QR-Stil bearbeiten",
|
||||
"flyerExporting": "Wird exportiert...",
|
||||
"flyerHeadlineGradient": "Überschrift-Farbverlauf",
|
||||
"flyerHeadlineSubColor": "Unterüberschrift",
|
||||
"flyerMargins": "Seitenränder",
|
||||
"flyerPerPage": "Flyer pro Seite",
|
||||
"flyerPresetCustom": "Benutzerdefiniert",
|
||||
"flyerPresetName": "Name der Voreinstellung",
|
||||
"flyerPresetSave": "Voreinstellung speichern",
|
||||
"flyerPrintLayout": "Drucklayout",
|
||||
"flyerSections": "Abschnitte",
|
||||
"flyerSubtextColor": "Untertext",
|
||||
"flyerTextColor": "Text",
|
||||
"flyerTextOverrides": "Eigene Texte",
|
||||
"flyerToggleDivider": "Trennlinie",
|
||||
"flyerToggleFeatures": "Funktionen unten",
|
||||
"flyerToggleSteps": "Schritte 'So funktioniert's'",
|
||||
"flyerToggleSubtitle": "Untertitel",
|
||||
"flyerToggleTagline": "Slogan unten",
|
||||
"flyerUploadLogo": "Logo hochladen",
|
||||
"managePayouts": "Auszahlungen verwalten",
|
||||
"payoutTitle": "Auszahlungen & Bankkonto",
|
||||
"tabFlyer": "Druckbarer Flyer",
|
||||
"tabQrCode": "QR-Code",
|
||||
"toolsTitle": "QR-Code- & Flyer-Generator",
|
||||
"updateBankAccount": "Bankkonto aktualisieren",
|
||||
"connectFailed": "Etwas ist schiefgelaufen. Bitte versuche es erneut.",
|
||||
"flyerRemoveLogo": "Entfernen"
|
||||
},
|
||||
"crashReport": {
|
||||
"backToDashboard": "Zurück zum Dashboard",
|
||||
"copied": "Kopiert!",
|
||||
"copyDebug": "Debug-Info kopieren",
|
||||
"hideStack": "Technische Details ausblenden",
|
||||
"reportFailed": "Wir konnten den Absturzbericht nicht automatisch senden. Bitte kopiere die Details und kontaktiere den Support.",
|
||||
"reportSending": "Absturzbericht wird gesendet…",
|
||||
"reportSent": "Absturzbericht gesendet — wir wurden benachrichtigt.",
|
||||
"sendReport": "Absturzbericht erneut senden",
|
||||
"subtitle": "Die App ist auf einen unerwarteten Fehler gestoßen. Du kannst die Details kopieren oder zum Dashboard zurückkehren.",
|
||||
"title": "Etwas ist schiefgelaufen",
|
||||
"toggleStack": "Technische Details anzeigen",
|
||||
"updateAvailable": "Eine neuere Version ist verfügbar — sie könnte dieses Problem beheben.",
|
||||
"updateAvailableSubtitle": "Wir aktualisieren die Seite und laden den neuesten Code.",
|
||||
"updateNow": "Jetzt aktualisieren",
|
||||
"retry": "Erneut versuchen"
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"replaceSegmentRecommended": "Προτείνεται για προσαρμοσμένους στίχους",
|
||||
"replaceAllTitle": "Αντικατάσταση Όλων των Στίχων",
|
||||
"replaceAllDesc": "Επικόλλησε εντελώς νέους στίχους από το πρόχειρο και συγχρόνισε χειροκίνητα τον χρονισμό για όλες τις λέξεις από την αρχή.",
|
||||
"replaceAllWarning": "Όλα τα υπάρχοντα δεδομένα χρονισμού θα χαθούν"
|
||||
"replaceAllWarning": "Όλα τα υπάρχοντα δεδομένα χρονισμού θα χαθούν",
|
||||
"changeCaseDesc": "Μετάτρεψε όλους τους στίχους σε ΚΕΦΑΛΑΙΑ, πεζά, Γράμματα τίτλου ή Πεζά-κεφαλαία πρότασης. Ο χρονισμός διατηρείται πλήρως.",
|
||||
"changeCaseRecommended": "Συνιστάται για συνέπεια στο στυλ",
|
||||
"changeCaseTitle": "Αλλαγή πεζών/κεφαλαίων"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Επικόλλησε τους νέους σου στίχους παρακάτω:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"resyncExisting": "Επανασυγχρονισμός Υπαρχόντων Στίχων",
|
||||
"noLyricsToSync": "Δεν υπάρχουν στίχοι για συγχρονισμό",
|
||||
"goBackAndPaste": "Πήγαινε πίσω και επικόλλησε νέους στίχους, ή κλείσε αυτό το modal.",
|
||||
"backToSelection": "Πίσω στην Επιλογή"
|
||||
"backToSelection": "Πίσω στην Επιλογή",
|
||||
"caseLower": "πεζά",
|
||||
"caseLowerDesc": "όλα τα γράμματα πεζά",
|
||||
"caseSentence": "Πεζά-κεφαλαία πρότασης",
|
||||
"caseSentenceDesc": "Η πρώτη λέξη κάθε γραμμής με κεφαλαίο",
|
||||
"caseTitle": "Γράμματα τίτλου",
|
||||
"caseTitleDesc": "Κάθε Λέξη Με Κεφαλαίο",
|
||||
"caseUpper": "ΚΕΦΑΛΑΙΑ",
|
||||
"caseUpperDesc": "ΟΛΑ ΤΑ ΓΡΑΜΜΑΤΑ ΚΕΦΑΛΑΙΑ",
|
||||
"changeCase": "Αλλαγή πεζών/κεφαλαίων",
|
||||
"changeCaseApply": "Εφαρμογή: {case}",
|
||||
"changeCaseNote": "Ο χρονισμός των λέξεων διατηρείται πλήρως — αλλάζουν μόνο τα πεζά/κεφαλαία.",
|
||||
"changeCasePreview": "Προεπισκόπηση",
|
||||
"changeCasePrompt": "Επίλεξε ένα στυλ πεζών/κεφαλαίων για να εφαρμόσεις σε όλους τους στίχους:"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Προεπισκόπηση Βίντεο (Με Φωνητικά)",
|
||||
@@ -1308,6 +1324,63 @@
|
||||
"appliedAtCheckout": "Εφαρμόζεται αυτόματα κατά την ολοκλήρωση της αγοράς",
|
||||
"expires": "Λήγει στις {date}",
|
||||
"referredBy": "Σύσταση από {name}",
|
||||
"usingCode": "Κωδικός: {code}"
|
||||
"usingCode": "Κωδικός: {code}",
|
||||
"connectBankLoading": "Ρύθμιση...",
|
||||
"connectDetailsNeeded": "Η Stripe χρειάζεται πρόσθετες πληροφορίες για να ενεργοποιήσει τις πληρωμές. Κάνε κλικ στο \"Ενημέρωση Τραπεζικού Λογαριασμού\" παρακάτω για να ολοκληρώσεις τη ρύθμιση.",
|
||||
"connectRefresh": "Φαίνεται ότι δεν ολοκλήρωσες τη ρύθμιση του τραπεζικού σου λογαριασμού. Κάνε κλικ παρακάτω για να δοκιμάσεις ξανά.",
|
||||
"connectStatusActive": "Οι πληρωμές ενεργοποιήθηκαν",
|
||||
"connectStatusPending": "Η ρύθμιση είναι σε εξέλιξη",
|
||||
"connectStripeNote": "Θα ανακατευθυνθείς στον ασφαλή ιστότοπο της Stripe για να εισαγάγεις τα τραπεζικά σου στοιχεία. Αυτό συνήθως διαρκεί μερικά λεπτά.",
|
||||
"flyerAccentColor": "Έμφαση",
|
||||
"flyerBranding": "Επωνυμία",
|
||||
"flyerColors": "Χρώματα",
|
||||
"flyerDownloadHtml": "Λήψη HTML",
|
||||
"flyerDownloadPdf": "Λήψη PDF",
|
||||
"flyerDownloadPng": "Λήψη PNG",
|
||||
"flyerEditQr": "Επεξεργασία Στυλ QR",
|
||||
"flyerExporting": "Εξαγωγή...",
|
||||
"flyerHeadlineGradient": "Ντεγκραντέ Επικεφαλίδας",
|
||||
"flyerHeadlineSubColor": "Δευτερεύουσα Επικεφαλίδα",
|
||||
"flyerMargins": "Περιθώρια Σελίδας",
|
||||
"flyerPerPage": "Φυλλάδια Ανά Σελίδα",
|
||||
"flyerPresetCustom": "Προσαρμοσμένο",
|
||||
"flyerPresetName": "Όνομα προεπιλογής",
|
||||
"flyerPresetSave": "Αποθήκευση Προεπιλογής",
|
||||
"flyerPrintLayout": "Διάταξη Εκτύπωσης",
|
||||
"flyerSections": "Ενότητες",
|
||||
"flyerSubtextColor": "Δευτερεύον κείμενο",
|
||||
"flyerTextColor": "Κείμενο",
|
||||
"flyerTextOverrides": "Παρακάμψεις Κειμένου",
|
||||
"flyerToggleDivider": "Διαχωριστικό",
|
||||
"flyerToggleFeatures": "Χαρακτηριστικά στο κάτω μέρος",
|
||||
"flyerToggleSteps": "Βήματα «Πώς λειτουργεί»",
|
||||
"flyerToggleSubtitle": "Υπότιτλος",
|
||||
"flyerToggleTagline": "Σλόγκαν στο κάτω μέρος",
|
||||
"flyerUploadLogo": "Μεταφόρτωση Λογότυπου",
|
||||
"managePayouts": "Διαχείριση Πληρωμών",
|
||||
"payoutTitle": "Πληρωμές & Τραπεζικός Λογαριασμός",
|
||||
"tabFlyer": "Εκτυπώσιμο Φυλλάδιο",
|
||||
"tabQrCode": "Κωδικός QR",
|
||||
"toolsTitle": "Generator Κωδικού QR & Φυλλαδίου",
|
||||
"updateBankAccount": "Ενημέρωση Τραπεζικού Λογαριασμού",
|
||||
"connectFailed": "Κάτι πήγε στραβά. Παρακαλώ δοκίμασε ξανά.",
|
||||
"flyerRemoveLogo": "Αφαίρεση"
|
||||
},
|
||||
"crashReport": {
|
||||
"backToDashboard": "Επιστροφή στον πίνακα ελέγχου",
|
||||
"copied": "Αντιγράφηκε!",
|
||||
"copyDebug": "Αντιγραφή πληροφοριών εντοπισμού σφαλμάτων",
|
||||
"hideStack": "Απόκρυψη τεχνικών λεπτομερειών",
|
||||
"reportFailed": "Δεν μπορέσαμε να στείλουμε την αναφορά σφάλματος αυτόματα. Παρακαλούμε, αντέγραψε τις λεπτομέρειες και στείλε μήνυμα στην υποστήριξη.",
|
||||
"reportSending": "Αποστολή αναφοράς σφάλματος…",
|
||||
"reportSent": "Η αναφορά σφάλματος στάλθηκε — έχουμε ειδοποιηθεί.",
|
||||
"sendReport": "Αποστολή αναφοράς σφάλματος ξανά",
|
||||
"subtitle": "Η εφαρμογή αντιμετώπισε ένα απροσδόκητο σφάλμα. Μπορείς να αντιγράψεις τις λεπτομέρειες ή να επιστρέψεις στον πίνακα ελέγχου.",
|
||||
"title": "Κάτι πήγε στραβά",
|
||||
"toggleStack": "Εμφάνιση τεχνικών λεπτομερειών",
|
||||
"updateAvailable": "Μια νεότερη έκδοση είναι διαθέσιμη — μπορεί να διορθώσει αυτό το πρόβλημα.",
|
||||
"updateAvailableSubtitle": "Θα ανανεώσουμε τη σελίδα και θα φορτώσουμε τον πιο πρόσφατο κώδικα.",
|
||||
"updateNow": "Ενημέρωση τώρα",
|
||||
"retry": "Δοκίμασε ξανά"
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"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"
|
||||
"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"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Paste your new lyrics below:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"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"
|
||||
"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}"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Preview Video (With Vocals)",
|
||||
@@ -1266,9 +1282,19 @@
|
||||
"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.",
|
||||
"connectComplete": "Bank account connected!",
|
||||
"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",
|
||||
"payoutThreshold": "Payouts are automatically sent when your balance reaches $20.",
|
||||
"interstitialTitle": "You've been referred!",
|
||||
"interstitialReferred": "Referred by {name}",
|
||||
@@ -1308,6 +1334,53 @@
|
||||
"flyerThemeLight": "Light",
|
||||
"flyerThemeDark": "Dark",
|
||||
"flyerGenerate": "Generate Flyer",
|
||||
"flyerGenerating": "Generating..."
|
||||
"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..."
|
||||
},
|
||||
"crashReport": {
|
||||
"title": "Something went wrong",
|
||||
"subtitle": "The app hit an unexpected error. You can copy the details or go back to the dashboard.",
|
||||
"reportSent": "Crash report sent — we've been alerted.",
|
||||
"reportSending": "Sending crash report…",
|
||||
"reportFailed": "We couldn't send the crash report automatically. Please copy the details and message support.",
|
||||
"copyDebug": "Copy debug info",
|
||||
"copied": "Copied!",
|
||||
"sendReport": "Send crash report again",
|
||||
"retry": "Try again",
|
||||
"backToDashboard": "Back to dashboard",
|
||||
"toggleStack": "Show technical details",
|
||||
"hideStack": "Hide technical details",
|
||||
"updateAvailable": "A newer version is available — it may fix this issue.",
|
||||
"updateAvailableSubtitle": "We'll refresh the page and load the latest code.",
|
||||
"updateNow": "Update now"
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"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"
|
||||
"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"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Pega tus nuevas letras a continuación:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"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"
|
||||
"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:"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Video de vista previa (Con voces)",
|
||||
@@ -1308,6 +1324,63 @@
|
||||
"appliedAtCheckout": "Aplicado automáticamente al finalizar la compra",
|
||||
"expires": "Expira {date}",
|
||||
"referredBy": "Referido por {name}",
|
||||
"usingCode": "Código: {code}"
|
||||
"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"
|
||||
},
|
||||
"crashReport": {
|
||||
"backToDashboard": "Volver al panel",
|
||||
"copied": "¡Copiado!",
|
||||
"copyDebug": "Copiar información de depuración",
|
||||
"hideStack": "Ocultar detalles técnicos",
|
||||
"reportFailed": "No pudimos enviar el informe de error automáticamente. Por favor, copia los detalles y envía un mensaje a soporte.",
|
||||
"reportSending": "Enviando informe de error…",
|
||||
"reportSent": "Informe de error enviado — hemos recibido la alerta.",
|
||||
"sendReport": "Enviar informe de error de nuevo",
|
||||
"subtitle": "La aplicación encontró un error inesperado. Puedes copiar los detalles o volver al panel.",
|
||||
"title": "Algo salió mal",
|
||||
"toggleStack": "Mostrar detalles técnicos",
|
||||
"updateAvailable": "Hay una nueva versión disponible — podría solucionar este problema.",
|
||||
"updateAvailableSubtitle": "Actualizaremos la página y cargaremos el código más reciente.",
|
||||
"updateNow": "Actualizar ahora",
|
||||
"retry": "Intentar de nuevo"
|
||||
}
|
||||
}
|
||||
@@ -991,7 +991,10 @@
|
||||
"replaceSegmentRecommended": "Suositellaan mukautetuille sanoituksille",
|
||||
"replaceAllTitle": "Korvaa kaikki sanoitukset",
|
||||
"replaceAllDesc": "Liitä täysin uudet sanoitukset leikepöydältä ja synkronoi ajoitus manuaalisesti kaikille sanoille alusta alkaen.",
|
||||
"replaceAllWarning": "Kaikki olemassa olevat ajoitustiedot menetetään"
|
||||
"replaceAllWarning": "Kaikki olemassa olevat ajoitustiedot menetetään",
|
||||
"changeCaseDesc": "Muunna kaikki sanoitukset muotoon ISOT KIRJAIMET, pienet kirjaimet, Otsikkotyyli tai Virkkeen alkukirjain. Ajoitus säilyy täysin.",
|
||||
"changeCaseRecommended": "Suositellaan tyylin yhtenäisyyden vuoksi",
|
||||
"changeCaseTitle": "Vaihda kirjainkokoa"
|
||||
},
|
||||
"replaceAllLyrics": {
|
||||
"pastePrompt": "Liitä uudet sanoituksesi alle:",
|
||||
@@ -1009,7 +1012,20 @@
|
||||
"resyncExisting": "Synkronoi olemassa olevat sanoitukset uudelleen",
|
||||
"noLyricsToSync": "Ei synkronoitavia sanoituksia",
|
||||
"goBackAndPaste": "Mene takaisin ja liitä uudet sanoitukset, tai sulje tämä modaali.",
|
||||
"backToSelection": "Takaisin valintaan"
|
||||
"backToSelection": "Takaisin valintaan",
|
||||
"caseLower": "pienet kirjaimet",
|
||||
"caseLowerDesc": "kaikki kirjaimet pieniä",
|
||||
"caseSentence": "Virkkeen alkukirjain",
|
||||
"caseSentenceDesc": "Jokaisen rivin ensimmäinen sana isolla",
|
||||
"caseTitle": "Otsikkotyyli",
|
||||
"caseTitleDesc": "Jokainen Sana Isolla",
|
||||
"caseUpper": "ISOT KIRJAIMET",
|
||||
"caseUpperDesc": "KAIKKI KIRJAIMET ISOLLA",
|
||||
"changeCase": "Vaihda kirjainkokoa",
|
||||
"changeCaseApply": "Ota käyttöön {case}",
|
||||
"changeCaseNote": "Sanojen ajoitus säilyy täysin — vain kirjainkoko muuttuu.",
|
||||
"changeCasePreview": "Esikatselu",
|
||||
"changeCasePrompt": "Valitse kirjainkoko, jota käytetään kaikkiin sanoituksiin:"
|
||||
},
|
||||
"reviewChanges": {
|
||||
"previewWithVocals": "Esikatseluvideo (laulun kanssa)",
|
||||
@@ -1308,6 +1324,63 @@
|
||||
"appliedAtCheckout": "Lisätään automaattisesti kassalla",
|
||||
"expires": "Vanhenee {date}",
|
||||
"referredBy": "Suosittelija: {name}",
|
||||
"usingCode": "Koodi: {code}"
|
||||
"usingCode": "Koodi: {code}",
|
||||
"connectBankLoading": "Määritetään...",
|
||||
"connectDetailsNeeded": "Stripe tarvitsee lisätietoja tilitysten aktivoimiseksi. Klikkaa alta \"Päivitä pankkitili\" viimeistelläksesi asetukset.",
|
||||
"connectRefresh": "Näyttää siltä, että pankkitilisi asetukset jäivät kesken. Klikkaa alta yrittääksesi uudelleen.",
|
||||
"connectStatusActive": "Tilitykset käytössä",
|
||||
"connectStatusPending": "Asetukset kesken",
|
||||
"connectStripeNote": "Sinut ohjataan Stripen turvalliselle sivustolle syöttämään pankkitietosi. Tämä kestää yleensä pari minuuttia.",
|
||||
"flyerAccentColor": "Korostusväri",
|
||||
"flyerBranding": "Brändäys",
|
||||
"flyerColors": "Värit",
|
||||
"flyerDownloadHtml": "Lataa HTML",
|
||||
"flyerDownloadPdf": "Lataa PDF",
|
||||
"flyerDownloadPng": "Lataa PNG",
|
||||
"flyerEditQr": "Muokkaa QR-tyyliä",
|
||||
"flyerExporting": "Viedään...",
|
||||
"flyerHeadlineGradient": "Otsikon liukuväri",
|
||||
"flyerHeadlineSubColor": "Alaotsikon väri",
|
||||
"flyerMargins": "Sivun marginaalit",
|
||||
"flyerPerPage": "Esitteitä sivulla",
|
||||
"flyerPresetCustom": "Mukautettu",
|
||||
"flyerPresetName": "Esiasetuksen nimi",
|
||||
"flyerPresetSave": "Tallenna esiasetus",
|
||||
"flyerPrintLayout": "Tulostusasettelu",
|
||||
"flyerSections": "Osiot",
|
||||
"flyerSubtextColor": "Alatekstin väri",
|
||||
"flyerTextColor": "Tekstin väri",
|
||||
"flyerTextOverrides": "Mukautetut tekstit",
|
||||
"flyerToggleDivider": "Erotin",
|
||||
"flyerToggleFeatures": "Alaosan ominaisuudet",
|
||||
"flyerToggleSteps": "Näin se toimii -vaiheet",
|
||||
"flyerToggleSubtitle": "Alaotsikko",
|
||||
"flyerToggleTagline": "Alaosan iskulause",
|
||||
"flyerUploadLogo": "Lataa logo",
|
||||
"managePayouts": "Hallinnoi tilityksiä",
|
||||
"payoutTitle": "Tilitykset ja pankkitili",
|
||||
"tabFlyer": "Tulostettava esite",
|
||||
"tabQrCode": "QR-koodi",
|
||||
"toolsTitle": "QR-koodi- ja esite-Generator",
|
||||
"updateBankAccount": "Päivitä pankkitili",
|
||||
"connectFailed": "Jotain meni pieleen. Yritä uudelleen.",
|
||||
"flyerRemoveLogo": "Poista"
|
||||
},
|
||||
"crashReport": {
|
||||
"backToDashboard": "Takaisin hallintapaneeliin",
|
||||
"copied": "Kopioitu!",
|
||||
"copyDebug": "Kopioi vianmääritystiedot",
|
||||
"hideStack": "Piilota tekniset tiedot",
|
||||
"reportFailed": "Emme voineet lähettää virheraporttia automaattisesti. Kopioi tiedot ja laita viestiä tukeen.",
|
||||
"reportSending": "Lähetetään virheraporttia…",
|
||||
"reportSent": "Virheraportti lähetetty — olemme saaneet ilmoituksen.",
|
||||
"sendReport": "Lähetä virheraportti uudelleen",
|
||||
"subtitle": "Sovelluksessa tapahtui odottamaton virhe. Voit kopioida tiedot tai palata hallintapaneeliin.",
|
||||
"title": "Jotain meni pieleen",
|
||||
"toggleStack": "Näytä tekniset tiedot",
|
||||
"updateAvailable": "Uudempi versio on saatavilla — se saattaa korjata tämän ongelman.",
|
||||
"updateAvailableSubtitle": "Päivitämme sivun ja lataamme uusimman koodin.",
|
||||
"updateNow": "Päivitä nyt",
|
||||
"retry": "Yritä uudelleen"
|
||||
}
|
||||
}
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user