|
| 1 | +"""Founder-tour persistence — per-user `tour_state` read/write. |
| 2 | +
|
| 3 | +Tiny endpoint pair behind ``/api/v1/users/me/tour-state``: |
| 4 | +
|
| 5 | +* ``GET`` → return the JSON blob (or an empty default if NULL). |
| 6 | +* ``PUT`` → upsert the JSON blob. No partial updates — caller sends |
| 7 | + the full shape every time. Keeps the contract honest. |
| 8 | +
|
| 9 | +Authentication is the standard cookie/bearer dep (``get_current_user``). |
| 10 | +Per-user — there is no admin-fetch-other-user surface here. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import json |
| 16 | +import logging |
| 17 | +from datetime import UTC, datetime |
| 18 | +from typing import Any |
| 19 | + |
| 20 | +from fastapi import APIRouter, Depends, HTTPException |
| 21 | +from pydantic import BaseModel |
| 22 | +from sqlalchemy import text |
| 23 | + |
| 24 | +from .auth import get_current_user |
| 25 | +from .deps import get_store |
| 26 | +from .store._sqlite import SqliteStore |
| 27 | + |
| 28 | +log = logging.getLogger("tour_routes") |
| 29 | + |
| 30 | +router = APIRouter(prefix="/users/me", tags=["tour"]) |
| 31 | + |
| 32 | + |
| 33 | +class TourState(BaseModel): |
| 34 | + """Shape of the per-user tour-completion state. |
| 35 | +
|
| 36 | + All fields are optional — the frontend treats absence of |
| 37 | + ``completed_at`` as "tour has not been finished; auto-fire OK" |
| 38 | + unless ``dismissed_at`` is set (then replay only via the |
| 39 | + `?` launcher, never auto-fire). |
| 40 | + """ |
| 41 | + |
| 42 | + completed_at: str | None = None |
| 43 | + dismissed_at: str | None = None |
| 44 | + current_step: int = 0 |
| 45 | + |
| 46 | + |
| 47 | +def _parse(raw: str | None) -> TourState: |
| 48 | + """Decode the TEXT column into a ``TourState``. Empty → defaults.""" |
| 49 | + if not raw: |
| 50 | + return TourState() |
| 51 | + try: |
| 52 | + data = json.loads(raw) |
| 53 | + except json.JSONDecodeError: |
| 54 | + # Corrupt row — surface as "fresh" rather than 500ing the UI. |
| 55 | + log.warning("tour_state JSON decode failed; returning defaults") |
| 56 | + return TourState() |
| 57 | + if not isinstance(data, dict): |
| 58 | + return TourState() |
| 59 | + return TourState( |
| 60 | + completed_at=data.get("completed_at"), |
| 61 | + dismissed_at=data.get("dismissed_at"), |
| 62 | + current_step=int(data.get("current_step", 0)), |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +def _serialize(state: TourState) -> str: |
| 67 | + """Encode for the TEXT column. Compact JSON, stable key order.""" |
| 68 | + return json.dumps( |
| 69 | + { |
| 70 | + "completed_at": state.completed_at, |
| 71 | + "dismissed_at": state.dismissed_at, |
| 72 | + "current_step": state.current_step, |
| 73 | + }, |
| 74 | + sort_keys=True, |
| 75 | + separators=(",", ":"), |
| 76 | + ) |
| 77 | + |
| 78 | + |
| 79 | +def _read_sync(store: SqliteStore, username: str) -> str | None: |
| 80 | + with store._engine.connect() as conn: # noqa: SLF001 |
| 81 | + row = conn.execute( |
| 82 | + text("SELECT tour_state FROM users WHERE username = :u"), |
| 83 | + {"u": username}, |
| 84 | + ).fetchone() |
| 85 | + return row[0] if row is not None else None |
| 86 | + |
| 87 | + |
| 88 | +def _write_sync(store: SqliteStore, username: str, blob: str) -> int: |
| 89 | + with store._engine.begin() as conn: # noqa: SLF001 |
| 90 | + result = conn.execute( |
| 91 | + text("UPDATE users SET tour_state = :s WHERE username = :u"), |
| 92 | + {"s": blob, "u": username}, |
| 93 | + ) |
| 94 | + return int(result.rowcount or 0) |
| 95 | + |
| 96 | + |
| 97 | +@router.get("/tour-state", response_model=TourState) |
| 98 | +async def get_tour_state( |
| 99 | + username: str = Depends(get_current_user), |
| 100 | + store: SqliteStore = Depends(get_store), |
| 101 | +) -> TourState: |
| 102 | + """Return the caller's tour-state, or empty defaults if never set.""" |
| 103 | + raw = await store._run_sync(_read_sync, store, username) # noqa: SLF001 |
| 104 | + return _parse(raw) |
| 105 | + |
| 106 | + |
| 107 | +@router.put("/tour-state", response_model=TourState) |
| 108 | +async def put_tour_state( |
| 109 | + payload: TourState, |
| 110 | + username: str = Depends(get_current_user), |
| 111 | + store: SqliteStore = Depends(get_store), |
| 112 | +) -> TourState: |
| 113 | + """Replace the caller's tour-state with the supplied blob. |
| 114 | +
|
| 115 | + Server stamps ``completed_at`` / ``dismissed_at`` to now if the |
| 116 | + caller sent the literal string ``"now"`` — convenience so the |
| 117 | + frontend doesn't need to grab a clock. |
| 118 | + """ |
| 119 | + now = datetime.now(UTC).isoformat() |
| 120 | + if payload.completed_at == "now": |
| 121 | + payload.completed_at = now |
| 122 | + if payload.dismissed_at == "now": |
| 123 | + payload.dismissed_at = now |
| 124 | + |
| 125 | + blob = _serialize(payload) |
| 126 | + rowcount = await store._run_sync(_write_sync, store, username, blob) # noqa: SLF001 |
| 127 | + if rowcount == 0: |
| 128 | + raise HTTPException(status_code=404, detail="User not found") |
| 129 | + return payload |
0 commit comments