phase D milestones 1+2: referral system + paid-access gate
Lays the billing-prep spine before Paddle lands in D.3.
D.1 — referrals
- users.referral_code: unique 8-char URL-safe code (alphabet excludes the
ambiguous 0/O/1/I/L). Generated lazily on first /settings hit so existing
accounts pick one up without a backfill migration.
- users.referred_by_user_id + new referrals audit table (referrer,
referred, created_at, converted_at, credited_at). converted_at /
credited_at stay null until D.3 fills them via the Paddle webhook.
- POST /login accepts ?ref=<code>; the code rides on the signed
pending-verify cookie so it survives the GET → POST → /verify hop.
- /settings page: email, tier badge, referral code chip + invite link
with one-click copy, pending/converted/active-credits stats grid.
Settings nav link added to the top bar.
Reward shape: when the referred user makes their first paid Paddle
subscription, both they and the referrer get 50% off for 3 months.
(D.3 wires the actual credit application via the Paddle webhook.)
D.2 — paid-access gate
- users.credit_until: timestamp until which a free-tier account has
paid-tier access. Null = no credit. Populated by admin CLI now and the
D.3 webhook later.
- app.services.access exposes paid_status(user) → PaidStatus dataclass
(active / source / expires_at / days_remaining), is_paid_active() with
admin-bearer-token bypass, and a require_paid FastAPI dependency that
raises 402 Payment Required for free-tier callers.
- POST /api/analyze (portfolio AI commentary) gated behind require_paid.
- Settings page surfaces credit window when active ("free · credit · N
day(s) remaining (expires YYYY-MM-DD)") and the upgrade hint when not.
- Admin CLI: python -m app.cli {grant-credit,revoke-credit,show-status}.
grant-credit is idempotent — extends from max(now, current expiry) so
re-running the command never erodes an existing grant.
Migrations 0013 (referrals) and 0014 (credit_until). Tests cover the
paid-status truth table, code generation + normalisation, CLI argument
parsing, and the pending-cookie ref roundtrip (29 new tests).
This commit is contained in:
parent
2013bfa8cc
commit
9759080134
18 changed files with 1159 additions and 21 deletions
95
app/services/access.py
Normal file
95
app/services/access.py
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
"""Paid-tier access checks.
|
||||
|
||||
Two sources can grant paid access:
|
||||
|
||||
1. ``user.tier in {"paid", "enterprise"}`` — set by Paddle webhook in
|
||||
Phase D.3 once a subscription is active.
|
||||
2. ``user.credit_until > now()`` — non-subscription credit. Currently
|
||||
populated by the admin CLI (`python -m app.cli grant-credit`) and, in
|
||||
D.3, by the referral-conversion path (3 months at 50% off).
|
||||
|
||||
Either is sufficient. We use a single ``paid_status`` function so the
|
||||
Settings page can show *why* a user has paid access ("paid subscription"
|
||||
vs "credit, 47 days left") without duplicating the rules.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
|
||||
from app.auth import CurrentUser, require_auth
|
||||
from app.models import User
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PaidStatus:
|
||||
"""Snapshot of paid-tier status for one user."""
|
||||
active: bool
|
||||
source: str | None # "tier" | "credit" | None
|
||||
expires_at: datetime | None # only meaningful when source == "credit"
|
||||
days_remaining: int | None # only meaningful when source == "credit"
|
||||
|
||||
|
||||
def _aware(dt: datetime | None) -> datetime | None:
|
||||
"""MariaDB round-trips DateTime(timezone=True) as a naive UTC value
|
||||
via aiomysql. Normalise to tz-aware so comparisons against utcnow()
|
||||
never raise."""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
return dt.replace(tzinfo=timezone.utc)
|
||||
return dt
|
||||
|
||||
|
||||
def paid_status(user: User | None) -> PaidStatus:
|
||||
"""Compute paid-tier status for a User row. ``user=None`` (anonymous
|
||||
or admin bearer-token) returns inactive — callers should special-case
|
||||
admin separately via ``is_paid_active``."""
|
||||
if user is None:
|
||||
return PaidStatus(False, None, None, None)
|
||||
if user.tier in ("paid", "enterprise"):
|
||||
return PaidStatus(True, "tier", None, None)
|
||||
cu = _aware(getattr(user, "credit_until", None))
|
||||
if cu is not None and cu > _utcnow():
|
||||
days = max(0, (cu - _utcnow()).days)
|
||||
return PaidStatus(True, "credit", cu, days)
|
||||
return PaidStatus(False, None, None, None)
|
||||
|
||||
|
||||
def is_paid_active(principal: CurrentUser | User | None) -> bool:
|
||||
"""True if the principal has paid-tier access right now. Admin
|
||||
bearer-token (``CurrentUser.is_admin=True``) always passes."""
|
||||
if principal is None:
|
||||
return False
|
||||
if isinstance(principal, CurrentUser):
|
||||
if principal.is_admin:
|
||||
return True
|
||||
return paid_status(principal.user).active
|
||||
return paid_status(principal).active
|
||||
|
||||
|
||||
async def require_paid(
|
||||
principal: CurrentUser = Depends(require_auth),
|
||||
) -> CurrentUser:
|
||||
"""FastAPI dependency for paid-only endpoints. Returns the principal
|
||||
on success; raises 402 Payment Required otherwise.
|
||||
|
||||
402 is the semantically-correct code for "auth succeeded but plan
|
||||
insufficient" — distinct from 401 (not authenticated) and 403
|
||||
(authenticated but forbidden by ACL). Frontends key off it to show
|
||||
the upgrade prompt rather than redirecting to /login."""
|
||||
if is_paid_active(principal):
|
||||
return principal
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_402_PAYMENT_REQUIRED,
|
||||
detail={
|
||||
"code": "paid_required",
|
||||
"message": "This feature requires an active paid plan or credit.",
|
||||
},
|
||||
)
|
||||
119
app/services/referral_service.py
Normal file
119
app/services/referral_service.py
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
"""Referral-code generation, lookup, and signup-time linkage.
|
||||
|
||||
D.1 lays down the bookkeeping only — actual credit application happens
|
||||
in D.3 when the Paddle webhook fires. The flow:
|
||||
|
||||
1. /login renders an "invited" banner when the URL carries `?ref=<code>`.
|
||||
2. The code travels through the email-OTP flow inside the pending cookie
|
||||
so it survives the GET /login → POST /login → /verify hops.
|
||||
3. When the new user's row is first created (POST /login on an unknown
|
||||
email), `referred_by_user_id` is set and a `Referral` row is written.
|
||||
4. On the new user's first paid subscription (D.3), we read the
|
||||
`Referral` row to apply discounts to both parties.
|
||||
|
||||
The code itself is 8 characters from an unambiguous alphabet so users
|
||||
can read it off a phone screen or dictate it over the phone.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db import utcnow
|
||||
from app.logging import get_logger
|
||||
from app.models import Referral, User
|
||||
|
||||
|
||||
log = get_logger("referral")
|
||||
|
||||
|
||||
# Unambiguous alphabet — no 0/O, no 1/I/L. 32 chars → 8 positions ≈ 1e12
|
||||
# combinations, plenty for our scale, and a unique-constraint catches
|
||||
# collisions if we ever generate the same one twice.
|
||||
_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||
_CODE_LEN = 8
|
||||
|
||||
|
||||
def generate_code() -> str:
|
||||
"""Cryptographically random 8-char code from the unambiguous alphabet."""
|
||||
return "".join(secrets.choice(_ALPHABET) for _ in range(_CODE_LEN))
|
||||
|
||||
|
||||
def normalise_code(raw: str | None) -> str | None:
|
||||
"""Trim, uppercase, strip non-alphabet characters. Used on inbound
|
||||
`?ref=<code>` params so users can paste with spaces / lowercase.
|
||||
Returns None if the result isn't a plausible code."""
|
||||
if not raw:
|
||||
return None
|
||||
cleaned = "".join(c for c in raw.upper() if c in _ALPHABET)
|
||||
if len(cleaned) != _CODE_LEN:
|
||||
return None
|
||||
return cleaned
|
||||
|
||||
|
||||
async def assign_code_if_missing(session: AsyncSession, user: User) -> User:
|
||||
"""Generate + persist a referral code on `user` if they don't have
|
||||
one yet. Retries on the (very rare) collision."""
|
||||
if user.referral_code:
|
||||
return user
|
||||
for _ in range(8):
|
||||
code = generate_code()
|
||||
existing = (await session.execute(
|
||||
select(User.id).where(User.referral_code == code)
|
||||
)).scalar_one_or_none()
|
||||
if existing is None:
|
||||
user.referral_code = code
|
||||
await session.commit()
|
||||
await session.refresh(user)
|
||||
log.info("referral.code_assigned", user_id=user.id, code=code)
|
||||
return user
|
||||
# 8 collisions in a row would be a statistical event we'd want to
|
||||
# know about.
|
||||
raise RuntimeError("referral_service: exhausted code-collision retries")
|
||||
|
||||
|
||||
async def lookup_referrer(session: AsyncSession, code: str | None) -> User | None:
|
||||
"""Return the User whose `referral_code` matches, or None. Normalises
|
||||
the input via `normalise_code` so URL-paste variations all resolve."""
|
||||
code = normalise_code(code)
|
||||
if not code:
|
||||
return None
|
||||
return (await session.execute(
|
||||
select(User).where(User.referral_code == code)
|
||||
)).scalar_one_or_none()
|
||||
|
||||
|
||||
async def link_new_user(
|
||||
session: AsyncSession,
|
||||
new_user: User,
|
||||
referrer: User | None,
|
||||
) -> Referral | None:
|
||||
"""Record a referral if the supplied referrer is valid. Idempotent
|
||||
(safe to call multiple times for the same new user — the unique
|
||||
constraint on `referred_user_id` makes duplicate inserts a no-op).
|
||||
|
||||
Self-referral is silently rejected.
|
||||
"""
|
||||
if referrer is None or new_user.id is None or referrer.id == new_user.id:
|
||||
return None
|
||||
if new_user.referred_by_user_id is not None:
|
||||
# Already linked; this user can't be referred twice.
|
||||
return None
|
||||
|
||||
new_user.referred_by_user_id = referrer.id
|
||||
ref = Referral(
|
||||
referrer_user_id=referrer.id,
|
||||
referred_user_id=new_user.id,
|
||||
created_at=utcnow(),
|
||||
)
|
||||
session.add(ref)
|
||||
await session.commit()
|
||||
await session.refresh(new_user)
|
||||
await session.refresh(ref)
|
||||
log.info(
|
||||
"referral.linked",
|
||||
referrer_id=referrer.id, referred_id=new_user.id,
|
||||
)
|
||||
return ref
|
||||
Loading…
Add table
Add a link
Reference in a new issue