Files
Andrew Beveridge ☄️andClaude Opus 5.5 d76a136ee6 feat: mobile Phase 6 — RevenueCat IAP webhook, Expo push, self-serve account deletion (flagged off), App Review demo login (v0.284.0) (#1220)
Phase 6 (mobile release readiness) — gen side. Spec: nomad-mobile
`docs/superpowers/specs/2026-10-25-mobile-phase6-release-readiness-design.md`
(§4 payments, §5 push, §6 deletion, §9 demo account).

## What
- **`/me` app fields:** opaque `app_user_id` (UUID, used for
RevenueCat/Sentry — no email to third parties),
`capabilities.account_deletion`, `push_prefs`.
- **In-app purchases:** `POST /api/users/webhooks/revenuecat` (shared
Authorization header). Exactly-once grants keyed by
`{store}:{transaction_id}` inside the same Firestore transaction as the
balance change; refunds (REFUND / CANCELLATION with CUSTOMER_SUPPORT or
negative price) debit the granted account, refund tombstones block late
grants; other cancellations ignored. `store_payments` for accounting +
revenue sums; referral earnings on **net** proceeds; sandbox grants but
excluded from revenue/referrals. Credit packages gain `store_product_id`
+ server-driven `web_link` (iOS US only for now).
- **Push:** `POST/DELETE /api/push/expo-token` (token moves between
users atomically), `PATCH /api/users/me/push-prefs` (ready / review /
problems, gates Expo **and** Web Push), Expo sender (batched,
DeviceNotRegistered cleanup), new FAILED / AWAITING_AUDIO_SELECTION
triggers.
- **Account deletion** (`ACCOUNT_DELETION_ENABLED`, **off in prod**
until Andrew's manual pass): `GET /api/users/me/deletion-preview`,
`DELETE /api/users/me`. Refuses admin / unpaid referral balance / Stripe
Connect / made-for-you in progress (409). Cancels active jobs, deletes
decide data (partner call, twice), RevenueCat subscriber, revokes Sign
in with Apple (when a code is given), queues kjbox
(`/api/kjbox/account-deletions` pull + ack), deletes **inputs only**
(uploads, input/, audio_edit/, style/, staged instrumentals) — **never
published outputs** — strips personal fields, anonymises
jobs/referrals/song requests/show-credit records, keeps payment records.
Every step idempotent; failures → 503 retry; sessions revoked last.
- **Web:** `/account/delete` page (Google Play web deletion path),
hidden while the flag is off.
- **App Review demo login:** fixed code for one configured email — inert
until `APP_REVIEW_DEMO_EMAIL` is set (not set in prod).
- **CI:** mounts `REVENUECAT_WEBHOOK_AUTH`, `REVENUECAT_SECRET_API_KEY`,
`APP_REVIEW_DEMO_CODE` (secrets exist; runtime SA already has accessor).

## Tests
6838 backend unit tests pass (emulator suite needs emulators;
iap/deletion emulator tests pass locally), frontend jest 1785/1785.
Per-task reviews + local CodeRabbit review (5 minor findings fixed).

@coderabbitai ignore

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

https://claude.ai/code/session_01CZf1cM9vefnNw5djARRhyA

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:31:01 -04:00

418 lines
15 KiB
Python

"""
User model for authentication and credits.
Supports:
- Magic link authentication (email-based)
- Credit system for karaoke generation
- Role-based access control (user/admin)
- Stripe integration for payments
"""
from datetime import datetime, timezone
from enum import Enum
from typing import Annotated, Literal, Optional, List, Dict
from pydantic import BaseModel, EmailStr, Field, StringConstraints
class UserRole(str, Enum):
"""User roles for access control."""
USER = "user"
ADMIN = "admin"
class CreditTransaction(BaseModel):
"""Record of a credit transaction."""
id: str
amount: int # Positive = add, negative = deduct
reason: str # e.g., "purchase", "refund", "admin_grant", "job_creation"
job_id: Optional[str] = None
stripe_session_id: Optional[str] = None
created_at: datetime = Field(default_factory=datetime.utcnow)
created_by: Optional[str] = None # Admin email if granted by admin
class PushSubscription(BaseModel):
"""
Web Push subscription for a user's device.
Stores the push subscription endpoint and encryption keys needed
to send push notifications to the user's browser/device.
Subscriptions are scoped by tenant_id to prevent cross-tenant
notification leakage (e.g., a consumer job notification appearing
on a tenant portal's service worker).
"""
endpoint: str # Push service endpoint URL
keys: Dict[str, str] # p256dh and auth keys for encryption
device_name: Optional[str] = None # e.g., "iPhone", "Chrome on Windows"
tenant_id: Optional[str] = None # Tenant scope (None = consumer/default portal)
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
last_used_at: Optional[datetime] = None # Last time a notification was sent
PUSH_PREF_KINDS = ("ready", "review", "problems")
def effective_push_prefs(stored: Optional[Dict[str, bool]]) -> Dict[str, bool]:
"""Per-type mobile push preferences with defaults applied (all on unless stored False)."""
stored = stored or {}
return {kind: bool(stored.get(kind, True)) for kind in PUSH_PREF_KINDS}
class ExpoPushToken(BaseModel):
"""Expo push token for one device of the Nomad Karaoke mobile app."""
token: str
platform: Literal["ios", "android"]
device_id: str
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
last_used_at: Optional[datetime] = None
class User(BaseModel):
"""
User model stored in Firestore.
Users are identified by email address. Authentication is via magic links
(no passwords). Credits are consumed when creating karaoke jobs.
For multi-tenant white-label portals, users are scoped to a tenant.
Users with tenant_id=None are default Nomad Karaoke users.
"""
email: str # Primary identifier
role: UserRole = UserRole.USER
credits: int = 0
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
# Stripe integration
stripe_customer_id: Optional[str] = None
# Account state
is_active: bool = True
email_verified: bool = False
# Timestamps
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
last_login_at: Optional[datetime] = None
# Credit history (last 100 transactions)
credit_transactions: List[CreditTransaction] = Field(default_factory=list)
# Job tracking
total_jobs_created: int = 0
total_jobs_completed: int = 0
# Payment tracking (cached from stripe_payments, in cents)
total_spent: int = 0
# Optional profile fields for future use
display_name: Optional[str] = None
# i18n locale preference (set from Accept-Language on login, used for emails/push).
# Narrowed to the 3 email-supported locales (en/es/de) — do NOT widen, email
# rendering depends on it.
locale: Optional[str] = None
# Actual UI language the user browses in (primary Accept-Language subtag, any
# of the 33 supported locales, e.g. "pt", "ja"). Captured on login and job
# creation. Admin-only signal so support knows what language to communicate in.
ui_locale: Optional[str] = None
# Push notification subscriptions (Web Push API)
# Users can subscribe from multiple devices/browsers
push_subscriptions: List[PushSubscription] = Field(default_factory=list)
# Mobile app: opaque UUID4 sent to RevenueCat (never the email), minted once
# by UserService.ensure_app_user_id
app_user_id: Optional[str] = None
# Mobile push categories ("ready", "review", "problems"); missing key = on
push_prefs: Dict[str, bool] = Field(default_factory=dict)
# Expo push tokens, one per signed-in device (a token belongs to one user)
expo_push_tokens: List[ExpoPushToken] = Field(default_factory=list)
# Feedback-for-credits program
has_submitted_feedback: bool = False
# Anti-abuse: IP address and device fingerprint used during signup
signup_ip: Optional[str] = None
device_fingerprint: Optional[str] = None
# Flag to prevent duplicate welcome credit grants (idempotency)
welcome_credits_granted: bool = False
# Acquisition channel for accounts created outside the gen website, e.g.
# "kjbox" (signed up via an emailed code on a karaoke-night singer page).
# None = normal gen website signup (all pre-existing docs).
# Gen website signups record their first-touch marketing source here too:
# utm_source when the landing URL carried one, else the referring site's domain
# (e.g. "youtube", "google.com"). Full detail lives in signup_attribution.
signup_source: Optional[str] = None
signup_venue: Optional[str] = None # Venue name reported by the partner (kjbox)
# First-touch attribution captured by the frontend before signup (see
# backend/services/signup_attribution.py): utm_* params, external referrer
# domain, landing path and when it was captured.
signup_attribution: Optional[Dict[str, str]] = None
# Free-to-paid conversion emails (backend/services/conversion_emails.py)
conversion_e1_due_at: Optional[datetime] = None # set when the first video completes unpaid
conversion_e1_sent_at: Optional[datetime] = None
conversion_e1_skipped: bool = False # due but not sent (already paid / too late)
first_video_artist: Optional[str] = None # named in the E1 email
first_video_title: Optional[str] = None
conversion_e2_sent_at: Optional[datetime] = None
# Time-limited discount granted by the E1 offer, applied automatically at checkout
promo_discount_percent: Optional[int] = None
promo_discount_expires_at: Optional[datetime] = None
# 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):
"""
Magic link token for passwordless authentication.
Tokens are short-lived (15 minutes) and single-use.
Stored in Firestore with automatic TTL.
For multi-tenant portals, the tenant_id determines which portal
the user will be redirected to after verification.
"""
token: str # Secure random token
email: str
created_at: datetime = Field(default_factory=datetime.utcnow)
expires_at: datetime
used: bool = False
used_at: Optional[datetime] = None
ip_address: Optional[str] = None
user_agent: Optional[str] = None
device_fingerprint: Optional[str] = None
# 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
# Sign-in context. "requests_board" = passwordless identity only: skip the welcome
# credit + the per-IP signup limit (so a whole venue on shared WiFi can sign in to
# vote), and route the user back to the board after verifying.
purpose: Optional[str] = None
# True only for app → web handoff tokens (POST /auth/handoff-token): the
# verify page may then sign in without the email-scanner "Complete Sign-In" tap.
handoff: bool = False
# 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
credit_eval_error: Optional[str] = None
class Session(BaseModel):
"""
User session for authenticated requests.
Sessions are created after successful magic link verification.
Sessions expire after 7 days of inactivity or 30 days absolute.
For multi-tenant portals, sessions are scoped to a tenant.
"""
token: str # Secure random session token
user_email: str
created_at: datetime = Field(default_factory=datetime.utcnow)
expires_at: datetime
last_activity_at: datetime = Field(default_factory=datetime.utcnow)
ip_address: Optional[str] = None
user_agent: Optional[str] = None
device_fingerprint: Optional[str] = None
is_active: bool = True
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
# Pydantic models for API requests/responses
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
# First-touch marketing attribution (utm_*, referrer, landing_path), recorded on
# the user only when this request creates the account.
attribution: Optional[
Dict[Annotated[str, StringConstraints(max_length=32)], Optional[Annotated[str, StringConstraints(max_length=500)]]]
] = Field(default=None, max_length=16)
# "requests_board" = board sign-in (identity only; no welcome credit / no IP limit).
purpose: Optional[str] = None
class SendMagicLinkResponse(BaseModel):
"""Response after sending magic link."""
status: str
message: str
class VerifyMagicLinkRequest(BaseModel):
"""Request to verify a magic link token."""
token: str
class ResendFromTokenRequest(BaseModel):
"""Request to resend a magic link based on a previously-issued (expired/used) token."""
token: str
class ResendFromTokenResponse(BaseModel):
"""Response after attempting to resend a magic link from a known token."""
status: str # "sent" | "no_token"
masked_email: Optional[str] = None
message: str
class VerifyMagicLinkResponse(BaseModel):
"""Response after verifying magic link."""
status: str
session_token: str
user: "UserPublic"
message: str
tenant_subdomain: Optional[str] = None
credits_granted: int = 0
credit_status: str = "not_applicable" # "granted", "denied", "pending_review", "already_granted", "not_applicable"
# Where the frontend should land after verifying (e.g. "/requests" for board sign-in).
redirect_path: Optional[str] = None
class UserPublic(BaseModel):
"""Public user information (safe to expose to frontend)."""
email: str
role: UserRole
credits: int
display_name: Optional[str] = None
total_jobs_created: int = 0
total_jobs_completed: int = 0
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
# Active time-limited promo (conversion email offer), applied at checkout
promo_discount_percent: Optional[int] = None
promo_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
class AddCreditsRequest(BaseModel):
"""Admin request to add credits to a user."""
email: str
amount: int
reason: str = "admin_grant"
class AddCreditsResponse(BaseModel):
"""Response after adding credits."""
status: str
email: str
credits_added: int
new_balance: int
message: str
class AdminCreateUserRequest(BaseModel):
"""Admin request to create a user account directly."""
email: EmailStr
display_name: Optional[str] = None
initial_credits: int = 0
credit_reason: str = "admin_grant"
class AdminCreateUserResponse(BaseModel):
"""Response after admin creates a user."""
status: str
email: str
credits: int
message: str
class UserListResponse(BaseModel):
"""Response for listing users (admin only)."""
users: List[UserPublic]
total: int
# ============================================================================
# User Feedback-for-Credits Models
# ============================================================================
class UserFeedback(BaseModel):
"""
Feedback from any user (not just beta testers).
Stored in Firestore 'user_feedback' collection.
Users earn 1 free credit for submitting detailed feedback.
"""
id: str
user_email: str
# Ratings (1-5 scale)
overall_rating: int = Field(ge=1, le=5)
ease_of_use_rating: int = Field(ge=1, le=5)
lyrics_accuracy_rating: int = Field(ge=1, le=5)
correction_experience_rating: int = Field(ge=1, le=5)
# Open-ended feedback
what_went_well: Optional[str] = None
what_could_improve: Optional[str] = None
additional_comments: Optional[str] = None
# Would they recommend / use again?
would_recommend: bool = True
would_use_again: bool = True
# Metadata
created_at: datetime = Field(default_factory=datetime.utcnow)
submitted_via: str = "web"
class UserFeedbackRequest(BaseModel):
"""Request to submit user feedback for credits."""
# Ratings (1-5 scale)
overall_rating: int = Field(ge=1, le=5)
ease_of_use_rating: int = Field(ge=1, le=5)
lyrics_accuracy_rating: int = Field(ge=1, le=5)
correction_experience_rating: int = Field(ge=1, le=5)
# Open-ended feedback
what_went_well: Optional[str] = None
what_could_improve: Optional[str] = None
additional_comments: Optional[str] = None
# Would they recommend / use again?
would_recommend: bool = True
would_use_again: bool = True
class UserFeedbackResponse(BaseModel):
"""Response after submitting user feedback."""
status: str
message: str
credits_granted: int = 0
class FeedbackEligibilityResponse(BaseModel):
"""Response for feedback eligibility check."""
eligible: bool
has_submitted: bool
jobs_completed: int
credits_reward: int = 1