Files
karaoke-gen/backend/models/user.py
T
Andrew Beveridge ☄️andClaude Opus 5.5 4ad946c3aa feat: free-to-paid conversion emails + last-chance review nudge, OFF until copy approved (v0.271.0) (#1156)
## Summary
This is BACKLOG Frog #2 ("plug the gen revenue leaks"), conversion-email
track. 44% of signups finish a free video, but only 6% ever pay, and
buyers decide fast (median about 5h). 45 users opened lyrics review and
let the job expire.

**Ships dark.** Nothing sends until Andrew approves the copy and
`CONVERSION_EMAILS_ENABLED` / `REVIEW_LAST_CHANCE_ENABLED` are added to
the ci.yml deploy env.

| Email | When | Stream |
|---|---|---|
| E1 "Your karaoke video is done. What's next?" + 25% off any pack for
48h | 2h after a never-paid user's **first** video completes | broadcast
|
| E2 "Your 25% off ends in 8 hours" | last 8h of the offer, if unpaid |
broadcast |
| R2 "6 hours left to finish your karaoke video" | 42h into review (the
existing reminder is at 24h; expiry is 48h) | transactional |

- `services/conversion_emails.py`:
- A `JobManager` hook marks the user on their first unpaid completion.
Tenant, Made For You and test accounts are excluded.
- The hourly `process-stale-reviews` cron sends the emails. It's
idempotent per user, and due times more than 24h stale are skipped, so
turning it on never emails a backlog. No infra change is needed.
- **Promo:** E1 grants `promo_discount_percent` /
`promo_discount_expires_at`. Checkout applies coupon
`conversion-offer-{pct}pct` when it beats a referral discount.
- The buy dialog shows a banner, and its prices use the effective
discount (CodeRabbit finding).
  - The email button links to `/app?buy=1`, which opens the dialog.
- **Compliance:** E1 and E2 go on Postmark's `broadcast` stream, where
Postmark manages unsubscribes (verified: it appends the link). They
include a postal-address footer (`COMMERCIAL_EMAIL_POSTAL_ADDRESS`).
`EmailProvider` gains `message_stream`, and email_log records the
stream.
- Copy is in `backend/translations` (33 locales). Docs:
`docs/CONVERSION-EMAILS.md`, covering how it works, measurement and how
to turn it on.

## Testing
- `make test`: backend 6017, emulator 150, frontend Jest 1688, package
2044. All green. Re-ran the targeted suites after rebasing onto the tip
PR.
- New tests:
- `test_conversion_emails.py` (26): eligibility, E1/E2 windows,
staleness, promo vs referral, broadcast stream, rendering.
- Stale-review R2 tests (3), `BuyCreditsDialog.test.tsx` (3), and an
AuthStatus `?buy=1` test.
- Rendered E1 and R2 HTML and checked them visually.
- Local CodeRabbit: 1 finding fixed.

@coderabbitai ignore

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

https://claude.ai/code/session_019KuzHAU4rxkv8JfD8NmHTN

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 23:50:59 -04:00

388 lines
13 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, 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
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)
# 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
# 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