read.markets/app/services/access.py
Giorgio Gilestro 2297f9b2ed pricing: land £7/£70 paid tier and make behaviour match
Marketing + behaviour pass to get the site ready for Paddle approval.

Pricing page
- £7/month, £70/year headline (was "Coming soon").
- Bigger tier names (was 11px uppercase mono — looked like chips).
- Real CTAs (button base styles were only scoped to .hero__ctas).
- "Best value" badge + drop-shadow on the Paid card; full-width
  block CTAs that align across both cards.
- "Free vs Paid at a glance" comparison table beneath the cards.
- Compact "Invite a friend — both get 50% off for 3 months"
  callout with the detail explanation behind a <dialog> popup.

Tier copy + behaviour now consistent
- Free strategic-log refresh is every 6 hours, not hourly. New
  read-side filter on /api/log/{latest,by-date} restricts free
  users to logs at boundary hours (00/06/12/18 UTC); paid users
  still see the most recent.
- Follow-up chat is paid-only. /api/chat returns 402 for free;
  the chat sidebar on /log is replaced with a locked aside and
  chat.js no longer loads at all for free users.
- Dashboard meta lines + landing copy softened so they no longer
  promise hourly to everyone.

Future-proofing copy on public pages
- Dropped "free forever" wording (we may close the free tier).
- "Trading 212 CSV" became "broker CSV (Trading 212 today; more
  planned)" on pricing + landing; the actual import UIs stay
  T212-specific.

Terms
- Renamed Terms of Service -> Terms and Conditions (Paddle
  expectation), bumped last-updated to 2026-05-26.
- New §6 Refunds covering the 14-day cooling off, post-window
  cancellation, termination-by-us refunds, statutory rights, and
  how to request a refund.
- Renumbered §7-§14 and fixed the disclaimer link labels.

Tests
- 6 new tests in tests/test_chat_and_log_gates.py cover the
  chat 402 + the boundary-hour filter on both log endpoints.
- Full suite: 205 passed, 5 skipped, 0 failed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 11:34:37 +02:00

106 lines
3.9 KiB
Python

"""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
# How many hours of news the free tier sees. Paid sees whatever the
# endpoint's `since_hours` param requests (up to its own max).
FREE_NEWS_WINDOW_HOURS = 6.0
# The strategic-log job runs at :20 every hour (during trading windows).
# Free-tier users only see logs generated at these UTC hours — so the
# log refreshes for them roughly every 6 hours (00:20, 06:20, 12:20,
# 18:20). Paid users see the absolute latest log. Filtering happens
# read-side; we don't generate per-tier rows.
FREE_LOG_HOURS_UTC: tuple[int, ...] = (0, 6, 12, 18)
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.",
},
)