feat(admin): rebuild admin area around the Article domain

The admin area was managing a Hacker News-style Item model that the
public site never consumed, so the homepage always fell back to sample
data. Rebuild the admin area around the real public content model.

Backend:
- Remove the Item model, schema and admin API
- Admin API now manages articles at /api/v1/admin/articles (CRUD) with
  /api/v1/admin/authors and /api/v1/admin/categories reference data
- Add public read-only article endpoints (/api/v1/articles,
  /api/v1/articles/{id}): no auth, published-only, newest-first
- Rewrite Article schemas; ArticleRead embeds author and category
- Add idempotent seed_content.py dev seeder (3 authors, 4 categories,
  6 published articles)

Frontend:
- Admin UI rewritten around articles: AdminDashboard list, new
  EditArticlePage (create/edit, author/category selects, published
  toggle, Lexical editor, debounced auto-save)
- Replace AdminItem types and api client with the article domain
- Update App routes, AdminLayout sidebar, DeleteConfirmation, Lexical
  editor labels and Home/client comments to article terminology

Tests:
- Rewrite admin unit tests and the Playwright admin e2e spec for the
  article domain; add test_articles.py for the public endpoints and
  seeder
This commit is contained in:
Daniel Samson committed 2026-10-31 18:31:05 +00:00
1 parent de96d0b152
commit afa399776f
29 files changed
+2465 -1658

No files matched your search

+5 -1
View File
@@ -6,16 +6,20 @@ Mounted under ``/api/v1`` (see ``core.app.create_app``).
from fastapi import APIRouter
from api.v1 import admin as admin_routes
from api.v1 import articles as articles_routes
from api.v1 import auth as auth_routes
from config import APP_NAME, APP_VERSION
from schemas import HealthResponse, VersionResponse
router = APIRouter()
# Public article feed (no auth) under /api/v1/articles.
router.include_router(articles_routes.router)
# Authentication (register / login / logout / me) under /api/v1/auth.
router.include_router(auth_routes.router)
# Admin area (item CRUD, admin-only) under /api/v1/admin.
# Admin area (article CRUD, admin-only) under /api/v1/admin.
router.include_router(admin_routes.router)
+152 -77
View File
@@ -1,4 +1,4 @@
"""Admin area endpoints: item CRUD for site administrators.
"""Admin area endpoints: article CRUD for site administrators.
Every route requires a valid Bearer token **and** ``User.is_admin``
(see ``core.auth.get_current_admin``); non-admins receive 403. A simple
@@ -6,13 +6,20 @@ in-memory rate limiter (``_RateLimiter``) caps the request volume per
admin account — a deliberately light-weight placeholder that can be
replaced by a production-grade limiter later.
The admin area manages the content readers see: every article has a title,
an HTML body, an ``Author``, a ``Category`` and a ``published`` flag.
Two read-only reference endpoints (``/authors``, ``/categories``) feed the
article form's select boxes.
Routes (mounted under ``/api/v1/admin``):
- ``GET /items`` paginated list with search and sorting
- ``POST /items`` create an item
- ``GET /items/{id}`` fetch a single item
- ``PUT /items/{id}`` update an item (partial updates supported)
- ``DELETE /items/{id}`` delete an item
- ``GET /articles`` paginated list with search and sorting
- ``POST /articles`` create an article
- ``GET /articles/{id}`` fetch a single article
- ``PUT /articles/{id}`` update an article (partial updates supported)
- ``DELETE /articles/{id}`` delete an article
- ``GET /authors`` all authors (form reference data)
- ``GET /categories`` all categories (form reference data)
"""
from __future__ import annotations
@@ -23,12 +30,15 @@ from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import asc, desc, or_
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, joinedload
from core import auth
from db.session import get_db
from models import Item, User
from schemas import ItemAdminList, ItemCreate, ItemRead, ItemUpdate
from models import Article, Author, Category, User
from schemas import ArticleAdminList, ArticleCreate, ArticleRead, ArticleUpdate
from schemas.author import AuthorRead
from schemas.category import CategoryRead
router = APIRouter(prefix="/admin", tags=["admin"])
@@ -41,8 +51,8 @@ class _RateLimiter:
"""Fixed-window request limiter keyed by an arbitrary string.
Thread-safe (the admin endpoints run in FastAPI's threadpool). Kept
intentionally simple — a "placeholder" per the M6 milestone that can
be swapped for a shared/production limiter without touching routes.
intentionally simple — a "placeholder" per the M6 milestone that can be
swapped for a shared/production limiter without touching routes.
"""
def __init__(self, limit: int = 1000, window_seconds: float = 60.0) -> None:
@@ -86,54 +96,90 @@ def _rate_limit(admin: User = Depends(auth.get_current_admin)) -> User:
# ---------------------------------------------------------------------------
def _get_item_or_404(db: Session, item_id: int) -> Item:
item = db.query(Item).filter(Item.id == item_id).first()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
def _get_article_or_404(db: Session, article_id: int) -> Article:
article = (
db.query(Article)
.options(joinedload(Article.author), joinedload(Article.category))
.filter(Article.id == article_id)
.first()
)
if article is None:
raise HTTPException(status_code=404, detail="Article not found")
return article
def _apply_search(query, search: str):
"""Filter by ``title`` OR ``url`` (case-insensitive substring match)."""
"""Filter by ``title`` OR ``content`` (case-insensitive substring match)."""
if not search:
return query
pattern = f"%{search}%"
return query.filter(or_(Item.title.ilike(pattern), Item.url.ilike(pattern)))
return query.filter(
or_(Article.title.ilike(pattern), Article.content.ilike(pattern))
)
def _apply_sort(query, sort_by: str, sort_order: str):
column = getattr(Item, sort_by)
column = getattr(Article, sort_by)
return query.order_by(asc(column) if sort_order == "asc" else desc(column))
def _validate_author(db: Session, author_id: int) -> None:
"""422 with a clear message when the author does not exist."""
if db.get(Author, author_id) is None:
raise HTTPException(status_code=422, detail=f"Author {author_id} not found")
def _validate_category(db: Session, category_id: int) -> None:
"""422 with a clear message when the category does not exist."""
if db.get(Category, category_id) is None:
raise HTTPException(status_code=422, detail=f"Category {category_id} not found")
def _commit(db: Session, action: str) -> None:
"""Commit, converting a title collision into a 409 conflict."""
try:
db.commit()
except IntegrityError:
db.rollback()
raise HTTPException(
status_code=409,
detail=f"An article with this title already exists ({action}).",
)
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@router.get(
"/items",
response_model=ItemAdminList,
summary="List items (paginated, searchable, sortable)",
"/articles",
response_model=ArticleAdminList,
summary="List articles (paginated, searchable, sortable)",
)
def list_items(
def list_articles(
page: int = Query(default=1, ge=1, description="1-based page number"),
page_size: int = Query(
default=20, ge=1, le=100, description="Items per page (1-100)"
default=20, ge=1, le=100, description="Articles per page (1-100)"
),
search: str = Query(default="", max_length=200, description="Match title or URL"),
sort_by: Literal["title", "created_at", "points"] = "created_at",
search: str = Query(
default="", max_length=200, description="Match title or content"
),
sort_by: Literal["title", "created_at"] = "created_at",
sort_order: Literal["asc", "desc"] = "desc",
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> ItemAdminList:
"""List all items with pagination, case-insensitive search and sorting."""
query = _apply_sort(_apply_search(db.query(Item), search), sort_by, sort_order)
) -> ArticleAdminList:
"""List all articles with pagination, case-insensitive search and sorting."""
query = db.query(Article).options(
joinedload(Article.author), joinedload(Article.category)
)
query = _apply_sort(_apply_search(query, search), sort_by, sort_order)
total = query.count()
items = query.offset((page - 1) * page_size).limit(page_size).all()
articles = query.offset((page - 1) * page_size).limit(page_size).all()
total_pages = (total + page_size - 1) // page_size
return ItemAdminList(
items=[ItemRead.model_validate(item) for item in items],
return ArticleAdminList(
articles=[ArticleRead.model_validate(article) for article in articles],
total=total,
page=page,
page_size=page_size,
@@ -142,83 +188,112 @@ def list_items(
@router.post(
"/items",
response_model=ItemRead,
"/articles",
response_model=ArticleRead,
status_code=status.HTTP_201_CREATED,
summary="Create a new item",
summary="Create a new article",
)
def create_item(
payload: ItemCreate,
def create_article(
payload: ArticleCreate,
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> ItemRead:
"""Create an item; it belongs to ``username`` or the admin when omitted."""
item = Item(
) -> ArticleRead:
"""Create an article (draft by default unless ``published`` is set)."""
_validate_author(db, payload.author_id)
_validate_category(db, payload.category_id)
article = Article(
title=payload.title,
url=payload.url,
points=payload.points,
username=(payload.username or admin.username).strip(),
content=payload.content,
author_id=payload.author_id,
category_id=payload.category_id,
published=payload.published,
)
db.add(item)
db.commit()
db.refresh(item)
return ItemRead.model_validate(item)
db.add(article)
_commit(db, action="create")
db.refresh(article)
return ArticleRead.model_validate(article)
@router.get(
"/items/{item_id}",
response_model=ItemRead,
summary="Get a single item",
"/articles/{article_id}",
response_model=ArticleRead,
summary="Get a single article",
)
def get_item(
item_id: int,
def get_article(
article_id: int,
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> ItemRead:
"""Fetch one item by id (404 when it does not exist)."""
return ItemRead.model_validate(_get_item_or_404(db, item_id))
) -> ArticleRead:
"""Fetch one article by id (404 when it does not exist)."""
return ArticleRead.model_validate(_get_article_or_404(db, article_id))
@router.put(
"/items/{item_id}",
response_model=ItemRead,
summary="Update an item",
"/articles/{article_id}",
response_model=ArticleRead,
summary="Update an article",
)
def update_item(
item_id: int,
payload: ItemUpdate,
def update_article(
article_id: int,
payload: ArticleUpdate,
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> ItemRead:
"""Update an item; only the provided fields change (partial update)."""
item = _get_item_or_404(db, item_id)
) -> ArticleRead:
"""Update an article; only the provided fields change (partial update)."""
article = _get_article_or_404(db, article_id)
updates = payload.model_dump(exclude_unset=True)
if "username" in updates and updates["username"] is not None:
updates["username"] = updates["username"].strip()
if updates.get("author_id") is not None:
_validate_author(db, updates["author_id"])
if updates.get("category_id") is not None:
_validate_category(db, updates["category_id"])
for field, value in updates.items():
setattr(item, field, value)
db.commit()
db.refresh(item)
return ItemRead.model_validate(item)
setattr(article, field, value)
_commit(db, action="update")
db.refresh(article)
return ArticleRead.model_validate(article)
@router.delete(
"/items/{item_id}",
"/articles/{article_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Delete an item",
summary="Delete an article",
)
def delete_item(
item_id: int,
def delete_article(
article_id: int,
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> None:
"""Hard-delete an item (404 when it does not exist)."""
item = _get_item_or_404(db, item_id)
db.delete(item)
"""Hard-delete an article (404 when it does not exist)."""
article = _get_article_or_404(db, article_id)
db.delete(article)
db.commit()
return None
# ---------------------------------------------------------------------------
# Reference data for the article form
# ---------------------------------------------------------------------------
@router.get("/authors", response_model=list[AuthorRead], summary="List authors")
def list_authors(
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> list[Author]:
"""All authors, ordered by name (feeds the article form's author select)."""
return db.query(Author).order_by(asc(Author.name)).all()
@router.get(
"/categories", response_model=list[CategoryRead], summary="List categories"
)
def list_categories(
admin: User = Depends(_rate_limit),
db: Session = Depends(get_db),
) -> list[Category]:
"""All categories, ordered by name (feeds the article form's category select)."""
return db.query(Category).order_by(asc(Category.name)).all()
# Re-exported for tests and documentation.
__all__ = ["router", "_limiter", "_rate_limit"]
+55
View File
@@ -0,0 +1,55 @@
"""Public read API for articles.
No authentication required — these endpoints power the site front end:
* ``GET /api/v1/articles`` — the home page feed. Returns *published* articles
newest-first, each with its author and category embedded.
* ``GET /api/v1/articles/{id}`` — a single published article (404 when missing
or still a draft).
Drafts (``published=False``) are never exposed here; admins manage them via
the admin area (``api.v1.admin``).
"""
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session, joinedload
from db.session import get_db
from models import Article
from schemas import ArticleRead
router = APIRouter(prefix="/articles", tags=["articles"])
def _load_published_article(db: Session, article_id: int) -> Article:
article = (
db.query(Article)
.options(joinedload(Article.author), joinedload(Article.category))
.filter(Article.id == article_id, Article.published.is_(True))
.first()
)
if article is None:
raise HTTPException(status_code=404, detail="Article not found")
return article
@router.get("", response_model=list[ArticleRead], summary="List published articles")
def list_published_articles(
db: Session = Depends(get_db),
) -> list[Article]:
"""Published articles, newest first, with author and category embedded."""
return (
db.query(Article)
.options(joinedload(Article.author), joinedload(Article.category))
.filter(Article.published.is_(True))
.order_by(Article.created_at.desc())
.all()
)
@router.get("/{article_id}", response_model=ArticleRead, summary="Get a published article")
def get_published_article(
article_id: int,
db: Session = Depends(get_db),
) -> Article:
return _load_published_article(db, article_id)