Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 4.6 517dac00c8 fix: f-string backslash syntax error breaking backend deploy
The referral banner HTML in email_service.py used backslash-escaped
quotes inside an f-string expression, which is a SyntaxError in
Python 3.11 (Cloud Run runtime). Extract the HTML to a variable
before the f-string.

This has been blocking all backend deploys since PR #680.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:53:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 30bf8178aa feat(pricing): increase default price per track from $5 to $10 (#683)
## Summary
- Doubles base credit price from $5 to $10 per track
- Scales volume discount tiers proportionally (20%/30%/40% discounts
preserved)
- Updates all 33 i18n locale files, frontend savings calculation, and
E2E test fixtures

## Changes
- **Backend:** `CREDIT_PACKAGES` in `stripe_service.py` — 1cr: $10, 3cr:
$24, 5cr: $35, 10cr: $60
- **Frontend:** Savings calc base in `BuyCreditsDialog.tsx` (500 → 1000)
- **i18n:** `createYourselfPrice` "$5" → "$10" in all 33 locale files
- **Tests:** Updated price fixtures in `landing-page.spec.ts` and
`mobile.spec.ts`

## Testing
- [x] All 710 tests pass (`make test`)
- [x] No new logic — config value change only

## Review
- [x] CodeRabbit CLI review completed locally (no issues with pricing
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-05 19:30:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 54c83e924c feat(referral): QR code generator with customizable styles (#682)
@coderabbitai ignore

## Summary
- Adds a QR code generator dialog to the referral dashboard
(`/app/referrals`)
- Referrers can customize dot style (6 options), corner frame (3),
corner dot (2), foreground/background colors, and center logo (NK logo,
microphone, music note)
- Live preview updates as options change
- Download as PNG or SVG
- Style preferences persist in localStorage

## Changes
- **New:** `frontend/components/referrals/QRCodeDialog.tsx` — QR
generator dialog using `qr-code-styling` library
- **Modified:** `frontend/components/referrals/ReferralDashboard.tsx` —
added QR Code button next to Copy Link
- **New:**
`frontend/components/referrals/__tests__/QRCodeDialog.test.tsx` — 10
unit tests
- **Modified:** `frontend/messages/en.json` — 22 new i18n strings
- **New dep:** `qr-code-styling` (client-side QR generation with style
customization)

## Test plan
- [x] 10 unit tests covering: rendering, style options, localStorage
persistence, download calls
- [x] 720/720 total tests passing
- [x] Next.js build compiles cleanly
- [x] ~70% coverage on new component (uncovered lines are
jsdom-incompatible DOM SVG APIs)
- [ ] Manual: open referral dashboard, click QR button, customize
styles, download PNG/SVG

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 19:17:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 817f2aa1bd feat(admin): add Apply Discount to user detail page (#681)
## Summary

Admins can apply a referral discount to any user from the user detail
page — useful for grandfathering existing users when raising prices.

## Changes

### Backend
- New endpoint: `POST /api/referrals/admin/apply-discount` — sets
discount %, duration, and referral code on any user
- `UserDetailResponse` now includes `referred_by_code`,
`referral_discount_expires_at`, `referral_code`

### Frontend
- "Apply Discount" button on user detail page (next to Add Credits)
- Dialog with discount %, duration (days), and referral code inputs
- Current discount status shown on user detail page if active

## Usage
- Go to Admin → Users → click a user → "Apply Discount"
- Set 50% off for 3650 days with code "loyalty" to grandfather a user

@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 19:03:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 607c52bed3 feat(referral): embed referral code in magic link for cross-device attribution (#680)
## Summary

Referral attribution was failing because it relied solely on a browser
cookie. If the user opened the magic link email on a different device or
browser, the cookie wasn't there and attribution was lost.

## Fix: Triple-redundant referral code delivery

The referral code now travels through three independent paths:

1. **Cookie** (`x-referral-code` header) — same device, same browser
2. **Firestore** (magic link token doc) — stored server-side when magic
link is sent
3. **URL param** (`&ref=CODE` on the magic link) — travels with the
email itself

On verification, the backend checks all three and uses the first one
found.

## Changes

### Backend
- `SendMagicLinkRequest` + `MagicLinkToken` models: added
`referral_code` field
- `user_service.create_magic_link()`: accepts and stores referral_code
- `email_service.send_magic_link()`: appends `&ref=CODE` to URL, adds
discount banner to email
- `verify_magic_link`: reads referral code from header OR token doc OR
URL param

### Frontend
- `api.sendMagicLink()`: passes referral_code in request body
- Auth store `sendMagicLink`: reads referral cookie and passes it
- Verify page: reads `?ref=CODE` from magic link URL and stores cookie
before verification

## Testing
- 2952 backend tests pass
- Frontend build passes

@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 17:22:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3f00b08fb7 fix(referral): show display name on interstitial page (#679)
## Summary

The interstitial page wasn't showing the affiliate's display name
because of a field name mismatch — frontend type had `display_name` but
the API returns `referrer_display_name`.

## Changes

- `frontend/lib/types.ts` — `ReferralInterstitial.display_name` →
`referrer_display_name`, `code` → `referral_code`
- `frontend/app/[locale]/r/client.tsx` — Updated references to use
`data.referrer_display_name`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 16:44:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 af50b53cd8 feat(admin): add edit dialog for referral links (#678)
## Summary

Adds a pencil icon button on each row in the admin referrals table that
opens an edit dialog to modify display name, custom message, discount %,
and kickback %.

## Changes

- `frontend/app/admin/referrals/page.tsx` — Edit button + dialog with
form fields, uses existing `adminApi.updateReferralLink` endpoint

@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 16:29:49 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1cd747f170 fix(referral): compute and display referral discount status for users (#677)
## Summary

Three referral UX fixes:

1. **Discount visibility** — Backend now computes
`has_active_referral_discount` and returns discount details (percent,
expiry, referral code) in all UserPublic responses. Dashboard shows a
purple banner with discount info. Buy Credits dialog shows actual
percent + expiry.

2. **Existing user attribution** — Removed the `is_first_login` gate.
Any user who logs in with a referral code cookie and hasn't been
referred yet gets the referral attributed. This means existing users who
click a referral link will get the discount.

3. **Interstitial email signup** — Replaced the "Get Started" redirect
with an inline email input form. Users enter their email directly on the
interstitial page to receive a magic link. Shows "Check your email"
confirmation after sending. Already-logged-in users see a "Go to App"
CTA instead.

## Changes

### Backend
- `backend/api/routes/users.py` — New `_build_user_public()` helper
computes discount status. Attribution gate changed from `is_first_login`
to `not user.referred_by_code`.
- `backend/models/user.py` — Added `referral_discount_percent`,
`referral_discount_expires_at`, `referred_by_code` to UserPublic

### Frontend
- `frontend/app/[locale]/r/client.tsx` — Full rewrite: email signup form
with magic link, three states (form/sent/logged-in)
- `frontend/app/[locale]/app/page.tsx` — Referral discount banner on
dashboard
- `frontend/components/credits/BuyCreditsDialog.tsx` — Actual discount
percent + expiry date
- `frontend/lib/auth.ts` — Pass through referral fields
- `frontend/lib/types.ts` — New referral type fields

@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 16:22:58 -04:00
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
76 changed files with 8759 additions and 85 deletions

No files matched your search

+233
View File
@@ -0,0 +1,233 @@
"""
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, Request
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.post("/admin/apply-discount")
async def admin_apply_discount(
request: Request,
auth=Depends(require_admin),
):
"""Admin: apply a referral discount to any user, even without a referral link."""
from backend.services.user_service import get_user_service
body = await request.json()
user_email = body.get("email", "").lower()
discount_percent = body.get("discount_percent", 10)
duration_days = body.get("duration_days", 30)
referral_code = body.get("referral_code", "admin-grant")
if not user_email:
raise HTTPException(status_code=400, detail="Email is required")
user_service = get_user_service()
user = user_service.get_user(user_email)
if not user:
raise HTTPException(status_code=404, detail="User not found")
from datetime import datetime, timedelta
now = datetime.utcnow()
user_service.update_user(
user_email,
referred_by_code=referral_code,
referred_at=now,
referral_discount_expires_at=now + timedelta(days=duration_days),
)
# Create/ensure the Stripe coupon exists for this discount percent
service = get_referral_service()
service.get_or_create_stripe_coupon(discount_percent)
logger.info(f"Admin applied {discount_percent}% discount for {duration_days} days to {user_email}")
return {
"ok": True,
"message": f"Applied {discount_percent}% discount for {duration_days} days",
"discount_expires_at": (now + timedelta(days=duration_days)).isoformat(),
}
@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}
+113 -25
View File
@@ -64,6 +64,52 @@ from backend.services.auth_service import AuthResult
from backend.api.routes.file_upload import _prepare_theme_for_job
from backend.services.auth_service import UserType
from backend.utils.test_data import is_test_email
def _build_user_public(user, role_override=None, feedback_eligible=False):
"""Build UserPublic with computed referral discount status."""
from datetime import datetime
has_discount = False
discount_percent = None
discount_expires = None
if user.referral_discount_expires_at:
expires = user.referral_discount_expires_at
if isinstance(expires, datetime):
# Firestore returns timezone-aware datetimes; ensure comparison is compatible
now = datetime.utcnow()
if expires.tzinfo is not None:
now = now.replace(tzinfo=expires.tzinfo)
has_discount = expires > now
discount_expires = expires.isoformat() if has_discount else None
if has_discount and user.referred_by_code:
# Look up the discount percent from the referral link
try:
from backend.services.referral_service import get_referral_service
link = get_referral_service().get_link_by_code(user.referred_by_code)
if link:
discount_percent = link.discount_percent
except Exception:
discount_percent = 10 # default fallback
return UserPublic(
email=user.email,
role=role_override or user.role,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
tenant_id=getattr(user, 'tenant_id', None),
feedback_eligible=feedback_eligible,
total_spent=getattr(user, 'total_spent', 0),
referral_code=user.referral_code,
has_active_referral_discount=has_discount,
referral_discount_percent=discount_percent,
referral_discount_expires_at=discount_expires,
referred_by_code=user.referred_by_code,
)
from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
@@ -255,6 +301,7 @@ async def send_magic_link(
user_agent=user_agent,
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
referral_code=request.referral_code,
)
# Get tenant-specific email configuration
@@ -274,6 +321,7 @@ async def send_magic_link(
tenant_frontend_url=tenant_frontend_url,
tenant_name=tenant_name,
locale=locale,
referral_code=request.referral_code,
)
if not sent:
@@ -365,6 +413,28 @@ async def verify_magic_link(
elif credit_status == "denied":
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
# Referral attribution: try header first (cookie path), then magic link token (email path), then URL param
referral_code = (
http_request.headers.get("x-referral-code")
or (magic_link_data.get("referral_code") if magic_link_doc.exists else None)
)
if referral_code and not user.referred_by_code:
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)
user = user_service.get_user(user.email) # Refresh to include referral 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:
@@ -387,15 +457,7 @@ async def verify_magic_link(
email_service.send_welcome_email(user.email, user.credits, locale=locale)
# Return user info with tenant_id
user_public = UserPublic(
email=user.email,
role=user.role,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
tenant_id=user.tenant_id,
)
user_public = _build_user_public(user)
# Resolve tenant subdomain for cross-domain redirect safety
tenant_subdomain = None
@@ -473,13 +535,9 @@ async def get_current_user(
user.total_jobs_completed >= 2
and not user.has_submitted_feedback
)
user_public = UserPublic(
email=user.email,
role=user.role if not auth_result.is_admin else UserRole.ADMIN,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
user_public = _build_user_public(
user,
role_override=UserRole.ADMIN if auth_result.is_admin else None,
feedback_eligible=feedback_eligible,
)
return UserProfileResponse(user=user_public, has_session=True)
@@ -494,15 +552,7 @@ async def get_current_user(
user.total_jobs_completed >= 2
and not user.has_submitted_feedback
)
user_public = UserPublic(
email=user.email,
role=user.role,
credits=user.credits,
display_name=user.display_name,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
feedback_eligible=feedback_eligible,
)
user_public = _build_user_public(user, feedback_eligible=feedback_eligible)
return UserProfileResponse(user=user_public, has_session=True)
@@ -546,9 +596,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 +1079,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}")
@@ -1411,6 +1492,10 @@ class UserDetailResponse(BaseModel):
device_fingerprint: Optional[str] = None
welcome_credits_granted: bool = False
has_submitted_feedback: bool = False
# Referral fields
referred_by_code: Optional[str] = None
referral_discount_expires_at: Optional[str] = None
referral_code: Optional[str] = None
# Recent session details (IP, user agent, fingerprint)
recent_sessions: list[dict] = []
@@ -1606,6 +1691,9 @@ async def get_user_detail(
device_fingerprint=user.device_fingerprint,
welcome_credits_granted=user.welcome_credits_granted,
has_submitted_feedback=user.has_submitted_feedback,
referred_by_code=user.referred_by_code,
referral_discount_expires_at=user.referral_discount_expires_at.isoformat() if user.referral_discount_expires_at and hasattr(user.referral_discount_expires_at, 'isoformat') else str(user.referral_discount_expires_at) if user.referral_discount_expires_at else None,
referral_code=user.referral_code,
recent_sessions=active_sessions,
)
+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
+16
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):
"""
@@ -132,6 +139,9 @@ class MagicLinkToken(BaseModel):
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
# Referral attribution (travels with magic link for cross-device support)
referral_code: Optional[str] = None
# Pre-computed credit evaluation (set asynchronously after magic link is sent)
credit_eval_decision: Optional[str] = None # "grant", "deny", "pending_review"
credit_eval_reasoning: Optional[str] = None
@@ -167,6 +177,7 @@ class SendMagicLinkRequest(BaseModel):
"""Request to send a magic link email."""
email: str
device_fingerprint: Optional[str] = None
referral_code: Optional[str] = None # From referral interstitial
class SendMagicLinkResponse(BaseModel):
@@ -202,6 +213,11 @@ 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
referral_discount_percent: Optional[int] = None
referral_discount_expires_at: Optional[str] = None # ISO string
referred_by_code: Optional[str] = None
created_at: Optional[str] = None
last_login_at: Optional[str] = None
+16
View File
@@ -251,6 +251,7 @@ class EmailService:
tenant_frontend_url: Optional[str] = None,
tenant_name: Optional[str] = None,
locale: str = "en",
referral_code: Optional[str] = None,
) -> bool:
"""
Send a magic link email for authentication.
@@ -267,6 +268,8 @@ class EmailService:
"""
base_url = tenant_frontend_url or self.frontend_url
magic_link_url = f"{base_url}{get_locale_prefix(locale)}/auth/verify?token={token}"
if referral_code:
magic_link_url += f"&ref={referral_code}"
brand_name = tenant_name or "Nomad Karaoke"
subject = t(locale, "emails.magicLink.subject", brand_name=brand_name)
@@ -282,6 +285,17 @@ class EmailService:
}
"""
referral_banner = (
'<div style="background: linear-gradient(135deg, #7c3aed10, #a855f710); '
'border: 1px solid #a855f730; border-radius: 8px; padding: 16px; margin: 16px 0; '
'text-align: center;">'
'<p style="color: #a855f7; font-weight: 600; margin: 0;">&#127873; '
'Your referral discount is waiting!</p>'
'<p style="color: #666; font-size: 14px; margin: 4px 0 0;">'
'Sign in to claim your discount on credit purchases</p></div>'
if referral_code else ""
)
content = f"""
<p>{t(locale, "emails.magicLink.greeting")}</p>
@@ -291,6 +305,8 @@ class EmailService:
<a href="{magic_link_url}" class="button">{t(locale, "emails.magicLink.signInButton")}</a>
</p>
{referral_banner}
<div class="warning">
⏰ {t(locale, "emails.magicLink.expiryWarning")}
</div>
+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
+72 -4
View File
@@ -22,25 +22,25 @@ logger = logging.getLogger(__name__)
CREDIT_PACKAGES = {
"1_credit": {
"credits": 1,
"price_cents": 500, # $5.00
"price_cents": 1000, # $10.00
"name": "1 Karaoke Credit",
"description": "Create 1 professional karaoke video",
},
"3_credits": {
"credits": 3,
"price_cents": 1200, # $12.00 (20% discount)
"price_cents": 2400, # $24.00 (20% discount)
"name": "3 Karaoke Credits",
"description": "Create 3 professional karaoke videos (Save 20%)",
},
"5_credits": {
"credits": 5,
"price_cents": 1750, # $17.50 (30% discount)
"price_cents": 3500, # $35.00 (30% discount)
"name": "5 Karaoke Credits",
"description": "Create 5 professional karaoke videos (Save 30%)",
},
"10_credits": {
"credits": 10,
"price_cents": 3000, # $30.00 (40% discount)
"price_cents": 6000, # $60.00 (40% discount)
"name": "10 Karaoke Credits",
"description": "Create 10 professional karaoke videos (Save 40%)",
},
@@ -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.
+2
View File
@@ -218,6 +218,7 @@ class UserService:
user_agent: Optional[str] = None,
tenant_id: Optional[str] = None,
device_fingerprint: Optional[str] = None,
referral_code: Optional[str] = None,
) -> MagicLinkToken:
"""
Create a magic link token for email authentication.
@@ -253,6 +254,7 @@ class UserService:
user_agent=user_agent,
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
referral_code=referral_code,
)
# Save to Firestore
+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
@@ -0,0 +1,189 @@
# Affiliate QR Code Generator — Design Spec
**Date:** 2026-04-05
**Status:** Approved
**Scope:** Frontend-only feature in karaoke-gen
## Overview
Add a QR code generator to the referral dashboard (`/app/referrals`) that lets referrers create customizable, branded QR codes for their referral link. Users can choose dot styles, corner styles, colors, and center logos, then download the result as PNG or SVG.
## User Flow
1. User navigates to `/app/referrals`
2. Clicks "QR Code" button next to the existing "Copy Link" button
3. Dialog opens with live QR code preview and style controls
4. User customizes appearance (styles, colors, logo)
5. Clicks "Download PNG" or "Download SVG"
6. Dialog closes (or stays open for further tweaks)
7. Style preferences are saved to localStorage automatically
## Technical Approach
### Library
**`qr-code-styling`** (npm) — client-side QR code generation with styling support.
Provides:
- 6 dot styles: square, rounded, dots, classy, classy-rounded, extra-rounded
- 3 corner square styles: square, dot, extra-rounded
- 3 corner dot styles: square, dot
- Foreground/background color control
- Center image support
- PNG/SVG export
No backend changes required.
### New Files
| File | Purpose |
|------|---------|
| `frontend/components/referrals/QRCodeDialog.tsx` | QR code generator dialog component |
### Modified Files
| File | Change |
|------|--------|
| `frontend/components/referrals/ReferralDashboard.tsx` | Add "QR Code" button next to "Copy Link" |
| `frontend/messages/en.json` | Add i18n strings under `referrals` namespace |
| `frontend/package.json` | Add `qr-code-styling` dependency |
### No New Assets Needed
Center logo options will use:
- `/nomad-karaoke-logo.svg` (already in `public/`)
- Lucide icons rendered to data URLs at build time: `Mic`, `Music`
## Component Design
### `QRCodeDialog`
**Props:**
```typescript
interface QRCodeDialogProps {
referralUrl: string; // e.g. "https://nomadkaraoke.com/r/abc123"
open: boolean;
onOpenChange: (open: boolean) => void;
}
```
**Internal State:**
```typescript
interface QRStylePrefs {
dotStyle: 'square' | 'rounded' | 'dots' | 'classy' | 'classy-rounded' | 'extra-rounded';
cornerSquareStyle: 'square' | 'dot' | 'extra-rounded';
cornerDotStyle: 'square' | 'dot';
fgColor: string; // hex, default "#000000"
bgColor: string; // hex, default "#ffffff"
logo: 'none' | 'nomad' | 'mic' | 'music';
}
```
**localStorage key:** `nk-qr-style-prefs`
### Dialog Layout
Uses existing `Dialog`, `DialogContent`, `DialogHeader`, `DialogTitle` from `@/components/ui/dialog`.
The dialog uses `max-w-2xl` (wider than the default `max-w-lg`) to accommodate two columns.
```
+--------------------------------------------------+
| QR Code Generator [X] |
+--------------------------------------------------+
| | |
| [QR Preview] | Dot Style |
| 250x250 | [6 clickable thumbnails] |
| | |
| | Corner Frame |
| | [3 clickable thumbnails] |
| | |
| | Corner Dot |
| | [2 clickable options] |
| | |
| | Colors |
| | FG: [picker] BG: [picker] |
| | |
| | Center Logo |
| | (o) None (o) NK (o) Mic ... |
| | |
+--------------------------------------------------+
| [Download PNG] [Download SVG] |
+--------------------------------------------------+
```
**Responsive (<768px):** Single column — preview on top, controls below, scrollable.
### Style Picker UX
Each style option is a small clickable tile showing a mini QR code preview or icon representation. The selected tile has a ring/border highlight (matching the app's `--primary` color).
For dot styles and corner styles, render small labeled icons rather than live mini QR codes (which would be expensive). Labels like "Rounded", "Dots", "Classy" with a simple shape icon.
### Color Pickers
Use native `<input type="color">` for simplicity. Styled with a small swatch preview next to each picker. Two pickers: foreground and background.
### Center Logo Options
Radio group with 4 options:
- **None** — no center image
- **Nomad Karaoke** — `/nomad-karaoke-logo.svg`
- **Microphone** — Lucide `Mic` icon rendered as SVG data URL
- **Music** — Lucide `Music` icon rendered as SVG data URL
Logo is rendered at ~20% of QR code size with a white background margin for scannability.
### Download
- `qr-code-styling` provides `.download({ name, extension })` method
- PNG button: downloads as `referral-qr.png`
- SVG button: downloads as `referral-qr.svg`
## i18n Strings
Added to the `referrals` namespace in `en.json`:
```json
{
"qrCode": "QR Code",
"qrTitle": "QR Code Generator",
"qrDotStyle": "Dot Style",
"qrCornerFrame": "Corner Frame",
"qrCornerDot": "Corner Dot",
"qrColors": "Colors",
"qrForeground": "Foreground",
"qrBackground": "Background",
"qrLogo": "Center Logo",
"qrLogoNone": "None",
"qrLogoNomad": "Nomad Karaoke",
"qrLogoMic": "Microphone",
"qrLogoMusic": "Music",
"qrDownloadPng": "Download PNG",
"qrDownloadSvg": "Download SVG",
"qrStyleSquare": "Square",
"qrStyleRounded": "Rounded",
"qrStyleDots": "Dots",
"qrStyleClassy": "Classy",
"qrStyleClassyRounded": "Classy Rounded",
"qrStyleExtraRounded": "Extra Rounded"
}
```
## Persistence
On every style change, debounce (300ms) and save the `QRStylePrefs` object to `localStorage` under key `nk-qr-style-prefs`. On dialog open, read from localStorage and apply. If no saved prefs, use defaults (square dots, square corners, black on white, no logo).
## Testing
- **Unit tests:** Verify localStorage persistence logic (save/load/defaults)
- **Component test:** Verify dialog renders, style options are clickable, download buttons present
- **E2E test:** Open referral dashboard, click QR Code button, verify dialog opens with preview, change a style, download PNG
## Out of Scope
- Custom image upload for center logo
- Gradient colors (could add later)
- Saving QR style to backend/Firestore
- Sharing QR code directly (social media, etc.)
- QR code analytics (scan tracking)
@@ -0,0 +1,754 @@
# Affiliate QR Code Generator — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add a customizable QR code generator dialog to the referral dashboard so referrers can create branded QR codes for their referral links.
**Architecture:** Frontend-only feature. A new `QRCodeDialog` component renders a `qr-code-styling` QR code with live preview and style controls inside a Radix Dialog. Style prefs persist in localStorage. No backend changes.
**Tech Stack:** React 19, Next.js 16, `qr-code-styling` (client-side QR generation), Radix Dialog, Tailwind CSS, Lucide icons, next-intl, Jest + @testing-library/react
**Spec:** `docs/archive/2026-04-05-affiliate-qr-code-generator-design.md`
---
## File Map
| Action | File | Responsibility |
|--------|------|----------------|
| Create | `frontend/components/referrals/__tests__/QRCodeDialog.test.tsx` | Unit tests for the QR dialog |
| Create | `frontend/components/referrals/QRCodeDialog.tsx` | QR code generator dialog component |
| Modify | `frontend/components/referrals/ReferralDashboard.tsx` | Add QR Code button |
| Modify | `frontend/messages/en.json` | Add i18n strings |
| Modify | `frontend/package.json` | Add `qr-code-styling` dependency |
---
### Task 1: Install dependency and add i18n strings
**Files:**
- Modify: `frontend/package.json`
- Modify: `frontend/messages/en.json`
- [ ] **Step 1: Install qr-code-styling**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator/frontend && npm install qr-code-styling
```
- [ ] **Step 2: Add i18n strings to en.json**
Open `frontend/messages/en.json` and add these keys inside the existing `"referrals"` object, after the `"editProfile"` entry:
```json
"qrCode": "QR Code",
"qrTitle": "QR Code Generator",
"qrDotStyle": "Dot Style",
"qrCornerFrame": "Corner Frame",
"qrCornerDot": "Corner Dot",
"qrColors": "Colors",
"qrForeground": "Foreground",
"qrBackground": "Background",
"qrLogo": "Center Logo",
"qrLogoNone": "None",
"qrLogoNomad": "Nomad Karaoke",
"qrLogoMic": "Microphone",
"qrLogoMusic": "Music",
"qrDownloadPng": "Download PNG",
"qrDownloadSvg": "Download SVG",
"qrStyleSquare": "Square",
"qrStyleRounded": "Rounded",
"qrStyleDots": "Dots",
"qrStyleClassy": "Classy",
"qrStyleClassyRounded": "Classy Rounded",
"qrStyleExtraRounded": "Extra Rounded",
"qrStyleDot": "Dot"
```
- [ ] **Step 3: Commit**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
git add frontend/package.json frontend/package-lock.json frontend/messages/en.json
git commit -m "feat(referral): add qr-code-styling dep and i18n strings for QR generator"
```
---
### Task 2: Write failing tests for QRCodeDialog
**Files:**
- Create: `frontend/components/referrals/__tests__/QRCodeDialog.test.tsx`
The `qr-code-styling` library requires DOM/canvas and can't run in jsdom. We'll mock it and test the component's behavior: rendering controls, localStorage persistence, button interactions.
- [ ] **Step 1: Create the test file**
Create `frontend/components/referrals/__tests__/QRCodeDialog.test.tsx`:
```tsx
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { NextIntlClientProvider } from 'next-intl';
import QRCodeDialog from '../QRCodeDialog';
// Mock qr-code-styling — it requires canvas/DOM APIs not available in jsdom
const mockAppend = jest.fn();
const mockUpdate = jest.fn();
const mockDownload = jest.fn().mockResolvedValue(undefined);
jest.mock('qr-code-styling', () => {
return jest.fn().mockImplementation(() => ({
append: mockAppend,
update: mockUpdate,
download: mockDownload,
}));
});
// Load real English messages for the referrals namespace
const messages = require('../../../messages/en.json');
function renderDialog(props: Partial<React.ComponentProps<typeof QRCodeDialog>> = {}) {
return render(
<NextIntlClientProvider locale="en" messages={messages}>
<QRCodeDialog
referralUrl="https://nomadkaraoke.com/r/testcode"
open={true}
onOpenChange={jest.fn()}
{...props}
/>
</NextIntlClientProvider>
);
}
beforeEach(() => {
jest.clearAllMocks();
localStorage.clear();
});
describe('QRCodeDialog', () => {
it('renders the dialog title and download buttons when open', () => {
renderDialog();
expect(screen.getByText('QR Code Generator')).toBeInTheDocument();
expect(screen.getByText('Download PNG')).toBeInTheDocument();
expect(screen.getByText('Download SVG')).toBeInTheDocument();
});
it('does not render when closed', () => {
renderDialog({ open: false });
expect(screen.queryByText('QR Code Generator')).not.toBeInTheDocument();
});
it('renders all dot style options', () => {
renderDialog();
expect(screen.getByText('Square')).toBeInTheDocument();
expect(screen.getByText('Rounded')).toBeInTheDocument();
expect(screen.getByText('Dots')).toBeInTheDocument();
expect(screen.getByText('Classy')).toBeInTheDocument();
expect(screen.getByText('Classy Rounded')).toBeInTheDocument();
expect(screen.getByText('Extra Rounded')).toBeInTheDocument();
});
it('renders corner frame and corner dot style sections', () => {
renderDialog();
expect(screen.getByText('Corner Frame')).toBeInTheDocument();
expect(screen.getByText('Corner Dot')).toBeInTheDocument();
});
it('renders center logo options', () => {
renderDialog();
expect(screen.getByText('Center Logo')).toBeInTheDocument();
expect(screen.getByText('None')).toBeInTheDocument();
expect(screen.getByText('Nomad Karaoke')).toBeInTheDocument();
expect(screen.getByText('Microphone')).toBeInTheDocument();
expect(screen.getByText('Music')).toBeInTheDocument();
});
it('renders color picker inputs', () => {
renderDialog();
expect(screen.getByText('Foreground')).toBeInTheDocument();
expect(screen.getByText('Background')).toBeInTheDocument();
// Color inputs
const colorInputs = screen.getAllByDisplayValue('#000000');
expect(colorInputs.length).toBeGreaterThanOrEqual(1);
});
it('saves style prefs to localStorage on change', async () => {
renderDialog();
// Click "Rounded" dot style
fireEvent.click(screen.getByText('Rounded'));
await waitFor(() => {
const saved = JSON.parse(localStorage.getItem('nk-qr-style-prefs') || '{}');
expect(saved.dotStyle).toBe('rounded');
});
});
it('restores style prefs from localStorage on open', () => {
localStorage.setItem('nk-qr-style-prefs', JSON.stringify({
dotStyle: 'dots',
cornerSquareStyle: 'dot',
cornerDotStyle: 'dot',
fgColor: '#ff0000',
bgColor: '#00ff00',
logo: 'nomad',
}));
renderDialog();
// The foreground color input should have the saved value
const fgInput = screen.getByDisplayValue('#ff0000');
expect(fgInput).toBeInTheDocument();
});
it('calls download with PNG extension when Download PNG clicked', async () => {
renderDialog();
fireEvent.click(screen.getByText('Download PNG'));
await waitFor(() => {
expect(mockDownload).toHaveBeenCalledWith({
name: 'referral-qr',
extension: 'png',
});
});
});
it('calls download with SVG extension when Download SVG clicked', async () => {
renderDialog();
fireEvent.click(screen.getByText('Download SVG'));
await waitFor(() => {
expect(mockDownload).toHaveBeenCalledWith({
name: 'referral-qr',
extension: 'svg',
});
});
});
});
```
- [ ] **Step 2: Run tests to verify they fail**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator/frontend
npx jest components/referrals/__tests__/QRCodeDialog.test.tsx --no-coverage 2>&1 | tail -30
```
Expected: All tests FAIL because `QRCodeDialog` component doesn't exist yet.
- [ ] **Step 3: Commit**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
git add frontend/components/referrals/__tests__/QRCodeDialog.test.tsx
git commit -m "test(referral): add failing tests for QR code dialog"
```
---
### Task 3: Implement QRCodeDialog component
**Files:**
- Create: `frontend/components/referrals/QRCodeDialog.tsx`
- [ ] **Step 1: Create the QRCodeDialog component**
Create `frontend/components/referrals/QRCodeDialog.tsx`:
```tsx
'use client';
import { useEffect, useRef, useState, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { QrCode, Download, Mic, Music } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
const STORAGE_KEY = 'nk-qr-style-prefs';
type DotStyle = 'square' | 'rounded' | 'dots' | 'classy' | 'classy-rounded' | 'extra-rounded';
type CornerSquareStyle = 'square' | 'dot' | 'extra-rounded';
type CornerDotStyle = 'square' | 'dot';
type LogoOption = 'none' | 'nomad' | 'mic' | 'music';
interface QRStylePrefs {
dotStyle: DotStyle;
cornerSquareStyle: CornerSquareStyle;
cornerDotStyle: CornerDotStyle;
fgColor: string;
bgColor: string;
logo: LogoOption;
}
const DEFAULT_PREFS: QRStylePrefs = {
dotStyle: 'square',
cornerSquareStyle: 'square',
cornerDotStyle: 'square',
fgColor: '#000000',
bgColor: '#ffffff',
logo: 'none',
};
const DOT_STYLES: DotStyle[] = ['square', 'rounded', 'dots', 'classy', 'classy-rounded', 'extra-rounded'];
const CORNER_SQUARE_STYLES: CornerSquareStyle[] = ['square', 'dot', 'extra-rounded'];
const CORNER_DOT_STYLES: CornerDotStyle[] = ['square', 'dot'];
const DOT_STYLE_LABELS: Record<DotStyle, string> = {
'square': 'qrStyleSquare',
'rounded': 'qrStyleRounded',
'dots': 'qrStyleDots',
'classy': 'qrStyleClassy',
'classy-rounded': 'qrStyleClassyRounded',
'extra-rounded': 'qrStyleExtraRounded',
};
const CORNER_SQUARE_LABELS: Record<CornerSquareStyle, string> = {
'square': 'qrStyleSquare',
'dot': 'qrStyleDot',
'extra-rounded': 'qrStyleExtraRounded',
};
const CORNER_DOT_LABELS: Record<CornerDotStyle, string> = {
'square': 'qrStyleSquare',
'dot': 'qrStyleDot',
};
function loadPrefs(): QRStylePrefs {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
return { ...DEFAULT_PREFS, ...JSON.parse(saved) };
}
} catch {}
return { ...DEFAULT_PREFS };
}
function savePrefs(prefs: QRStylePrefs) {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
} catch {}
}
function getLucideIconDataUrl(IconComponent: typeof Mic, color: string = '#000000'): string {
// Render Lucide icon to SVG string for use as QR center image
const svgNs = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(svgNs, 'svg');
svg.setAttribute('xmlns', svgNs);
svg.setAttribute('width', '48');
svg.setAttribute('height', '48');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('fill', 'none');
svg.setAttribute('stroke', color);
svg.setAttribute('stroke-width', '2');
svg.setAttribute('stroke-linecap', 'round');
svg.setAttribute('stroke-linejoin', 'round');
// Get the icon's path data from lucide
// lucide-react icons have an iconNode property with SVG element definitions
const iconNode = (IconComponent as unknown as { iconNode: Array<[string, Record<string, string>]> }).iconNode;
if (iconNode) {
for (const [tag, attrs] of iconNode) {
const el = document.createElementNS(svgNs, tag);
for (const [key, val] of Object.entries(attrs)) {
el.setAttribute(key, val);
}
svg.appendChild(el);
}
}
const svgStr = new XMLSerializer().serializeToString(svg);
return `data:image/svg+xml;base64,${btoa(svgStr)}`;
}
interface QRCodeDialogProps {
referralUrl: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export default function QRCodeDialog({ referralUrl, open, onOpenChange }: QRCodeDialogProps) {
const t = useTranslations('referrals');
const containerRef = useRef<HTMLDivElement>(null);
const qrRef = useRef<InstanceType<typeof import('qr-code-styling').default> | null>(null);
const [prefs, setPrefs] = useState<QRStylePrefs>(DEFAULT_PREFS);
const [loaded, setLoaded] = useState(false);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Load prefs from localStorage on open
useEffect(() => {
if (open) {
setPrefs(loadPrefs());
}
}, [open]);
// Build QR options from prefs
const buildOptions = useCallback((p: QRStylePrefs) => {
let image: string | undefined;
if (p.logo === 'nomad') {
image = '/nomad-karaoke-logo.svg';
} else if (p.logo === 'mic') {
image = getLucideIconDataUrl(Mic, p.fgColor);
} else if (p.logo === 'music') {
image = getLucideIconDataUrl(Music, p.fgColor);
}
return {
width: 250,
height: 250,
data: referralUrl,
dotsOptions: { type: p.dotStyle, color: p.fgColor },
cornersSquareOptions: { type: p.cornerSquareStyle, color: p.fgColor },
cornersDotOptions: { type: p.cornerDotStyle, color: p.fgColor },
backgroundOptions: { color: p.bgColor },
image,
imageOptions: image ? { hideBackgroundDots: true, imageSize: 0.2, margin: 4 } : undefined,
};
}, [referralUrl]);
// Initialize / update QR code
useEffect(() => {
if (!open) return;
const init = async () => {
const QRCodeStyling = (await import('qr-code-styling')).default;
if (!qrRef.current) {
qrRef.current = new QRCodeStyling(buildOptions(prefs));
if (containerRef.current) {
containerRef.current.innerHTML = '';
qrRef.current.append(containerRef.current);
}
} else {
qrRef.current.update(buildOptions(prefs));
}
setLoaded(true);
};
init();
}, [open, prefs, buildOptions]);
// Clean up on close
useEffect(() => {
if (!open) {
qrRef.current = null;
setLoaded(false);
}
}, [open]);
const updatePref = <K extends keyof QRStylePrefs>(key: K, value: QRStylePrefs[K]) => {
setPrefs(prev => {
const next = { ...prev, [key]: value };
// Debounce localStorage save
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => savePrefs(next), 300);
return next;
});
};
const handleDownload = async (extension: 'png' | 'svg') => {
if (qrRef.current) {
await qrRef.current.download({ name: 'referral-qr', extension });
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl bg-card border-border max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<QrCode className="w-5 h-5" />
{t('qrTitle')}
</DialogTitle>
</DialogHeader>
<div className="flex flex-col md:flex-row gap-6">
{/* Left: QR Preview */}
<div className="flex-shrink-0 flex items-center justify-center">
<div
ref={containerRef}
className="w-[250px] h-[250px] rounded-lg border border-border flex items-center justify-center"
style={{ backgroundColor: prefs.bgColor }}
>
{!loaded && (
<div className="animate-pulse w-[200px] h-[200px] bg-muted rounded" />
)}
</div>
</div>
{/* Right: Controls */}
<div className="flex-1 space-y-4 min-w-0">
{/* Dot Style */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrDotStyle')}</label>
<div className="grid grid-cols-3 gap-1.5 mt-1">
{DOT_STYLES.map(style => (
<button
key={style}
onClick={() => updatePref('dotStyle', style)}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
prefs.dotStyle === style
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-border text-muted-foreground hover:border-primary/50'
}`}
>
{t(DOT_STYLE_LABELS[style])}
</button>
))}
</div>
</div>
{/* Corner Frame */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrCornerFrame')}</label>
<div className="grid grid-cols-3 gap-1.5 mt-1">
{CORNER_SQUARE_STYLES.map(style => (
<button
key={style}
onClick={() => updatePref('cornerSquareStyle', style)}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
prefs.cornerSquareStyle === style
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-border text-muted-foreground hover:border-primary/50'
}`}
>
{t(CORNER_SQUARE_LABELS[style])}
</button>
))}
</div>
</div>
{/* Corner Dot */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrCornerDot')}</label>
<div className="grid grid-cols-3 gap-1.5 mt-1">
{CORNER_DOT_STYLES.map(style => (
<button
key={style}
onClick={() => updatePref('cornerDotStyle', style)}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
prefs.cornerDotStyle === style
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-border text-muted-foreground hover:border-primary/50'
}`}
>
{t(CORNER_DOT_LABELS[style])}
</button>
))}
</div>
</div>
{/* Colors */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrColors')}</label>
<div className="flex gap-4 mt-1">
<div className="flex items-center gap-2">
<input
type="color"
value={prefs.fgColor}
onChange={(e) => updatePref('fgColor', e.target.value)}
className="w-8 h-8 rounded border border-border cursor-pointer"
/>
<span className="text-xs text-muted-foreground">{t('qrForeground')}</span>
</div>
<div className="flex items-center gap-2">
<input
type="color"
value={prefs.bgColor}
onChange={(e) => updatePref('bgColor', e.target.value)}
className="w-8 h-8 rounded border border-border cursor-pointer"
/>
<span className="text-xs text-muted-foreground">{t('qrBackground')}</span>
</div>
</div>
</div>
{/* Center Logo */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrLogo')}</label>
<div className="grid grid-cols-2 gap-1.5 mt-1">
{(['none', 'nomad', 'mic', 'music'] as LogoOption[]).map(option => {
const labelKeys: Record<LogoOption, string> = {
none: 'qrLogoNone',
nomad: 'qrLogoNomad',
mic: 'qrLogoMic',
music: 'qrLogoMusic',
};
return (
<button
key={option}
onClick={() => updatePref('logo', option)}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
prefs.logo === option
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-border text-muted-foreground hover:border-primary/50'
}`}
>
{t(labelKeys[option])}
</button>
);
})}
</div>
</div>
</div>
</div>
<DialogFooter>
<div className="flex gap-2 w-full sm:w-auto">
<button
onClick={() => handleDownload('png')}
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2"
>
<Download className="w-4 h-4" />
{t('qrDownloadPng')}
</button>
<button
onClick={() => handleDownload('svg')}
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary"
>
<Download className="w-4 h-4" />
{t('qrDownloadSvg')}
</button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
```
- [ ] **Step 2: Run tests to verify they pass**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator/frontend
npx jest components/referrals/__tests__/QRCodeDialog.test.tsx --no-coverage 2>&1 | tail -30
```
Expected: All 9 tests PASS.
- [ ] **Step 3: Commit**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
git add frontend/components/referrals/QRCodeDialog.tsx
git commit -m "feat(referral): implement QR code generator dialog with style customization"
```
---
### Task 4: Wire QRCodeDialog into ReferralDashboard
**Files:**
- Modify: `frontend/components/referrals/ReferralDashboard.tsx`
- [ ] **Step 1: Add QR Code button and dialog to ReferralDashboard**
In `frontend/components/referrals/ReferralDashboard.tsx`, make these changes:
**Add imports** at the top (after the existing imports):
```tsx
import { useState } from 'react'; // already imported, just ensure it's there
import { QrCode } from 'lucide-react';
import QRCodeDialog from './QRCodeDialog';
```
**Add state** inside the `ReferralDashboard` component (after the existing `useState` calls around line 21):
```tsx
const [qrOpen, setQrOpen] = useState(false);
```
**Add the QR Code button** next to the existing Copy Link button. Replace the `<div className="flex gap-2">` block (lines 85-94) with:
```tsx
<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>
<button
onClick={() => setQrOpen(true)}
className="px-3 py-2 rounded text-sm border"
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
title={t('qrCode')}
>
<QrCode className="w-4 h-4" />
</button>
</div>
```
**Add the QRCodeDialog** just before the closing `</div>` of the component (before line 212):
```tsx
<QRCodeDialog
referralUrl={`${typeof window !== 'undefined' ? window.location.origin : ''}/r/${data.link.code}`}
open={qrOpen}
onOpenChange={setQrOpen}
/>
```
- [ ] **Step 2: Run all tests**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator/frontend
npx jest --no-coverage 2>&1 | tail -30
```
Expected: All tests PASS.
- [ ] **Step 3: Verify the build compiles**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator/frontend
npx next build 2>&1 | tail -20
```
Expected: Build succeeds with no errors.
- [ ] **Step 4: Commit**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
git add frontend/components/referrals/ReferralDashboard.tsx
git commit -m "feat(referral): wire QR code dialog into referral dashboard"
```
---
### Task 5: Fix any test issues and final verification
**Files:**
- Possibly adjust: `frontend/components/referrals/__tests__/QRCodeDialog.test.tsx`
- Possibly adjust: `frontend/components/referrals/QRCodeDialog.tsx`
This task handles any test adjustments discovered during Task 3/4 and runs the full test suite.
- [ ] **Step 1: Run full test suite**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
make test 2>&1 | tail -50
```
Expected: All backend and frontend tests pass.
- [ ] **Step 2: Fix any failures**
If tests fail, fix the specific issues. Common things to watch for:
- `qr-code-styling` mock may need adjustment if the dynamic import pattern doesn't match the mock
- `next-intl` test provider may need `timeZone` or `now` props depending on the test setup
- Color input `getByDisplayValue` may need adjusting if the browser normalizes hex colors
- [ ] **Step 3: Commit fixes if any**
```bash
cd /Users/andrew/Projects/nomadkaraoke/karaoke-gen-affiliate-qr-generator
git add -A
git commit -m "fix(referral): address test issues in QR code dialog"
```
Only commit if there were actual fixes. Skip if all tests passed in Step 1.
+28 -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 && (
@@ -333,6 +337,28 @@ function AppPageContent() {
{/* Push notification prompt - shows once when appropriate */}
<PushNotificationPrompt />
{/* Referral discount banner */}
{user?.has_active_referral_discount && user?.referral_discount_percent && user?.referral_discount_expires_at && (
<div
className="rounded-xl p-4 flex items-center gap-3 border"
style={{
borderColor: 'var(--accent)',
backgroundColor: 'rgba(168, 85, 247, 0.05)',
}}
>
<Gift className="w-5 h-5 shrink-0" style={{ color: 'var(--accent)' }} />
<div className="min-w-0">
<p className="text-sm font-medium" style={{ color: 'var(--text)' }}>
{user.referral_discount_percent}% referral discount active
</p>
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
{user.referred_by_code && <>Referred with code <strong>{user.referred_by_code}</strong> · </>}
Expires {new Date(user.referral_discount_expires_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
</p>
</div>
</div>
)}
{/* Feedback-for-credits banner (consumer portal only) */}
{isDefaultTenant && user?.feedback_eligible && !feedbackBannerDismissed && (
<div className="flex items-center justify-between gap-3 rounded-lg border px-4 py-3"
@@ -0,0 +1,7 @@
'use client';
import ReferralDashboard from '@/components/referrals/ReferralDashboard';
export default function ReferralsPage() {
return <ReferralDashboard />;
}
@@ -6,6 +6,7 @@ import { useSearchParams } from "next/navigation"
import { Loader2, CheckCircle, XCircle, Gift, ShoppingCart } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useAuth } from "@/lib/auth"
import { setReferralCode } from "@/lib/referral"
import { useTranslations } from "next-intl"
type VerifyState = "verifying" | "preparing" | "credits_granted" | "credits_denied" | "credits_pending" | "success" | "error"
@@ -28,6 +29,12 @@ function VerifyMagicLinkContent() {
const token = searchParams.get("token")
// Store referral code from magic link URL (cross-device path)
const ref = searchParams.get("ref")
if (ref) {
setReferralCode(ref)
}
if (!token) {
setState("error")
setErrorMessage(t('noVerificationToken'))
+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>
);
+224
View File
@@ -0,0 +1,224 @@
'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 { useAuth } from '@/lib/auth';
import { getAccessToken } from '@/lib/api';
import type { ReferralInterstitial } from '@/lib/types';
import { Gift, ArrowRight, Mail, CheckCircle, Loader2 } from 'lucide-react';
export function ReferralInterstitialClient() {
const searchParams = useSearchParams();
const router = useRouter();
const t = useTranslations('referrals');
const { sendMagicLink } = useAuth();
const code = searchParams.get('code');
const [data, setData] = useState<ReferralInterstitial | null>(null);
const [loading, setLoading] = useState(true);
const [email, setEmail] = useState('');
const [sending, setSending] = useState(false);
const [sent, setSent] = useState(false);
const [error, setError] = useState('');
const [isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(() => {
if (!code) {
router.replace('/');
return;
}
// Store referral code immediately
setReferralCode(code);
// Check if already logged in
if (getAccessToken()) {
setIsLoggedIn(true);
}
getReferralInterstitial(code)
.then((result) => {
if (result.valid) {
setData(result);
} else {
router.replace('/');
}
})
.catch(() => {
router.replace('/');
})
.finally(() => setLoading(false));
}, [code, router]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
const trimmed = email.trim().toLowerCase();
if (!trimmed || !trimmed.includes('@') || !trimmed.includes('.')) {
setError('Please enter a valid email address');
return;
}
setSending(true);
try {
const success = await sendMagicLink(trimmed);
if (success) {
setSent(true);
} else {
setError('Failed to send magic link. Please try again.');
}
} catch {
setError('Something went wrong. Please try again.');
} finally {
setSending(false);
}
};
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.referrer_display_name && (
<p className="text-lg" style={{ color: 'var(--text-muted)' }}>
{t('interstitialReferred', { name: data.referrer_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>
{/* Already logged in */}
{isLoggedIn ? (
<div className="space-y-4">
<div className="flex items-center justify-center gap-2" style={{ color: 'var(--accent)' }}>
<CheckCircle className="w-5 h-5" />
<p className="font-medium">Your discount will be applied on your next login</p>
</div>
<button
onClick={() => router.push('/app')}
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' }}
>
Go to App
<ArrowRight className="w-5 h-5" />
</button>
</div>
) : sent ? (
/* Magic link sent confirmation */
<div className="space-y-4">
<div className="flex items-center justify-center gap-2" style={{ color: 'var(--accent)' }}>
<CheckCircle className="w-5 h-5" />
<p className="font-medium">Check your email!</p>
</div>
<p className="text-sm" style={{ color: 'var(--text-muted)' }}>
We sent a sign-in link to <strong>{email}</strong>. Click it to claim your {data.discount_percent}% discount.
</p>
</div>
) : (
/* Email signup form */
<form onSubmit={handleSubmit} className="space-y-3">
<div className="relative">
<Mail
className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5"
style={{ color: 'var(--text-muted)' }}
/>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter your email"
className="w-full pl-11 pr-4 py-4 rounded-xl text-base"
style={{
backgroundColor: 'var(--secondary)',
color: 'var(--text)',
border: '1px solid var(--card-border)',
}}
autoFocus
/>
</div>
{error && (
<p className="text-sm text-red-400">{error}</p>
)}
<button
type="submit"
disabled={sending}
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] disabled:opacity-50 disabled:hover:scale-100"
style={{ backgroundColor: 'var(--accent)', color: 'white' }}
>
{sending ? (
<>
<Loader2 className="w-5 h-5 animate-spin" />
Sending...
</>
) : (
<>
Claim Your Discount
<ArrowRight className="w-5 h-5" />
</>
)}
</button>
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
We&apos;ll send you a magic link to sign in. No password needed.
</p>
</form>
)}
</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") {
+515
View File
@@ -0,0 +1,515 @@
"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, Pencil,
} 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)
const [editOpen, setEditOpen] = useState(false)
const [editLink, setEditLink] = useState<AdminReferralLink | null>(null)
const [saving, setSaving] = useState(false)
const [editError, setEditError] = useState<string | null>(null)
// Edit form state
const [editDisplayName, setEditDisplayName] = useState("")
const [editMessage, setEditMessage] = useState("")
const [editDiscount, setEditDiscount] = useState("10")
const [editKickback, setEditKickback] = useState("20")
// 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 openEdit = (link: AdminReferralLink) => {
setEditLink(link)
setEditDisplayName(link.display_name || "")
setEditMessage(link.custom_message || "")
setEditDiscount(String(link.discount_percent))
setEditKickback(String(link.kickback_percent))
setEditError(null)
setEditOpen(true)
}
const handleEdit = async (e: React.FormEvent) => {
e.preventDefault()
if (!editLink) return
setSaving(true)
setEditError(null)
try {
await adminApi.updateReferralLink(editLink.code, {
display_name: editDisplayName || null,
custom_message: editMessage || null,
discount_percent: Number(editDiscount) || 10,
kickback_percent: Number(editKickback) || 20,
})
setEditOpen(false)
setEditLink(null)
await loadData()
} catch (err) {
console.error("Failed to update link:", err)
setEditError(err instanceof Error ? err.message : "Failed to update link")
} finally {
setSaving(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-[100px]">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>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => openEdit(link)}
title="Edit link"
>
<Pencil className="h-4 w-4" />
</Button>
<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>
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
{/* Edit Link Dialog */}
<Dialog open={editOpen} onOpenChange={(open) => { setEditOpen(open); if (!open) setEditLink(null) }}>
<DialogContent>
<DialogHeader>
<DialogTitle>Edit Referral Link: {editLink?.code}</DialogTitle>
<DialogDescription>
Update settings for this referral link. Owner: {editLink?.owner_email}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleEdit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="editDisplayName">Display Name</Label>
<Input
id="editDisplayName"
placeholder="Shown on the interstitial page"
value={editDisplayName}
onChange={(e) => setEditDisplayName(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="editMessage">Custom Message</Label>
<Input
id="editMessage"
placeholder="Welcome message for referred users"
value={editMessage}
onChange={(e) => setEditMessage(e.target.value)}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="editDiscount">Discount %</Label>
<Input
id="editDiscount"
type="number"
min="0"
max="100"
value={editDiscount}
onChange={(e) => setEditDiscount(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="editKickback">Kickback %</Label>
<Input
id="editKickback"
type="number"
min="0"
max="100"
value={editKickback}
onChange={(e) => setEditKickback(e.target.value)}
/>
</div>
</div>
{editError && (
<p className="text-sm text-destructive">{editError}</p>
)}
<div className="flex justify-end gap-2">
<Button type="button" variant="outline" onClick={() => setEditOpen(false)}>
Cancel
</Button>
<Button type="submit" disabled={saving}>
{saving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Save Changes
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</div>
)
}
+102
View File
@@ -47,6 +47,7 @@ import {
Trash2,
DollarSign,
LogIn,
Tag,
} from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import { useAuth } from "@/lib/auth"
@@ -74,6 +75,13 @@ export default function AdminUserDetailPage() {
const [creditAmount, setCreditAmount] = useState("")
const [creditReason, setCreditReason] = useState("")
// Discount dialog
const [discountDialogOpen, setDiscountDialogOpen] = useState(false)
const [discountPercent, setDiscountPercent] = useState("50")
const [discountDays, setDiscountDays] = useState("365")
const [discountCode, setDiscountCode] = useState("loyalty")
const [applyingDiscount, setApplyingDiscount] = useState(false)
const loadUser = async () => {
if (!email) {
setLoading(false)
@@ -148,6 +156,28 @@ export default function AdminUserDetailPage() {
}
}
const handleApplyDiscount = async () => {
setApplyingDiscount(true)
try {
const result = await adminApi.applyDiscount(email, {
discount_percent: Number(discountPercent) || 50,
duration_days: Number(discountDays) || 365,
referral_code: discountCode || "loyalty",
})
toast({ title: "Discount Applied", description: result.message })
setDiscountDialogOpen(false)
loadUser()
} catch (err) {
toast({
title: "Failed",
description: err instanceof Error ? err.message : "Failed to apply discount",
variant: "destructive",
})
} finally {
setApplyingDiscount(false)
}
}
const handleToggleStatus = async () => {
if (!user) return
@@ -311,6 +341,15 @@ export default function AdminUserDetailPage() {
<Plus className="w-4 h-4 mr-2" />
Add Credits
</Button>
<Button
variant="outline"
onClick={() => setDiscountDialogOpen(true)}
disabled={actionLoading}
title="Apply a referral discount to this user"
>
<Tag className="w-4 h-4 mr-2" />
Apply Discount
</Button>
<Button
variant={user.is_active ? "destructive" : "outline"}
onClick={handleToggleStatus}
@@ -425,6 +464,16 @@ export default function AdminUserDetailPage() {
{user.has_submitted_feedback ? "Yes" : "No"}
</Badge>
</div>
{user.referral_discount_expires_at && (
<div className="flex items-center gap-2 text-sm">
<Tag className="w-4 h-4 text-purple-500" />
<span>
Referral discount active
{user.referred_by_code && <> (code: <code className="bg-muted px-1 rounded">{user.referred_by_code}</code>)</>}
{' · '}Expires {new Date(user.referral_discount_expires_at).toLocaleDateString()}
</span>
</div>
)}
</CardContent>
</Card>
@@ -675,6 +724,59 @@ export default function AdminUserDetailPage() {
</DialogContent>
</Dialog>
{/* Apply Discount Dialog */}
<Dialog open={discountDialogOpen} onOpenChange={setDiscountDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Apply Discount</DialogTitle>
<DialogDescription>
Apply a referral discount to {email}. This sets the same discount fields as if they used a referral link.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label>Discount %</Label>
<Input
type="number"
min="1"
max="100"
value={discountPercent}
onChange={(e) => setDiscountPercent(e.target.value)}
/>
<p className="text-xs text-muted-foreground">Percentage off credit purchases at Stripe checkout</p>
</div>
<div className="space-y-2">
<Label>Duration (days)</Label>
<Input
type="number"
min="1"
value={discountDays}
onChange={(e) => setDiscountDays(e.target.value)}
/>
<p className="text-xs text-muted-foreground">How long the discount stays active. Use 3650 for ~10 years.</p>
</div>
<div className="space-y-2">
<Label>Referral Code</Label>
<Input
value={discountCode}
onChange={(e) => setDiscountCode(e.target.value)}
placeholder="loyalty"
/>
<p className="text-xs text-muted-foreground">Shows as the referral source. Use &quot;loyalty&quot; for grandfathered pricing, or an actual referral code.</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDiscountDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleApplyDiscount} disabled={applyingDiscount}>
{applyingDiscount && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
Apply Discount
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
{/* Delete User Confirmation Dialog */}
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
<AlertDialogContent>
+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,19 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
</DialogHeader>
<div className="space-y-4 mt-2">
{user?.has_active_referral_discount && user?.referral_discount_percent && (
<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: user.referral_discount_percent })}
</p>
{user.referral_discount_expires_at && (
<p className="text-green-600/70 dark:text-green-400/70 text-xs mt-1">
Applied automatically at checkout · Expires {new Date(user.referral_discount_expires_at).toLocaleDateString()}
</p>
)}
</div>
)}
{loading && (
<div className="flex justify-center py-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
@@ -88,7 +102,7 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
const isSelected = selectedPackage?.id === pkg.id
const isBestValue = pkg.credits === 5
const savings = pkg.credits > 1
? Math.round((1 - pkg.price_cents / (pkg.credits * 500)) * 100)
? Math.round((1 - pkg.price_cents / (pkg.credits * 1000)) * 100)
: 0
return (
@@ -0,0 +1,378 @@
'use client';
import { useEffect, useRef, useState, useCallback } from 'react';
import { useTranslations } from 'next-intl';
import { QrCode, Download, Mic, Music } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
const STORAGE_KEY = 'nk-qr-style-prefs';
type DotStyle = 'square' | 'rounded' | 'dots' | 'classy' | 'classy-rounded' | 'extra-rounded';
type CornerSquareStyle = 'square' | 'dot' | 'extra-rounded';
type CornerDotStyle = 'square' | 'dot';
type LogoOption = 'none' | 'nomad' | 'mic' | 'music';
interface QRStylePrefs {
dotStyle: DotStyle;
cornerSquareStyle: CornerSquareStyle;
cornerDotStyle: CornerDotStyle;
fgColor: string;
bgColor: string;
logo: LogoOption;
}
const DEFAULT_PREFS: QRStylePrefs = {
dotStyle: 'square',
cornerSquareStyle: 'square',
cornerDotStyle: 'square',
fgColor: '#000000',
bgColor: '#ffffff',
logo: 'none',
};
const DOT_STYLES: DotStyle[] = ['square', 'rounded', 'dots', 'classy', 'classy-rounded', 'extra-rounded'];
const CORNER_SQUARE_STYLES: CornerSquareStyle[] = ['square', 'dot', 'extra-rounded'];
const CORNER_DOT_STYLES: CornerDotStyle[] = ['square', 'dot'];
const DOT_STYLE_LABELS: Record<DotStyle, string> = {
'square': 'qrStyleSquare',
'rounded': 'qrStyleRounded',
'dots': 'qrStyleDots',
'classy': 'qrStyleClassy',
'classy-rounded': 'qrStyleClassyRounded',
'extra-rounded': 'qrStyleExtraRounded',
};
const CORNER_SQUARE_LABELS: Record<CornerSquareStyle, string> = {
'square': 'qrStyleSquare',
'dot': 'qrStyleDot',
'extra-rounded': 'qrStyleExtraRounded',
};
const CORNER_DOT_LABELS: Record<CornerDotStyle, string> = {
'square': 'qrStyleSquare',
'dot': 'qrStyleDot',
};
function loadPrefs(): QRStylePrefs {
try {
const saved = localStorage.getItem(STORAGE_KEY);
if (saved) {
return { ...DEFAULT_PREFS, ...JSON.parse(saved) };
}
} catch {}
return { ...DEFAULT_PREFS };
}
function savePrefs(prefs: QRStylePrefs) {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
} catch {}
}
function getLucideIconDataUrl(IconComponent: typeof Mic, color: string = '#000000'): string {
const svgNs = 'http://www.w3.org/2000/svg';
const svg = document.createElementNS(svgNs, 'svg');
svg.setAttribute('xmlns', svgNs);
svg.setAttribute('width', '48');
svg.setAttribute('height', '48');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('fill', 'none');
svg.setAttribute('stroke', color);
svg.setAttribute('stroke-width', '2');
svg.setAttribute('stroke-linecap', 'round');
svg.setAttribute('stroke-linejoin', 'round');
const iconNode = (IconComponent as unknown as { iconNode: Array<[string, Record<string, string>]> }).iconNode;
if (iconNode) {
for (const [tag, attrs] of iconNode) {
const el = document.createElementNS(svgNs, tag);
for (const [key, val] of Object.entries(attrs)) {
el.setAttribute(key, val);
}
svg.appendChild(el);
}
}
const svgStr = new XMLSerializer().serializeToString(svg);
return `data:image/svg+xml;base64,${btoa(svgStr)}`;
}
interface QRCodeDialogProps {
referralUrl: string;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export default function QRCodeDialog({ referralUrl, open, onOpenChange }: QRCodeDialogProps) {
const t = useTranslations('referrals');
const containerRef = useRef<HTMLDivElement>(null);
const qrRef = useRef<InstanceType<typeof import('qr-code-styling').default> | null>(null);
const [prefs, setPrefs] = useState<QRStylePrefs>(DEFAULT_PREFS);
const [loaded, setLoaded] = useState(false);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Load prefs from localStorage on open
useEffect(() => {
if (open) {
setPrefs(loadPrefs());
}
}, [open]);
// Build QR options from prefs
const buildOptions = useCallback((p: QRStylePrefs) => {
let image: string | undefined;
if (p.logo === 'nomad') {
image = '/nomad-karaoke-logo.svg';
} else if (p.logo === 'mic') {
image = getLucideIconDataUrl(Mic, p.fgColor);
} else if (p.logo === 'music') {
image = getLucideIconDataUrl(Music, p.fgColor);
}
return {
width: 250,
height: 250,
data: referralUrl,
dotsOptions: { type: p.dotStyle, color: p.fgColor },
cornersSquareOptions: { type: p.cornerSquareStyle, color: p.fgColor },
cornersDotOptions: { type: p.cornerDotStyle, color: p.fgColor },
backgroundOptions: { color: p.bgColor },
image,
imageOptions: image ? { hideBackgroundDots: true, imageSize: 0.2, margin: 4 } : undefined,
};
}, [referralUrl]);
// Initialize / update QR code
useEffect(() => {
if (!open) return;
let cancelled = false;
const init = async () => {
const QRCodeStyling = (await import('qr-code-styling')).default;
if (cancelled) return;
if (!qrRef.current) {
qrRef.current = new QRCodeStyling(buildOptions(prefs));
if (!cancelled && containerRef.current) {
containerRef.current.innerHTML = '';
qrRef.current.append(containerRef.current);
}
} else if (!cancelled) {
qrRef.current.update(buildOptions(prefs));
}
if (!cancelled) {
setLoaded(true);
}
};
init();
return () => {
cancelled = true;
};
}, [open, prefs, buildOptions]);
// Clean up on close
useEffect(() => {
if (!open) {
qrRef.current = null;
setLoaded(false);
}
}, [open]);
const updatePref = <K extends keyof QRStylePrefs>(key: K, value: QRStylePrefs[K]) => {
setPrefs(prev => {
const next = { ...prev, [key]: value };
// Debounce localStorage save
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => savePrefs(next), 300);
return next;
});
};
const handleDownload = async (extension: 'png' | 'svg') => {
// Initialize QR instance if not yet ready (e.g., download clicked before init effect completes)
if (!qrRef.current) {
const QRCodeStyling = (await import('qr-code-styling')).default;
qrRef.current = new QRCodeStyling(buildOptions(prefs));
}
await qrRef.current.download({ name: 'referral-qr', extension });
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl bg-card border-border max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<QrCode className="w-5 h-5" />
{t('qrTitle')}
</DialogTitle>
</DialogHeader>
<div className="flex flex-col md:flex-row gap-6">
{/* Left: QR Preview */}
<div className="flex-shrink-0 flex items-center justify-center">
<div
className="relative w-[250px] h-[250px] rounded-lg border border-border"
style={{ backgroundColor: prefs.bgColor }}
>
{/* QR code is appended into this container by qr-code-styling */}
<div ref={containerRef} className="w-full h-full" />
{/* Loading skeleton rendered as a sibling so innerHTML clear doesn't affect React tree */}
{!loaded && (
<div className="absolute inset-0 flex items-center justify-center">
<div className="animate-pulse w-[200px] h-[200px] bg-muted rounded" />
</div>
)}
</div>
</div>
{/* Right: Controls */}
<div className="flex-1 space-y-4 min-w-0">
{/* Dot Style */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrDotStyle')}</label>
<div className="grid grid-cols-3 gap-1.5 mt-1">
{DOT_STYLES.map(style => (
<button
key={style}
onClick={() => updatePref('dotStyle', style)}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
prefs.dotStyle === style
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-border text-muted-foreground hover:border-primary/50'
}`}
>
{t(DOT_STYLE_LABELS[style])}
</button>
))}
</div>
</div>
{/* Corner Frame */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrCornerFrame')}</label>
<div className="grid grid-cols-3 gap-1.5 mt-1">
{CORNER_SQUARE_STYLES.map(style => (
<button
key={style}
onClick={() => updatePref('cornerSquareStyle', style)}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
prefs.cornerSquareStyle === style
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-border text-muted-foreground hover:border-primary/50'
}`}
>
{t(CORNER_SQUARE_LABELS[style])}
</button>
))}
</div>
</div>
{/* Corner Dot */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrCornerDot')}</label>
<div className="grid grid-cols-3 gap-1.5 mt-1">
{CORNER_DOT_STYLES.map(style => (
<button
key={style}
onClick={() => updatePref('cornerDotStyle', style)}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
prefs.cornerDotStyle === style
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-border text-muted-foreground hover:border-primary/50'
}`}
>
{t(CORNER_DOT_LABELS[style])}
</button>
))}
</div>
</div>
{/* Colors */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrColors')}</label>
<div className="flex gap-4 mt-1">
<div className="flex items-center gap-2">
<input
type="color"
value={prefs.fgColor}
onChange={(e) => updatePref('fgColor', e.target.value)}
className="w-8 h-8 rounded border border-border cursor-pointer"
/>
<span className="text-xs text-muted-foreground">{t('qrForeground')}</span>
</div>
<div className="flex items-center gap-2">
<input
type="color"
value={prefs.bgColor}
onChange={(e) => updatePref('bgColor', e.target.value)}
className="w-8 h-8 rounded border border-border cursor-pointer"
/>
<span className="text-xs text-muted-foreground">{t('qrBackground')}</span>
</div>
</div>
</div>
{/* Center Logo */}
<div>
<label className="text-sm font-medium text-foreground">{t('qrLogo')}</label>
<div className="grid grid-cols-2 gap-1.5 mt-1">
{(['none', 'nomad', 'mic', 'music'] as LogoOption[]).map(option => {
const labelKeys: Record<LogoOption, string> = {
none: 'qrLogoNone',
nomad: 'qrLogoNomad',
mic: 'qrLogoMic',
music: 'qrLogoMusic',
};
return (
<button
key={option}
onClick={() => updatePref('logo', option)}
className={`px-2 py-1.5 text-xs rounded border transition-colors ${
prefs.logo === option
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-border text-muted-foreground hover:border-primary/50'
}`}
>
{t(labelKeys[option])}
</button>
);
})}
</div>
</div>
</div>
</div>
<DialogFooter>
<div className="flex gap-2 w-full sm:w-auto">
<button
onClick={() => handleDownload('png')}
className="flex-1 sm:flex-none px-4 py-2 bg-primary text-primary-foreground rounded text-sm flex items-center justify-center gap-2"
>
<Download className="w-4 h-4" />
{t('qrDownloadPng')}
</button>
<button
onClick={() => handleDownload('svg')}
className="flex-1 sm:flex-none px-4 py-2 rounded text-sm border border-border text-foreground flex items-center justify-center gap-2 hover:bg-secondary"
>
<Download className="w-4 h-4" />
{t('qrDownloadSvg')}
</button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,232 @@
'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';
import { QrCode } from 'lucide-react';
import QRCodeDialog from './QRCodeDialog';
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 [qrOpen, setQrOpen] = useState(false);
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>
<button
type="button"
onClick={() => setQrOpen(true)}
className="px-3 py-2 rounded text-sm border"
style={{ borderColor: 'var(--card-border)', color: 'var(--text)' }}
title={t('qrCode')}
aria-label={t('qrCode')}
>
<QrCode className="w-4 h-4" />
</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>
)}
<QRCodeDialog
referralUrl={`${typeof window !== 'undefined' ? window.location.origin : ''}/r/${data.link.code}`}
open={qrOpen}
onOpenChange={setQrOpen}
/>
</div>
);
}
@@ -0,0 +1,138 @@
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { NextIntlClientProvider } from 'next-intl';
import QRCodeDialog from '../QRCodeDialog';
// Mock qr-code-styling — it requires canvas/DOM APIs not available in jsdom
const mockAppend = jest.fn();
const mockUpdate = jest.fn();
const mockDownload = jest.fn().mockResolvedValue(undefined);
jest.mock('qr-code-styling', () => {
return jest.fn().mockImplementation(() => ({
append: mockAppend,
update: mockUpdate,
download: mockDownload,
}));
});
// Load real English messages for the referrals namespace
const messages = require('../../../messages/en.json');
function renderDialog(props: Partial<React.ComponentProps<typeof QRCodeDialog>> = {}) {
return render(
<NextIntlClientProvider locale="en" messages={messages}>
<QRCodeDialog
referralUrl="https://nomadkaraoke.com/r/testcode"
open={true}
onOpenChange={jest.fn()}
{...props}
/>
</NextIntlClientProvider>
);
}
beforeEach(() => {
jest.clearAllMocks();
localStorage.clear();
});
describe('QRCodeDialog', () => {
it('renders the dialog title and download buttons when open', () => {
renderDialog();
expect(screen.getByText('QR Code Generator')).toBeInTheDocument();
expect(screen.getByText('Download PNG')).toBeInTheDocument();
expect(screen.getByText('Download SVG')).toBeInTheDocument();
});
it('does not render when closed', () => {
renderDialog({ open: false });
expect(screen.queryByText('QR Code Generator')).not.toBeInTheDocument();
});
it('renders all dot style options', () => {
renderDialog();
// "Square" appears multiple times (dot style, corner frame, corner dot) — use getAllByText
expect(screen.getAllByText('Square').length).toBeGreaterThanOrEqual(1);
expect(screen.getByText('Rounded')).toBeInTheDocument();
expect(screen.getByText('Dots')).toBeInTheDocument();
expect(screen.getByText('Classy')).toBeInTheDocument();
expect(screen.getByText('Classy Rounded')).toBeInTheDocument();
expect(screen.getAllByText('Extra Rounded').length).toBeGreaterThanOrEqual(1);
});
it('renders corner frame and corner dot style sections', () => {
renderDialog();
expect(screen.getByText('Corner Frame')).toBeInTheDocument();
expect(screen.getByText('Corner Dot')).toBeInTheDocument();
});
it('renders center logo options', () => {
renderDialog();
expect(screen.getByText('Center Logo')).toBeInTheDocument();
expect(screen.getByText('None')).toBeInTheDocument();
expect(screen.getByText('Nomad Karaoke')).toBeInTheDocument();
expect(screen.getByText('Microphone')).toBeInTheDocument();
expect(screen.getByText('Music')).toBeInTheDocument();
});
it('renders color picker inputs', () => {
renderDialog();
expect(screen.getByText('Foreground')).toBeInTheDocument();
expect(screen.getByText('Background')).toBeInTheDocument();
// Color inputs
const colorInputs = screen.getAllByDisplayValue('#000000');
expect(colorInputs.length).toBeGreaterThanOrEqual(1);
});
it('saves style prefs to localStorage on change', async () => {
jest.useFakeTimers();
renderDialog();
// Click "Rounded" dot style
fireEvent.click(screen.getByText('Rounded'));
// Flush the debounce timer
act(() => { jest.runAllTimers(); });
const saved = JSON.parse(localStorage.getItem('nk-qr-style-prefs') || '{}');
expect(saved.dotStyle).toBe('rounded');
jest.useRealTimers();
});
it('restores style prefs from localStorage on open', () => {
localStorage.setItem('nk-qr-style-prefs', JSON.stringify({
dotStyle: 'dots',
cornerSquareStyle: 'dot',
cornerDotStyle: 'dot',
fgColor: '#ff0000',
bgColor: '#00ff00',
logo: 'nomad',
}));
renderDialog();
// The foreground color input should have the saved value
const fgInput = screen.getByDisplayValue('#ff0000');
expect(fgInput).toBeInTheDocument();
});
it('calls download with PNG extension when Download PNG clicked', async () => {
const user = userEvent.setup();
renderDialog();
await user.click(screen.getByText('Download PNG'));
await waitFor(() => {
expect(mockDownload).toHaveBeenCalledWith({
name: 'referral-qr',
extension: 'png',
});
});
});
it('calls download with SVG extension when Download SVG clicked', async () => {
const user = userEvent.setup();
renderDialog();
await user.click(screen.getByText('Download SVG'));
await waitFor(() => {
expect(mockDownload).toHaveBeenCalledWith({
name: 'referral-qr',
extension: 'svg',
});
});
});
});
+9 -9
View File
@@ -36,10 +36,10 @@ test.describe('Landing Page', () => {
response: {
body: {
packages: [
{ id: 'credit_1', credits: 1, price_cents: 500 },
{ id: 'credit_3', credits: 3, price_cents: 1200 },
{ id: 'credit_5', credits: 5, price_cents: 1750 },
{ id: 'credit_10', credits: 10, price_cents: 3000 },
{ id: 'credit_1', credits: 1, price_cents: 1000 },
{ id: 'credit_3', credits: 3, price_cents: 2400 },
{ id: 'credit_5', credits: 5, price_cents: 3500 },
{ id: 'credit_10', credits: 10, price_cents: 6000 },
],
},
},
@@ -71,10 +71,10 @@ test.describe('Landing Page', () => {
response: {
body: {
packages: [
{ id: 'credit_1', credits: 1, price_cents: 500 },
{ id: 'credit_3', credits: 3, price_cents: 1200 },
{ id: 'credit_5', credits: 5, price_cents: 1750 },
{ id: 'credit_10', credits: 10, price_cents: 3000 },
{ id: 'credit_1', credits: 1, price_cents: 1000 },
{ id: 'credit_3', credits: 3, price_cents: 2400 },
{ id: 'credit_5', credits: 5, price_cents: 3500 },
{ id: 'credit_10', credits: 10, price_cents: 6000 },
],
},
},
@@ -175,7 +175,7 @@ test.describe('Landing Page', () => {
response: {
body: {
packages: [
{ id: 'credit_5', credits: 5, price_cents: 1750 },
{ id: 'credit_5', credits: 5, price_cents: 3500 },
],
},
},
+1 -1
View File
@@ -108,7 +108,7 @@ test.describe('Mobile - Landing Page', () => {
response: {
body: {
packages: [
{ id: 'credit_1', credits: 1, price_cents: 500 },
{ id: 'credit_1', credits: 1, price_cents: 1000 },
],
},
},
+105 -3
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)
@@ -1273,11 +1273,14 @@ export const api = {
/**
* Send a magic link email for passwordless login
*/
async sendMagicLink(email: string, deviceFingerprint?: string | null): Promise<MagicLinkResponse> {
async sendMagicLink(email: string, deviceFingerprint?: string | null, referralCode?: string | null): Promise<MagicLinkResponse> {
const body: Record<string, string> = { email }
if (deviceFingerprint) {
body.device_fingerprint = deviceFingerprint
}
if (referralCode) {
body.referral_code = referralCode
}
const response = await fetch(`${API_BASE_URL}/api/users/auth/magic-link`, {
method: 'POST',
headers: {
@@ -1291,9 +1294,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);
},
@@ -1669,6 +1677,10 @@ export interface AdminUserDetail {
device_fingerprint?: string | null;
welcome_credits_granted?: boolean;
has_submitted_feedback?: boolean;
// Referral fields
referred_by_code?: string | null;
referral_discount_expires_at?: string | null;
referral_code?: string | null;
recent_sessions?: Array<{
ip_address?: string;
user_agent?: string;
@@ -1817,6 +1829,22 @@ export const adminApi = {
return handleResponse(response);
},
/**
* Apply a referral discount to a user (admin only)
*/
async applyDiscount(email: string, data: {
discount_percent?: number;
duration_days?: number;
referral_code?: string;
}): Promise<{ ok: boolean; message: string; discount_expires_at: string }> {
const response = await fetch(`${API_BASE_URL}/api/referrals/admin/apply-discount`, {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ email, ...data }),
});
return handleResponse(response);
},
/**
* Impersonate a user (admin only)
* Creates a session token that allows viewing the app as the target user
@@ -2510,6 +2538,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 +3531,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();
}
+24 -2
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
@@ -56,7 +57,8 @@ export const useAuth = create<AuthStore>()(
// Get device fingerprint for anti-abuse rate limiting
const { getDeviceFingerprint } = await import('./fingerprint')
const fingerprint = await getDeviceFingerprint()
await api.sendMagicLink(email, fingerprint)
const referralCode = getReferralCode()
await api.sendMagicLink(email, fingerprint, referralCode)
set({ isLoading: false })
return true
} catch (err) {
@@ -71,11 +73,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__ = {
@@ -95,6 +101,10 @@ export const useAuth = create<AuthStore>()(
total_jobs_created: response.user.total_jobs_created,
total_jobs_completed: response.user.total_jobs_completed,
feedback_eligible: response.user.feedback_eligible,
has_active_referral_discount: response.user.has_active_referral_discount,
referral_discount_percent: response.user.referral_discount_percent,
referral_discount_expires_at: response.user.referral_discount_expires_at,
referred_by_code: response.user.referred_by_code,
}
set({ user, isLoading: false })
@@ -128,6 +138,10 @@ export const useAuth = create<AuthStore>()(
total_jobs_created: response.user.total_jobs_created,
total_jobs_completed: response.user.total_jobs_completed,
feedback_eligible: response.user.feedback_eligible,
has_active_referral_discount: response.user.has_active_referral_discount,
referral_discount_percent: response.user.referral_discount_percent,
referral_discount_expires_at: response.user.referral_discount_expires_at,
referred_by_code: response.user.referred_by_code,
}
set({ user, isLoading: false })
@@ -181,6 +195,10 @@ export const useAuth = create<AuthStore>()(
total_jobs_created: response.user.total_jobs_created,
total_jobs_completed: response.user.total_jobs_completed,
feedback_eligible: response.user.feedback_eligible,
has_active_referral_discount: response.user.has_active_referral_discount,
referral_discount_percent: response.user.referral_discount_percent,
referral_discount_expires_at: response.user.referral_discount_expires_at,
referred_by_code: response.user.referred_by_code,
}
set({ user, isLoading: false })
@@ -243,6 +261,10 @@ export const useAuth = create<AuthStore>()(
total_jobs_created: userResponse.user.total_jobs_created,
total_jobs_completed: userResponse.user.total_jobs_completed,
feedback_eligible: userResponse.user.feedback_eligible,
has_active_referral_discount: userResponse.user.has_active_referral_discount,
referral_discount_percent: userResponse.user.referral_discount_percent,
referral_discount_expires_at: userResponse.user.referral_discount_expires_at,
referred_by_code: userResponse.user.referred_by_code,
}
set({
+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);
}
+65
View File
@@ -9,6 +9,10 @@ export interface User {
total_jobs_created?: number
total_jobs_completed?: number
feedback_eligible?: boolean
has_active_referral_discount?: boolean
referral_discount_percent?: number
referral_discount_expires_at?: string
referred_by_code?: string
}
export interface UserPublic {
@@ -19,6 +23,11 @@ export interface UserPublic {
total_jobs_created?: number
total_jobs_completed?: number
feedback_eligible?: boolean
referral_code?: string
has_active_referral_discount?: boolean
referral_discount_percent?: number
referral_discount_expires_at?: string
referred_by_code?: string
}
export interface MagicLinkResponse {
@@ -66,3 +75,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 {
referral_code: string;
referrer_display_name: string | null;
custom_message: string | null;
discount_percent: number;
discount_duration_days: number;
valid: boolean;
}
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "أنشئه بنفسك",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "يتضمن رصيداً مجانياً واحداً - لا يتطلب الدفع",
"makeForYou": "سنصنعه لك",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Crea'l tu mateix",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 crèdit gratuït inclòs - no cal pagar",
"makeForYou": "Ho farem per tu",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Vytvoř si ho sám",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Obsahuje 1 kredit zdarma - není nutná žádná platba",
"makeForYou": "Uděláme to za tebe",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Lav den selv",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 gratis credit inkluderet - ingen betaling påkrævet",
"makeForYou": "Vi laver den for dig",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Erstelle es selbst",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 kostenloses Guthaben inklusive - keine Zahlung erforderlich",
"makeForYou": "Wir machen es für dich",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Δημιούργησέ το Μόνος σου",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Περιλαμβάνεται 1 δωρεάν μονάδα - δεν απαιτείται πληρωμή",
"makeForYou": "Θα το Φτιάξουμε Εμείς για Σένα",
"makeForYouPrice": "$50",
+59 -2
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Create It Yourself",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 free credit included - no payment required",
"makeForYou": "We'll Make It For You",
"makeForYouPrice": "$50",
@@ -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,61 @@
"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",
"qrCode": "QR Code",
"qrTitle": "QR Code Generator",
"qrDotStyle": "Dot Style",
"qrCornerFrame": "Corner Frame",
"qrCornerDot": "Corner Dot",
"qrColors": "Colors",
"qrForeground": "Foreground",
"qrBackground": "Background",
"qrLogo": "Center Logo",
"qrLogoNone": "None",
"qrLogoNomad": "Nomad Karaoke",
"qrLogoMic": "Microphone",
"qrLogoMusic": "Music",
"qrDownloadPng": "Download PNG",
"qrDownloadSvg": "Download SVG",
"qrStyleSquare": "Square",
"qrStyleRounded": "Rounded",
"qrStyleDots": "Dots",
"qrStyleClassy": "Classy",
"qrStyleClassyRounded": "Classy Rounded",
"qrStyleExtraRounded": "Extra Rounded",
"qrStyleDot": "Dot"
}
}
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Créalo tú mismo",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 crédito gratis incluido - sin necesidad de pago",
"makeForYou": "Lo haremos por ti",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Luo se itse",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Sisältää 1 ilmaisen krediitin - ei vaadi maksua",
"makeForYou": "Me teemme sen puolestasi",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Crée-le toi-même",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 crédit gratuit inclus - aucun paiement requis",
"makeForYou": "Nous le créons pour toi",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "צור בעצמך",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "כולל קרדיט 1 חינם - ללא צורך בתשלום",
"makeForYou": "אנחנו נכין את זה עבורך",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "इसे खुद बनाओ",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 मुफ़्त क्रेडिट शामिल - कोई पेमेंट ज़रूरी नहीं",
"makeForYou": "हम तुम्हारे लिए बनाएंगे",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Izradi sam",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Uključen 1 besplatan kredit - nije potrebno plaćanje",
"makeForYou": "Mi ćemo to izraditi za tebe",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Készítsd el te magad",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 ingyenes kreditet tartalmaz - nem szükséges fizetni",
"makeForYou": "Mi elkészítjük neked",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Buat Sendiri",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Termasuk 1 kredit gratis - tidak perlu membayar",
"makeForYou": "Kami Buatkan Untuk Anda",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Crealo tu stesso",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 credito gratuito incluso - nessun pagamento richiesto",
"makeForYou": "Lo facciamo noi per te",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "自分で作成する",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1無料クレジット付き - お支払いは不要です",
"makeForYou": "おまかせ作成",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "직접 만들기",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "무료 크레딧 1개 포함 - 결제 불필요",
"makeForYou": "제작 맡기기",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Cipta Sendiri",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Termasuk 1 kredit percuma - tiada pembayaran diperlukan",
"makeForYou": "Kami Akan Buatkannya Untuk Anda",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Lag den selv",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 gratis kreditt inkludert - ingen betaling kreves",
"makeForYou": "Vi lager den for deg",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Maak het zelf",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Inclusief 1 gratis credit - geen betaling vereist",
"makeForYou": "Wij maken het voor je",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Stwórz samodzielnie",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Zawiera 1 darmowy kredyt - nie wymaga płatności",
"makeForYou": "Zrobimy to za Ciebie",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Crie Você Mesmo",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 crédito grátis incluído - sem necessidade de pagamento",
"makeForYou": "Nós Fazemos Para Você",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Creează-l singur",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 credit gratuit inclus - nu este necesară nicio plată",
"makeForYou": "Îl creăm noi pentru tine",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Создай сам",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Включен 1 бесплатный кредит — оплата не требуется",
"makeForYou": "Мы сделаем это для тебя",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Vytvor si to sám",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 bezplatný kredit v cene - nevyžaduje sa žiadna platba",
"makeForYou": "Urobíme to za teba",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Skapa den själv",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 gratis kredit ingår - ingen betalning krävs",
"makeForYou": "Vi gör den åt dig",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "สร้างด้วยตัวเอง",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "รับฟรี 1 เครดิต - ไม่มีค่าใช้จ่าย",
"makeForYou": "ให้เราทำให้คุณ",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Ikaw Mismo ang Gumawa",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Kasama ang 1 libreng credit - walang kailangang bayaran",
"makeForYou": "Kami na ang Gagawa Para sa Iyo",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Kendin Oluştur",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 ücretsiz kredi dahil - ödeme gerekmez",
"makeForYou": "Biz Senin İçin Yapalım",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Створи самостійно",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "1 безкоштовний кредит включено - оплата не потрібна",
"makeForYou": "Ми зробимо це для тебе",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "Tự tạo",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "Bao gồm 1 credit miễn phí - không cần thanh toán",
"makeForYou": "Chúng tôi sẽ làm cho bạn",
"makeForYouPrice": "$50",
+1 -1
View File
@@ -56,7 +56,7 @@
},
"heroCTA": {
"createYourself": "自己创建",
"createYourselfPrice": "$5",
"createYourselfPrice": "$10",
"createYourselfNote": "包含 1 个免费点数 —— 无需付款",
"makeForYou": "我们为您制作",
"makeForYouPrice": "$50",
+19
View File
@@ -51,6 +51,7 @@
"next": "16.0.7",
"next-intl": "^4.9.0",
"next-themes": "^0.4.6",
"qr-code-styling": "^1.9.2",
"react": "19.2.0",
"react-day-picker": "9.8.0",
"react-dom": "19.2.0",
@@ -11429,6 +11430,24 @@
],
"license": "MIT"
},
"node_modules/qr-code-styling": {
"version": "1.9.2",
"resolved": "https://registry.npmjs.org/qr-code-styling/-/qr-code-styling-1.9.2.tgz",
"integrity": "sha512-RgJaZJ1/RrXJ6N0j7a+pdw3zMBmzZU4VN2dtAZf8ZggCfRB5stEQ3IoDNGaNhYY3nnZKYlYSLl5YkfWN5dPutg==",
"license": "MIT",
"dependencies": {
"qrcode-generator": "^1.4.4"
},
"engines": {
"node": ">=18.18.0"
}
},
"node_modules/qrcode-generator": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-1.5.2.tgz",
"integrity": "sha512-pItrW0Z9HnDBnFmgiNrY1uxRdri32Uh9EjNYLPVC2zZ3ZRIIEqBoDgm4DkvDwNNDHTK7FNkmr8zAa77BYc9xNw==",
"license": "MIT"
},
"node_modules/querystringify": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
+1
View File
@@ -73,6 +73,7 @@
"next": "16.0.7",
"next-intl": "^4.9.0",
"next-themes": "^0.4.6",
"qr-code-styling": "^1.9.2",
"react": "19.2.0",
"react-day-picker": "9.8.0",
"react-dom": "19.2.0",
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.162.2"
version = "0.164.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"