Implements docs/read-markets-compliance-changes.md as flag-gated changes (no deletions) so paused features stay in the tree for future re-enable. All four flags default False so a fresh deploy is compliance-safe. - New env flags: PORTFOLIO_AI_ENABLED, PORTFOLIO_SYNC_ENABLED, TICKER_UNIVERSE_AGGREGATE_ENABLED, SUBSCRIPTIONS_ENABLED. - Gates: /api/analyze, /api/portfolio/sync*, /api/stripe/*, /pricing, ticker_universe writes, portfolio_analysis.analyse(). is_paid_active() returns True for any auth'd user when subscriptions are paused. - Prompts (PROMPT_VERSION 10): universal _COMPLIANCE_RIDER prepended to every system prompt; watch list removed; price-target / close-above-below / trigger / forward-state-as-description rules added; SPECULATIVE pivoted to regime-only scenarios; daily + weekly digests tightened. - Reviewer: deterministic regex/lexicon pre-check fail-closed under the Haiku call; portfolio rider gated by PORTFOLIO_AI_ENABLED; base prompt sharpened for forward-state and MAR forward-opinion patterns; ReviewerVerdict audit table; generate_with_review retry helper. - Migration 0026: purge portfolio_sync + ticker_universe; create reviewer_verdicts. - Copy: MAR cite fixed to Art 3(1)(35) + Art 20 + Del Reg 2016/958; portfolio reframed as browser-only viewer in disclaimer / privacy / terms / about / pricing / landing (en + it). TODO(legal) marker for lawyer sign-off on disclaimer. - Tests: 13 lexicon + 6 reviewer compliance regressions; conftest enables all flags so existing 402 tests still cover their code paths. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
117 lines
4.3 KiB
Python
117 lines
4.3 KiB
Python
"""Paid-tier access checks.
|
|
|
|
Two sources can grant paid access:
|
|
|
|
1. ``user.tier in {"paid", "enterprise"}`` — set by the Stripe webhook
|
|
once a subscription is active.
|
|
2. ``user.credit_until > now()`` — non-subscription credit. Populated
|
|
by the admin CLI (``python -m app.cli grant-credit``) and by the
|
|
referral-conversion path (45 days per converted referral, both
|
|
parties).
|
|
|
|
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.config import get_settings
|
|
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.
|
|
|
|
When ``SUBSCRIPTIONS_ENABLED=False`` the subscription system is paused:
|
|
any authenticated principal is treated as paid (free-for-all). Anonymous
|
|
callers still return False so ``require_paid`` continues to enforce auth.
|
|
"""
|
|
if principal is None:
|
|
return False
|
|
if isinstance(principal, CurrentUser):
|
|
if principal.is_admin:
|
|
return True
|
|
if not get_settings().SUBSCRIPTIONS_ENABLED:
|
|
return principal.user is not None
|
|
return paid_status(principal.user).active
|
|
if not get_settings().SUBSCRIPTIONS_ENABLED:
|
|
return True
|
|
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.",
|
|
},
|
|
)
|