Compare commits

...
8 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 686402d643 fix(i18n): admin link 404 when accessed from locale-prefixed pages (#676)
## Summary
- `AuthStatus.tsx` imported `Link` from `@/i18n/routing` which
auto-prefixes hrefs with the current locale (e.g. `/en/admin`)
- Since `/admin` lives outside the `[locale]` route group, `/en/admin`
has no matching static page → 404
- Changed to `NextLink` from `next/link` which preserves the href as-is,
correctly navigating to `/admin`

## Test plan
- [x] `make test` passes (710 tests)
- [x] `next build` succeeds
- [ ] Verify clicking "Admin Dashboard" from `/en/app` navigates to
`/admin` (not `/en/admin`)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 15:53:34 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 bb86722008 fix(referral): dedicated interstitial page instead of banner overlay (#675)
## Summary

Replace the banner overlay (which looked terrible floating over the
landing page) with a proper full-screen interstitial page.

## Flow

1. `nomadkaraoke.com/r/bevvy` → Worker redirects to
`gen.nomadkaraoke.com/en/r?code=bevvy`
2. Static `/en/r` page loads, reads `?code=` param, fetches referral
data from API
3. Full-screen interstitial: gift icon, referrer name, custom message,
discount details, "Get Started" CTA
4. User clicks "Get Started" → landing page (referral code already
stored in cookie)

## Changes

- New: `frontend/app/[locale]/r/page.tsx` + `client.tsx` — dedicated
interstitial page
- Reverted: `frontend/components/ReferralCapture.tsx` — back to silent
cookie-setter (no banner)
- Cleaned: `frontend/public/_redirects` — removed broken `:splat` rules

Also pushed: `public-website/worker.js` updated to redirect to
`/en/r?code=` instead of `/en/?ref=`

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 22:44:22 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 74eac6f5ee feat(referral): show interstitial banner on landing page for referral links (#674)
## Summary

When a user arrives via a referral link (`nomadkaraoke.com/r/CODE` →
`gen.nomadkaraoke.com/en/?ref=CODE`), the landing page now shows a
dismissible banner with the referrer's name, custom message, and
discount details.

## Changes

- `frontend/components/ReferralCapture.tsx` — Enhanced from silent
cookie-setter to interstitial banner. Fetches referral data from API,
shows referrer name/message/discount in a fixed top banner with slide-in
animation. Dismissible via X button.

## How it works

1. User clicks `nomadkaraoke.com/r/bevvy`
2. Cloudflare Worker redirects to `gen.nomadkaraoke.com/en/?ref=bevvy`
3. `ReferralCapture` component detects `?ref=bevvy`, stores cookie,
fetches interstitial data
4. Banner slides in showing "You've been referred! Referred by [name].
[message]. Enjoy 10% off..."
5. User dismisses or scrolls to sign up — referral code is already
stored for checkout

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 21:42:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d142156138 fix: use correct :splat syntax for referral redirect (#673)
## Summary

The referral redirect `/r/:code → /en/?ref=:code` was passing the
literal string `:code` instead of the actual referral code. Cloudflare
Pages uses `*` + `:splat` syntax, not named parameters.

## Fix

`/r/:code /en/?ref=:code 302` → `/r/* /en/?ref=:splat 302`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 19:03:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0353f5890d fix: use redirect for /r/CODE referral links instead of dynamic route (#672)
## Summary

The previous approach (catch-all `[[...code]]` route) doesn't work with
Next.js static export on Cloudflare Pages — dynamic paths 404 because no
HTML file exists for them.

## Fix

Replace the dynamic route with a simple Cloudflare Pages `_redirects`
rule:
- `/r/CODE` → `/en/?ref=CODE` (302 redirect)
- The `ReferralCapture` component on the landing page already captures
`?ref=CODE` and stores it in a cookie

This means referral links redirect to the landing page with the code as
a query param, which is simpler and fully compatible with static export.

## Tradeoff

The custom interstitial page (with referrer name/message) is removed for
now. The referral still works — the code gets stored and applied at
checkout. The interstitial can be added back later as a component on the
landing page that detects `?ref=` and shows the referral info.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:57:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c97a340389 fix: add Cloudflare Pages rewrites for referral /r/CODE routes (#671)
## Summary

Referral interstitial pages at `/r/CODE` return 404 because Cloudflare
Pages doesn't know to serve the catch-all page for dynamic paths.

## Changes

Add `_redirects` rules:
- `/r/*` → `/en/r/:splat` (302) — bare paths get locale prefix
- `/{locale}/r/*` → `/{locale}/r/index.html` (200 rewrite) — all 33
locales get SPA-style fallback

## Testing
- Fixes `gen.nomadkaraoke.com/r/bevvy` (currently 404)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:42:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1154adc150 feat(admin): add referral links management page (#670)
## Summary

- Add Referrals page to admin dashboard for managing referral links
- Stats overview: total links, clicks, signups, earnings
- Links table with enable/disable toggle and copy-to-clipboard
- Create Vanity Link dialog with custom discount/kickback rates

## Changes

- `frontend/app/admin/referrals/page.tsx` — New admin referrals page
- `frontend/components/admin/admin-sidebar.tsx` — Added Referrals nav
item
- `frontend/app/admin/layout.tsx` — Added breadcrumb support
- `frontend/lib/api.ts` — Added 3 admin referral API methods

## Testing
- [x] Frontend build passes
- [x] 710 frontend unit tests pass
- [x] No backend changes

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:26:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 80cb53f3a2 feat: referral link system with discounts and Stripe Connect payouts (#669)
## Summary

- Add a referral system where any user gets a shareable link (`/r/CODE`)
with a personalized interstitial page
- Referred users get a configurable discount (default 10%) on credit
purchases for 30 days
- Referrers earn a cash kickback (default 20% of revenue) paid out via
Stripe Connect at $20 threshold
- Admin can create vanity links with custom rates and manage all
referral links

## Changes

### Backend
- **New models** (`backend/models/referral.py`): ReferralLink,
ReferralEarning, ReferralPayout + API request/response models
- **New service** (`backend/services/referral_service.py`): Link CRUD,
attribution, discount detection, earnings recording, Stripe Connect
onboarding, auto-payout
- **New routes** (`backend/api/routes/referrals.py`): 7 endpoints —
public interstitial, user dashboard, link updates, Connect onboarding,
admin vanity/list/update
- **Stripe integration**: Coupon creation/lookup, Connect Express
accounts, transfers
- **Webhook hook**: Referral earnings recorded on credit purchases
- **Auth hook**: Referral attribution on first magic link verification
via `x-referral-code` header
- **User model**: Added referral fields (referral_code,
referred_by_code, referred_at, discount_expires_at,
stripe_connect_account_id)

### Frontend
- **Interstitial page** (`/r/CODE`): Shows referrer's name, custom
message, discount details
- **Referral dashboard** (`/app/referrals`): Link sharing, stats,
earnings, payout history, Stripe Connect CTA
- **Discount badge**: Shown in Buy Credits dialog during active referral
window
- **Referral capture**: Cookie + localStorage via `/r/CODE` route and
`?ref=CODE` query param
- **Auth integration**: Passes referral code on magic link verification,
clears after use
- **i18n**: 33 new translation keys in `referrals` namespace

### Documentation
- Design spec: `docs/archive/2026-04-04-referral-system-design.md`
- Implementation plan: `docs/archive/2026-04-04-referral-system-plan.md`
- Updated `docs/README.md` status table and `docs/API.md` with referral
endpoints

## Testing
- 68 referral-specific tests (models, service, routes) — all passing
- 2935 total backend tests — zero regressions
- 710 frontend tests — all passing
- Covers: link management, attribution, self-referral blocking, discount
detection, earnings calculation, payout threshold, edge cases (rounding,
zero amounts), all API endpoints

## Review
- [x] CodeRabbit CLI review completed locally (11 findings, 7 fixed)
- [x] Test review completed (P0/P1 gaps identified and filled)
- [x] Docs reviewed and updated

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 17:39:18 -04:00
32 changed files with 6650 additions and 10 deletions

No files matched your search

+188
View File
@@ -0,0 +1,188 @@
"""
Referral API routes.
Handles:
- Public referral interstitial (click tracking)
- Authenticated referral dashboard
- Stripe Connect onboarding
- Admin vanity link creation and link management
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from backend.api.dependencies import require_auth, require_admin
from backend.models.referral import (
CreateReferralLinkRequest,
UpdateReferralLinkRequest,
ReferralInterstitialResponse,
)
from backend.services.referral_service import get_referral_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/referrals", tags=["referrals"])
# ============================================================================
# Public endpoints
# ============================================================================
@router.get("/r/{code}", response_model=ReferralInterstitialResponse)
async def get_referral_interstitial(code: str):
"""
Public endpoint: get interstitial data for a referral link.
Increments click count. Returns valid=False if code not found.
"""
service = get_referral_service()
link = service.get_link_by_code(code)
if not link:
return ReferralInterstitialResponse(valid=False)
# Track the click
try:
service.increment_clicks(code)
except Exception:
logger.warning("Failed to increment clicks for code %s", code, exc_info=True)
return ReferralInterstitialResponse(
valid=True,
referral_code=link.code,
referrer_display_name=link.display_name,
discount_percent=link.discount_percent,
discount_duration_days=link.discount_duration_days,
custom_message=link.custom_message,
)
# ============================================================================
# Authenticated user endpoints
# ============================================================================
@router.get("/me")
async def get_my_dashboard(auth=Depends(require_auth)):
"""Get referral dashboard data for the authenticated user."""
service = get_referral_service()
return service.get_dashboard_data(auth.user_email)
@router.put("/me")
async def update_my_link(
updates: UpdateReferralLinkRequest,
auth=Depends(require_auth),
):
"""Update display_name and custom_message on the user's own referral link."""
service = get_referral_service()
link = service.get_or_create_link(auth.user_email)
update_fields = {}
if updates.display_name is not None:
update_fields["display_name"] = updates.display_name
if updates.custom_message is not None:
update_fields["custom_message"] = updates.custom_message
if not update_fields:
return {"ok": True, "message": "No changes"}
success, message = service.update_link(link.code, **update_fields)
if not success:
raise HTTPException(status_code=400, detail=message)
return {"ok": True, "message": message}
@router.post("/me/connect")
async def start_stripe_connect(auth=Depends(require_auth)):
"""Start Stripe Connect onboarding for the authenticated user."""
# Check if user already has a Connect account
from backend.services.user_service import get_user_service
user_service = get_user_service()
user = user_service.get_user(auth.user_email)
if user and user.stripe_connect_account_id:
raise HTTPException(status_code=400, detail="Stripe Connect account already configured")
service = get_referral_service()
account_id, onboarding_url = service.create_connect_account(auth.user_email)
if not account_id:
raise HTTPException(status_code=500, detail="Failed to create Stripe Connect account")
user_service.update_user(auth.user_email, stripe_connect_account_id=account_id)
return {"account_id": account_id, "onboarding_url": onboarding_url}
# ============================================================================
# Admin endpoints
# ============================================================================
@router.post("/admin/vanity")
async def create_vanity_link(
request: CreateReferralLinkRequest,
auth=Depends(require_admin),
):
"""Admin: create a vanity referral link."""
if not request.vanity_code:
raise HTTPException(status_code=400, detail="vanity_code is required")
service = get_referral_service()
success, link, message = service.create_vanity_link(
code=request.vanity_code,
owner_email=request.owner_email,
display_name=request.display_name,
custom_message=request.custom_message,
discount_percent=request.discount_percent,
kickback_percent=request.kickback_percent,
discount_duration_days=request.discount_duration_days,
earning_duration_days=request.earning_duration_days,
)
if not success:
raise HTTPException(status_code=400, detail=message)
return {"ok": True, "code": link.code, "message": message}
@router.get("/admin/links")
async def list_links(
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
auth=Depends(require_admin),
):
"""Admin: list all referral links."""
service = get_referral_service()
links = service.list_links(limit=limit, offset=offset)
return {
"links": [link.model_dump(mode="json") for link in links],
"count": len(links),
}
@router.put("/admin/links/{code}")
async def update_link(
code: str,
updates: UpdateReferralLinkRequest,
auth=Depends(require_admin),
):
"""Admin: update any referral link's settings."""
service = get_referral_service()
update_fields = {
k: v for k, v in updates.model_dump().items() if v is not None
}
if not update_fields:
return {"ok": True, "message": "No changes"}
success, message = service.update_link(code, **update_fields)
if not success:
raise HTTPException(status_code=404, detail=message)
return {"ok": True, "message": message}
+49
View File
@@ -365,6 +365,24 @@ async def verify_magic_link(
elif credit_status == "denied":
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
# Referral attribution (first login only, if referral code provided)
referral_code = http_request.headers.get("x-referral-code")
if referral_code and is_first_login:
try:
from backend.services.referral_service import get_referral_service
referral_svc = get_referral_service()
attr_success, attr_msg = referral_svc.attribute_referral(
referred_email=user.email,
referral_code=referral_code,
)
if attr_success:
attr_data = referral_svc.get_attribution_data(referral_code)
if attr_data:
user_service.update_user(user.email, **attr_data)
logger.info(f"Referral attributed for {_mask_email(user.email)} via code '{referral_code}'")
except Exception as ref_err:
logger.warning(f"Referral attribution failed for {_mask_email(user.email)}: {ref_err}")
# Persist user's locale preference (from Accept-Language header)
if locale and locale != (user.locale or "en"):
try:
@@ -546,9 +564,21 @@ async def create_checkout(
if not stripe_service.is_configured():
raise HTTPException(status_code=503, detail="Payment processing is not available")
# Check for referral discount
referral_coupon_id = None
try:
from backend.services.referral_service import get_referral_service
referral_svc = get_referral_service()
discount_info = referral_svc.get_discount_for_checkout(request.email)
if discount_info:
referral_coupon_id = discount_info["coupon_id"]
except Exception as ref_err:
logger.warning(f"Referral discount lookup failed: {ref_err}")
success, checkout_url, message = stripe_service.create_checkout_session(
package_id=request.package_id,
user_email=request.email,
coupon_id=referral_coupon_id,
)
if not success or not checkout_url:
@@ -1017,6 +1047,25 @@ async def stripe_webhook(
# Send confirmation email
email_service.send_credits_added(user_email, credits, new_balance)
logger.info(f"Added {credits} credits to {user_email}, new balance: {new_balance}")
# Record referral earning if applicable
try:
from backend.services.referral_service import get_referral_service
referral_svc = get_referral_service()
amount_charged = session.get("amount_total", 0)
if amount_charged > 0:
earning_result = referral_svc.record_earning(
referred_email=user_email,
stripe_session_id=session_id,
purchase_amount_cents=amount_charged,
)
if earning_result:
logger.info(
f"Referral earning: ${earning_result['earning_amount_cents'] / 100:.2f} "
f"for {earning_result['referrer_email']}"
)
except Exception as ref_err:
logger.warning(f"Referral earning recording failed: {ref_err}")
else:
logger.error(f"Failed to add credits: {credit_msg}")
+2
View File
@@ -159,6 +159,8 @@ app.include_router(auth.router, prefix="/api") # OAuth credential management
app.include_router(audio_search.router, prefix="/api") # Audio search (artist+title mode)
app.include_router(themes.router, prefix="/api") # Theme selection for styles
app.include_router(users.router, prefix="/api") # User auth, credits, and Stripe webhooks
from backend.api.routes import referrals
app.include_router(referrals.router, prefix="/api") # Referral links and payouts
app.include_router(admin.router, prefix="/api") # Admin dashboard and management
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
app.include_router(push.router, prefix="/api") # Push notification subscription management
+178
View File
@@ -0,0 +1,178 @@
"""
Referral system models.
Supports:
- Referral link creation and management
- Earnings tracking from referred purchases
- Payout processing via Stripe Connect
- API request/response shapes for referral endpoints
"""
from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, Field
# ============================================================================
# Firestore Document Models
# ============================================================================
class ReferralLinkStats(BaseModel):
"""Aggregated statistics for a referral link."""
clicks: int = 0
signups: int = 0
purchases: int = 0
total_earned_cents: int = 0
class ReferralLink(BaseModel):
"""
Referral link stored in Firestore.
Each user can have one referral link. Vanity links use a custom code
(e.g., "karaoke-king") while standard links use a generated code.
"""
code: str # Unique referral code (URL slug)
owner_email: str # Email of the referrer
display_name: Optional[str] = None # Public name shown on interstitial
custom_message: Optional[str] = None # Optional message on interstitial
# Reward configuration
discount_percent: int = 10 # Discount for referred user
kickback_percent: int = 20 # Earnings for referrer
discount_duration_days: int = 30 # How long the discount lasts
earning_duration_days: int = 365 # How long referrer earns from this link
# Stripe
stripe_coupon_id: Optional[str] = None # Stripe coupon for this link
# Flags
is_vanity: bool = False # Custom vanity code vs generated
enabled: bool = True # Can be disabled without deleting
# Timestamps
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
# Aggregated stats
stats: ReferralLinkStats = Field(default_factory=ReferralLinkStats)
class ReferralEarning(BaseModel):
"""
Record of a single earning from a referred purchase.
Created when a referred user completes a Stripe checkout.
"""
id: str
referrer_email: str
referred_email: str
referral_code: str
stripe_session_id: str
purchase_amount_cents: int
earning_amount_cents: int
status: str = "pending" # pending, paid, cancelled
created_at: datetime = Field(default_factory=datetime.utcnow)
paid_at: Optional[datetime] = None
payout_id: Optional[str] = None
class ReferralPayout(BaseModel):
"""
Record of a payout to a referrer via Stripe Connect.
Groups multiple earnings into a single transfer.
"""
id: str
referrer_email: str
stripe_transfer_id: str
amount_cents: int
earnings_included: List[str] # List of ReferralEarning IDs
status: str = "processing" # processing, completed, failed
created_at: datetime = Field(default_factory=datetime.utcnow)
# ============================================================================
# API Request Models
# ============================================================================
class CreateReferralLinkRequest(BaseModel):
"""Admin request to create a vanity referral link."""
vanity_code: Optional[str] = None
owner_email: str
display_name: Optional[str] = None
custom_message: Optional[str] = None
discount_percent: int = 10
kickback_percent: int = 20
discount_duration_days: int = 30
earning_duration_days: int = 365
class UpdateReferralLinkRequest(BaseModel):
"""Request to update a referral link (user: name/message only, admin: all fields)."""
display_name: Optional[str] = None
custom_message: Optional[str] = None
discount_percent: Optional[int] = None
kickback_percent: Optional[int] = None
discount_duration_days: Optional[int] = None
earning_duration_days: Optional[int] = None
enabled: Optional[bool] = None
# ============================================================================
# API Response Models
# ============================================================================
class ReferralLinkResponse(BaseModel):
"""Public referral link information."""
code: str
owner_email: str
display_name: Optional[str] = None
custom_message: Optional[str] = None
discount_percent: int
kickback_percent: int
is_vanity: bool
enabled: bool
stats: ReferralLinkStats
created_at: datetime
class ReferralEarningResponse(BaseModel):
"""Public earning information (for referrer dashboard)."""
id: str
referred_email: str
referral_code: str
purchase_amount_cents: int
earning_amount_cents: int
status: str
created_at: datetime
paid_at: Optional[datetime] = None
class ReferralPayoutResponse(BaseModel):
"""Public payout information (for referrer dashboard)."""
id: str
amount_cents: int
earnings_count: int
status: str
created_at: datetime
class ReferralDashboardResponse(BaseModel):
"""Full referral dashboard data for the referrer."""
referral_link: ReferralLinkResponse
recent_earnings: List[ReferralEarningResponse]
recent_payouts: List[ReferralPayoutResponse]
total_earned_cents: int
total_paid_cents: int
pending_balance_cents: int
stripe_connect_onboarded: bool
class ReferralInterstitialResponse(BaseModel):
"""Data for the referral landing/interstitial page."""
valid: bool = True
referral_code: str = ""
referrer_display_name: Optional[str] = None
discount_percent: int = 0
discount_duration_days: int = 0
custom_message: Optional[str] = None
+9
View File
@@ -108,6 +108,13 @@ class User(BaseModel):
# Flag to prevent duplicate welcome credit grants (idempotency)
welcome_credits_granted: bool = False
# Referral system
referral_code: Optional[str] = None # User's own referral code
referred_by_code: Optional[str] = None # Code used when this user signed up
referred_at: Optional[datetime] = None # When the referral was applied
referral_discount_expires_at: Optional[datetime] = None # When referral discount ends
stripe_connect_account_id: Optional[str] = None # For receiving referral payouts
class MagicLinkToken(BaseModel):
"""
@@ -202,6 +209,8 @@ class UserPublic(BaseModel):
tenant_id: Optional[str] = None
feedback_eligible: bool = False
total_spent: int = 0
referral_code: Optional[str] = None
has_active_referral_discount: bool = False
created_at: Optional[str] = None
last_login_at: Optional[str] = None
+497
View File
@@ -0,0 +1,497 @@
"""
Referral service for link management, earnings tracking, and payouts.
Handles:
- Referral link creation (generated and vanity codes)
- Link lookup and validation
- Click tracking
- Admin listing
"""
import logging
import re
import secrets
import string
from datetime import datetime, timedelta
from typing import List, Optional, Tuple
from google.cloud import firestore
from backend.models.referral import (
ReferralLink,
ReferralLinkStats,
ReferralEarning,
ReferralPayout,
)
logger = logging.getLogger(__name__)
# ============================================================================
# Constants
# ============================================================================
REFERRAL_LINKS_COLLECTION = "referral_links"
REFERRAL_EARNINGS_COLLECTION = "referral_earnings"
REFERRAL_PAYOUTS_COLLECTION = "referral_payouts"
RESERVED_CODES = frozenset({
"admin", "app", "api", "r", "pricing", "order", "payment",
"login", "auth", "webhook", "webhooks", "internal", "health",
"static", "assets", "public", "private",
})
PAYOUT_THRESHOLD_CENTS = 2000
VANITY_CODE_PATTERN = re.compile(r"^[a-z0-9][a-z0-9\-]{1,28}[a-z0-9]$")
# Characters for generated codes
_CODE_ALPHABET = string.ascii_lowercase + string.digits
# ============================================================================
# Service
# ============================================================================
class ReferralService:
"""Service for referral link management and earnings."""
def __init__(self, db=None, stripe_service=None):
if db is None:
db = firestore.Client()
self.db = db
self.stripe_service = stripe_service
# ========================================================================
# Code Generation & Validation
# ========================================================================
def _generate_code(self) -> str:
"""Generate an 8-character lowercase alphanumeric referral code."""
return "".join(secrets.choice(_CODE_ALPHABET) for _ in range(8))
def _validate_vanity_code(self, code: str) -> Tuple[bool, str]:
"""Validate a vanity code against reserved words and pattern rules.
Returns (is_valid, message).
"""
if code.lower() in RESERVED_CODES:
return False, f"'{code}' is a reserved code"
if not VANITY_CODE_PATTERN.match(code.lower()):
return False, (
"Code must be 3-30 characters, start/end with alphanumeric, "
"and contain only lowercase letters, digits, and hyphens"
)
return True, "Valid"
# ========================================================================
# Link CRUD
# ========================================================================
def get_link_by_code(self, code: str) -> Optional[ReferralLink]:
"""Get a referral link by its code. Returns None if not found or disabled."""
doc = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code).get()
if not doc.exists:
return None
data = doc.to_dict()
if not data.get("enabled", True):
return None
return ReferralLink(**data)
def get_or_create_link(self, owner_email: str) -> ReferralLink:
"""Get existing referral link for owner, or create a new one.
Retries up to 10 times if generated code collides with existing doc.
"""
# Check for existing link
existing = (
self.db.collection(REFERRAL_LINKS_COLLECTION)
.where("owner_email", "==", owner_email)
.limit(1)
.stream()
)
for doc in existing:
return ReferralLink(**doc.to_dict())
# Create new link with retry for code collision
for attempt in range(10):
code = self._generate_code()
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
doc_snapshot = doc_ref.get()
if doc_snapshot.exists:
logger.warning("Code collision on attempt %d: %s", attempt + 1, code)
continue
now = datetime.utcnow()
link = ReferralLink(
code=code,
owner_email=owner_email,
created_at=now,
updated_at=now,
)
doc_ref.set(link.model_dump())
return link
raise RuntimeError("Failed to generate unique referral code after 10 attempts")
def create_vanity_link(
self,
code: str,
owner_email: str,
display_name: Optional[str] = None,
custom_message: Optional[str] = None,
discount_percent: int = 10,
kickback_percent: int = 20,
discount_duration_days: int = 30,
earning_duration_days: int = 365,
) -> Tuple[bool, Optional[ReferralLink], str]:
"""Create a vanity referral link.
Returns (success, link_or_none, message).
"""
valid, msg = self._validate_vanity_code(code)
if not valid:
return False, None, msg
normalized = code.lower()
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(normalized)
doc_snapshot = doc_ref.get()
if doc_snapshot.exists:
return False, None, f"Code '{normalized}' is already taken"
now = datetime.utcnow()
link = ReferralLink(
code=normalized,
owner_email=owner_email,
display_name=display_name,
custom_message=custom_message,
discount_percent=discount_percent,
kickback_percent=kickback_percent,
discount_duration_days=discount_duration_days,
earning_duration_days=earning_duration_days,
is_vanity=True,
created_at=now,
updated_at=now,
)
doc_ref.set(link.model_dump())
return True, link, "Vanity link created"
def update_link(self, code: str, **updates) -> Tuple[bool, str]:
"""Update fields on an existing referral link.
Returns (success, message).
"""
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
doc_snapshot = doc_ref.get()
if not doc_snapshot.exists:
return False, f"Link '{code}' not found"
updates["updated_at"] = datetime.utcnow()
doc_ref.update(updates)
return True, "Link updated"
def increment_clicks(self, code: str) -> None:
"""Increment the click counter for a referral link."""
doc_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(code)
doc_ref.update({"stats.clicks": firestore.Increment(1)})
# ========================================================================
# Attribution
# ========================================================================
def attribute_referral(self, referred_email: str, referral_code: str) -> Tuple[bool, str]:
"""Attribute a referral to a user. Called during first login/signup."""
referred_email = referred_email.lower()
referral_code = referral_code.lower()
link = self.get_link_by_code(referral_code)
if not link:
return False, "Invalid or disabled referral code"
if link.owner_email == referred_email:
return False, "Cannot use your own referral code"
# Increment signup count
self.db.collection(REFERRAL_LINKS_COLLECTION).document(referral_code).update({
"stats.signups": firestore.Increment(1),
})
return True, "Referral attributed"
def get_attribution_data(self, referral_code: str) -> Optional[dict]:
"""Get the data to set on user doc for referral attribution."""
link = self.get_link_by_code(referral_code)
if not link:
return None
now = datetime.utcnow()
return {
"referred_by_code": referral_code.lower(),
"referred_at": now,
"referral_discount_expires_at": now + timedelta(days=link.discount_duration_days),
}
def get_or_create_stripe_coupon(self, discount_percent: int) -> Optional[str]:
if not self.stripe_service:
return None
return self.stripe_service.get_or_create_referral_coupon(discount_percent)
def should_apply_discount(self, user_data: dict) -> bool:
if not user_data.get("referred_by_code"):
return False
expires_at = user_data.get("referral_discount_expires_at")
if not expires_at:
return False
if isinstance(expires_at, datetime):
return expires_at > datetime.utcnow()
return False
def get_discount_for_checkout(self, user_email: str) -> Optional[dict]:
from backend.services.user_service import get_user_service
user_service = get_user_service()
user = user_service.get_user(user_email)
if not user or not user.referred_by_code:
return None
user_data = {
"referred_by_code": user.referred_by_code,
"referral_discount_expires_at": user.referral_discount_expires_at,
}
if not self.should_apply_discount(user_data):
return None
link = self.get_link_by_code(user.referred_by_code)
if not link:
return None
coupon_id = self.get_or_create_stripe_coupon(link.discount_percent)
if not coupon_id:
return None
return {"coupon_id": coupon_id, "discount_percent": link.discount_percent}
# ========================================================================
# Earnings
# ========================================================================
def record_earning(self, referred_email: str, stripe_session_id: str, purchase_amount_cents: int) -> Optional[dict]:
"""Record a referral earning after a credit purchase."""
referred_email = referred_email.lower()
# Look up the referred user
user_doc = self.db.collection("gen_users").document(referred_email).get()
if not user_doc.exists:
return None
user_data = user_doc.to_dict()
referral_code = user_data.get("referred_by_code")
if not referral_code:
return None
referred_at = user_data.get("referred_at")
if not referred_at:
return None
link = self.get_link_by_code(referral_code)
if not link:
return None
# Check earning window
earning_expires = referred_at + timedelta(days=link.earning_duration_days)
if datetime.utcnow() > earning_expires:
return None
# Calculate earning
earning_amount = int(purchase_amount_cents * link.kickback_percent / 100)
if earning_amount <= 0:
return None
import uuid
earning_id = str(uuid.uuid4())
earning = ReferralEarning(
id=earning_id,
referrer_email=link.owner_email,
referred_email=referred_email,
referral_code=referral_code,
stripe_session_id=stripe_session_id,
purchase_amount_cents=purchase_amount_cents,
earning_amount_cents=earning_amount,
)
self.db.collection(REFERRAL_EARNINGS_COLLECTION).document(earning_id).set(
earning.model_dump(mode="json")
)
self.db.collection(REFERRAL_LINKS_COLLECTION).document(referral_code).update({
"stats.purchases": firestore.Increment(1),
"stats.total_earned_cents": firestore.Increment(earning_amount),
})
logger.info(f"Referral earning recorded: ${earning_amount / 100:.2f} for {link.owner_email}")
return {"earning_id": earning_id, "referrer_email": link.owner_email, "earning_amount_cents": earning_amount}
# ========================================================================
# Stripe Connect & Payouts
# ========================================================================
def create_connect_account(self, email: str) -> Tuple[Optional[str], Optional[str]]:
"""Create Stripe Connect account for a referrer."""
if not self.stripe_service:
return None, None
return self.stripe_service.create_connect_account(email)
def get_pending_earnings(self, referrer_email: str) -> List[dict]:
"""Get all pending earnings for a referrer."""
query = (
self.db.collection(REFERRAL_EARNINGS_COLLECTION)
.where("referrer_email", "==", referrer_email.lower())
.where("status", "==", "pending")
)
return [
{**doc.to_dict(), "_ref": doc.reference}
for doc in query.get()
]
def check_and_trigger_payout(self, referrer_email: str, stripe_connect_account_id: str) -> bool:
"""Check if pending earnings meet threshold and trigger payout."""
pending = self.get_pending_earnings(referrer_email)
total_pending = sum(e.get("earning_amount_cents", 0) for e in pending)
if total_pending < PAYOUT_THRESHOLD_CENTS:
return False
if not self.stripe_service:
return False
transfer_id = self.stripe_service.create_transfer(
amount_cents=total_pending,
destination_account_id=stripe_connect_account_id,
)
if not transfer_id:
return False
import uuid
payout_id = str(uuid.uuid4())
earning_ids = [e["id"] for e in pending]
payout = ReferralPayout(
id=payout_id,
referrer_email=referrer_email.lower(),
stripe_transfer_id=transfer_id,
amount_cents=total_pending,
earnings_included=earning_ids,
)
self.db.collection(REFERRAL_PAYOUTS_COLLECTION).document(payout_id).set(
payout.model_dump(mode="json")
)
for earning in pending:
if "_ref" in earning:
earning["_ref"].update({
"status": "paid",
"paid_at": datetime.utcnow(),
"payout_id": payout_id,
})
logger.info(f"Payout triggered: ${total_pending / 100:.2f} to {referrer_email} (transfer: {transfer_id})")
return True
def get_dashboard_data(self, user_email: str) -> dict:
"""Get full referral dashboard data for a user."""
user_email = user_email.lower()
link = self.get_or_create_link(user_email)
# Get recent earnings (last 20)
earnings_query = (
self.db.collection(REFERRAL_EARNINGS_COLLECTION)
.where("referrer_email", "==", user_email)
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(20)
)
earnings = [doc.to_dict() for doc in earnings_query.stream()]
# Get recent payouts (last 10)
payouts_query = (
self.db.collection(REFERRAL_PAYOUTS_COLLECTION)
.where("referrer_email", "==", user_email)
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(10)
)
payouts = [doc.to_dict() for doc in payouts_query.stream()]
# Compute pending balance from ALL pending earnings (not limited to recent)
pending_earnings = self.get_pending_earnings(user_email)
pending_balance = sum(e.get("earning_amount_cents", 0) for e in pending_earnings)
total_earned = link.stats.total_earned_cents
# total_paid = total_earned - pending (since total_earned tracks all time)
total_paid = total_earned - pending_balance
# Check Connect status
from backend.services.user_service import get_user_service
user = get_user_service().get_user(user_email)
has_connect = bool(user and user.stripe_connect_account_id)
return {
"link": {
"code": link.code,
"display_name": link.display_name,
"custom_message": link.custom_message,
"discount_percent": link.discount_percent,
"kickback_percent": link.kickback_percent,
"discount_duration_days": link.discount_duration_days,
"earning_duration_days": link.earning_duration_days,
"stats": link.stats.model_dump(),
"enabled": link.enabled,
"is_vanity": link.is_vanity,
},
"pending_balance_cents": pending_balance,
"total_earned_cents": total_earned,
"total_paid_cents": total_paid,
"recent_earnings": [
{
"id": e["id"],
"referred_email": e.get("referred_email", ""),
"purchase_amount_cents": e.get("purchase_amount_cents", 0),
"earning_amount_cents": e.get("earning_amount_cents", 0),
"status": e.get("status", "pending"),
"created_at": str(e.get("created_at", "")),
}
for e in earnings
],
"recent_payouts": [
{
"id": p["id"],
"amount_cents": p.get("amount_cents", 0),
"status": p.get("status", "processing"),
"created_at": str(p.get("created_at", "")),
}
for p in payouts
],
"stripe_connect_configured": has_connect,
}
def list_links(self, limit: int = 50, offset: int = 0) -> list[ReferralLink]:
"""List referral links for admin view."""
query = (
self.db.collection(REFERRAL_LINKS_COLLECTION)
.order_by("created_at", direction=firestore.Query.DESCENDING)
.offset(offset)
.limit(limit)
)
links = []
for doc in query.stream():
try:
links.append(ReferralLink(**doc.to_dict()))
except Exception:
logger.warning("Skipping malformed referral link doc: %s", doc.id)
return links
# ============================================================================
# Singleton accessor
# ============================================================================
_referral_service = None
def get_referral_service() -> ReferralService:
global _referral_service
if _referral_service is None:
from backend.services.stripe_service import get_stripe_service
_referral_service = ReferralService(stripe_service=get_stripe_service())
return _referral_service
+68
View File
@@ -96,6 +96,7 @@ class StripeService:
user_email: str,
success_url: Optional[str] = None,
cancel_url: Optional[str] = None,
coupon_id: Optional[str] = None,
) -> Tuple[bool, Optional[str], str]:
"""
Create a Stripe Checkout session for purchasing credits.
@@ -151,6 +152,11 @@ class StripeService:
'allow_promotion_codes': True,
}
# If a referral coupon is applied, use discounts instead of allow_promotion_codes
if coupon_id:
session_params.pop('allow_promotion_codes', None)
session_params['discounts'] = [{'coupon': coupon_id}]
# Add payment method configuration if set (enables Google Pay, Link, etc.)
if self.payment_method_config:
session_params['payment_method_configuration'] = self.payment_method_config
@@ -351,6 +357,68 @@ class StripeService:
logger.error(f"Error retrieving session {session_id}: {e}")
return None
def get_or_create_referral_coupon(self, discount_percent: int) -> Optional[str]:
"""Get or create a Stripe coupon for a referral discount percentage."""
if not self.is_configured():
return None
coupon_id = f"referral-{discount_percent}pct"
try:
stripe.Coupon.retrieve(coupon_id)
return coupon_id
except stripe.error.InvalidRequestError:
try:
stripe.Coupon.create(
id=coupon_id,
percent_off=discount_percent,
duration="once",
name=f"Referral {discount_percent}% off",
)
logger.info(f"Created Stripe coupon: {coupon_id}")
return coupon_id
except stripe.error.StripeError as e:
logger.error(f"Failed to create coupon {coupon_id}: {e}")
return None
def create_connect_account(self, email: str) -> Tuple[Optional[str], Optional[str]]:
"""Create a Stripe Connect Express account. Returns (account_id, onboarding_url)."""
if not self.is_configured():
return None, None
try:
account = stripe.Account.create(
type="express",
email=email,
capabilities={"transfers": {"requested": True}},
metadata={"source": "nomad_karaoke_referrals"},
)
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",
type="account_onboarding",
)
logger.info(f"Created Connect account {account.id} for {email}")
return account.id, account_link.url
except stripe.error.StripeError as e:
logger.error(f"Failed to create Connect account for {email}: {e}")
return None, 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():
return None
try:
transfer = stripe.Transfer.create(
amount=amount_cents,
currency="usd",
destination=destination_account_id,
description=description,
)
logger.info(f"Created transfer {transfer.id}: ${amount_cents / 100:.2f} to {destination_account_id}")
return transfer.id
except stripe.error.StripeError as e:
logger.error(f"Failed to create transfer to {destination_account_id}: {e}")
return None
def create_customer(self, email: str, name: Optional[str] = None) -> Optional[str]:
"""
Create or get a Stripe customer for a user.
+291
View File
@@ -0,0 +1,291 @@
"""
Unit tests for referral system Pydantic models.
Tests validate:
- ReferralLinkStats defaults
- ReferralLink default and custom values
- ReferralEarning pending status default
- ReferralPayout creation with earnings list
- User model referral fields default to None
- UserPublic referral fields
- API request/response model shapes
"""
import pytest
from datetime import datetime, UTC
from pydantic import ValidationError
from backend.models.referral import (
ReferralLinkStats,
ReferralLink,
ReferralEarning,
ReferralPayout,
CreateReferralLinkRequest,
UpdateReferralLinkRequest,
ReferralLinkResponse,
ReferralEarningResponse,
ReferralPayoutResponse,
ReferralDashboardResponse,
ReferralInterstitialResponse,
)
from backend.models.user import User, UserPublic, UserRole
class TestReferralLinkStats:
"""Test ReferralLinkStats model defaults."""
def test_all_defaults_zero(self):
stats = ReferralLinkStats()
assert stats.clicks == 0
assert stats.signups == 0
assert stats.purchases == 0
assert stats.total_earned_cents == 0
def test_custom_values(self):
stats = ReferralLinkStats(clicks=10, signups=5, purchases=2, total_earned_cents=5000)
assert stats.clicks == 10
assert stats.signups == 5
assert stats.purchases == 2
assert stats.total_earned_cents == 5000
class TestReferralLink:
"""Test ReferralLink model defaults and custom values."""
def test_default_values(self):
link = ReferralLink(
code="abc123",
owner_email="user@example.com",
)
assert link.code == "abc123"
assert link.owner_email == "user@example.com"
assert link.discount_percent == 10
assert link.kickback_percent == 20
assert link.discount_duration_days == 30
assert link.earning_duration_days == 365
assert link.is_vanity is False
assert link.enabled is True
assert link.display_name is None
assert link.custom_message is None
assert link.stripe_coupon_id is None
# Stats should be all zeros
assert link.stats.clicks == 0
assert link.stats.signups == 0
assert link.stats.purchases == 0
assert link.stats.total_earned_cents == 0
def test_vanity_link_with_custom_values(self):
link = ReferralLink(
code="karaoke-king",
owner_email="king@example.com",
display_name="The Karaoke King",
custom_message="Sing with me!",
discount_percent=15,
kickback_percent=25,
discount_duration_days=60,
earning_duration_days=730,
is_vanity=True,
stripe_coupon_id="coupon_abc",
)
assert link.code == "karaoke-king"
assert link.display_name == "The Karaoke King"
assert link.custom_message == "Sing with me!"
assert link.discount_percent == 15
assert link.kickback_percent == 25
assert link.discount_duration_days == 60
assert link.earning_duration_days == 730
assert link.is_vanity is True
assert link.stripe_coupon_id == "coupon_abc"
def test_timestamps_set_automatically(self):
link = ReferralLink(code="test", owner_email="a@b.com")
assert isinstance(link.created_at, datetime)
assert isinstance(link.updated_at, datetime)
class TestReferralEarning:
"""Test ReferralEarning model."""
def test_pending_status_default(self):
earning = ReferralEarning(
id="earn_001",
referrer_email="referrer@example.com",
referred_email="newuser@example.com",
referral_code="abc123",
stripe_session_id="cs_test_123",
purchase_amount_cents=2999,
earning_amount_cents=600,
)
assert earning.status == "pending"
assert earning.paid_at is None
assert earning.payout_id is None
assert isinstance(earning.created_at, datetime)
def test_custom_status(self):
earning = ReferralEarning(
id="earn_002",
referrer_email="referrer@example.com",
referred_email="newuser@example.com",
referral_code="abc123",
stripe_session_id="cs_test_456",
purchase_amount_cents=2999,
earning_amount_cents=600,
status="paid",
)
assert earning.status == "paid"
class TestReferralPayout:
"""Test ReferralPayout model."""
def test_creation_with_earnings_list(self):
payout = ReferralPayout(
id="payout_001",
referrer_email="referrer@example.com",
stripe_transfer_id="tr_test_123",
amount_cents=1200,
earnings_included=["earn_001", "earn_002"],
)
assert payout.id == "payout_001"
assert payout.amount_cents == 1200
assert payout.earnings_included == ["earn_001", "earn_002"]
assert payout.status == "processing"
assert isinstance(payout.created_at, datetime)
def test_empty_earnings_list(self):
payout = ReferralPayout(
id="payout_002",
referrer_email="referrer@example.com",
stripe_transfer_id="tr_test_456",
amount_cents=0,
earnings_included=[],
)
assert payout.earnings_included == []
class TestUserReferralFields:
"""Test that User model has referral fields defaulting to None."""
def test_referral_fields_default_none(self):
user = User(email="test@example.com")
assert user.referral_code is None
assert user.referred_by_code is None
assert user.referred_at is None
assert user.referral_discount_expires_at is None
assert user.stripe_connect_account_id is None
def test_referral_fields_set(self):
now = datetime.now(UTC)
user = User(
email="test@example.com",
referral_code="mycode",
referred_by_code="friendcode",
referred_at=now,
referral_discount_expires_at=now,
stripe_connect_account_id="acct_123",
)
assert user.referral_code == "mycode"
assert user.referred_by_code == "friendcode"
assert user.referred_at == now
assert user.referral_discount_expires_at == now
assert user.stripe_connect_account_id == "acct_123"
class TestUserPublicReferralFields:
"""Test UserPublic has referral fields."""
def test_defaults(self):
pub = UserPublic(email="test@example.com", role=UserRole.USER, credits=0)
assert pub.referral_code is None
assert pub.has_active_referral_discount is False
def test_with_referral(self):
pub = UserPublic(
email="test@example.com",
role=UserRole.USER,
credits=5,
referral_code="mycode",
has_active_referral_discount=True,
)
assert pub.referral_code == "mycode"
assert pub.has_active_referral_discount is True
class TestReferralAPIModels:
"""Test API request/response models exist and have correct shapes."""
def test_create_request(self):
req = CreateReferralLinkRequest(owner_email="user@example.com", display_name="My Link")
assert req.display_name == "My Link"
assert req.owner_email == "user@example.com"
assert req.discount_percent == 10
assert req.kickback_percent == 20
def test_update_request(self):
req = UpdateReferralLinkRequest(enabled=False)
assert req.enabled is False
def test_link_response(self):
resp = ReferralLinkResponse(
code="abc",
owner_email="a@b.com",
discount_percent=10,
kickback_percent=20,
is_vanity=False,
enabled=True,
stats=ReferralLinkStats(),
created_at=datetime.now(UTC),
)
assert resp.code == "abc"
def test_earning_response(self):
resp = ReferralEarningResponse(
id="e1",
referred_email="new@b.com",
referral_code="abc",
purchase_amount_cents=2999,
earning_amount_cents=600,
status="pending",
created_at=datetime.now(UTC),
)
assert resp.status == "pending"
def test_payout_response(self):
resp = ReferralPayoutResponse(
id="p1",
amount_cents=1200,
earnings_count=2,
status="processing",
created_at=datetime.now(UTC),
)
assert resp.amount_cents == 1200
def test_dashboard_response(self):
resp = ReferralDashboardResponse(
referral_link=ReferralLinkResponse(
code="abc",
owner_email="a@b.com",
discount_percent=10,
kickback_percent=20,
is_vanity=False,
enabled=True,
stats=ReferralLinkStats(),
created_at=datetime.now(UTC),
),
recent_earnings=[],
recent_payouts=[],
total_earned_cents=0,
total_paid_cents=0,
pending_balance_cents=0,
stripe_connect_onboarded=False,
)
assert resp.total_earned_cents == 0
def test_interstitial_response(self):
resp = ReferralInterstitialResponse(
referral_code="abc",
referrer_display_name="Friend",
discount_percent=10,
discount_duration_days=30,
)
assert resp.referral_code == "abc"
assert resp.referrer_display_name == "Friend"
+330
View File
@@ -0,0 +1,330 @@
"""
Tests for Referral API routes.
Tests the /api/referrals/* endpoints for referral link management,
interstitial pages, dashboard, and admin operations.
"""
import pytest
from unittest.mock import Mock, patch, MagicMock
from fastapi.testclient import TestClient
from backend.main import app
from backend.api.dependencies import require_auth, require_admin
from backend.services.auth_service import UserType, AuthResult
from backend.models.referral import ReferralLink, ReferralLinkStats
@pytest.fixture(autouse=True)
def _clear_overrides():
"""Clear dependency overrides before and after each test."""
app.dependency_overrides.clear()
yield
app.dependency_overrides.clear()
@pytest.fixture
def client():
"""Create test client."""
return TestClient(app)
@pytest.fixture
def mock_auth_result():
"""Create a mock AuthResult for regular user."""
return AuthResult(
is_valid=True,
user_type=UserType.UNLIMITED,
remaining_uses=-1,
message="Valid",
user_email="test@example.com",
is_admin=False,
)
@pytest.fixture
def mock_admin_auth_result():
"""Create a mock AuthResult for admin user."""
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=-1,
message="Valid",
user_email="admin@nomadkaraoke.com",
is_admin=True,
)
def _make_referral_link(**overrides) -> ReferralLink:
"""Helper to create a ReferralLink with sensible defaults."""
defaults = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"display_name": "Test Referrer",
"custom_message": "Join karaoke!",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"stats": ReferralLinkStats(clicks=5, signups=2, purchases=1, total_earned_cents=500),
}
defaults.update(overrides)
return ReferralLink(**defaults)
# ============================================================================
# GET /api/referrals/r/{code} - Public interstitial
# ============================================================================
class TestGetInterstitial:
"""Tests for GET /api/referrals/r/{code}."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_valid_code_returns_interstitial(self, mock_get_service, client):
"""Valid code returns 200 with referral data and display_name."""
mock_service = Mock()
link = _make_referral_link()
mock_service.get_link_by_code.return_value = link
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/r/abc12345")
assert response.status_code == 200
data = response.json()
assert data["valid"] is True
assert data["referral_code"] == "abc12345"
assert data["referrer_display_name"] == "Test Referrer"
assert data["discount_percent"] == 10
assert data["discount_duration_days"] == 30
assert data["custom_message"] == "Join karaoke!"
mock_service.increment_clicks.assert_called_once_with("abc12345")
@patch("backend.api.routes.referrals.get_referral_service")
def test_invalid_code_returns_valid_false(self, mock_get_service, client):
"""Invalid code returns 200 with valid=False."""
mock_service = Mock()
mock_service.get_link_by_code.return_value = None
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/r/nonexistent")
assert response.status_code == 200
data = response.json()
assert data["valid"] is False
mock_service.increment_clicks.assert_not_called()
@patch("backend.api.routes.referrals.get_referral_service")
def test_click_increment_failure_does_not_break_response(self, mock_get_service, client):
"""Click tracking failure should not affect the response."""
mock_service = Mock()
link = _make_referral_link()
mock_service.get_link_by_code.return_value = link
mock_service.increment_clicks.side_effect = Exception("Firestore error")
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/r/abc12345")
assert response.status_code == 200
data = response.json()
assert data["valid"] is True
# ============================================================================
# GET /api/referrals/me - Dashboard
# ============================================================================
class TestGetDashboard:
"""Tests for GET /api/referrals/me."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_authenticated_user_gets_dashboard(self, mock_get_service, client, mock_auth_result):
"""Authenticated user gets their referral dashboard."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
mock_service = Mock()
mock_service.get_dashboard_data.return_value = {
"link": {"code": "abc12345", "display_name": "Test"},
"pending_balance_cents": 500,
"total_earned_cents": 1000,
"total_paid_cents": 200,
"recent_earnings": [],
"recent_payouts": [],
"stripe_connect_configured": False,
}
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/me")
assert response.status_code == 200
data = response.json()
assert data["link"]["code"] == "abc12345"
assert data["pending_balance_cents"] == 500
assert data["stripe_connect_configured"] is False
mock_service.get_dashboard_data.assert_called_once_with("test@example.com")
def test_unauthenticated_returns_401(self, client):
"""Unauthenticated request returns 401."""
# No dependency override -- real auth will reject
response = client.get("/api/referrals/me")
assert response.status_code == 401
# ============================================================================
# PUT /api/referrals/me - Update own link
# ============================================================================
class TestUpdateMyLink:
"""Tests for PUT /api/referrals/me."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_update_display_name(self, mock_get_service, client, mock_auth_result):
"""User can update their display name."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
mock_service = Mock()
link = _make_referral_link(owner_email="test@example.com")
mock_service.get_or_create_link.return_value = link
mock_service.update_link.return_value = (True, "Link updated")
mock_get_service.return_value = mock_service
response = client.put(
"/api/referrals/me",
json={"display_name": "New Name"},
)
assert response.status_code == 200
assert response.json()["ok"] is True
mock_service.update_link.assert_called_once_with(
"abc12345", display_name="New Name"
)
# ============================================================================
# POST /api/referrals/me/connect - Stripe Connect
# ============================================================================
class TestStripeConnect:
"""Tests for POST /api/referrals/me/connect."""
@patch("backend.services.user_service.get_user_service")
@patch("backend.api.routes.referrals.get_referral_service")
def test_start_connect_onboarding(self, mock_get_service, mock_get_user_svc, client, mock_auth_result):
"""User can start Stripe Connect onboarding."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
mock_service = Mock()
mock_service.create_connect_account.return_value = ("acct_123", "https://connect.stripe.com/onboard")
mock_get_service.return_value = mock_service
# Mock user without existing Connect account
mock_user = Mock()
mock_user.stripe_connect_account_id = None
mock_user_service = Mock()
mock_user_service.get_user.return_value = mock_user
mock_get_user_svc.return_value = mock_user_service
response = client.post("/api/referrals/me/connect")
assert response.status_code == 200
data = response.json()
assert data["account_id"] == "acct_123"
assert "onboarding_url" in data
# ============================================================================
# Admin endpoints
# ============================================================================
class TestAdminVanityLink:
"""Tests for POST /api/referrals/admin/vanity."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_create_vanity_link(self, mock_get_service, client, mock_admin_auth_result):
"""Admin can create a vanity referral link."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
link = _make_referral_link(code="karaoke-king", is_vanity=True)
mock_service.create_vanity_link.return_value = (True, link, "Vanity link created")
mock_get_service.return_value = mock_service
response = client.post(
"/api/referrals/admin/vanity",
json={"vanity_code": "karaoke-king", "owner_email": "king@example.com", "display_name": "King of Karaoke"},
)
assert response.status_code == 200
data = response.json()
assert data["ok"] is True
assert data["code"] == "karaoke-king"
@patch("backend.api.routes.referrals.get_referral_service")
def test_vanity_code_required(self, mock_get_service, client, mock_admin_auth_result):
"""Vanity code is required for vanity link creation."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
response = client.post(
"/api/referrals/admin/vanity",
json={"owner_email": "user@example.com", "display_name": "No Code"},
)
assert response.status_code == 400
class TestAdminListLinks:
"""Tests for GET /api/referrals/admin/links."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_list_links(self, mock_get_service, client, mock_admin_auth_result):
"""Admin can list all referral links."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.list_links.return_value = [
_make_referral_link(code="link1"),
_make_referral_link(code="link2"),
]
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/admin/links")
assert response.status_code == 200
data = response.json()
assert data["count"] == 2
assert len(data["links"]) == 2
def test_non_admin_returns_403(self, client, mock_auth_result):
"""Non-admin user gets 403."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
# Don't override require_admin -- it will check is_admin=False and raise 403
response = client.get("/api/referrals/admin/links")
assert response.status_code == 403
class TestAdminUpdateLink:
"""Tests for PUT /api/referrals/admin/links/{code}."""
@patch("backend.api.routes.referrals.get_referral_service")
def test_admin_update_link(self, mock_get_service, client, mock_admin_auth_result):
"""Admin can update any link."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.update_link.return_value = (True, "Link updated")
mock_get_service.return_value = mock_service
response = client.put(
"/api/referrals/admin/links/abc12345",
json={"enabled": False},
)
assert response.status_code == 200
assert response.json()["ok"] is True
mock_service.update_link.assert_called_once_with("abc12345", enabled=False)
+854
View File
@@ -0,0 +1,854 @@
"""
Unit tests for ReferralService — link management.
Tests cover:
- Code generation (8-char lowercase alphanumeric, uniqueness)
- Vanity code validation (length, chars, reserved words, hyphens)
- get_or_create_link (returns existing, creates new)
- get_link_by_code (found, not found, disabled)
- get_or_create_stripe_coupon (delegates to stripe service)
- should_apply_discount (active, expired, no referral)
"""
import pytest
import sys
import types
from unittest.mock import MagicMock, patch
from datetime import datetime, timedelta
from backend.services.referral_service import (
ReferralService,
RESERVED_CODES,
VANITY_CODE_PATTERN,
REFERRAL_LINKS_COLLECTION,
)
# ============================================================================
# Fixtures
# ============================================================================
@pytest.fixture
def mock_db():
return MagicMock()
@pytest.fixture
def mock_stripe_service():
return MagicMock()
@pytest.fixture
def service(mock_db, mock_stripe_service):
svc = ReferralService.__new__(ReferralService)
svc.db = mock_db
svc.stripe_service = mock_stripe_service
return svc
@pytest.fixture
def mock_user_service():
"""Inject a fake backend.services.user_service module so local imports resolve."""
mock_get_user_svc = MagicMock()
fake_module = types.ModuleType("backend.services.user_service")
fake_module.get_user_service = mock_get_user_svc
with patch.dict(sys.modules, {"backend.services.user_service": fake_module}):
yield mock_get_user_svc
# ============================================================================
# TestGenerateCode
# ============================================================================
class TestGenerateCode:
"""Tests for _generate_code()."""
def test_generates_8_char_lowercase_alphanumeric(self, service):
code = service._generate_code()
assert len(code) == 8
assert code == code.lower()
assert code.isalnum()
def test_generates_unique_codes(self, service):
codes = {service._generate_code() for _ in range(100)}
# With 36^8 possible codes, 100 should all be unique
assert len(codes) == 100
# ============================================================================
# TestValidateVanityCode
# ============================================================================
class TestValidateVanityCode:
"""Tests for _validate_vanity_code()."""
def test_valid_code(self, service):
valid, msg = service._validate_vanity_code("karaoke-king")
assert valid is True
def test_too_short(self, service):
valid, msg = service._validate_vanity_code("ab")
assert valid is False
assert "3-30" in msg or "characters" in msg.lower()
def test_too_long(self, service):
valid, msg = service._validate_vanity_code("a" * 31)
assert valid is False
def test_invalid_chars(self, service):
valid, msg = service._validate_vanity_code("bad_code!")
assert valid is False
def test_reserved_words(self, service):
valid, msg = service._validate_vanity_code("admin")
assert valid is False
assert "reserved" in msg.lower()
valid, msg = service._validate_vanity_code("api")
assert valid is False
assert "reserved" in msg.lower()
def test_allows_hyphens(self, service):
valid, msg = service._validate_vanity_code("my-cool-code")
assert valid is True
# ============================================================================
# TestGetOrCreateLink
# ============================================================================
class TestGetOrCreateLink:
"""Tests for get_or_create_link()."""
def test_returns_existing_link(self, service, mock_db):
# Set up mock: query returns an existing doc
mock_query = MagicMock()
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = [
MagicMock(to_dict=lambda: {
"code": "abc12345",
"owner_email": "user@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"created_at": datetime(2026, 1, 1),
"updated_at": datetime(2026, 1, 1),
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
})
]
link = service.get_or_create_link("user@example.com")
assert link.code == "abc12345"
assert link.owner_email == "user@example.com"
# Should NOT have called document().set()
mock_db.collection.return_value.document.return_value.set.assert_not_called()
def test_creates_new_if_none_exists(self, service, mock_db):
# Query returns empty — no existing link
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
# doc.get() returns a doc that doesn't exist (no collision)
mock_doc_ref = MagicMock()
mock_doc_snapshot = MagicMock()
mock_doc_snapshot.exists = False
mock_doc_ref.get.return_value = mock_doc_snapshot
mock_db.collection.return_value.document.return_value = mock_doc_ref
link = service.get_or_create_link("new@example.com")
assert link is not None
assert link.owner_email == "new@example.com"
assert len(link.code) == 8
mock_doc_ref.set.assert_called_once()
# ============================================================================
# TestGetLinkByCode
# ============================================================================
class TestGetLinkByCode:
"""Tests for get_link_by_code()."""
def test_returns_link_if_exists(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "user@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"created_at": datetime(2026, 1, 1),
"updated_at": datetime(2026, 1, 1),
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
link = service.get_link_by_code("abc12345")
assert link is not None
assert link.code == "abc12345"
def test_returns_none_if_not_found(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
link = service.get_link_by_code("nonexistent")
assert link is None
def test_returns_none_if_disabled(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "user@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": False,
"created_at": datetime(2026, 1, 1),
"updated_at": datetime(2026, 1, 1),
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
link = service.get_link_by_code("abc12345")
assert link is None
# ============================================================================
# TestAttributeReferral
# ============================================================================
def _mock_valid_link_doc(mock_db, owner_email="referrer@example.com"):
"""Helper: set up mock_db so get_link_by_code returns a valid link."""
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": owner_email,
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"created_at": datetime(2026, 1, 1),
"updated_at": datetime(2026, 1, 1),
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
class TestAttributeReferral:
"""Tests for attribute_referral()."""
def test_successful_attribution(self, service, mock_db):
_mock_valid_link_doc(mock_db, owner_email="referrer@example.com")
success, msg = service.attribute_referral("newuser@example.com", "abc12345")
assert success is True
assert "attributed" in msg.lower()
# Should have incremented signups
mock_db.collection.return_value.document.return_value.update.assert_called_once()
def test_self_referral_blocked(self, service, mock_db):
_mock_valid_link_doc(mock_db, owner_email="user@example.com")
success, msg = service.attribute_referral("user@example.com", "abc12345")
assert success is False
assert "own" in msg.lower() or "self" in msg.lower()
def test_invalid_code_rejected(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
success, msg = service.attribute_referral("newuser@example.com", "nonexistent")
assert success is False
assert "invalid" in msg.lower() or "disabled" in msg.lower()
# ============================================================================
# TestGetOrCreateStripeCoupon
# ============================================================================
class TestGetOrCreateStripeCoupon:
def test_creates_coupon_for_new_percentage(self, service, mock_stripe_service):
mock_stripe_service.get_or_create_referral_coupon.return_value = "referral-10pct"
coupon_id = service.get_or_create_stripe_coupon(10)
assert coupon_id == "referral-10pct"
mock_stripe_service.get_or_create_referral_coupon.assert_called_once_with(10)
# ============================================================================
# TestShouldApplyDiscount
# ============================================================================
class TestShouldApplyDiscount:
def test_active_discount(self, service):
user_data = {
"referred_by_code": "abc12345",
"referral_discount_expires_at": datetime.utcnow() + timedelta(days=15),
}
assert service.should_apply_discount(user_data) is True
def test_expired_discount(self, service):
user_data = {
"referred_by_code": "abc12345",
"referral_discount_expires_at": datetime.utcnow() - timedelta(days=1),
}
assert service.should_apply_discount(user_data) is False
def test_no_referral(self, service):
user_data = {}
assert service.should_apply_discount(user_data) is False
# ============================================================================
# TestRecordEarning
# ============================================================================
class TestRecordEarning:
def test_creates_earning_within_window(self, service, mock_db):
"""Earning is created when purchase is within earning window."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {
"email": "referred@example.com",
"referred_by_code": "abc12345",
"referred_at": datetime.utcnow() - timedelta(days=30),
}
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"kickback_percent": 20,
"earning_duration_days": 365,
"discount_percent": 10,
"discount_duration_days": 30,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
def collection_side_effect(name):
mock_col = MagicMock()
if name == "gen_users":
mock_col.document.return_value.get.return_value = mock_user_doc
elif name == REFERRAL_LINKS_COLLECTION:
mock_col.document.return_value.get.return_value = mock_link_doc
return mock_col
mock_db.collection.side_effect = collection_side_effect
result = service.record_earning(
referred_email="referred@example.com",
stripe_session_id="cs_test_123",
purchase_amount_cents=1575,
)
assert result is not None
assert result["earning_amount_cents"] == 315 # 20% of 1575
def test_no_earning_outside_window(self, service, mock_db):
"""No earning created when purchase is outside earning window."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {
"email": "referred@example.com",
"referred_by_code": "abc12345",
"referred_at": datetime.utcnow() - timedelta(days=400),
}
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"kickback_percent": 20,
"earning_duration_days": 365,
"discount_percent": 10,
"discount_duration_days": 30,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
def collection_side_effect(name):
mock_col = MagicMock()
if name == "gen_users":
mock_col.document.return_value.get.return_value = mock_user_doc
elif name == REFERRAL_LINKS_COLLECTION:
mock_col.document.return_value.get.return_value = mock_link_doc
return mock_col
mock_db.collection.side_effect = collection_side_effect
result = service.record_earning(
referred_email="referred@example.com",
stripe_session_id="cs_test_456",
purchase_amount_cents=1575,
)
assert result is None
def test_no_earning_for_non_referred_user(self, service, mock_db):
"""No earning for users without referral attribution."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {"email": "user@example.com"}
mock_db.collection.return_value.document.return_value.get.return_value = mock_user_doc
result = service.record_earning(
referred_email="user@example.com",
stripe_session_id="cs_test_789",
purchase_amount_cents=1750,
)
assert result is None
# ============================================================================
# TestStripeConnectOnboarding
# ============================================================================
class TestStripeConnectOnboarding:
def test_create_connect_account(self, service, mock_stripe_service):
mock_stripe_service.create_connect_account.return_value = ("acct_123", "https://connect.stripe.com/onboard")
account_id, onboard_url = service.create_connect_account("referrer@example.com")
assert account_id == "acct_123"
assert "stripe.com" in onboard_url
# ============================================================================
# TestTriggerPayout
# ============================================================================
class TestTriggerPayout:
def test_payout_triggered_at_threshold(self, service, mock_db, mock_stripe_service):
"""Payout is triggered when pending earnings >= $20."""
earning_docs = []
for i in range(4):
doc = MagicMock()
doc.to_dict.return_value = {
"id": f"earn-{i}",
"referrer_email": "referrer@example.com",
"referred_email": f"user{i}@example.com",
"referral_code": "abc12345",
"stripe_session_id": f"cs_{i}",
"purchase_amount_cents": 1750,
"earning_amount_cents": 525, # $5.25 each, 4 = $21.00
"status": "pending",
"created_at": datetime.utcnow(),
}
doc.reference = MagicMock()
earning_docs.append(doc)
mock_query = MagicMock()
mock_query.where.return_value = mock_query
mock_query.get.return_value = earning_docs
mock_db.collection.return_value = mock_query
mock_stripe_service.create_transfer.return_value = "tr_123"
result = service.check_and_trigger_payout(
referrer_email="referrer@example.com",
stripe_connect_account_id="acct_123",
)
assert result is True
def test_no_payout_below_threshold(self, service, mock_db, mock_stripe_service):
"""No payout when pending earnings < $20."""
earning_doc = MagicMock()
earning_doc.to_dict.return_value = {
"id": "earn-1",
"referrer_email": "referrer@example.com",
"earning_amount_cents": 315,
"status": "pending",
"created_at": datetime.utcnow(),
}
earning_doc.reference = MagicMock()
mock_query = MagicMock()
mock_query.where.return_value = mock_query
mock_query.get.return_value = [earning_doc]
mock_db.collection.return_value = mock_query
result = service.check_and_trigger_payout(
referrer_email="referrer@example.com",
stripe_connect_account_id="acct_123",
)
assert result is False
# ============================================================================
# TestFullReferralFlow
# ============================================================================
class TestFullReferralFlow:
"""Integration-style test covering the full referral lifecycle."""
def test_full_flow(self, service, mock_db, mock_stripe_service):
"""
1. Referrer gets a link
2. Referred user signs up (attribution)
3. Discount check
4. Earning calculation
"""
# Step 1: Referrer gets a link
mock_query = MagicMock()
mock_query.limit.return_value.get.return_value = []
mock_code_doc = MagicMock()
mock_code_doc.exists = False
mock_db.collection.return_value.where.return_value = mock_query
mock_db.collection.return_value.document.return_value.get.return_value = mock_code_doc
link = service.get_or_create_link("referrer@example.com")
assert link is not None
assert link.owner_email == "referrer@example.com"
# Step 2: Attribution
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": link.code,
"owner_email": "referrer@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_link_doc
success, msg = service.attribute_referral("newuser@example.com", link.code)
assert success is True
# Step 3: Discount check
user_data = {
"referred_by_code": link.code,
"referral_discount_expires_at": datetime.utcnow() + timedelta(days=15),
}
assert service.should_apply_discount(user_data) is True
# Step 4: Earning calculation
assert int(1575 * 20 / 100) == 315 # 20% of $15.75 = $3.15
# ============================================================================
# TestGetAttributionData
# ============================================================================
class TestGetAttributionData:
"""Tests for get_attribution_data() — returns dict for user doc update."""
def test_returns_attribution_dict(self, service, mock_db):
"""Attribution data includes correct fields and timedelta calculation."""
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
data = service.get_attribution_data("abc12345")
assert data is not None
assert data["referred_by_code"] == "abc12345"
assert "referred_at" in data
assert "referral_discount_expires_at" in data
# Discount should expire ~30 days from now
delta = data["referral_discount_expires_at"] - data["referred_at"]
assert delta.days == 30
def test_returns_none_for_invalid_code(self, service, mock_db):
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
data = service.get_attribution_data("nonexistent")
assert data is None
def test_custom_discount_duration(self, service, mock_db):
"""Links with custom duration calculate correct expiry."""
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "custom90",
"owner_email": "referrer@example.com",
"discount_percent": 15,
"kickback_percent": 25,
"discount_duration_days": 90, # Custom 90-day duration
"earning_duration_days": 365,
"is_vanity": True,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
data = service.get_attribution_data("custom90")
delta = data["referral_discount_expires_at"] - data["referred_at"]
assert delta.days == 90
# ============================================================================
# TestGetDiscountForCheckout
# ============================================================================
class TestGetDiscountForCheckout:
"""Tests for get_discount_for_checkout() — coupon lookup for Stripe checkout."""
def test_returns_discount_for_active_referred_user(self, service, mock_db, mock_stripe_service, mock_user_service):
"""Returns coupon info when user has active referral discount."""
mock_user = MagicMock()
mock_user.referred_by_code = "abc12345"
mock_user.referral_discount_expires_at = datetime.utcnow() + timedelta(days=15)
mock_user_svc = MagicMock()
mock_user_svc.get_user.return_value = mock_user
mock_user_service.return_value = mock_user_svc
# Mock referral link lookup
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
mock_stripe_service.get_or_create_referral_coupon.return_value = "referral-10pct"
result = service.get_discount_for_checkout("referred@example.com")
assert result is not None
assert result["coupon_id"] == "referral-10pct"
assert result["discount_percent"] == 10
def test_returns_none_for_expired_discount(self, service, mock_db, mock_user_service):
"""Returns None when user's discount has expired."""
mock_user = MagicMock()
mock_user.referred_by_code = "abc12345"
mock_user.referral_discount_expires_at = datetime.utcnow() - timedelta(days=1)
mock_user_svc = MagicMock()
mock_user_svc.get_user.return_value = mock_user
mock_user_service.return_value = mock_user_svc
result = service.get_discount_for_checkout("referred@example.com")
assert result is None
def test_returns_none_for_non_referred_user(self, service, mock_db, mock_user_service):
"""Returns None when user has no referral."""
mock_user = MagicMock()
mock_user.referred_by_code = None
mock_user.referral_discount_expires_at = None
mock_user_svc = MagicMock()
mock_user_svc.get_user.return_value = mock_user
mock_user_service.return_value = mock_user_svc
result = service.get_discount_for_checkout("regular@example.com")
assert result is None
# ============================================================================
# TestGetDashboardData
# ============================================================================
class TestGetDashboardData:
"""Tests for get_dashboard_data() — full referral dashboard payload."""
def test_returns_complete_dashboard(self, service, mock_db, mock_user_service):
"""Dashboard data includes link, earnings, payouts, and balances."""
# Mock user service for Connect status check
mock_user = MagicMock()
mock_user.stripe_connect_account_id = None
mock_user_svc = MagicMock()
mock_user_svc.get_user.return_value = mock_user
mock_user_service.return_value = mock_user_svc
# Mock get_or_create_link: query stream returns existing link doc
mock_link_doc = MagicMock()
mock_link_doc.to_dict.return_value = {
"code": "mycode12",
"owner_email": "user@example.com",
"discount_percent": 10,
"kickback_percent": 20,
"discount_duration_days": 30,
"earning_duration_days": 365,
"is_vanity": False,
"enabled": True,
"display_name": None,
"custom_message": None,
"stripe_coupon_id": None,
"stats": {"clicks": 5, "signups": 2, "purchases": 1, "total_earned_cents": 350},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
# Complex mock setup for multiple collection queries
mock_link_query = MagicMock()
mock_link_query.limit.return_value.stream.return_value = [mock_link_doc]
mock_earnings_query = MagicMock()
mock_earnings_query.order_by.return_value.limit.return_value.stream.return_value = []
mock_payouts_query = MagicMock()
mock_payouts_query.order_by.return_value.limit.return_value.stream.return_value = []
def collection_side_effect(name):
mock_col = MagicMock()
if name == "referral_links":
mock_col.where.return_value = mock_link_query
elif name == "referral_earnings":
mock_col.where.return_value = mock_earnings_query
elif name == "referral_payouts":
mock_col.where.return_value = mock_payouts_query
return mock_col
mock_db.collection.side_effect = collection_side_effect
data = service.get_dashboard_data("user@example.com")
assert "link" in data
assert data["link"]["code"] == "mycode12"
assert data["link"]["stats"]["clicks"] == 5
assert data["pending_balance_cents"] == 0
assert data["total_earned_cents"] == 350
assert data["stripe_connect_configured"] is False
assert isinstance(data["recent_earnings"], list)
assert isinstance(data["recent_payouts"], list)
# ============================================================================
# TestEarningCalculationEdgeCases
# ============================================================================
class TestEarningCalculationEdgeCases:
"""Edge cases for record_earning() — rounding and zero amounts."""
def test_earning_rounds_down(self, service, mock_db):
"""Earning calculation truncates fractional cents."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {
"email": "referred@example.com",
"referred_by_code": "abc12345",
"referred_at": datetime.utcnow() - timedelta(days=10),
}
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"kickback_percent": 20,
"earning_duration_days": 365,
"discount_percent": 10,
"discount_duration_days": 30,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
def collection_side_effect(name):
mock_col = MagicMock()
if name == "gen_users":
mock_col.document.return_value.get.return_value = mock_user_doc
elif name == REFERRAL_LINKS_COLLECTION:
mock_col.document.return_value.get.return_value = mock_link_doc
return mock_col
mock_db.collection.side_effect = collection_side_effect
# 1999 * 20 / 100 = 399.8 -> should truncate to 399
result = service.record_earning(
referred_email="referred@example.com",
stripe_session_id="cs_edge_1",
purchase_amount_cents=1999,
)
assert result is not None
assert result["earning_amount_cents"] == 399
def test_zero_amount_returns_none(self, service, mock_db):
"""Zero purchase amount produces no earning."""
mock_user_doc = MagicMock()
mock_user_doc.exists = True
mock_user_doc.to_dict.return_value = {
"email": "referred@example.com",
"referred_by_code": "abc12345",
"referred_at": datetime.utcnow() - timedelta(days=10),
}
mock_link_doc = MagicMock()
mock_link_doc.exists = True
mock_link_doc.to_dict.return_value = {
"code": "abc12345",
"owner_email": "referrer@example.com",
"kickback_percent": 20,
"earning_duration_days": 365,
"discount_percent": 10,
"discount_duration_days": 30,
"is_vanity": False,
"enabled": True,
"stats": {"clicks": 0, "signups": 0, "purchases": 0, "total_earned_cents": 0},
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
}
def collection_side_effect(name):
mock_col = MagicMock()
if name == "gen_users":
mock_col.document.return_value.get.return_value = mock_user_doc
elif name == REFERRAL_LINKS_COLLECTION:
mock_col.document.return_value.get.return_value = mock_link_doc
return mock_col
mock_db.collection.side_effect = collection_side_effect
result = service.record_earning(
referred_email="referred@example.com",
stripe_session_id="cs_edge_2",
purchase_amount_cents=0,
)
assert result is None
+81
View File
@@ -1856,6 +1856,87 @@ POST /api/internal/process-stale-reviews
```
Called by Cloud Scheduler hourly. Queries for jobs in `awaiting_review` or `in_review` status, sends reminder emails at 24h, and auto-cancels with credit refund at 48h. Excludes made-for-you and tenant jobs. Returns `{status: "started", message: "..."}` immediately; processing runs in background.
## Referral System
### Get Referral Interstitial (Public)
```http
GET /api/referrals/r/{code}
```
No auth required. Returns referral link data for the interstitial page. Increments click count. Returns `valid: false` if code not found or disabled.
### Get Referral Dashboard
```http
GET /api/referrals/me
Authorization: Bearer TOKEN
```
Returns the current user's referral link, stats (clicks, signups, purchases), pending balance, recent earnings, recent payouts, and Stripe Connect status.
### Update Referral Link
```http
PUT /api/referrals/me
Authorization: Bearer TOKEN
Content-Type: application/json
{"display_name": "DJ Tommy", "custom_message": "Best karaoke tool!"}
```
Update the current user's referral link display name and custom message (shown on interstitial page).
### Start Stripe Connect Onboarding
```http
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.
### Create Vanity Link (Admin)
```http
POST /api/referrals/admin/vanity
Authorization: Bearer ADMIN_TOKEN
Content-Type: application/json
{"code": "djtommy", "owner_email": "tommy@example.com", "discount_percent": 15, "kickback_percent": 25}
```
Admin creates a custom vanity referral link with optional override rates.
### List Referral Links (Admin)
```http
GET /api/referrals/admin/links?limit=50&offset=0
Authorization: Bearer ADMIN_TOKEN
```
### Update Any Link (Admin)
```http
PUT /api/referrals/admin/links/{code}
Authorization: Bearer ADMIN_TOKEN
Content-Type: application/json
{"discount_percent": 20, "enabled": false}
```
### Referral Attribution
Referral codes are passed via the `x-referral-code` HTTP header during magic link verification. Attribution is one-time on first login only.
### Referral Discounts at Checkout
Referred users with an active discount window (default 30 days) automatically receive a Stripe coupon at checkout. The discount replaces `allow_promotion_codes` on the checkout session.
### Referral Earnings
After a credit purchase by a referred user, earnings are recorded automatically in the Stripe webhook handler. When a referrer's pending balance reaches $20 and they have a Stripe Connect account, a payout is triggered automatically.
## Webhooks
Stripe webhooks implemented at `/api/users/webhooks/stripe`.
+1
View File
@@ -37,6 +37,7 @@
| **Review session backup/restore** | Working (auto-save + restore UI) |
| **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) |
## Known Issues
@@ -0,0 +1,202 @@
# Referral Link System — Design Spec
**Date:** 2026-04-04
**Status:** Approved
**Scope:** karaoke-gen (backend + frontend + public-website)
## Overview
A referral system where any registered user can share a personalized link. Referred users get a time-limited discount on credit purchases. Referrers earn a cash kickback (percentage of actual revenue) paid out via Stripe Connect.
## Key Parameters
| Parameter | Default | Configurable? |
|-----------|---------|---------------|
| Discount for referred user | 10% | Per-link (admin) |
| Discount window | 30 days from signup | Per-link (admin) |
| Referrer kickback | 20% of amount charged | Per-link (admin) |
| Earning window | 1 year from referred signup | Per-link (admin) |
| Payout threshold | $20 | Global |
| Applies to | Credit purchases only | Fixed (excludes Made-for-You) |
## Data Model
### New collection: `referral_links`
| Field | Type | Description |
|-------|------|-------------|
| `code` | string | Unique, URL-safe. Auto-generated (8-char lowercase alphanumeric) or admin vanity (3-30 chars, alphanumeric + hyphens). |
| `owner_email` | string | Referrer's email |
| `display_name` | string | Shown on interstitial (defaults to user's name/email) |
| `custom_message` | string | Optional, max 200 chars. Shown on interstitial. |
| `discount_percent` | int | Default 10 |
| `kickback_percent` | int | Default 20 |
| `discount_duration_days` | int | Default 30 |
| `earning_duration_days` | int | Default 365 |
| `stripe_coupon_id` | string | Corresponding Stripe coupon for this discount % |
| `is_vanity` | bool | Whether admin-created vanity link |
| `enabled` | bool | Admin can disable (soft delete) |
| `created_at` | datetime | |
| `updated_at` | datetime | |
| `stats.clicks` | int | Interstitial page views |
| `stats.signups` | int | Users who signed up via this link |
| `stats.purchases` | int | Purchases attributed to this link |
| `stats.total_earned_cents` | int | Total kickback earned |
### New collection: `referral_earnings`
| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Document ID |
| `referrer_email` | string | |
| `referred_email` | string | |
| `referral_code` | string | The code used |
| `stripe_session_id` | string | Payment that triggered this earning |
| `purchase_amount_cents` | int | Amount charged (after discount) |
| `earning_amount_cents` | int | Kickback amount |
| `status` | string | `pending` / `paid` / `refunded` |
| `created_at` | datetime | |
| `paid_at` | datetime | When included in a payout |
| `payout_id` | string | Links to payout record |
### New collection: `referral_payouts`
| Field | Type | Description |
|-------|------|-------------|
| `id` | string | Document ID |
| `referrer_email` | string | |
| `stripe_transfer_id` | string | Stripe Connect transfer ID |
| `amount_cents` | int | Total payout amount |
| `earnings_included` | list[string] | Earning doc IDs included |
| `status` | string | `processing` / `completed` / `failed` |
| `created_at` | datetime | |
### Additions to existing `users` collection
| Field | Type | Description |
|-------|------|-------------|
| `referral_code` | string | User's auto-generated referral code |
| `referred_by_code` | string | Code they signed up with (if any) |
| `referred_at` | datetime | When referral was attributed |
| `referral_discount_expires_at` | datetime | `referred_at` + discount duration |
| `stripe_connect_account_id` | string | For receiving payouts |
## Referral Link Formats
- **Primary:** `nomadkaraoke.com/r/CODE` — dedicated route, shows interstitial, redirects to landing page
- **Secondary:** `nomadkaraoke.com/?ref=CODE` — query param on any page, silent cookie set
- If both present, `/r/CODE` takes priority
- Cookie: 30-day expiry + localStorage backup
## Interstitial Page (`/r/CODE`)
A branded page shown when someone clicks a referral link:
- Referrer's `display_name` and `custom_message` (if set)
- Discount details: "Enjoy 10% off all credit purchases for 30 days"
- CTA button: "Get Started" → redirects to landing page
- Sets referral cookie before redirect
- Increments `stats.clicks` on the referral link doc
## Referral Attribution Flow
1. User visits `/r/CODE` or any page with `?ref=CODE`
2. Code stored in cookie (30-day expiry) + localStorage
3. User signs up or logs in
4. On first authentication, backend checks for referral code:
- Validates code exists and is enabled
- Validates code isn't the user's own (self-referral block)
- Sets `referred_by_code`, `referred_at`, `referral_discount_expires_at` on user doc
- Increments `stats.signups` on referral link doc
5. Attribution is one-time — first valid code wins, cannot be changed
## Checkout Flow (Discounted)
1. User initiates credit purchase
2. Backend checks `referral_discount_expires_at > now`
3. If active discount: creates Stripe checkout session with coupon for configured discount %
4. Discount visible on Stripe checkout page
5. After successful payment (webhook):
a. Normal credit grant flow (unchanged)
b. Check if user has `referred_by_code` and within earning window (1 year)
c. If yes: calculate kickback = `purchase_amount_cents * kickback_percent / 100`
d. Create `referral_earnings` doc with status `pending`
e. Increment `stats.purchases` and `stats.total_earned_cents` on referral link doc
f. Check referrer's total unpaid earnings — if >= $20 and Connect account exists, trigger payout
**Stripe coupon strategy:** One coupon per unique discount percentage (e.g., `referral-10pct`, `referral-15pct`). Reused across all links with the same rate. Applied at checkout session level.
## Stripe Connect & Payouts
### Onboarding
1. User visits Referrals dashboard, clicks "Connect your bank account"
2. Backend creates Stripe Connect Express account, returns onboarding link
3. User completes Stripe's onboarding (bank details, identity, tax info)
4. Backend stores `stripe_connect_account_id` on user doc
5. Stripe handles compliance (1099s for US referrers earning $600+/year)
### Payout Lifecycle
1. Earnings accumulate as `pending` docs in `referral_earnings`
2. When total unpaid earnings >= $20 AND referrer has Connect account:
- Create Stripe Transfer to Connect account
- Create `referral_payouts` doc with status `processing`
- Mark included earnings as `paid`
3. If >= $20 but no Connect account: earnings accumulate, user sees prompt to connect
4. Stripe webhook confirms transfer → update payout status to `completed`
### Refund Handling
- If referred purchase is refunded before payout: earning doc marked `refunded`, deducted from unpaid balance
- If refunded after payout: refunded amount deducted from future earnings (negative balance carries forward)
- If referrer never earns enough to offset: written off (acceptable at this scale)
## Admin Features
### Referral Links Management
- List all referral links with stats
- Create vanity links: custom code, assign to user, override discount/kickback %
- Edit any link's parameters (discount %, kickback %, display name, message, duration)
- Disable/enable links (soft delete)
- Code validation: alphanumeric + hyphens, 3-30 chars, no collisions with reserved words (`admin`, `app`, `api`, `r`, `pricing`, etc.)
### Activity & Analytics
- Per-link stats: clicks, signups, conversions, revenue generated, total paid out
- Global referral activity feed: recent signups, purchases, earnings
- Payout oversight: pending/completed payouts, manually trigger or hold payouts
### Abuse Controls
- Disable any referral link
- Hold payouts for specific referrers (fraud review flag)
- Self-referral blocked at attribution time
- Leverage existing fingerprint/IP infrastructure: flag if referred user shares `device_fingerprint` or `signup_ip` with referrer
- Admin alerts for suspicious patterns (e.g., many signups with no purchases, shared fingerprints)
## Frontend: Referrer Experience
**New "Referrals" section in app dashboard:**
- Referral link with copy button
- Edit display name and custom message
- Stats: signups, purchases, total earned, pending balance
- Stripe Connect onboarding CTA (if not connected)
- Payout history (once connected)
- Lightweight — not a full affiliate dashboard
## Frontend: Referred User Experience
- **On signup with referral attribution:** Toast/banner — "You've got 10% off all credit purchases for 30 days!"
- **During discount window:** Discount badge on Buy Credits dialog, discount applied automatically at checkout
- **After discount expires:** Normal pricing, no visual changes
- No mention of referrer earning money
## Scope Exclusions
- Referral discounts do NOT apply to Made-for-You ($50) orders
- No multi-level/MLM referrals — only direct referrals earn
- No referral link for white-label tenants (default Nomad Karaoke portal only, for now)
- No public-facing leaderboard or referral tiers
File diff suppressed because it is too large. Load diff
+6 -2
View File
@@ -1,7 +1,7 @@
"use client"
import { useState, useEffect, useCallback, useMemo, Suspense, useRef } from "react"
import { useRouter } from "@/i18n/routing"
import { useRouter, Link } from "@/i18n/routing"
import { useSearchParams } from "next/navigation"
import { api, Job, getAccessToken } from "@/lib/api"
import { useAuth } from "@/lib/auth"
@@ -16,7 +16,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { Music2, RefreshCw, Loader2, Moon, Sun, Search, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone } from "lucide-react"
import { Music2, RefreshCw, Loader2, Moon, Sun, Search, Gift, X, Shield, ShieldOff, HelpCircle, Mail, Phone, Users } from "lucide-react"
import { useTranslations } from "next-intl"
import { sortJobsByDate } from "@/lib/job-status"
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
@@ -293,6 +293,10 @@ function AppPageContent() {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Link href="/app/referrals" className="flex items-center gap-1.5 text-sm hover:underline min-h-[40px] px-2 sm:px-3" style={{ color: 'var(--text-muted)' }}>
<Users className="w-4 h-4" />
<span className="hidden sm:inline">{t('referrals')}</span>
</Link>
<LanguageSwitcher />
<AuthStatus />
{mounted && (
@@ -0,0 +1,7 @@
'use client';
import ReferralDashboard from '@/components/referrals/ReferralDashboard';
export default function ReferralsPage() {
return <ReferralDashboard />;
}
+5
View File
@@ -1,8 +1,10 @@
import { Suspense } from 'react';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages, setRequestLocale } from 'next-intl/server';
import { hasLocale } from 'next-intl';
import { notFound } from 'next/navigation';
import { routing } from '@/i18n/routing';
import { ReferralCapture } from '@/components/ReferralCapture';
export function generateStaticParams() {
return routing.locales.map((locale) => ({ locale }));
@@ -32,6 +34,9 @@ export default async function LocaleLayout({
__html: `document.documentElement.lang="${locale}";document.documentElement.dir="${['ar', 'he'].includes(locale) ? 'rtl' : 'ltr'}";`,
}}
/>
<Suspense fallback={null}>
<ReferralCapture />
</Suspense>
{children}
</NextIntlClientProvider>
);
+123
View File
@@ -0,0 +1,123 @@
'use client';
import { useEffect, useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { getReferralInterstitial } from '@/lib/api';
import { setReferralCode } from '@/lib/referral';
import type { ReferralInterstitial } from '@/lib/types';
import { Gift, ArrowRight } from 'lucide-react';
export function ReferralInterstitialClient() {
const searchParams = useSearchParams();
const router = useRouter();
const t = useTranslations('referrals');
const code = searchParams.get('code');
const [data, setData] = useState<ReferralInterstitial | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!code) {
router.replace('/');
return;
}
// Store referral code immediately
setReferralCode(code);
getReferralInterstitial(code)
.then((result) => {
if (result.valid) {
setData(result);
} else {
router.replace('/');
}
})
.catch(() => {
router.replace('/');
})
.finally(() => setLoading(false));
}, [code, router]);
if (loading || !data) {
return (
<div className="min-h-screen flex items-center justify-center" style={{ background: 'var(--bg)' }}>
<div className="animate-spin rounded-full h-8 w-8 border-b-2" style={{ borderColor: 'var(--accent)' }} />
</div>
);
}
return (
<div
className="min-h-screen flex items-center justify-center p-4"
style={{ background: 'var(--bg)' }}
>
<div
className="max-w-md w-full rounded-2xl shadow-2xl p-8 text-center space-y-6"
style={{
backgroundColor: 'var(--card)',
border: '1px solid var(--card-border)',
}}
>
{/* Gift icon */}
<div className="flex justify-center">
<div className="p-4 rounded-full" style={{ backgroundColor: 'rgba(168, 85, 247, 0.1)' }}>
<Gift className="w-10 h-10" style={{ color: 'var(--accent)' }} />
</div>
</div>
{/* Title */}
<h1 className="text-2xl font-bold" style={{ color: 'var(--text)' }}>
{t('interstitialTitle')}
</h1>
{/* Referrer name */}
{data.display_name && (
<p className="text-lg" style={{ color: 'var(--text-muted)' }}>
{t('interstitialReferred', { name: data.display_name })}
</p>
)}
{/* Custom message */}
{data.custom_message && (
<blockquote
className="italic border-l-4 pl-4 py-2 text-left"
style={{
color: 'var(--text-muted)',
borderColor: 'var(--accent)',
}}
>
&ldquo;{data.custom_message}&rdquo;
</blockquote>
)}
{/* Discount badge */}
<div
className="rounded-xl px-6 py-4"
style={{ backgroundColor: 'rgba(168, 85, 247, 0.1)' }}
>
<p className="font-semibold text-lg" style={{ color: 'var(--accent)' }}>
{t('interstitialDiscount', {
percent: data.discount_percent,
days: data.discount_duration_days,
})}
</p>
</div>
{/* CTA */}
<button
onClick={() => router.push('/')}
className="w-full py-4 px-6 rounded-xl font-semibold text-lg flex items-center justify-center gap-2 transition-all hover:scale-[1.02] active:scale-[0.98]"
style={{
backgroundColor: 'var(--accent)',
color: 'white',
}}
>
{t('interstitialCta')}
<ArrowRight className="w-5 h-5" />
</button>
</div>
</div>
);
}
+14
View File
@@ -0,0 +1,14 @@
import { Suspense } from 'react';
import { ReferralInterstitialClient } from './client';
export default function ReferralInterstitialPage() {
return (
<Suspense fallback={
<div className="min-h-screen flex items-center justify-center" style={{ background: 'var(--bg)' }}>
<div className="animate-spin rounded-full h-8 w-8 border-b-2" style={{ borderColor: 'var(--accent)' }} />
</div>
}>
<ReferralInterstitialClient />
</Suspense>
);
}
+2
View File
@@ -51,6 +51,8 @@ function AdminBreadcrumb() {
}
} else if (segments[1] === "payments") {
breadcrumbs.push({ label: "Payments" })
} else if (segments[1] === "referrals") {
breadcrumbs.push({ label: "Referrals" })
} else if (segments[1] === "searches") {
breadcrumbs.push({ label: "Audio Searches" })
} else if (segments[1] === "payments") {
+393
View File
@@ -0,0 +1,393 @@
"use client"
import { useEffect, useState, useCallback } from "react"
import { adminApi } from "@/lib/api"
import type { ReferralLink } from "@/lib/types"
import { StatsCard, StatsGrid } from "@/components/admin/stats-card"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Skeleton } from "@/components/ui/skeleton"
import {
Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table"
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogDescription,
} from "@/components/ui/dialog"
import {
Share2, Link as LinkIcon, Users, MousePointerClick, DollarSign,
Plus, Copy, Check, RefreshCw, Loader2, ToggleLeft, ToggleRight,
} from "lucide-react"
function formatCents(cents: number): string {
return `$${(cents / 100).toFixed(2)}`
}
// Extend ReferralLink with owner_email from admin endpoint
interface AdminReferralLink extends ReferralLink {
owner_email?: string;
}
export default function ReferralsPage() {
const [links, setLinks] = useState<AdminReferralLink[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [copiedCode, setCopiedCode] = useState<string | null>(null)
const [togglingCode, setTogglingCode] = useState<string | null>(null)
const [createOpen, setCreateOpen] = useState(false)
const [creating, setCreating] = useState(false)
const [createError, setCreateError] = useState<string | null>(null)
// Create form state
const [formCode, setFormCode] = useState("")
const [formEmail, setFormEmail] = useState("")
const [formDisplayName, setFormDisplayName] = useState("")
const [formMessage, setFormMessage] = useState("")
const [formDiscount, setFormDiscount] = useState("10")
const [formKickback, setFormKickback] = useState("20")
const loadData = useCallback(async () => {
setLoading(true)
setError(null)
try {
const result = await adminApi.listReferralLinks({ limit: 200 })
setLinks(result.links as AdminReferralLink[])
} catch (err) {
console.error("Failed to load referral links:", err)
setError(err instanceof Error ? err.message : "Failed to load referral links")
} finally {
setLoading(false)
}
}, [])
useEffect(() => { loadData() }, [loadData])
// Aggregate stats
const totalLinks = links.length
const totalClicks = links.reduce((sum, l) => sum + (l.stats?.clicks ?? 0), 0)
const totalSignups = links.reduce((sum, l) => sum + (l.stats?.signups ?? 0), 0)
const totalEarned = links.reduce((sum, l) => sum + (l.stats?.total_earned_cents ?? 0), 0)
const handleCopy = async (code: string) => {
try {
await navigator.clipboard.writeText(`https://nomadkaraoke.com/r/${code}`)
setCopiedCode(code)
setTimeout(() => setCopiedCode(null), 2000)
} catch {
// Fallback for non-secure contexts
}
}
const handleToggle = async (link: AdminReferralLink) => {
setTogglingCode(link.code)
try {
await adminApi.updateReferralLink(link.code, { enabled: !link.enabled })
await loadData()
} catch (err) {
console.error("Failed to toggle link:", err)
} finally {
setTogglingCode(null)
}
}
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault()
setCreating(true)
setCreateError(null)
try {
await adminApi.createVanityLink({
vanity_code: formCode,
owner_email: formEmail,
display_name: formDisplayName || undefined,
custom_message: formMessage || undefined,
discount_percent: Number(formDiscount) || 10,
kickback_percent: Number(formKickback) || 20,
})
setCreateOpen(false)
resetForm()
await loadData()
} catch (err) {
console.error("Failed to create vanity link:", err)
setCreateError(err instanceof Error ? err.message : "Failed to create link")
} finally {
setCreating(false)
}
}
const resetForm = () => {
setFormCode("")
setFormEmail("")
setFormDisplayName("")
setFormMessage("")
setFormDiscount("10")
setFormKickback("20")
setCreateError(null)
}
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight">Referrals</h1>
<p className="text-muted-foreground">Manage referral links, track performance, and create vanity codes</p>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" onClick={loadData} disabled={loading}>
<RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} />
Refresh
</Button>
<Dialog open={createOpen} onOpenChange={(open) => { setCreateOpen(open); if (!open) resetForm() }}>
<DialogTrigger asChild>
<Button size="sm">
<Plus className="w-4 h-4 mr-2" />
Create Vanity Link
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create Vanity Link</DialogTitle>
<DialogDescription>
Create a custom referral link with a memorable code.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleCreate} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="code">Code *</Label>
<Input
id="code"
placeholder="e.g. john, divebar"
value={formCode}
onChange={(e) => setFormCode(e.target.value)}
required
/>
<p className="text-xs text-muted-foreground">
URL will be: nomadkaraoke.com/r/{formCode || "..."}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="email">Owner Email *</Label>
<Input
id="email"
type="email"
placeholder="owner@example.com"
value={formEmail}
onChange={(e) => setFormEmail(e.target.value)}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="displayName">Display Name</Label>
<Input
id="displayName"
placeholder="e.g. John's Karaoke"
value={formDisplayName}
onChange={(e) => setFormDisplayName(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="message">Custom Message</Label>
<Input
id="message"
placeholder="Welcome message for referred users"
value={formMessage}
onChange={(e) => setFormMessage(e.target.value)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="discount">Discount %</Label>
<Input
id="discount"
type="number"
min="0"
max="100"
value={formDiscount}
onChange={(e) => setFormDiscount(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="kickback">Kickback %</Label>
<Input
id="kickback"
type="number"
min="0"
max="100"
value={formKickback}
onChange={(e) => setFormKickback(e.target.value)}
/>
</div>
</div>
{createError && (
<p className="text-sm text-destructive">{createError}</p>
)}
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={() => setCreateOpen(false)}>
Cancel
</Button>
<Button type="submit" disabled={creating || !formCode || !formEmail}>
{creating && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Create Link
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</div>
</div>
{/* Stats */}
<StatsGrid>
<StatsCard
title="Total Links"
value={totalLinks}
description={`${links.filter(l => l.enabled).length} active`}
icon={LinkIcon}
loading={loading}
/>
<StatsCard
title="Total Clicks"
value={totalClicks.toLocaleString()}
description="Across all links"
icon={MousePointerClick}
loading={loading}
/>
<StatsCard
title="Total Signups"
value={totalSignups.toLocaleString()}
description="From referrals"
icon={Users}
loading={loading}
/>
<StatsCard
title="Total Earned"
value={formatCents(totalEarned)}
description="Kickback earnings"
icon={DollarSign}
loading={loading}
valueClassName="text-green-600 dark:text-green-400"
/>
</StatsGrid>
{/* Error State */}
{error && (
<Card>
<CardContent className="py-8 text-center">
<p className="text-destructive">{error}</p>
<Button variant="outline" size="sm" className="mt-4" onClick={loadData}>
Try Again
</Button>
</CardContent>
</Card>
)}
{/* Links Table */}
<Card>
<CardHeader>
<CardTitle className="text-base">Referral Links</CardTitle>
</CardHeader>
<CardContent>
<div className="rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Code</TableHead>
<TableHead>Owner</TableHead>
<TableHead>Display Name</TableHead>
<TableHead className="text-center">Discount / Kickback</TableHead>
<TableHead className="text-right">Clicks</TableHead>
<TableHead className="text-right">Signups</TableHead>
<TableHead className="text-right">Purchases</TableHead>
<TableHead className="text-right">Earned</TableHead>
<TableHead>Status</TableHead>
<TableHead className="w-[80px]">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
Array.from({ length: 5 }).map((_, i) => (
<TableRow key={i}>
{Array.from({ length: 10 }).map((_, j) => (
<TableCell key={j}><Skeleton className="h-4 w-16" /></TableCell>
))}
</TableRow>
))
) : links.length === 0 ? (
<TableRow>
<TableCell colSpan={10} className="text-center py-8 text-muted-foreground">
No referral links found
</TableCell>
</TableRow>
) : (
links.map((link) => (
<TableRow key={link.code}>
<TableCell>
<div className="flex items-center gap-1">
<code className="text-sm font-mono bg-muted px-1.5 py-0.5 rounded">
{link.code}
</code>
<Button
variant="ghost"
size="icon"
className="h-6 w-6"
onClick={() => handleCopy(link.code)}
title="Copy referral URL"
>
{copiedCode === link.code ? (
<Check className="h-3 w-3 text-green-500" />
) : (
<Copy className="h-3 w-3" />
)}
</Button>
</div>
</TableCell>
<TableCell className="text-sm max-w-[160px] truncate">
{link.owner_email || "-"}
</TableCell>
<TableCell className="text-sm max-w-[140px] truncate">
{link.display_name || "-"}
</TableCell>
<TableCell className="text-center text-sm">
{link.discount_percent}% / {link.kickback_percent}%
</TableCell>
<TableCell className="text-right text-sm">{link.stats?.clicks ?? 0}</TableCell>
<TableCell className="text-right text-sm">{link.stats?.signups ?? 0}</TableCell>
<TableCell className="text-right text-sm">{link.stats?.purchases ?? 0}</TableCell>
<TableCell className="text-right text-sm font-medium">
{formatCents(link.stats?.total_earned_cents ?? 0)}
</TableCell>
<TableCell>
<Badge variant={link.enabled ? "default" : "secondary"}>
{link.enabled ? "Enabled" : "Disabled"}
</Badge>
</TableCell>
<TableCell>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => handleToggle(link)}
disabled={togglingCode === link.code}
title={link.enabled ? "Disable link" : "Enable link"}
>
{togglingCode === link.code ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : link.enabled ? (
<ToggleRight className="h-4 w-4 text-green-500" />
) : (
<ToggleLeft className="h-4 w-4 text-muted-foreground" />
)}
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
</div>
)
}
+23
View File
@@ -0,0 +1,23 @@
'use client';
import { useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { getReferralCode, setReferralCode } from '@/lib/referral';
/**
* Captures ?ref=CODE query param and stores it as a referral cookie.
* This is the secondary capture mechanism — the primary is the /r/CODE
* interstitial page which stores the code before redirecting here.
*/
export function ReferralCapture() {
const searchParams = useSearchParams();
useEffect(() => {
const ref = searchParams.get('ref');
if (ref && !getReferralCode()) {
setReferralCode(ref);
}
}, [searchParams]);
return null;
}
@@ -15,6 +15,7 @@ import {
Scissors,
Fingerprint,
MessageSquare,
Share2,
} from "lucide-react"
import {
@@ -52,6 +53,11 @@ const navItems = [
href: "/admin/payments",
icon: DollarSign,
},
{
title: "Referrals",
href: "/admin/referrals",
icon: Share2,
},
{
title: "Audio Searches",
href: "/admin/searches",
+3 -3
View File
@@ -2,7 +2,7 @@
import { useState, useEffect } from "react"
import { User, LogOut, CreditCard, Coins, KeyRound, Shield, FlaskConical, Gift } from "lucide-react"
import { Link } from "@/i18n/routing"
import NextLink from "next/link"
import { Button } from "@/components/ui/button"
import {
DropdownMenu,
@@ -124,10 +124,10 @@ export function AuthStatus({ onAuthChange }: AuthStatusProps) {
<>
<DropdownMenuSeparator className="bg-border" />
<DropdownMenuItem asChild className="text-muted-foreground focus:text-foreground focus:bg-secondary">
<Link href="/admin">
<NextLink href="/admin">
<Shield className="w-4 h-4 mr-2" />
<span>{tHeader('adminDashboard')}</span>
</Link>
</NextLink>
</DropdownMenuItem>
<DropdownMenuItem
onSelect={(e) => e.preventDefault()}
@@ -20,6 +20,7 @@ const pricePerVideo = (pkg: CreditPackage) =>
export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
const t = useTranslations('credits')
const tCommon = useTranslations('common')
const tRef = useTranslations('referrals')
const { user } = useAuth()
const [packages, setPackages] = useState<CreditPackage[]>([])
const [selectedPackage, setSelectedPackage] = useState<CreditPackage | null>(null)
@@ -71,6 +72,14 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
</DialogHeader>
<div className="space-y-4 mt-2">
{user?.has_active_referral_discount && (
<div className="bg-green-500/10 border border-green-500/20 rounded-lg p-3 text-center">
<p className="text-green-600 dark:text-green-400 text-sm font-medium">
{tRef('discountBadge', { percent: 10 })}
</p>
</div>
)}
{loading && (
<div className="flex justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
@@ -0,0 +1,213 @@
'use client';
import { useEffect, useState, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import {
getReferralDashboard,
updateReferralLink,
startConnectOnboarding,
} from '@/lib/api';
import type { ReferralDashboard as ReferralDashboardData } from '@/lib/types';
function formatCents(cents: number): string {
return `$${(cents / 100).toFixed(2)}`;
}
export default function ReferralDashboard() {
const t = useTranslations('referrals');
const [data, setData] = useState<ReferralDashboardData | null>(null);
const [loading, setLoading] = useState(true);
const [copied, setCopied] = useState(false);
const [editing, setEditing] = useState(false);
const [displayName, setDisplayName] = useState('');
const [customMessage, setCustomMessage] = useState('');
const fetchDashboard = useCallback(async () => {
try {
const result = await getReferralDashboard();
setData(result);
setDisplayName(result.link.display_name || '');
setCustomMessage(result.link.custom_message || '');
} catch (err) {
console.error('Failed to load referral dashboard:', err);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchDashboard();
}, [fetchDashboard]);
const copyLink = () => {
if (!data) return;
const url = `${window.location.origin}/r/${data.link.code}`;
navigator.clipboard.writeText(url);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const saveProfile = async () => {
try {
await updateReferralLink({ display_name: displayName, custom_message: customMessage });
setEditing(false);
fetchDashboard();
} catch (err) {
console.error('Failed to save:', err);
}
};
const handleConnectBank = async () => {
try {
const { onboarding_url } = await startConnectOnboarding();
window.location.href = onboarding_url;
} catch (err) {
console.error('Failed to start Connect onboarding:', err);
}
};
if (loading) {
return <div className="animate-pulse space-y-4 p-4">
<div className="h-8 bg-muted rounded w-1/3" />
<div className="h-24 bg-muted rounded" />
</div>;
}
if (!data) return null;
return (
<div className="space-y-6 p-4">
<h2 className="text-xl font-bold">{t('title')}</h2>
{/* Referral Link */}
<div className="rounded-lg p-4 space-y-3" style={{ backgroundColor: 'var(--card)', borderColor: 'var(--card-border)', border: '1px solid' }}>
<h3 className="font-semibold">{t('yourLink')}</h3>
<div className="flex gap-2">
<input
readOnly
value={`${typeof window !== 'undefined' ? window.location.origin : ''}/r/${data.link.code}`}
className="flex-1 rounded px-3 py-2 text-sm font-mono"
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text)' }}
/>
<button onClick={copyLink} className="px-4 py-2 bg-primary text-primary-foreground rounded text-sm">
{copied ? t('copied') : t('copyLink')}
</button>
</div>
{editing ? (
<div className="space-y-2">
<input
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
placeholder={t('displayName')}
className="w-full rounded px-3 py-2 text-sm"
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text)' }}
/>
<textarea
value={customMessage}
onChange={(e) => setCustomMessage(e.target.value.slice(0, 200))}
placeholder={t('customMessagePlaceholder')}
rows={3}
className="w-full rounded px-3 py-2 text-sm"
style={{ backgroundColor: 'var(--secondary)', color: 'var(--text)' }}
/>
<div className="flex gap-2">
<button onClick={saveProfile} className="px-4 py-2 bg-primary text-primary-foreground rounded text-sm">
{t('save')}
</button>
<button onClick={() => setEditing(false)} className="px-4 py-2 rounded text-sm" style={{ backgroundColor: 'var(--secondary)' }}>
{t('cancel')}
</button>
</div>
</div>
) : (
<button onClick={() => setEditing(true)} className="text-sm text-primary hover:underline">
{t('editProfile')}
</button>
)}
</div>
{/* Stats */}
<div className="rounded-lg p-4" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
<h3 className="font-semibold mb-3">{t('stats')}</h3>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div>
<p className="text-2xl font-bold">{data.link.stats.clicks}</p>
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('clicks')}</p>
</div>
<div>
<p className="text-2xl font-bold">{data.link.stats.signups}</p>
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('signups')}</p>
</div>
<div>
<p className="text-2xl font-bold">{data.link.stats.purchases}</p>
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('purchases')}</p>
</div>
<div>
<p className="text-2xl font-bold">{formatCents(data.total_earned_cents)}</p>
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('totalEarned')}</p>
</div>
</div>
</div>
{/* Payout section */}
<div className="rounded-lg p-4 space-y-3" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
<div className="flex justify-between items-center">
<h3 className="font-semibold">{t('earnings')}</h3>
<div className="text-right">
<p className="text-lg font-bold">{formatCents(data.pending_balance_cents)}</p>
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('pendingBalance')}</p>
</div>
</div>
{!data.stripe_connect_configured ? (
<div className="rounded-lg p-4 space-y-2" style={{ backgroundColor: 'var(--secondary)' }}>
<p className="text-sm">{t('connectDescription')}</p>
<button onClick={handleConnectBank} className="px-4 py-2 bg-primary text-primary-foreground rounded text-sm">
{t('connectBank')}
</button>
</div>
) : (
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('payoutThreshold')}</p>
)}
</div>
{/* Recent earnings */}
<div className="rounded-lg p-4" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
<h3 className="font-semibold mb-3">{t('recentEarnings')}</h3>
{data.recent_earnings.length === 0 ? (
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>{t('noEarnings')}</p>
) : (
<div className="space-y-2">
{data.recent_earnings.map((e) => (
<div key={e.id} className="flex justify-between text-sm">
<span style={{ color: 'var(--text-muted)' }}>{e.referred_email}</span>
<span className="font-mono">
{formatCents(e.earning_amount_cents)}
<span className={`ml-2 text-xs ${e.status === 'paid' ? 'text-green-500' : 'text-yellow-500'}`}>
{e.status}
</span>
</span>
</div>
))}
</div>
)}
</div>
{/* Recent payouts */}
{data.recent_payouts.length > 0 && (
<div className="rounded-lg p-4" style={{ backgroundColor: 'var(--card)', border: '1px solid var(--card-border)' }}>
<h3 className="font-semibold mb-3">{t('recentPayouts')}</h3>
<div className="space-y-2">
{data.recent_payouts.map((p) => (
<div key={p.id} className="flex justify-between text-sm">
<span style={{ color: 'var(--text-muted)' }}>{new Date(p.created_at).toLocaleDateString()}</span>
<span className="font-mono">{formatCents(p.amount_cents)}</span>
</div>
))}
</div>
</div>
)}
</div>
);
}
+81 -2
View File
@@ -3,7 +3,7 @@
*/
import type { VideoThemeSummary, VideoThemeDetail, ThemesListResponse, ThemeDetailResponse, ColorOverrides } from './video-themes';
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse } from './types';
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse, ReferralInterstitial, ReferralDashboard, ReferralLink } from './types';
import type { CorrectionData, CorrectionAnnotation, EditLog, SearchLyricsResponse } from './lyrics-review/types';
// In development, use relative URLs to go through Next.js proxy (avoids CORS)
@@ -1291,9 +1291,14 @@ export const api = {
/**
* Verify a magic link token and get a session
*/
async verifyMagicLink(token: string): Promise<VerifyMagicLinkResponse> {
async verifyMagicLink(token: string, referralCode?: string | null): Promise<VerifyMagicLinkResponse> {
const headers: HeadersInit = {};
if (referralCode) {
headers['x-referral-code'] = referralCode;
}
const response = await fetch(`${API_BASE_URL}/api/users/auth/verify?token=${encodeURIComponent(token)}`, {
method: 'GET',
headers,
});
return handleResponse(response);
},
@@ -2510,6 +2515,41 @@ export const adminApi = {
});
return handleResponse(response);
},
// Referral Management
async listReferralLinks(params?: { limit?: number; offset?: number }): Promise<{ links: ReferralLink[]; count: number }> {
const searchParams = new URLSearchParams();
if (params?.limit) searchParams.set('limit', String(params.limit));
if (params?.offset) searchParams.set('offset', String(params.offset));
const url = `${API_BASE_URL}/api/referrals/admin/links${searchParams.toString() ? '?' + searchParams.toString() : ''}`;
const response = await fetch(url, { headers: getAuthHeaders() });
return handleResponse(response);
},
async createVanityLink(data: {
vanity_code: string;
owner_email: string;
display_name?: string;
custom_message?: string;
discount_percent?: number;
kickback_percent?: number;
}): Promise<{ ok: boolean; code: string; message: string }> {
const response = await fetch(`${API_BASE_URL}/api/referrals/admin/vanity`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
return handleResponse(response);
},
async updateReferralLink(code: string, updates: Record<string, any>): Promise<{ ok: boolean; message: string }> {
const response = await fetch(`${API_BASE_URL}/api/referrals/admin/links/${encodeURIComponent(code)}`, {
method: 'PUT',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(updates),
});
return handleResponse(response);
},
};
export interface EditReviewSummary {
@@ -3468,3 +3508,42 @@ export interface AdminFeedbackListResponse {
export { ApiError };
// ============================================================================
// Referral API
// ============================================================================
export async function getReferralInterstitial(code: string): Promise<ReferralInterstitial> {
const response = await fetch(`${API_BASE_URL}/api/referrals/r/${encodeURIComponent(code)}`);
if (!response.ok) throw new Error('Failed to fetch referral info');
return response.json();
}
export async function getReferralDashboard(): Promise<ReferralDashboard> {
const response = await fetch(`${API_BASE_URL}/api/referrals/me`, {
headers: getAuthHeaders(),
});
if (!response.ok) throw new Error('Failed to fetch referral dashboard');
return response.json();
}
export async function updateReferralLink(updates: {
display_name?: string;
custom_message?: string;
}): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/referrals/me`, {
method: 'PUT',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(updates),
});
if (!response.ok) throw new Error('Failed to update referral link');
}
export async function startConnectOnboarding(): Promise<{ account_id: string; onboarding_url: string }> {
const response = await fetch(`${API_BASE_URL}/api/referrals/me/connect`, {
method: 'POST',
headers: getAuthHeaders(),
});
if (!response.ok) throw new Error('Failed to start Connect onboarding');
return response.json();
}
+6 -1
View File
@@ -4,6 +4,7 @@ import { create } from "zustand"
import { persist } from "zustand/middleware"
import type { User, UserPublic } from "./types"
import { api, adminApi, setAccessToken, clearAccessToken, getAccessToken } from "./api"
import { getReferralCode, clearReferralCode } from './referral'
interface AuthStore {
user: User | null
@@ -71,11 +72,15 @@ export const useAuth = create<AuthStore>()(
verifyMagicLink: async (token: string) => {
set({ isLoading: true, error: null })
try {
const response = await api.verifyMagicLink(token)
const referralCode = getReferralCode();
const response = await api.verifyMagicLink(token, referralCode)
// Store the session token
setAccessToken(response.session_token)
// Clear referral code after successful verification
clearReferralCode();
// Store verify response data for cross-domain redirect and welcome credits
if (typeof window !== 'undefined') {
(window as any).__LAST_VERIFY_RESPONSE__ = {
+27
View File
@@ -0,0 +1,27 @@
/**
* Referral code storage — cookie + localStorage for resilience.
*/
const REFERRAL_COOKIE_NAME = 'nk_ref';
const REFERRAL_STORAGE_KEY = 'nk_referral_code';
const COOKIE_MAX_AGE_DAYS = 30;
export function setReferralCode(code: string): void {
if (typeof window === 'undefined') return;
const maxAge = COOKIE_MAX_AGE_DAYS * 24 * 60 * 60;
document.cookie = `${REFERRAL_COOKIE_NAME}=${encodeURIComponent(code)};path=/;max-age=${maxAge};samesite=lax`;
localStorage.setItem(REFERRAL_STORAGE_KEY, code);
}
export function getReferralCode(): string | null {
if (typeof window === 'undefined') return null;
const match = document.cookie.match(new RegExp(`(?:^|; )${REFERRAL_COOKIE_NAME}=([^;]*)`));
if (match) return decodeURIComponent(match[1]);
return localStorage.getItem(REFERRAL_STORAGE_KEY);
}
export function clearReferralCode(): void {
if (typeof window === 'undefined') return;
document.cookie = `${REFERRAL_COOKIE_NAME}=;path=/;max-age=0`;
localStorage.removeItem(REFERRAL_STORAGE_KEY);
}
+59
View File
@@ -9,6 +9,7 @@ export interface User {
total_jobs_created?: number
total_jobs_completed?: number
feedback_eligible?: boolean
has_active_referral_discount?: boolean
}
export interface UserPublic {
@@ -19,6 +20,8 @@ export interface UserPublic {
total_jobs_created?: number
total_jobs_completed?: number
feedback_eligible?: boolean
referral_code?: string
has_active_referral_discount?: boolean
}
export interface MagicLinkResponse {
@@ -66,3 +69,59 @@ export interface JobStage {
progress: number
message?: string
}
// Referral system types
export interface ReferralLinkStats {
clicks: number;
signups: number;
purchases: number;
total_earned_cents: number;
}
export interface ReferralLink {
code: string;
display_name: string | null;
custom_message: string | null;
discount_percent: number;
kickback_percent: number;
discount_duration_days: number;
earning_duration_days: number;
stats: ReferralLinkStats;
enabled: boolean;
is_vanity: boolean;
}
export interface ReferralEarning {
id: string;
referred_email: string;
purchase_amount_cents: number;
earning_amount_cents: number;
status: 'pending' | 'paid' | 'refunded';
created_at: string;
}
export interface ReferralPayout {
id: string;
amount_cents: number;
status: 'processing' | 'completed' | 'failed';
created_at: string;
}
export interface ReferralDashboard {
link: ReferralLink;
pending_balance_cents: number;
total_earned_cents: number;
total_paid_cents: number;
recent_earnings: ReferralEarning[];
recent_payouts: ReferralPayout[];
stripe_connect_configured: boolean;
}
export interface ReferralInterstitial {
code: string;
display_name: string | null;
custom_message: string | null;
discount_percent: number;
discount_duration_days: number;
valid: boolean;
}
+36 -1
View File
@@ -231,7 +231,8 @@
"jobsCount": "{count} {count, plural, one {job} other {jobs}}",
"loadingJobs": "Loading jobs...",
"noJobsMatchFilters": "No jobs match your filters.",
"noJobsYet": "No jobs yet. Create one to get started!"
"noJobsYet": "No jobs yet. Create one to get started!",
"referrals": "Referrals"
},
"auth": {
"noVerificationToken": "No verification token provided",
@@ -1222,5 +1223,39 @@
"noBackingDetected": "No backing vocals detected — clean instrumental recommended.",
"addToMuteRegions": "Add to mute regions"
}
},
"referrals": {
"title": "Referrals",
"yourLink": "Your Referral Link",
"copyLink": "Copy Link",
"copied": "Copied!",
"displayName": "Display Name",
"customMessage": "Custom Message",
"customMessagePlaceholder": "Tell your friends why they should try Nomad Karaoke...",
"save": "Save",
"stats": "Stats",
"clicks": "Clicks",
"signups": "Signups",
"purchases": "Purchases",
"earnings": "Earnings",
"pendingBalance": "Pending Balance",
"totalEarned": "Total Earned",
"totalPaid": "Total Paid Out",
"recentEarnings": "Recent Earnings",
"recentPayouts": "Recent Payouts",
"noEarnings": "No earnings yet. Share your link to start earning!",
"noPayouts": "No payouts yet.",
"connectBank": "Connect Bank Account",
"connectDescription": "Connect your bank account via Stripe to receive referral payouts when your balance reaches $20.",
"connectComplete": "Bank account connected!",
"payoutThreshold": "Payouts are automatically sent when your balance reaches $20.",
"interstitialTitle": "You've been referred!",
"interstitialReferred": "Referred by {name}",
"interstitialDiscount": "Enjoy {percent}% off all credit purchases for {days} days",
"interstitialCta": "Get Started",
"discountBadge": "{percent}% referral discount",
"discountActive": "Referral discount active — {percent}% off for {days} more days",
"cancel": "Cancel",
"editProfile": "Edit display name & message"
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.162.2"
version = "0.163.2"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"