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
136
app/cli.py
Normal file
136
app/cli.py
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
"""Admin CLI — runs inside the `app` container.
|
||||
|
||||
Usage from the host::
|
||||
|
||||
docker compose exec app python -m app.cli grant-credit <email> <months>
|
||||
docker compose exec app python -m app.cli revoke-credit <email>
|
||||
docker compose exec app python -m app.cli show-status <email>
|
||||
|
||||
`grant-credit` is idempotent: it extends `users.credit_until` from
|
||||
``max(now, current_credit_until)``, so granting "1 month" twice gives
|
||||
two months, not one (avoids accidental erosion of an existing grant
|
||||
when re-running the command).
|
||||
|
||||
This is the manual lever for Phase D.2. In D.3 the Paddle webhook will
|
||||
call the same helper for both sides of a referral conversion.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import sys
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db import get_engine, get_session_factory
|
||||
from app.models import User
|
||||
from app.services.access import _aware, paid_status
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
async def _get_user_by_email(session, email: str) -> User | None:
|
||||
return (await session.execute(
|
||||
select(User).where(User.email == email)
|
||||
)).scalar_one_or_none()
|
||||
|
||||
|
||||
async def grant_credit(email: str, months: float) -> int:
|
||||
if months <= 0:
|
||||
print(f"error: months must be positive (got {months})", file=sys.stderr)
|
||||
return 2
|
||||
factory = get_session_factory()
|
||||
async with factory() as session:
|
||||
user = await _get_user_by_email(session, email)
|
||||
if user is None:
|
||||
print(f"error: no user with email {email!r}", file=sys.stderr)
|
||||
return 1
|
||||
anchor = max(_utcnow(), _aware(user.credit_until) or _utcnow())
|
||||
# 30-day months — simple, predictable, no calendar arithmetic.
|
||||
days = int(round(months * 30))
|
||||
new_expiry = anchor + timedelta(days=days)
|
||||
user.credit_until = new_expiry
|
||||
await session.commit()
|
||||
# Refresh status snapshot from the just-committed value.
|
||||
st = paid_status(user)
|
||||
print(
|
||||
f"granted {months} month(s) to {email}: "
|
||||
f"credit_until={new_expiry.isoformat()} "
|
||||
f"(~{st.days_remaining} days remaining)"
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
async def revoke_credit(email: str) -> int:
|
||||
factory = get_session_factory()
|
||||
async with factory() as session:
|
||||
user = await _get_user_by_email(session, email)
|
||||
if user is None:
|
||||
print(f"error: no user with email {email!r}", file=sys.stderr)
|
||||
return 1
|
||||
user.credit_until = None
|
||||
await session.commit()
|
||||
print(f"revoked: credit_until cleared for {email}")
|
||||
return 0
|
||||
|
||||
|
||||
async def show_status(email: str) -> int:
|
||||
factory = get_session_factory()
|
||||
async with factory() as session:
|
||||
user = await _get_user_by_email(session, email)
|
||||
if user is None:
|
||||
print(f"error: no user with email {email!r}", file=sys.stderr)
|
||||
return 1
|
||||
st = paid_status(user)
|
||||
print(f"email: {user.email}")
|
||||
print(f"tier: {user.tier}")
|
||||
print(f"credit_until: {user.credit_until or '—'}")
|
||||
print(f"paid active: {st.active} (source={st.source or '—'})")
|
||||
if st.expires_at:
|
||||
print(f"expires in: {st.days_remaining} days")
|
||||
return 0
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
p = argparse.ArgumentParser(prog="app.cli", description="Cassandra admin CLI")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
|
||||
g = sub.add_parser("grant-credit", help="Extend a user's paid-credit window")
|
||||
g.add_argument("email")
|
||||
g.add_argument("months", type=float)
|
||||
|
||||
r = sub.add_parser("revoke-credit", help="Clear a user's credit_until")
|
||||
r.add_argument("email")
|
||||
|
||||
s = sub.add_parser("show-status", help="Print paid-tier status for a user")
|
||||
s.add_argument("email")
|
||||
|
||||
return p
|
||||
|
||||
|
||||
async def _dispatch(args) -> int:
|
||||
"""Run the chosen sub-command, then dispose the async engine cleanly
|
||||
so aiomysql's __del__ doesn't squawk at interpreter shutdown about a
|
||||
closed event loop."""
|
||||
try:
|
||||
if args.cmd == "grant-credit":
|
||||
return await grant_credit(args.email, args.months)
|
||||
if args.cmd == "revoke-credit":
|
||||
return await revoke_credit(args.email)
|
||||
if args.cmd == "show-status":
|
||||
return await show_status(args.email)
|
||||
return 2
|
||||
finally:
|
||||
await get_engine().dispose()
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
return asyncio.run(_dispatch(args))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Loading…
Add table
Add a link
Reference in a new issue