gen: vanity referral request approve/deny queue (rename-in-place) (#967)

## Problem

When a user requests a custom vanity referral code, the backend only
emailed the admin — nothing was persisted. To "approve," the admin had
to open **Create Vanity Link** and hand-retype the owner email + desired
code, which created a *second* link alongside the user's auto-generated
one (split stats, two live codes). The **Edit** modal can't change a
link's code. There was no approve/deny concept and no notification to
the requester. Confusing and unintuitive (reported first-hand while
setting up the YouTube referral link).

## Solution

User vanity requests now persist to Firestore and surface as a
**"Pending Vanity Requests"** banner at the top of `/admin/referrals`
with one-click **Approve** / **Deny**.

- **Approve** = renames the user's existing link *in place* (`odu4brd8`
→ `youtube`): stats/earnings preserved, referral attribution
(`referred_by_code` + earnings) migrated, old code disabled as a
breadcrumb (stats zeroed so admin totals don't double-count), and the
requester is **emailed** that their link is live.
- **Deny** = marks the request denied.
- One unified code per user — no more duplicate links or split stats.

## Changes

**Backend**
- `VanityRequestDoc` model (`referral_vanity_requests`, keyed by
owner_email so a re-request overwrites).
- `referral_service`: `create_vanity_request` / `list` / `get` /
`approve` / `deny` + `rename_link` (atomic `create()` to close the
destination-code race; migrates attribution; zeroes old-alias stats).
`get_or_create_link` now prefers enabled links so the renamed alias
never resurfaces.
- 3 admin endpoints: `GET/POST /admin/vanity-requests[...]`.
`request_vanity_url` now validates the code up-front (before link
creation) and persists the request.

**Frontend** (`/admin/referrals` is English-only, no i18n)
- Pending-requests banner card +
`adminApi.listVanityRequests/approveVanityRequest/denyVanityRequest` +
`VanityRequest` type.

## Testing

- Backend unit/route: **21** (approve/deny/list, request validation,
404/400 paths)
- Emulator (real Firestore): **11** (rename preserves stats + migrates
attribution + disables/zeroes old alias; atomic create blocks taken
codes; approve/deny/re-request)
- Frontend: **4** (banner renders, approve/deny wiring, hidden when
empty)
- Version `0.214.0` → `0.215.0`. Local CodeRabbit review completed (2
fix cycles).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Andrew Beveridge ☄️andClaude Opus 4.8 authored and GitHub committed 2026-08-30 21:52:26 -04:00
1 parent 0bebf5c170
commit feb4c86842
12 files changed
+970 -12

No files matched your search

+89 -2
View File
@@ -19,6 +19,7 @@ from backend.models.referral import (
CreateReferralLinkRequest,
UpdateReferralLinkRequest,
ReferralInterstitialResponse,
VanityRequestResponse,
)
from backend.services.flyer_service import get_flyer_service, FlyerError
from backend.services.referral_service import get_referral_service
@@ -172,13 +173,29 @@ async def request_vanity_url(
from backend.services.email_service import get_email_service
service = get_referral_service()
link = service.get_or_create_link(auth.user_email)
# Validate up-front against the same rules approval enforces (reserved words,
# vanity pattern) so a request that would later be auto-rejected never lands
# in the admin queue. Do this before get_or_create_link so a rejected request
# from a brand-new user doesn't leave an orphaned auto-generated link behind.
valid, msg = service._validate_vanity_code(request.desired_code)
if not valid:
raise HTTPException(status_code=400, detail=msg)
# Check if code is already taken
existing = service.get_link_by_code(request.desired_code)
if existing:
raise HTTPException(status_code=409, detail="That code is already taken. Please try another.")
link = service.get_or_create_link(auth.user_email)
# Persist the request so it shows up as a pending item in the admin dashboard.
service.create_vanity_request(
owner_email=auth.user_email,
current_code=link.code,
desired_code=request.desired_code,
)
email_service = get_email_service()
email_service.provider.send_email(
to_email="andrew@nomadkaraoke.com",
@@ -188,7 +205,7 @@ async def request_vanity_url(
<p><strong>User:</strong> {auth.user_email}</p>
<p><strong>Current code:</strong> {link.code}</p>
<p><strong>Desired vanity code:</strong> {request.desired_code}</p>
<p>To approve, create the vanity link in the <a href="https://gen.nomadkaraoke.com/admin/referrals">admin dashboard</a>.</p>
<p>Approve or deny it under "Pending Vanity Requests" in the <a href="https://gen.nomadkaraoke.com/admin/referrals">admin dashboard</a>.</p>
""",
text_content=f"Vanity URL request from {auth.user_email}: {request.desired_code} (current: {link.code})",
)
@@ -258,6 +275,76 @@ async def create_vanity_link(
return {"ok": True, "code": link.code, "message": message}
@router.get("/admin/vanity-requests")
async def list_vanity_requests(
status: str = Query("pending", pattern="^(pending|approved|denied)$"),
auth=Depends(require_admin),
):
"""Admin: list vanity code requests (pending by default)."""
service = get_referral_service()
requests = service.list_vanity_requests(status=status)
return {
"requests": [
VanityRequestResponse(**r.model_dump()).model_dump(mode="json")
for r in requests
],
"count": len(requests),
}
@router.post("/admin/vanity-requests/{request_id}/approve")
async def approve_vanity_request(
request_id: str,
auth=Depends(require_admin),
):
"""Admin: approve a vanity request by renaming the owner's link, then notify them."""
from backend.services.email_service import get_email_service
service = get_referral_service()
req = service.get_vanity_request(request_id)
if not req:
raise HTTPException(status_code=404, detail="Request not found")
success, link, message = service.approve_vanity_request(
request_id, resolved_by=auth.user_email
)
if not success:
raise HTTPException(status_code=400, detail=message)
# Notify the requester that their vanity URL is live.
try:
referral_url = f"https://nomadkaraoke.com/r/{link.code}"
get_email_service().provider.send_email(
to_email=req.owner_email,
subject="Your custom referral link is live 🎉",
html_content=f"""
<h2>Your custom referral link is ready</h2>
<p>Good news — your requested referral code <strong>{link.code}</strong> is now active.</p>
<p>Share it anywhere: <a href="{referral_url}">{referral_url}</a></p>
<p>All your existing clicks, signups, and earnings carried over automatically.</p>
""",
text_content=f"Your custom referral link is live: {referral_url}",
)
except Exception:
logger.warning("Failed to send vanity-approved email to %s", req.owner_email, exc_info=True)
return {"ok": True, "code": link.code, "message": message}
@router.post("/admin/vanity-requests/{request_id}/deny")
async def deny_vanity_request(
request_id: str,
auth=Depends(require_admin),
):
"""Admin: deny a vanity request."""
service = get_referral_service()
success, message = service.deny_vanity_request(request_id, resolved_by=auth.user_email)
if not success:
raise HTTPException(status_code=400, detail=message)
return {"ok": True, "message": message}
@router.get("/admin/links")
async def list_links(
limit: int = Query(50, ge=1, le=200),
+28
View File
@@ -57,6 +57,24 @@ class ReferralLink(BaseModel):
stats: ReferralLinkStats = Field(default_factory=ReferralLinkStats)
class VanityRequestDoc(BaseModel):
"""
A user's request for a custom vanity referral code, awaiting admin review.
Stored in Firestore keyed by ``owner_email`` so a re-request overwrites the
previous pending one (a user only ever has one outstanding request).
"""
id: str # Firestore doc id (owner_email, lowercased)
owner_email: str
current_code: str # The user's existing (usually auto-generated) code
desired_code: str # The vanity code they want
status: str = "pending" # pending, approved, denied
created_at: datetime = Field(default_factory=datetime.utcnow)
resolved_at: Optional[datetime] = None
resolved_by: Optional[str] = None # Admin who approved/denied
note: Optional[str] = None # Optional reason (e.g. denial reason)
class ReferralEarning(BaseModel):
"""
Record of a single earning from a referred purchase.
@@ -136,6 +154,16 @@ class ReferralLinkResponse(BaseModel):
created_at: datetime
class VanityRequestResponse(BaseModel):
"""Pending vanity request info for the admin dashboard."""
id: str
owner_email: str
current_code: str
desired_code: str
status: str
created_at: datetime
class ReferralEarningResponse(BaseModel):
"""Public earning information (for referrer dashboard)."""
id: str
+176 -3
View File
@@ -14,6 +14,7 @@ import string
from datetime import datetime, timedelta
from typing import List, Optional, Tuple
from google.api_core.exceptions import AlreadyExists
from google.cloud import firestore
from backend.models.referral import (
@@ -21,6 +22,7 @@ from backend.models.referral import (
ReferralLinkStats,
ReferralEarning,
ReferralPayout,
VanityRequestDoc,
)
@@ -34,6 +36,8 @@ logger = logging.getLogger(__name__)
REFERRAL_LINKS_COLLECTION = "referral_links"
REFERRAL_EARNINGS_COLLECTION = "referral_earnings"
REFERRAL_PAYOUTS_COLLECTION = "referral_payouts"
REFERRAL_VANITY_REQUESTS_COLLECTION = "referral_vanity_requests"
USERS_COLLECTION = "gen_users"
RESERVED_CODES = frozenset({
"admin", "app", "api", "r", "pricing", "order", "payment",
@@ -103,15 +107,22 @@ class ReferralService:
Retries up to 10 times if generated code collides with existing doc.
"""
# Check for existing link
# Check for an existing link. Prefer an enabled one — a link that was
# renamed (vanity approval) leaves a disabled alias doc behind with the
# same owner_email, and we must never hand that stale code back.
existing = (
self.db.collection(REFERRAL_LINKS_COLLECTION)
.where("owner_email", "==", owner_email)
.limit(1)
.stream()
)
fallback: Optional[ReferralLink] = None
for doc in existing:
return ReferralLink(**doc.to_dict())
link = ReferralLink(**doc.to_dict())
if link.enabled:
return link
fallback = fallback or link
if fallback is not None:
return fallback
# Create new link with retry for code collision
for attempt in range(10):
@@ -190,6 +201,168 @@ class ReferralService:
doc_ref.update(updates)
return True, "Link updated"
def rename_link(self, old_code: str, new_code: str) -> Tuple[bool, Optional[ReferralLink], str]:
"""Rename a referral link's code in place, preserving stats and config.
The Firestore doc id *is* the code, so this copies the old doc to a new
doc under ``new_code`` (marked as a vanity link), migrates referral
attribution that pointed at ``old_code``, then disables the old doc and
records ``renamed_to`` so stale links resolve to nothing.
Returns (success, new_link_or_none, message).
"""
old_code = old_code.lower()
valid, msg = self._validate_vanity_code(new_code)
if not valid:
return False, None, msg
new_code = new_code.lower()
if new_code == old_code:
return False, None, "New code is the same as the current code"
old_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(old_code)
old_snapshot = old_ref.get()
if not old_snapshot.exists:
return False, None, f"Link '{old_code}' not found"
data = old_snapshot.to_dict()
now = datetime.utcnow()
data["code"] = new_code
data["is_vanity"] = True
data["enabled"] = True
data["updated_at"] = now
data.pop("renamed_to", None)
# create() (not set()) atomically claims the new code — it fails fast if
# the code was taken between here and the caller's checks, closing the
# time-of-check/time-of-use race for two concurrent approvals.
new_ref = self.db.collection(REFERRAL_LINKS_COLLECTION).document(new_code)
try:
new_ref.create(data)
except AlreadyExists:
return False, None, f"Code '{new_code}' is already taken"
# Migrate attribution that referenced the old code so existing referred
# users keep earning under the renamed link.
self._migrate_code_references(old_code, new_code)
# Disable the old doc, leaving a breadcrumb. Keeping (not deleting) it
# reserves the code so it can't be re-issued to someone else. Stats now
# live on the new doc, so zero them here to avoid double-counting in the
# admin dashboard's aggregate totals.
old_ref.update({
"enabled": False,
"renamed_to": new_code,
"updated_at": now,
"stats": ReferralLinkStats().model_dump(),
})
return True, ReferralLink(**data), f"Renamed '{old_code}' to '{new_code}'"
def _migrate_code_references(self, old_code: str, new_code: str) -> None:
"""Repoint user attribution and earnings records from old_code to new_code."""
users = (
self.db.collection(USERS_COLLECTION)
.where("referred_by_code", "==", old_code)
.stream()
)
for doc in users:
doc.reference.update({"referred_by_code": new_code})
earnings = (
self.db.collection(REFERRAL_EARNINGS_COLLECTION)
.where("referral_code", "==", old_code)
.stream()
)
for doc in earnings:
doc.reference.update({"referral_code": new_code})
# ========================================================================
# Vanity requests (user-requested code changes, admin-reviewed)
# ========================================================================
def create_vanity_request(
self, owner_email: str, current_code: str, desired_code: str
) -> VanityRequestDoc:
"""Persist a pending vanity request. Keyed by owner so re-requests overwrite."""
owner_email = owner_email.lower()
req = VanityRequestDoc(
id=owner_email,
owner_email=owner_email,
current_code=current_code.lower(),
desired_code=desired_code.lower(),
status="pending",
created_at=datetime.utcnow(),
)
self.db.collection(REFERRAL_VANITY_REQUESTS_COLLECTION).document(owner_email).set(
req.model_dump()
)
return req
def get_vanity_request(self, request_id: str) -> Optional[VanityRequestDoc]:
doc = (
self.db.collection(REFERRAL_VANITY_REQUESTS_COLLECTION)
.document(request_id.lower())
.get()
)
if not doc.exists:
return None
return VanityRequestDoc(**doc.to_dict())
def list_vanity_requests(self, status: Optional[str] = "pending") -> List[VanityRequestDoc]:
"""List vanity requests, optionally filtered by status."""
col = self.db.collection(REFERRAL_VANITY_REQUESTS_COLLECTION)
query = col.where("status", "==", status) if status else col
requests = [VanityRequestDoc(**doc.to_dict()) for doc in query.stream()]
requests.sort(key=lambda r: r.created_at, reverse=True)
return requests
def approve_vanity_request(
self, request_id: str, resolved_by: Optional[str] = None
) -> Tuple[bool, Optional[ReferralLink], str]:
"""Approve a pending vanity request by renaming the owner's link.
Returns (success, new_link_or_none, message).
"""
req = self.get_vanity_request(request_id)
if not req:
return False, None, "Request not found"
if req.status != "pending":
return False, None, f"Request already {req.status}"
# Re-fetch the owner's current enabled link rather than trusting the
# stored current_code, in case it changed since the request was filed.
current = self.get_or_create_link(req.owner_email)
success, link, message = self.rename_link(current.code, req.desired_code)
if not success:
return False, None, message
self.db.collection(REFERRAL_VANITY_REQUESTS_COLLECTION).document(req.id).update({
"status": "approved",
"resolved_at": datetime.utcnow(),
"resolved_by": resolved_by,
})
return True, link, message
def deny_vanity_request(
self, request_id: str, resolved_by: Optional[str] = None, note: Optional[str] = None
) -> Tuple[bool, str]:
"""Deny a pending vanity request."""
req = self.get_vanity_request(request_id)
if not req:
return False, "Request not found"
if req.status != "pending":
return False, f"Request already {req.status}"
self.db.collection(REFERRAL_VANITY_REQUESTS_COLLECTION).document(req.id).update({
"status": "denied",
"resolved_at": datetime.utcnow(),
"resolved_by": resolved_by,
"note": note,
})
return True, "Request denied"
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)
@@ -0,0 +1,216 @@
"""
Emulator integration tests for the vanity referral request approve/deny flow.
Exercises ReferralService against a REAL Firestore emulator so the multi-doc
rename migration (copy → migrate attribution → disable old) is verified for real,
not mocked. Run with: scripts/run-emulator-tests.sh
"""
import uuid
import pytest
from google.cloud import firestore
from backend.models.referral import ReferralLink, ReferralLinkStats
from backend.services.referral_service import (
ReferralService,
REFERRAL_LINKS_COLLECTION,
REFERRAL_EARNINGS_COLLECTION,
REFERRAL_VANITY_REQUESTS_COLLECTION,
USERS_COLLECTION,
)
@pytest.fixture
def service():
"""ReferralService backed by the Firestore emulator."""
return ReferralService(db=firestore.Client())
def _uniq() -> str:
return uuid.uuid4().hex[:8]
def _seed_link(service, code, owner_email, **overrides):
"""Create a referral link doc directly in the emulator."""
data = ReferralLink(
code=code,
owner_email=owner_email,
display_name="Seeded",
stats=ReferralLinkStats(clicks=5, signups=2, purchases=1, total_earned_cents=500),
**overrides,
).model_dump()
service.db.collection(REFERRAL_LINKS_COLLECTION).document(code).set(data)
return data
class TestRenameLink:
def test_preserves_stats_and_disables_old(self, service):
suffix = _uniq()
old, new = f"old{suffix}", f"yt{suffix}"
owner = f"{suffix}@example.com"
_seed_link(service, old, owner)
ok, link, _ = service.rename_link(old, new)
assert ok is True
assert link.code == new
assert link.is_vanity is True
assert link.enabled is True
# Stats carried over
assert link.stats.clicks == 5
assert link.stats.signups == 2
assert link.stats.total_earned_cents == 500
# New doc exists & enabled; old doc kept but disabled with a breadcrumb
new_doc = service.db.collection(REFERRAL_LINKS_COLLECTION).document(new).get().to_dict()
old_doc = service.db.collection(REFERRAL_LINKS_COLLECTION).document(old).get().to_dict()
assert new_doc["enabled"] is True
assert old_doc["enabled"] is False
assert old_doc["renamed_to"] == new
# Stats moved to the new doc; the alias is zeroed so aggregate admin
# totals don't double-count the same clicks/earnings.
assert new_doc["stats"]["clicks"] == 5
assert old_doc["stats"]["clicks"] == 0
assert old_doc["stats"]["total_earned_cents"] == 0
def test_rejects_invalid_new_code(self, service):
suffix = _uniq()
old = f"old{suffix}"
_seed_link(service, old, f"{suffix}@example.com")
ok, link, msg = service.rename_link(old, "admin") # reserved
assert ok is False
assert link is None
def test_rejects_taken_code(self, service):
suffix = _uniq()
old, taken = f"old{suffix}", f"taken{suffix}"
_seed_link(service, old, f"{suffix}@example.com")
_seed_link(service, taken, f"other{suffix}@example.com")
ok, link, msg = service.rename_link(old, taken)
assert ok is False
assert "taken" in msg.lower()
def test_migrates_attribution(self, service):
suffix = _uniq()
old, new = f"old{suffix}", f"yt{suffix}"
owner = f"{suffix}@example.com"
_seed_link(service, old, owner)
# A referred user and an earning both point at the old code
referred_email = f"referred{suffix}@example.com"
service.db.collection(USERS_COLLECTION).document(referred_email).set({
"email": referred_email,
"referred_by_code": old,
})
earning_id = f"earn{suffix}"
service.db.collection(REFERRAL_EARNINGS_COLLECTION).document(earning_id).set({
"id": earning_id,
"referral_code": old,
"referrer_email": owner,
})
service.rename_link(old, new)
user_doc = service.db.collection(USERS_COLLECTION).document(referred_email).get().to_dict()
earning_doc = service.db.collection(REFERRAL_EARNINGS_COLLECTION).document(earning_id).get().to_dict()
assert user_doc["referred_by_code"] == new
assert earning_doc["referral_code"] == new
def test_get_or_create_link_prefers_enabled_after_rename(self, service):
suffix = _uniq()
old, new = f"old{suffix}", f"yt{suffix}"
owner = f"{suffix}@example.com"
_seed_link(service, old, owner)
service.rename_link(old, new)
# Owner now has a disabled old doc + enabled new doc with same owner_email
link = service.get_or_create_link(owner)
assert link.code == new
assert link.enabled is True
class TestVanityRequestFlow:
def test_create_and_list(self, service):
suffix = _uniq()
owner = f"{suffix}@example.com"
service.create_vanity_request(owner, f"old{suffix}", f"yt{suffix}")
pending = service.list_vanity_requests(status="pending")
assert any(r.owner_email == owner and r.desired_code == f"yt{suffix}" for r in pending)
def test_rerequest_overwrites(self, service):
suffix = _uniq()
owner = f"{suffix}@example.com"
service.create_vanity_request(owner, f"old{suffix}", f"first{suffix}")
service.create_vanity_request(owner, f"old{suffix}", f"second{suffix}")
req = service.get_vanity_request(owner)
assert req.desired_code == f"second{suffix}"
# Only one doc for this owner
docs = list(
service.db.collection(REFERRAL_VANITY_REQUESTS_COLLECTION)
.where("owner_email", "==", owner)
.stream()
)
assert len(docs) == 1
def test_approve_renames_link_and_marks_approved(self, service):
suffix = _uniq()
old, desired = f"old{suffix}", f"yt{suffix}"
owner = f"{suffix}@example.com"
_seed_link(service, old, owner)
service.create_vanity_request(owner, old, desired)
ok, link, _ = service.approve_vanity_request(owner, resolved_by="admin@nomadkaraoke.com")
assert ok is True
assert link.code == desired
assert link.stats.clicks == 5 # preserved
req = service.get_vanity_request(owner)
assert req.status == "approved"
assert req.resolved_by == "admin@nomadkaraoke.com"
def test_approve_fails_when_desired_code_taken(self, service):
suffix = _uniq()
old, desired = f"old{suffix}", f"yt{suffix}"
owner = f"{suffix}@example.com"
_seed_link(service, old, owner)
# Someone else already owns the desired code
_seed_link(service, desired, f"squatter{suffix}@example.com")
service.create_vanity_request(owner, old, desired)
ok, link, msg = service.approve_vanity_request(owner)
assert ok is False
assert link is None
# Request stays pending so the admin can retry / deny
assert service.get_vanity_request(owner).status == "pending"
def test_approve_twice_is_rejected(self, service):
suffix = _uniq()
old, desired = f"old{suffix}", f"yt{suffix}"
owner = f"{suffix}@example.com"
_seed_link(service, old, owner)
service.create_vanity_request(owner, old, desired)
service.approve_vanity_request(owner)
ok, _, msg = service.approve_vanity_request(owner)
assert ok is False
assert "approved" in msg.lower()
def test_deny_marks_denied(self, service):
suffix = _uniq()
owner = f"{suffix}@example.com"
service.create_vanity_request(owner, f"old{suffix}", f"yt{suffix}")
ok, _ = service.deny_vanity_request(owner, resolved_by="admin@nomadkaraoke.com", note="taken")
assert ok is True
req = service.get_vanity_request(owner)
assert req.status == "denied"
assert req.note == "taken"
+167
View File
@@ -345,3 +345,170 @@ class TestAdminUpdateLink:
assert response.status_code == 200
assert response.json()["ok"] is True
mock_service.update_link.assert_called_once_with("abc12345", enabled=False)
class TestRequestVanityUrl:
"""Tests for POST /api/referrals/me/vanity-request (user-facing request)."""
@patch("backend.services.email_service.get_email_service")
@patch("backend.api.routes.referrals.get_referral_service")
def test_valid_request_persists_and_emails(
self, mock_get_service, mock_get_email, client, mock_auth_result
):
"""A valid request is validated, persisted, and emailed to the admin."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
mock_service = Mock()
mock_service.get_or_create_link.return_value = _make_referral_link(code="odu4brd8")
mock_service._validate_vanity_code.return_value = (True, "Valid")
mock_service.get_link_by_code.return_value = None
mock_get_service.return_value = mock_service
mock_get_email.return_value = Mock()
response = client.post("/api/referrals/me/vanity-request", json={"desired_code": "youtube"})
assert response.status_code == 200
mock_service.create_vanity_request.assert_called_once()
assert mock_service.create_vanity_request.call_args.kwargs["desired_code"] == "youtube"
@patch("backend.api.routes.referrals.get_referral_service")
def test_reserved_code_rejected_before_persisting(
self, mock_get_service, client, mock_auth_result
):
"""A code that fails vanity validation is rejected (400) and not persisted."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
mock_service = Mock()
mock_service._validate_vanity_code.return_value = (False, "'admin' is a reserved code")
mock_get_service.return_value = mock_service
response = client.post("/api/referrals/me/vanity-request", json={"desired_code": "admin"})
assert response.status_code == 400
mock_service.create_vanity_request.assert_not_called()
# A rejected request must not create a link for a brand-new user
mock_service.get_or_create_link.assert_not_called()
class TestAdminVanityRequests:
"""Tests for the vanity request approve/deny queue endpoints."""
def _make_request_doc(self, **overrides):
from backend.models.referral import VanityRequestDoc
from datetime import datetime
defaults = {
"id": "user@example.com",
"owner_email": "user@example.com",
"current_code": "odu4brd8",
"desired_code": "youtube",
"status": "pending",
"created_at": datetime.utcnow(),
}
defaults.update(overrides)
return VanityRequestDoc(**defaults)
@patch("backend.api.routes.referrals.get_referral_service")
def test_list_pending_requests(self, mock_get_service, client, mock_admin_auth_result):
"""Admin can list pending vanity requests."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.list_vanity_requests.return_value = [self._make_request_doc()]
mock_get_service.return_value = mock_service
response = client.get("/api/referrals/admin/vanity-requests")
assert response.status_code == 200
data = response.json()
assert data["count"] == 1
assert data["requests"][0]["desired_code"] == "youtube"
mock_service.list_vanity_requests.assert_called_once_with(status="pending")
def test_list_requests_non_admin_403(self, client, mock_auth_result):
"""Non-admin cannot list vanity requests."""
app.dependency_overrides[require_auth] = lambda: mock_auth_result
response = client.get("/api/referrals/admin/vanity-requests")
assert response.status_code == 403
@patch("backend.services.email_service.get_email_service")
@patch("backend.api.routes.referrals.get_referral_service")
def test_approve_request_renames_and_emails(
self, mock_get_service, mock_get_email, client, mock_admin_auth_result
):
"""Approving renames the link and emails the requester."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.get_vanity_request.return_value = self._make_request_doc()
link = _make_referral_link(code="youtube", is_vanity=True)
mock_service.approve_vanity_request.return_value = (True, link, "Renamed 'odu4brd8' to 'youtube'")
mock_get_service.return_value = mock_service
mock_email = Mock()
mock_get_email.return_value = mock_email
response = client.post("/api/referrals/admin/vanity-requests/user@example.com/approve")
assert response.status_code == 200
data = response.json()
assert data["ok"] is True
assert data["code"] == "youtube"
mock_service.approve_vanity_request.assert_called_once_with(
"user@example.com", resolved_by="admin@nomadkaraoke.com"
)
# Requester notified
mock_email.provider.send_email.assert_called_once()
assert mock_email.provider.send_email.call_args.kwargs["to_email"] == "user@example.com"
@patch("backend.services.email_service.get_email_service")
@patch("backend.api.routes.referrals.get_referral_service")
def test_approve_request_not_found(
self, mock_get_service, mock_get_email, client, mock_admin_auth_result
):
"""Approving a missing request returns 404."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.get_vanity_request.return_value = None
mock_get_service.return_value = mock_service
response = client.post("/api/referrals/admin/vanity-requests/missing@example.com/approve")
assert response.status_code == 404
mock_get_email.return_value.provider.send_email.assert_not_called()
@patch("backend.services.email_service.get_email_service")
@patch("backend.api.routes.referrals.get_referral_service")
def test_approve_request_code_taken(
self, mock_get_service, mock_get_email, client, mock_admin_auth_result
):
"""Approving fails (400) if the desired code was taken meanwhile, no email."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.get_vanity_request.return_value = self._make_request_doc()
mock_service.approve_vanity_request.return_value = (False, None, "Code 'youtube' is already taken")
mock_get_service.return_value = mock_service
response = client.post("/api/referrals/admin/vanity-requests/user@example.com/approve")
assert response.status_code == 400
mock_get_email.return_value.provider.send_email.assert_not_called()
@patch("backend.api.routes.referrals.get_referral_service")
def test_deny_request(self, mock_get_service, client, mock_admin_auth_result):
"""Admin can deny a vanity request."""
app.dependency_overrides[require_admin] = lambda: mock_admin_auth_result
mock_service = Mock()
mock_service.deny_vanity_request.return_value = (True, "Request denied")
mock_get_service.return_value = mock_service
response = client.post("/api/referrals/admin/vanity-requests/user@example.com/deny")
assert response.status_code == 200
assert response.json()["ok"] is True
mock_service.deny_vanity_request.assert_called_once_with(
"user@example.com", resolved_by="admin@nomadkaraoke.com"
)
+3 -3
View File
@@ -122,7 +122,7 @@ class TestGetOrCreateLink:
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 = [
mock_db.collection.return_value.where.return_value.stream.return_value = [
MagicMock(to_dict=lambda: {
"code": "abc12345",
"owner_email": "user@example.com",
@@ -146,7 +146,7 @@ class TestGetOrCreateLink:
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 = []
mock_db.collection.return_value.where.return_value.stream.return_value = []
# doc.get() returns a doc that doesn't exist (no collision)
mock_doc_ref = MagicMock()
mock_doc_snapshot = MagicMock()
@@ -816,7 +816,7 @@ class TestGetDashboardData:
# Complex mock setup for multiple collection queries
mock_link_query = MagicMock()
mock_link_query.limit.return_value.stream.return_value = [mock_link_doc]
mock_link_query.stream.return_value = [mock_link_doc]
mock_earnings_query = MagicMock()
mock_earnings_query.order_by.return_value.limit.return_value.stream.return_value = []
@@ -0,0 +1,71 @@
# Vanity Referral URL — Approve/Deny Queue (rename-in-place)
**Date:** 2026-08-30
**Branch:** feat/sess-20260830-2049-vanity-referral-approval
## Problem
When a user requests a vanity referral code, the backend only emails Andrew — no
record is persisted. To "approve", the admin had to click **Create Vanity Link** and
retype the owner email + desired code, which creates a *second* link alongside the
user's auto-generated one (split stats, two live codes). The **Edit** modal cannot
change a link's code. There is no approve/deny concept and no notification to the user.
Net: confusing and unintuitive.
## Decisions (confirmed with Andrew)
1. **Approve = rename in place.** Change the user's existing link's `code` to the
vanity code (stats preserved, one unified link). Old code doc is kept but **disabled**
with a `renamed_to` pointer so stale links 404 cleanly.
2. **Full approve/deny queue.** Persist requests in Firestore; show a "Pending Vanity
Requests" banner on `/admin/referrals` with one-click Approve/Deny; email the user on
approval.
## Backend
### Model (`backend/models/referral.py`)
- `VanityRequestDoc`: `id`, `owner_email`, `current_code`, `desired_code`,
`status` ("pending"|"approved"|"denied"), `created_at`, `resolved_at`,
`resolved_by`, `note`.
- `VanityRequestResponse` for the admin list.
### Service (`backend/services/referral_service.py`)
- `REFERRAL_VANITY_REQUESTS_COLLECTION = "referral_vanity_requests"`.
- `create_vanity_request(owner_email, current_code, desired_code)` — doc id =
owner_email (a re-request overwrites the pending one). Resets status→pending.
- `list_vanity_requests(status="pending")`, `get_vanity_request(request_id)`.
- `rename_link(old_code, new_code)` → `(success, link, message)`:
1. validate new code (vanity pattern + reserved + not taken by a *different* link),
2. copy old doc → new doc (`is_vanity=True`, stats + config preserved, `updated_at` bumped),
3. migrate `referred_by_code` on `gen_users` and `referral_code` on `referral_earnings`
that point at `old_code` → `new_code`,
4. disable old doc (`enabled=False`, `renamed_to=new_code`).
- `approve_vanity_request(request_id, resolved_by)` — re-fetch owner's *enabled* link,
rename it to `desired_code`, mark request approved.
- `deny_vanity_request(request_id, resolved_by, note=None)`.
- **Fix `get_or_create_link`**: prefer an `enabled` link for the owner; only fall back to
a disabled one / create if none enabled. Prevents the renamed old alias resurfacing.
### Routes (`backend/api/routes/referrals.py`)
- `request_vanity_url`: also `create_vanity_request(...)` (keep the existing email).
- `GET /admin/vanity-requests?status=pending`
- `POST /admin/vanity-requests/{request_id}/approve` → approve + email user
("Your vanity referral URL is live: nomadkaraoke.com/r/<code>").
- `POST /admin/vanity-requests/{request_id}/deny` → deny (+ optional note; no email by default).
## Frontend (`/admin/referrals` — English-only, no i18n)
- `frontend/lib/types.ts`: `VanityRequest`.
- `frontend/lib/api.ts` `adminApi`: `listVanityRequests`, `approveVanityRequest`,
`denyVanityRequest`.
- `frontend/app/admin/referrals/page.tsx`: "Pending Vanity Requests" Card above the
links table — one row per request: `owner — current → desired`, `[Approve] [Deny]`
with per-request loading + error, then reload requests + links.
## Tests
- Backend unit (`backend/tests/test_referral_service.py` + routes):
rename preserves stats & disables old; attribution (`referred_by_code`) migrated;
`get_or_create_link` prefers enabled; approve renames + marks approved;
approve fails cleanly if desired code was taken meanwhile; deny marks denied;
request persisted on `me/vanity-request`.
- Frontend: light Jest test that the banner renders a pending request and calls approve.
- Bump `pyproject.toml`.
@@ -0,0 +1,87 @@
/**
* @jest-environment jsdom
*
* Tests for the admin Referrals page "Pending Vanity Requests" banner —
* approving/denying a user-requested vanity code. adminApi is mocked.
*/
import React from 'react'
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
const listReferralLinks = jest.fn()
const listVanityRequests = jest.fn()
const approveVanityRequest = jest.fn()
const denyVanityRequest = jest.fn()
// ReferralToolsDialog pulls in jspdf (ESM) which jest can't transform — stub it.
jest.mock('@/components/referrals/ReferralToolsDialog', () => ({
__esModule: true,
default: () => null,
}))
jest.mock('@/lib/api', () => ({
adminApi: {
listReferralLinks: (...args: unknown[]) => listReferralLinks(...args),
listVanityRequests: (...args: unknown[]) => listVanityRequests(...args),
approveVanityRequest: (...args: unknown[]) => approveVanityRequest(...args),
denyVanityRequest: (...args: unknown[]) => denyVanityRequest(...args),
createVanityLink: jest.fn(),
updateReferralLink: jest.fn(),
},
}))
import ReferralsPage from '@/app/admin/referrals/page'
const pendingRequest = {
id: 'youtube@nomadkaraoke.com',
owner_email: 'youtube@nomadkaraoke.com',
current_code: 'odu4brd8',
desired_code: 'youtube',
status: 'pending' as const,
created_at: '2026-08-30T00:00:00Z',
}
beforeEach(() => {
jest.clearAllMocks()
listReferralLinks.mockResolvedValue({ links: [], count: 0 })
listVanityRequests.mockResolvedValue({ requests: [pendingRequest], count: 1 })
approveVanityRequest.mockResolvedValue({ ok: true, code: 'youtube', message: 'Renamed' })
denyVanityRequest.mockResolvedValue({ ok: true, message: 'Request denied' })
})
describe('Admin Referrals — pending vanity requests', () => {
it('shows the pending request with current → desired codes', async () => {
render(<ReferralsPage />)
expect(await screen.findByText('Pending Vanity Requests')).toBeInTheDocument()
expect(screen.getByText('youtube@nomadkaraoke.com')).toBeInTheDocument()
expect(screen.getByText('odu4brd8')).toBeInTheDocument()
expect(screen.getByText('youtube')).toBeInTheDocument()
})
it('approving calls approveVanityRequest and reloads', async () => {
render(<ReferralsPage />)
const approveBtn = await screen.findByRole('button', { name: /approve/i })
fireEvent.click(approveBtn)
await waitFor(() =>
expect(approveVanityRequest).toHaveBeenCalledWith('youtube@nomadkaraoke.com')
)
// Data reloaded (initial load + post-approve reload)
await waitFor(() => expect(listVanityRequests).toHaveBeenCalledTimes(2))
})
it('denying calls denyVanityRequest', async () => {
render(<ReferralsPage />)
const denyBtn = await screen.findByRole('button', { name: /deny/i })
fireEvent.click(denyBtn)
await waitFor(() =>
expect(denyVanityRequest).toHaveBeenCalledWith('youtube@nomadkaraoke.com')
)
})
it('renders no banner when there are no pending requests', async () => {
listVanityRequests.mockResolvedValue({ requests: [], count: 0 })
render(<ReferralsPage />)
await waitFor(() => expect(listReferralLinks).toHaveBeenCalled())
expect(screen.queryByText('Pending Vanity Requests')).not.toBeInTheDocument()
})
})
+99 -2
View File
@@ -2,7 +2,7 @@
import { useEffect, useState, useCallback } from "react"
import { adminApi } from "@/lib/api"
import type { ReferralLink } from "@/lib/types"
import type { ReferralLink, VanityRequest } 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"
@@ -19,6 +19,7 @@ import {
import {
Share2, Link as LinkIcon, Users, MousePointerClick, DollarSign,
Plus, Copy, Check, RefreshCw, Loader2, ToggleLeft, ToggleRight, Pencil, QrCode,
Sparkles, ArrowRight, X,
} from "lucide-react"
import ReferralToolsDialog from "@/components/referrals/ReferralToolsDialog"
import { NextIntlClientProvider } from "next-intl"
@@ -47,6 +48,9 @@ export default function ReferralsPage() {
const [saving, setSaving] = useState(false)
const [editError, setEditError] = useState<string | null>(null)
const [qrDialogCode, setQrDialogCode] = useState<string | null>(null)
const [pendingRequests, setPendingRequests] = useState<VanityRequest[]>([])
const [actioningRequestId, setActioningRequestId] = useState<string | null>(null)
const [requestError, setRequestError] = useState<string | null>(null)
// Edit form state
const [editDisplayName, setEditDisplayName] = useState("")
@@ -70,8 +74,15 @@ export default function ReferralsPage() {
setLoading(true)
setError(null)
try {
const result = await adminApi.listReferralLinks({ limit: 200 })
const [result, requests] = await Promise.all([
adminApi.listReferralLinks({ limit: 200 }),
adminApi.listVanityRequests("pending").catch((err) => {
console.error("Failed to load vanity requests:", err)
return { requests: [] as VanityRequest[], count: 0 }
}),
])
setLinks(result.links as AdminReferralLink[])
setPendingRequests(requests.requests)
} catch (err) {
console.error("Failed to load referral links:", err)
setError(err instanceof Error ? err.message : "Failed to load referral links")
@@ -80,6 +91,34 @@ export default function ReferralsPage() {
}
}, [])
const handleApproveRequest = async (req: VanityRequest) => {
setActioningRequestId(req.id)
setRequestError(null)
try {
await adminApi.approveVanityRequest(req.id)
await loadData()
} catch (err) {
console.error("Failed to approve vanity request:", err)
setRequestError(err instanceof Error ? err.message : "Failed to approve request")
} finally {
setActioningRequestId(null)
}
}
const handleDenyRequest = async (req: VanityRequest) => {
setActioningRequestId(req.id)
setRequestError(null)
try {
await adminApi.denyVanityRequest(req.id)
await loadData()
} catch (err) {
console.error("Failed to deny vanity request:", err)
setRequestError(err instanceof Error ? err.message : "Failed to deny request")
} finally {
setActioningRequestId(null)
}
}
useEffect(() => { loadData() }, [loadData])
// Aggregate stats
@@ -353,6 +392,64 @@ export default function ReferralsPage() {
/>
</StatsGrid>
{/* Pending Vanity Requests */}
{pendingRequests.length > 0 && (
<Card className="border-primary/50">
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
<Sparkles className="w-4 h-4 text-primary" />
Pending Vanity Requests
<Badge variant="default">{pendingRequests.length}</Badge>
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
Approving renames the user&apos;s existing code — stats and earnings carry over, and they get an email.
</p>
{requestError && <p className="text-sm text-destructive">{requestError}</p>}
<div className="space-y-2">
{pendingRequests.map((req) => {
const busy = actioningRequestId === req.id
return (
<div
key={req.id}
className="flex flex-wrap items-center justify-between gap-3 rounded-md border p-3"
>
<div className="flex flex-col gap-1 text-sm">
<span className="font-medium">{req.owner_email}</span>
<span className="flex items-center gap-2 font-mono text-xs">
<code className="bg-muted px-1.5 py-0.5 rounded">{req.current_code}</code>
<ArrowRight className="w-3 h-3 text-muted-foreground" />
<code className="bg-primary/10 text-primary px-1.5 py-0.5 rounded">{req.desired_code}</code>
</span>
</div>
<div className="flex items-center gap-2">
<Button
size="sm"
onClick={() => handleApproveRequest(req)}
disabled={busy}
>
{busy ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Check className="w-4 h-4 mr-2" />}
Approve
</Button>
<Button
size="sm"
variant="outline"
onClick={() => handleDenyRequest(req)}
disabled={busy}
>
<X className="w-4 h-4 mr-2" />
Deny
</Button>
</div>
</div>
)
})}
</div>
</CardContent>
</Card>
)}
{/* Error State */}
{error && (
<Card>
+24 -1
View File
@@ -3,7 +3,7 @@
*/
import type { VideoThemeSummary, VideoThemeDetail, ThemesListResponse, ThemeDetailResponse, ColorOverrides } from './video-themes';
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse, ReferralInterstitial, ReferralDashboard, ReferralLink } from './types';
import type { MagicLinkResponse, VerifyMagicLinkResponse, UserProfileResponse, ReferralInterstitial, ReferralDashboard, ReferralLink, VanityRequest } from './types';
import type { CorrectionData, CorrectionAnnotation, EditLog, SearchLyricsResponse, AddLyricsResult } from './lyrics-review/types';
import { beginRequest, endRequest, configureHealthProbe } from './backend-status';
@@ -3384,6 +3384,29 @@ export const adminApi = {
return handleResponse(response);
},
async listVanityRequests(status: 'pending' | 'approved' | 'denied' = 'pending'): Promise<{ requests: VanityRequest[]; count: number }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/vanity-requests?status=${status}`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
async approveVanityRequest(requestId: string): Promise<{ ok: boolean; code: string; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/vanity-requests/${encodeURIComponent(requestId)}/approve`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
async denyVanityRequest(requestId: string): Promise<{ ok: boolean; message: string }> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/vanity-requests/${encodeURIComponent(requestId)}/deny`, {
method: 'POST',
headers: getAuthHeaders(),
});
return handleResponse(response);
},
async generateFlyer(code: string, theme: 'light' | 'dark', qrDataUrl: string): Promise<Blob> {
const response = await apiFetch(`${API_BASE_URL}/api/referrals/admin/links/${encodeURIComponent(code)}/flyer`, {
method: 'POST',
+9
View File
@@ -97,6 +97,15 @@ export interface ReferralLink {
is_vanity: boolean;
}
export interface VanityRequest {
id: string;
owner_email: string;
current_code: string;
desired_code: string;
status: 'pending' | 'approved' | 'denied';
created_at: string;
}
export interface ReferralEarning {
id: string;
referred_email: string;
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.214.0"
version = "0.215.0"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"