Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afa399776f |
No files matched your search
@@ -6,16 +6,20 @@ Mounted under ``/api/v1`` (see ``core.app.create_app``).
|
|||||||
from fastapi import APIRouter
|
from fastapi import APIRouter
|
||||||
|
|
||||||
from api.v1 import admin as admin_routes
|
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 api.v1 import auth as auth_routes
|
||||||
from config import APP_NAME, APP_VERSION
|
from config import APP_NAME, APP_VERSION
|
||||||
from schemas import HealthResponse, VersionResponse
|
from schemas import HealthResponse, VersionResponse
|
||||||
|
|
||||||
router = APIRouter()
|
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.
|
# Authentication (register / login / logout / me) under /api/v1/auth.
|
||||||
router.include_router(auth_routes.router)
|
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)
|
router.include_router(admin_routes.router)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+152
-77
@@ -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``
|
Every route requires a valid Bearer token **and** ``User.is_admin``
|
||||||
(see ``core.auth.get_current_admin``); non-admins receive 403. A simple
|
(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
|
admin account — a deliberately light-weight placeholder that can be
|
||||||
replaced by a production-grade limiter later.
|
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``):
|
Routes (mounted under ``/api/v1/admin``):
|
||||||
|
|
||||||
- ``GET /items`` paginated list with search and sorting
|
- ``GET /articles`` paginated list with search and sorting
|
||||||
- ``POST /items`` create an item
|
- ``POST /articles`` create an article
|
||||||
- ``GET /items/{id}`` fetch a single item
|
- ``GET /articles/{id}`` fetch a single article
|
||||||
- ``PUT /items/{id}`` update an item (partial updates supported)
|
- ``PUT /articles/{id}`` update an article (partial updates supported)
|
||||||
- ``DELETE /items/{id}`` delete an item
|
- ``DELETE /articles/{id}`` delete an article
|
||||||
|
- ``GET /authors`` all authors (form reference data)
|
||||||
|
- ``GET /categories`` all categories (form reference data)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -23,12 +30,15 @@ from typing import Literal
|
|||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
from sqlalchemy import asc, desc, or_
|
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 core import auth
|
||||||
from db.session import get_db
|
from db.session import get_db
|
||||||
from models import Item, User
|
from models import Article, Author, Category, User
|
||||||
from schemas import ItemAdminList, ItemCreate, ItemRead, ItemUpdate
|
from schemas import ArticleAdminList, ArticleCreate, ArticleRead, ArticleUpdate
|
||||||
|
from schemas.author import AuthorRead
|
||||||
|
from schemas.category import CategoryRead
|
||||||
|
|
||||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||||
|
|
||||||
@@ -41,8 +51,8 @@ class _RateLimiter:
|
|||||||
"""Fixed-window request limiter keyed by an arbitrary string.
|
"""Fixed-window request limiter keyed by an arbitrary string.
|
||||||
|
|
||||||
Thread-safe (the admin endpoints run in FastAPI's threadpool). Kept
|
Thread-safe (the admin endpoints run in FastAPI's threadpool). Kept
|
||||||
intentionally simple — a "placeholder" per the M6 milestone that can
|
intentionally simple — a "placeholder" per the M6 milestone that can be
|
||||||
be swapped for a shared/production limiter without touching routes.
|
swapped for a shared/production limiter without touching routes.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, limit: int = 1000, window_seconds: float = 60.0) -> None:
|
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:
|
def _get_article_or_404(db: Session, article_id: int) -> Article:
|
||||||
item = db.query(Item).filter(Item.id == item_id).first()
|
article = (
|
||||||
if item is None:
|
db.query(Article)
|
||||||
raise HTTPException(status_code=404, detail="Item not found")
|
.options(joinedload(Article.author), joinedload(Article.category))
|
||||||
return item
|
.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):
|
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:
|
if not search:
|
||||||
return query
|
return query
|
||||||
pattern = f"%{search}%"
|
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):
|
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))
|
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
|
# Endpoints
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/items",
|
"/articles",
|
||||||
response_model=ItemAdminList,
|
response_model=ArticleAdminList,
|
||||||
summary="List items (paginated, searchable, sortable)",
|
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: int = Query(default=1, ge=1, description="1-based page number"),
|
||||||
page_size: int = Query(
|
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"),
|
search: str = Query(
|
||||||
sort_by: Literal["title", "created_at", "points"] = "created_at",
|
default="", max_length=200, description="Match title or content"
|
||||||
|
),
|
||||||
|
sort_by: Literal["title", "created_at"] = "created_at",
|
||||||
sort_order: Literal["asc", "desc"] = "desc",
|
sort_order: Literal["asc", "desc"] = "desc",
|
||||||
admin: User = Depends(_rate_limit),
|
admin: User = Depends(_rate_limit),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
) -> ItemAdminList:
|
) -> ArticleAdminList:
|
||||||
"""List all items with pagination, case-insensitive search and sorting."""
|
"""List all articles with pagination, case-insensitive search and sorting."""
|
||||||
query = _apply_sort(_apply_search(db.query(Item), search), sort_by, sort_order)
|
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()
|
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
|
total_pages = (total + page_size - 1) // page_size
|
||||||
return ItemAdminList(
|
return ArticleAdminList(
|
||||||
items=[ItemRead.model_validate(item) for item in items],
|
articles=[ArticleRead.model_validate(article) for article in articles],
|
||||||
total=total,
|
total=total,
|
||||||
page=page,
|
page=page,
|
||||||
page_size=page_size,
|
page_size=page_size,
|
||||||
@@ -142,83 +188,112 @@ def list_items(
|
|||||||
|
|
||||||
|
|
||||||
@router.post(
|
@router.post(
|
||||||
"/items",
|
"/articles",
|
||||||
response_model=ItemRead,
|
response_model=ArticleRead,
|
||||||
status_code=status.HTTP_201_CREATED,
|
status_code=status.HTTP_201_CREATED,
|
||||||
summary="Create a new item",
|
summary="Create a new article",
|
||||||
)
|
)
|
||||||
def create_item(
|
def create_article(
|
||||||
payload: ItemCreate,
|
payload: ArticleCreate,
|
||||||
admin: User = Depends(_rate_limit),
|
admin: User = Depends(_rate_limit),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
) -> ItemRead:
|
) -> ArticleRead:
|
||||||
"""Create an item; it belongs to ``username`` or the admin when omitted."""
|
"""Create an article (draft by default unless ``published`` is set)."""
|
||||||
item = Item(
|
_validate_author(db, payload.author_id)
|
||||||
|
_validate_category(db, payload.category_id)
|
||||||
|
article = Article(
|
||||||
title=payload.title,
|
title=payload.title,
|
||||||
url=payload.url,
|
|
||||||
points=payload.points,
|
|
||||||
username=(payload.username or admin.username).strip(),
|
|
||||||
content=payload.content,
|
content=payload.content,
|
||||||
|
author_id=payload.author_id,
|
||||||
|
category_id=payload.category_id,
|
||||||
|
published=payload.published,
|
||||||
)
|
)
|
||||||
db.add(item)
|
db.add(article)
|
||||||
db.commit()
|
_commit(db, action="create")
|
||||||
db.refresh(item)
|
db.refresh(article)
|
||||||
return ItemRead.model_validate(item)
|
return ArticleRead.model_validate(article)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
"/items/{item_id}",
|
"/articles/{article_id}",
|
||||||
response_model=ItemRead,
|
response_model=ArticleRead,
|
||||||
summary="Get a single item",
|
summary="Get a single article",
|
||||||
)
|
)
|
||||||
def get_item(
|
def get_article(
|
||||||
item_id: int,
|
article_id: int,
|
||||||
admin: User = Depends(_rate_limit),
|
admin: User = Depends(_rate_limit),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
) -> ItemRead:
|
) -> ArticleRead:
|
||||||
"""Fetch one item by id (404 when it does not exist)."""
|
"""Fetch one article by id (404 when it does not exist)."""
|
||||||
return ItemRead.model_validate(_get_item_or_404(db, item_id))
|
return ArticleRead.model_validate(_get_article_or_404(db, article_id))
|
||||||
|
|
||||||
|
|
||||||
@router.put(
|
@router.put(
|
||||||
"/items/{item_id}",
|
"/articles/{article_id}",
|
||||||
response_model=ItemRead,
|
response_model=ArticleRead,
|
||||||
summary="Update an item",
|
summary="Update an article",
|
||||||
)
|
)
|
||||||
def update_item(
|
def update_article(
|
||||||
item_id: int,
|
article_id: int,
|
||||||
payload: ItemUpdate,
|
payload: ArticleUpdate,
|
||||||
admin: User = Depends(_rate_limit),
|
admin: User = Depends(_rate_limit),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
) -> ItemRead:
|
) -> ArticleRead:
|
||||||
"""Update an item; only the provided fields change (partial update)."""
|
"""Update an article; only the provided fields change (partial update)."""
|
||||||
item = _get_item_or_404(db, item_id)
|
article = _get_article_or_404(db, article_id)
|
||||||
updates = payload.model_dump(exclude_unset=True)
|
updates = payload.model_dump(exclude_unset=True)
|
||||||
if "username" in updates and updates["username"] is not None:
|
if updates.get("author_id") is not None:
|
||||||
updates["username"] = updates["username"].strip()
|
_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():
|
for field, value in updates.items():
|
||||||
setattr(item, field, value)
|
setattr(article, field, value)
|
||||||
db.commit()
|
_commit(db, action="update")
|
||||||
db.refresh(item)
|
db.refresh(article)
|
||||||
return ItemRead.model_validate(item)
|
return ArticleRead.model_validate(article)
|
||||||
|
|
||||||
|
|
||||||
@router.delete(
|
@router.delete(
|
||||||
"/items/{item_id}",
|
"/articles/{article_id}",
|
||||||
status_code=status.HTTP_204_NO_CONTENT,
|
status_code=status.HTTP_204_NO_CONTENT,
|
||||||
summary="Delete an item",
|
summary="Delete an article",
|
||||||
)
|
)
|
||||||
def delete_item(
|
def delete_article(
|
||||||
item_id: int,
|
article_id: int,
|
||||||
admin: User = Depends(_rate_limit),
|
admin: User = Depends(_rate_limit),
|
||||||
db: Session = Depends(get_db),
|
db: Session = Depends(get_db),
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Hard-delete an item (404 when it does not exist)."""
|
"""Hard-delete an article (404 when it does not exist)."""
|
||||||
item = _get_item_or_404(db, item_id)
|
article = _get_article_or_404(db, article_id)
|
||||||
db.delete(item)
|
db.delete(article)
|
||||||
db.commit()
|
db.commit()
|
||||||
return None
|
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.
|
# Re-exported for tests and documentation.
|
||||||
__all__ = ["router", "_limiter", "_rate_limit"]
|
__all__ = ["router", "_limiter", "_rate_limit"]
|
||||||
@@ -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)
|
||||||
@@ -4,7 +4,6 @@ from models.article import Article
|
|||||||
from models.author import Author
|
from models.author import Author
|
||||||
from models.base import Base
|
from models.base import Base
|
||||||
from models.category import Category, slugify
|
from models.category import Category, slugify
|
||||||
from models.item import Item
|
|
||||||
from models.user import User
|
from models.user import User
|
||||||
|
|
||||||
__all__ = ["Article", "Author", "Base", "Category", "Item", "User", "slugify"]
|
__all__ = ["Article", "Author", "Base", "Category", "User", "slugify"]
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
"""Item model: a news story managed through the admin area.
|
|
||||||
|
|
||||||
Unlike ``Article`` (long-form pieces filed under an author and category),
|
|
||||||
an ``Item`` is a lightweight news entry — headline, optional external URL,
|
|
||||||
community points and an optional HTML body — created and maintained by
|
|
||||||
administrators through the admin API (see ``api.v1.admin``).
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
|
|
||||||
from sqlalchemy import DateTime, Integer, String, Text
|
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
|
||||||
|
|
||||||
from models.base import Base
|
|
||||||
|
|
||||||
|
|
||||||
def _utcnow() -> datetime:
|
|
||||||
return datetime.now(timezone.utc)
|
|
||||||
|
|
||||||
|
|
||||||
class Item(Base):
|
|
||||||
"""A news item (story) listed on the front page and managed by admins.
|
|
||||||
|
|
||||||
``username`` stores the (denormalized) name of the user the item
|
|
||||||
belongs to, defaulting to the account that created it.
|
|
||||||
"""
|
|
||||||
|
|
||||||
__tablename__ = "items"
|
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
|
||||||
title: Mapped[str] = mapped_column(String(300), nullable=False, index=True)
|
|
||||||
url: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
|
||||||
points: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
|
||||||
username: Mapped[str] = mapped_column(String(60), default="anonymous", nullable=False)
|
|
||||||
content: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
|
||||||
created_at: Mapped[datetime] = mapped_column(
|
|
||||||
DateTime(timezone=True), default=_utcnow, nullable=False
|
|
||||||
)
|
|
||||||
|
|
||||||
def __repr__(self) -> str: # pragma: no cover
|
|
||||||
return f"<Item id={self.id} title={self.title!r}>"
|
|
||||||
@@ -1,13 +1,24 @@
|
|||||||
"""Pydantic request/response schemas for newzy."""
|
"""Pydantic request/response schemas for newzy."""
|
||||||
|
|
||||||
from schemas.article import ArticleBase, ArticleCreate, ArticleRead, ArticleUpdate
|
from schemas.article import (
|
||||||
|
ArticleAdminList,
|
||||||
|
ArticleBase,
|
||||||
|
ArticleCreate,
|
||||||
|
ArticleRead,
|
||||||
|
ArticleUpdate,
|
||||||
|
)
|
||||||
from schemas.auth import LoginIn, RegisterIn, TokenOut, UserOut
|
from schemas.auth import LoginIn, RegisterIn, TokenOut, UserOut
|
||||||
from schemas.author import AuthorBase, AuthorCreate, AuthorRead, AuthorUpdate
|
from schemas.author import AuthorBase, AuthorCreate, AuthorRead, AuthorUpdate
|
||||||
from schemas.category import CategoryBase, CategoryCreate, CategoryRead, CategoryUpdate
|
from schemas.category import (
|
||||||
|
CategoryBase,
|
||||||
|
CategoryCreate,
|
||||||
|
CategoryRead,
|
||||||
|
CategoryUpdate,
|
||||||
|
)
|
||||||
from schemas.common import ErrorDetail, HealthResponse, VersionResponse
|
from schemas.common import ErrorDetail, HealthResponse, VersionResponse
|
||||||
from schemas.item import ItemAdminList, ItemCreate, ItemRead, ItemUpdate
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
"ArticleAdminList",
|
||||||
"ArticleBase",
|
"ArticleBase",
|
||||||
"ArticleCreate",
|
"ArticleCreate",
|
||||||
"ArticleRead",
|
"ArticleRead",
|
||||||
@@ -22,10 +33,6 @@ __all__ = [
|
|||||||
"CategoryUpdate",
|
"CategoryUpdate",
|
||||||
"ErrorDetail",
|
"ErrorDetail",
|
||||||
"HealthResponse",
|
"HealthResponse",
|
||||||
"ItemAdminList",
|
|
||||||
"ItemCreate",
|
|
||||||
"ItemRead",
|
|
||||||
"ItemUpdate",
|
|
||||||
"LoginIn",
|
"LoginIn",
|
||||||
"RegisterIn",
|
"RegisterIn",
|
||||||
"TokenOut",
|
"TokenOut",
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
"""Schemas for the Article model."""
|
"""Schemas for the Article model.
|
||||||
|
|
||||||
|
``ArticleRead`` embeds the related ``author`` and ``category`` so both the
|
||||||
|
public feed and the admin area can render full article details from a single
|
||||||
|
payload (the ORM relationships are loaded via ``from_attributes``).
|
||||||
|
"""
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
from schemas.author import AuthorRead
|
||||||
|
from schemas.category import CategoryRead
|
||||||
|
|
||||||
|
|
||||||
class ArticleBase(BaseModel):
|
class ArticleBase(BaseModel):
|
||||||
"""Fields shared by create/update/read article schemas."""
|
"""Fields shared by create/update/read article schemas."""
|
||||||
@@ -31,7 +39,7 @@ class ArticleUpdate(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class ArticleRead(BaseModel):
|
class ArticleRead(BaseModel):
|
||||||
"""Article as returned by the API."""
|
"""Article as returned by the API, with related author/category."""
|
||||||
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
@@ -42,3 +50,15 @@ class ArticleRead(BaseModel):
|
|||||||
category_id: int
|
category_id: int
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
published: bool
|
published: bool
|
||||||
|
author: AuthorRead
|
||||||
|
category: CategoryRead
|
||||||
|
|
||||||
|
|
||||||
|
class ArticleAdminList(BaseModel):
|
||||||
|
"""Paginated article list of ``GET /api/v1/admin/articles``."""
|
||||||
|
|
||||||
|
articles: list[ArticleRead]
|
||||||
|
total: int
|
||||||
|
page: int
|
||||||
|
page_size: int
|
||||||
|
total_pages: int
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
"""Schemas for the Item model (admin area, see ``api.v1.admin``)."""
|
|
||||||
|
|
||||||
from datetime import datetime
|
|
||||||
from urllib.parse import urlsplit
|
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
||||||
|
|
||||||
|
|
||||||
def _clean_title(value: str) -> str:
|
|
||||||
stripped = value.strip()
|
|
||||||
if not stripped:
|
|
||||||
raise ValueError("title must not be empty")
|
|
||||||
return stripped
|
|
||||||
|
|
||||||
|
|
||||||
def _clean_url(value: str | None) -> str:
|
|
||||||
"""Normalize an optional URL: empty/blank -> ``""``, otherwise it must
|
|
||||||
be an absolute ``http://`` or ``https://`` URL."""
|
|
||||||
if value is None:
|
|
||||||
return ""
|
|
||||||
stripped = value.strip()
|
|
||||||
if not stripped:
|
|
||||||
return ""
|
|
||||||
parsed = urlsplit(stripped)
|
|
||||||
if parsed.scheme not in ("http", "https") or not parsed.netloc:
|
|
||||||
raise ValueError("must be an absolute http:// or https:// URL")
|
|
||||||
return stripped
|
|
||||||
|
|
||||||
|
|
||||||
class ItemBase(BaseModel):
|
|
||||||
"""Fields shared by the item create schema and the read model."""
|
|
||||||
|
|
||||||
title: str = Field(..., min_length=1, max_length=300)
|
|
||||||
url: str = Field(default="", max_length=500)
|
|
||||||
points: int = Field(default=0, ge=0)
|
|
||||||
content: str = Field(default="", description="HTML body from the Lexical editor.")
|
|
||||||
|
|
||||||
@field_validator("title")
|
|
||||||
@classmethod
|
|
||||||
def _strip_title(cls, value: str) -> str:
|
|
||||||
return _clean_title(value)
|
|
||||||
|
|
||||||
@field_validator("url")
|
|
||||||
@classmethod
|
|
||||||
def _validate_url(cls, value: str) -> str:
|
|
||||||
return _clean_url(value)
|
|
||||||
|
|
||||||
|
|
||||||
class ItemCreate(ItemBase):
|
|
||||||
"""Payload of ``POST /api/v1/admin/items``.
|
|
||||||
|
|
||||||
``username`` is optional: when omitted the item belongs to the
|
|
||||||
authenticated admin.
|
|
||||||
"""
|
|
||||||
|
|
||||||
username: str | None = Field(default=None, min_length=1, max_length=60)
|
|
||||||
|
|
||||||
|
|
||||||
class ItemUpdate(BaseModel):
|
|
||||||
"""Payload of ``PUT /api/v1/admin/items/{id}`` (all fields optional)."""
|
|
||||||
|
|
||||||
title: str | None = Field(default=None, max_length=300)
|
|
||||||
url: str | None = Field(default=None, max_length=500)
|
|
||||||
points: int | None = Field(default=None, ge=0)
|
|
||||||
username: str | None = Field(default=None, min_length=1, max_length=60)
|
|
||||||
content: str | None = None
|
|
||||||
|
|
||||||
@field_validator("title")
|
|
||||||
@classmethod
|
|
||||||
def _strip_title(cls, value: str | None) -> str | None:
|
|
||||||
if value is None:
|
|
||||||
return None
|
|
||||||
return _clean_title(value)
|
|
||||||
|
|
||||||
@field_validator("url")
|
|
||||||
@classmethod
|
|
||||||
def _validate_url(cls, value: str | None) -> str | None:
|
|
||||||
return None if value is None else _clean_url(value)
|
|
||||||
|
|
||||||
|
|
||||||
class ItemRead(BaseModel):
|
|
||||||
"""Item as returned by the admin API."""
|
|
||||||
|
|
||||||
model_config = ConfigDict(from_attributes=True)
|
|
||||||
|
|
||||||
id: int
|
|
||||||
title: str
|
|
||||||
url: str
|
|
||||||
points: int
|
|
||||||
username: str
|
|
||||||
content: str
|
|
||||||
created_at: datetime
|
|
||||||
|
|
||||||
|
|
||||||
class ItemAdminList(BaseModel):
|
|
||||||
"""Paginated item list of ``GET /api/v1/admin/items``."""
|
|
||||||
|
|
||||||
items: list[ItemRead]
|
|
||||||
total: int
|
|
||||||
page: int
|
|
||||||
page_size: int
|
|
||||||
total_pages: int
|
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
"""Seed demo content: authors, categories and published articles.
|
||||||
|
|
||||||
|
Usage (inside the backend container or with the backend venv)::
|
||||||
|
|
||||||
|
python seed_content.py
|
||||||
|
|
||||||
|
Idempotent — safe to re-run. Existing authors (matched by email),
|
||||||
|
categories (matched by slug) and articles (matched by title) are left
|
||||||
|
untouched; only missing rows are created. The seeded dataset mirrors the
|
||||||
|
front end's sample data (``frontend/src/data/sample.ts``) so the site has
|
||||||
|
real content to serve until the admin area is used.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from db.session import SessionLocal
|
||||||
|
from models import Article, Author, Category
|
||||||
|
|
||||||
|
AUTHORS: list[dict] = [
|
||||||
|
{
|
||||||
|
"name": "Ada Lovelace",
|
||||||
|
"email": "ada@example.com",
|
||||||
|
"bio": "Writes about technology and computation.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Grace Hopper",
|
||||||
|
"email": "grace@example.com",
|
||||||
|
"bio": "Covers science and engineering.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Alan Turing",
|
||||||
|
"email": "alan@example.com",
|
||||||
|
"bio": "Follows sports and culture.",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
CATEGORIES: list[dict] = [
|
||||||
|
{"name": "Technology", "slug": "technology"},
|
||||||
|
{"name": "Science", "slug": "science"},
|
||||||
|
{"name": "Sports", "slug": "sports"},
|
||||||
|
{"name": "Culture", "slug": "culture"},
|
||||||
|
]
|
||||||
|
|
||||||
|
# (title, body, author_email, category_slug, created_at, published)
|
||||||
|
ARTICLES: list[tuple[str, str, str, str, str, bool]] = [
|
||||||
|
(
|
||||||
|
"Inside the new wave of open-source language models",
|
||||||
|
'Open-source language models are closing the gap with proprietary systems, '
|
||||||
|
"and the ecosystem around them is growing fast. Researchers now release "
|
||||||
|
"pretrained weights alongside detailed training recipes, letting smaller "
|
||||||
|
'teams fine-tune models for narrow tasks that once required large budgets. '
|
||||||
|
'The result is a new layer of the AI stack: community-maintained tooling '
|
||||||
|
'for evaluation, deployment, and safety testing that moves at a pace big '
|
||||||
|
'vendors struggle to match. As hardware costs keep falling, expect the line '
|
||||||
|
'between "research model" and "production model" to blur further this year.',
|
||||||
|
"ada@example.com",
|
||||||
|
"technology",
|
||||||
|
"2025-06-02T09:30:00Z",
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Fusion milestone: net energy gain repeated for the third time",
|
||||||
|
"Scientists have repeated a net-energy-gain fusion reaction for the third "
|
||||||
|
"consecutive time, confirming that last months breakthrough was not a fluke. "
|
||||||
|
"The latest run sustained the plasma for a record duration and produced "
|
||||||
|
"energy output within a few percent of the original measurement. Engineers "
|
||||||
|
"now say the remaining challenges are engineering, not physics: materials "
|
||||||
|
"that survive repeated shots and power systems that deliver pulses on "
|
||||||
|
"demand. A commercial demonstration plant could enter the design phase as "
|
||||||
|
"early as next decade.",
|
||||||
|
"grace@example.com",
|
||||||
|
"science",
|
||||||
|
"2025-05-28T14:10:00Z",
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"City marathon sets record turnout as first-timers flood the course",
|
||||||
|
"More than 40,000 runners started this weekend city marathon, a record that "
|
||||||
|
"organizers attributed to a wave of first-time participants. The 21-kilometer "
|
||||||
|
"fun run sold out in under an hour, and volunteers reported the most positive "
|
||||||
|
"start-line atmosphere in the events history. Pacing groups, music zones, and "
|
||||||
|
"a free post-race breakfast kept the mood festive even in the rain. Officials "
|
||||||
|
"are already planning capacity expansions for next year, with an eye on adding "
|
||||||
|
"a night race.",
|
||||||
|
"alan@example.com",
|
||||||
|
"sports",
|
||||||
|
"2025-05-25T08:00:00Z",
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"The quiet return of the neighborhood library",
|
||||||
|
"After years of budget cuts, the neighborhood library is staging an unlikely "
|
||||||
|
"comeback. Community volunteers now staff the Saturday makerspace, where 3D "
|
||||||
|
"printing, sewing machines, and a small recording studio are booked weeks in "
|
||||||
|
"advance. Librarians report that circulation is up, but the real story is "
|
||||||
|
"programming: repair cafés, language tables, and civic workshops that have "
|
||||||
|
"made the building a second living room for the district. City planners are "
|
||||||
|
"taking note, and two more branches are slated for renovation this fall.",
|
||||||
|
"ada@example.com",
|
||||||
|
"culture",
|
||||||
|
"2025-05-20T17:45:00Z",
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Rust keeps climbing the systems programming charts",
|
||||||
|
"Rust has moved up again in the annual systems programming survey, now the "
|
||||||
|
"most-wanted language for kernel and infrastructure work among respondents. "
|
||||||
|
"Adoption is no longer limited to startups: several large platforms report "
|
||||||
|
"that new storage and networking services are written in Rust by default. The "
|
||||||
|
"ecosystems memory-safety guarantees, combined with a mature async story, "
|
||||||
|
"continue to draw engineers from C and C++. Tooling improvements in debugging "
|
||||||
|
"and profiling have been the most cited reasons for teams crossing over this "
|
||||||
|
"year.",
|
||||||
|
"grace@example.com",
|
||||||
|
"technology",
|
||||||
|
"2025-05-15T11:20:00Z",
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"Ocean robots map the deepest trenches in record time",
|
||||||
|
"A fleet of autonomous underwater vehicles has completed the most detailed "
|
||||||
|
"survey of the ocean trench yet, mapping 80 percent of the basin floor in six "
|
||||||
|
"weeks. The robots, equipped with multibeam sonar and high-resolution "
|
||||||
|
"cameras, collected terabytes of data that reveal previously unknown "
|
||||||
|
"seamounts and hydrothermal vent fields. Biologists have already flagged "
|
||||||
|
"three candidate species from the first batch of imagery. The team plans to "
|
||||||
|
"return next winter with sampling landers to study the vent communities up "
|
||||||
|
"close.",
|
||||||
|
"alan@example.com",
|
||||||
|
"science",
|
||||||
|
"2025-05-10T19:05:00Z",
|
||||||
|
True,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
authors: dict[str, Author] = {}
|
||||||
|
for spec in AUTHORS:
|
||||||
|
existing = (
|
||||||
|
db.query(Author).filter(Author.email == spec["email"]).first()
|
||||||
|
)
|
||||||
|
if existing is not None:
|
||||||
|
authors[spec["email"]] = existing
|
||||||
|
continue
|
||||||
|
author = Author(**spec)
|
||||||
|
db.add(author)
|
||||||
|
db.flush()
|
||||||
|
authors[spec["email"]] = author
|
||||||
|
print(f"Created author '{spec['name']}'.")
|
||||||
|
|
||||||
|
categories: dict[str, Category] = {}
|
||||||
|
for spec in CATEGORIES:
|
||||||
|
existing = (
|
||||||
|
db.query(Category).filter(Category.slug == spec["slug"]).first()
|
||||||
|
)
|
||||||
|
if existing is not None:
|
||||||
|
categories[spec["slug"]] = existing
|
||||||
|
continue
|
||||||
|
category = Category(**spec)
|
||||||
|
db.add(category)
|
||||||
|
db.flush()
|
||||||
|
categories[spec["slug"]] = category
|
||||||
|
print(f"Created category '{spec['name']}'.")
|
||||||
|
|
||||||
|
for title, content, email, slug, created, published in ARTICLES:
|
||||||
|
if db.query(Article).filter(Article.title == title).first() is not None:
|
||||||
|
continue
|
||||||
|
article = Article(
|
||||||
|
title=title,
|
||||||
|
content=content,
|
||||||
|
author_id=authors[email].id,
|
||||||
|
category_id=categories[slug].id,
|
||||||
|
created_at=datetime.fromisoformat(created.replace("Z", "+00:00")),
|
||||||
|
published=published,
|
||||||
|
)
|
||||||
|
db.add(article)
|
||||||
|
print(f"Created article '{title}'.")
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
print(
|
||||||
|
"Done. "
|
||||||
|
f"{db.query(Author).count()} authors, "
|
||||||
|
f"{db.query(Category).count()} categories, "
|
||||||
|
f"{db.query(Article).count()} articles."
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
+316
-164
@@ -1,7 +1,9 @@
|
|||||||
"""Tests for the admin area: /api/v1/admin/items CRUD, access control.
|
"""Tests for the admin area (M6): /api/v1/admin/articles CRUD, reference
|
||||||
|
data (authors/categories), access control, rate limiting, and the is_admin
|
||||||
|
startup migration.
|
||||||
|
|
||||||
Covers the M6 acceptance criteria: 401/403 handling for the admin
|
Covers the M6 acceptance criteria: 401/403 handling for the admin
|
||||||
dependency, pagination/search/sort on the list endpoint, item creation,
|
dependency, pagination/search/sort on the list endpoint, article creation,
|
||||||
partial updates, deletion and input validation.
|
partial updates, deletion and input validation.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -13,9 +15,9 @@ import pytest
|
|||||||
|
|
||||||
from api.v1 import admin as admin_api
|
from api.v1 import admin as admin_api
|
||||||
from core import auth
|
from core import auth
|
||||||
from models import Item, User
|
from models import Article, Author, Category, User
|
||||||
|
|
||||||
BASE = "/api/v1/admin/items"
|
BASE = "/api/v1/admin/articles"
|
||||||
|
|
||||||
|
|
||||||
def _make_user(session, username: str, is_admin: bool = False) -> User:
|
def _make_user(session, username: str, is_admin: bool = False) -> User:
|
||||||
@@ -30,37 +32,65 @@ def _headers(session, username: str) -> dict:
|
|||||||
return {"Authorization": f"Bearer {auth.create_token(username)}"}
|
return {"Authorization": f"Bearer {auth.create_token(username)}"}
|
||||||
|
|
||||||
|
|
||||||
def _seed_items(session, count: int, prefix: str = "Story") -> list[Item]:
|
def _make_author(
|
||||||
items = []
|
session, name: str = "Byline Writer", email: str = "writer@example.com"
|
||||||
for i in range(count):
|
) -> Author:
|
||||||
item = Item(
|
author = Author(name=name, email=email)
|
||||||
title=f"{prefix} {i:02d}",
|
session.add(author)
|
||||||
url=f"https://example.com/story-{i}",
|
|
||||||
points=i,
|
|
||||||
username="alice",
|
|
||||||
content=f"<p>Body {i}</p>",
|
|
||||||
)
|
|
||||||
session.add(item)
|
|
||||||
items.append(item)
|
|
||||||
session.commit()
|
session.commit()
|
||||||
return items
|
return author
|
||||||
|
|
||||||
|
|
||||||
|
def _make_category(
|
||||||
|
session, name: str = "Technology", slug: str = "technology"
|
||||||
|
) -> Category:
|
||||||
|
category = Category(name=name, slug=slug)
|
||||||
|
session.add(category)
|
||||||
|
session.commit()
|
||||||
|
return category
|
||||||
|
|
||||||
|
|
||||||
|
def _seed_articles(
|
||||||
|
session,
|
||||||
|
count: int,
|
||||||
|
prefix: str = "Story",
|
||||||
|
author: Author | None = None,
|
||||||
|
category: Category | None = None,
|
||||||
|
) -> list[Article]:
|
||||||
|
author = author or _make_author(session)
|
||||||
|
category = category or _make_category(session)
|
||||||
|
articles = []
|
||||||
|
for i in range(count):
|
||||||
|
article = Article(
|
||||||
|
title=f"{prefix} {i:02d}",
|
||||||
|
content=f"<p>Body {i}</p>",
|
||||||
|
author_id=author.id,
|
||||||
|
category_id=category.id,
|
||||||
|
published=True,
|
||||||
|
)
|
||||||
|
session.add(article)
|
||||||
|
articles.append(article)
|
||||||
|
session.commit()
|
||||||
|
return articles
|
||||||
|
|
||||||
|
|
||||||
|
ADMIN_ROUTES = [
|
||||||
|
("GET", f"{BASE}"),
|
||||||
|
("POST", BASE),
|
||||||
|
("GET", f"{BASE}/1"),
|
||||||
|
("PUT", f"{BASE}/1"),
|
||||||
|
("DELETE", f"{BASE}/1"),
|
||||||
|
("GET", "/api/v1/admin/authors"),
|
||||||
|
("GET", "/api/v1/admin/categories"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class TestAdminAccessControl:
|
class TestAdminAccessControl:
|
||||||
"""The admin dependency validates the JWT AND the is_admin flag."""
|
"""The admin dependency validates the JWT AND the is_admin flag."""
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize("method, path", ADMIN_ROUTES)
|
||||||
"method, path",
|
|
||||||
[
|
|
||||||
("GET", f"{BASE}"),
|
|
||||||
("POST", BASE),
|
|
||||||
("GET", f"{BASE}/1"),
|
|
||||||
("PUT", f"{BASE}/1"),
|
|
||||||
("DELETE", f"{BASE}/1"),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_missing_token_returns_401(self, client, method, path) -> None:
|
def test_missing_token_returns_401(self, client, method, path) -> None:
|
||||||
payload = {"title": "x"} if method == "POST" else ({"title": "y"} if method == "PUT" else None)
|
payload = {"title": "x"} if method in ("POST", "PUT") else None
|
||||||
response = client.request(method, path, json=payload)
|
response = client.request(method, path, json=payload)
|
||||||
assert response.status_code == 401
|
assert response.status_code == 401
|
||||||
assert response.json()["code"] == "unauthorized"
|
assert response.json()["code"] == "unauthorized"
|
||||||
@@ -82,27 +112,18 @@ class TestAdminAccessControl:
|
|||||||
assert response.status_code == 401
|
assert response.status_code == 401
|
||||||
|
|
||||||
def test_token_for_deleted_user_returns_401(self, client, session) -> None:
|
def test_token_for_deleted_user_returns_401(self, client, session) -> None:
|
||||||
user = _make_user(session, "admin", is_admin=True)
|
_make_user(session, "admin", is_admin=True)
|
||||||
headers = _headers(session, "admin")
|
headers = _headers(session, "admin")
|
||||||
session.delete(user)
|
session.delete(session.query(User).filter(User.username == "admin").one())
|
||||||
session.commit()
|
session.commit()
|
||||||
response = client.get(BASE, headers=headers)
|
response = client.get(BASE, headers=headers)
|
||||||
assert response.status_code == 401
|
assert response.status_code == 401
|
||||||
assert response.json()["detail"] == "Unknown user"
|
assert response.json()["detail"] == "Unknown user"
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize("method, path", ADMIN_ROUTES)
|
||||||
"method, path",
|
|
||||||
[
|
|
||||||
("GET", f"{BASE}"),
|
|
||||||
("POST", BASE),
|
|
||||||
("GET", f"{BASE}/1"),
|
|
||||||
("PUT", f"{BASE}/1"),
|
|
||||||
("DELETE", f"{BASE}/1"),
|
|
||||||
],
|
|
||||||
)
|
|
||||||
def test_non_admin_receives_403(self, client, session, method, path) -> None:
|
def test_non_admin_receives_403(self, client, session, method, path) -> None:
|
||||||
_make_user(session, "alice", is_admin=False)
|
_make_user(session, "alice", is_admin=False)
|
||||||
payload = {"title": "x"} if method == "POST" else ({"title": "y"} if method == "PUT" else None)
|
payload = {"title": "x"} if method in ("POST", "PUT") else None
|
||||||
response = client.request(
|
response = client.request(
|
||||||
method, path, json=payload, headers=_headers(session, "alice")
|
method, path, json=payload, headers=_headers(session, "alice")
|
||||||
)
|
)
|
||||||
@@ -111,21 +132,14 @@ class TestAdminAccessControl:
|
|||||||
assert body["code"] == "forbidden"
|
assert body["code"] == "forbidden"
|
||||||
assert body["detail"] == "Admin access required"
|
assert body["detail"] == "Admin access required"
|
||||||
|
|
||||||
def test_admin_dependency_returns_the_user_object(self, client, session) -> None:
|
|
||||||
"""get_current_admin yields the ORM user (used for audit logging later)."""
|
|
||||||
admin = _make_user(session, "root", is_admin=True)
|
|
||||||
response = client.get(BASE, headers=_headers(session, "root"))
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert admin.is_admin is True
|
|
||||||
|
|
||||||
|
class TestListArticles:
|
||||||
class TestListItems:
|
|
||||||
def test_empty_list(self, client, session) -> None:
|
def test_empty_list(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
response = client.get(BASE, headers=_headers(session, "root"))
|
response = client.get(BASE, headers=_headers(session, "root"))
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
body = response.json()
|
body = response.json()
|
||||||
assert body["items"] == []
|
assert body["articles"] == []
|
||||||
assert body["total"] == 0
|
assert body["total"] == 0
|
||||||
assert body["page"] == 1
|
assert body["page"] == 1
|
||||||
assert body["page_size"] == 20
|
assert body["page_size"] == 20
|
||||||
@@ -133,24 +147,24 @@ class TestListItems:
|
|||||||
|
|
||||||
def test_pagination_math_and_contents(self, client, session) -> None:
|
def test_pagination_math_and_contents(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
_seed_items(session, 25)
|
_seed_articles(session, 25)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
|
|
||||||
page1 = client.get(BASE, params={"page": 1, "page_size": 10}, headers=headers).json()
|
page1 = client.get(BASE, params={"page": 1, "page_size": 10}, headers=headers).json()
|
||||||
assert page1["total"] == 25
|
assert page1["total"] == 25
|
||||||
assert page1["total_pages"] == 3
|
assert page1["total_pages"] == 3
|
||||||
assert len(page1["items"]) == 10
|
assert len(page1["articles"]) == 10
|
||||||
assert page1["page"] == 1
|
assert page1["page"] == 1
|
||||||
|
|
||||||
page2 = client.get(BASE, params={"page": 2, "page_size": 10}, headers=headers).json()
|
page2 = client.get(BASE, params={"page": 2, "page_size": 10}, headers=headers).json()
|
||||||
assert len(page2["items"]) == 10
|
assert len(page2["articles"]) == 10
|
||||||
# Pages are disjoint.
|
# Pages are disjoint.
|
||||||
ids1 = {i["id"] for i in page1["items"]}
|
ids1 = {a["id"] for a in page1["articles"]}
|
||||||
ids2 = {i["id"] for i in page2["items"]}
|
ids2 = {a["id"] for a in page2["articles"]}
|
||||||
assert ids1.isdisjoint(ids2)
|
assert ids1.isdisjoint(ids2)
|
||||||
|
|
||||||
page3 = client.get(BASE, params={"page": 3, "page_size": 10}, headers=headers).json()
|
page3 = client.get(BASE, params={"page": 3, "page_size": 10}, headers=headers).json()
|
||||||
assert len(page3["items"]) == 5
|
assert len(page3["articles"]) == 5
|
||||||
|
|
||||||
def test_page_size_bounds(self, client, session) -> None:
|
def test_page_size_bounds(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
@@ -160,33 +174,33 @@ class TestListItems:
|
|||||||
assert client.get(BASE, params={"page": 0}, headers=headers).status_code == 422
|
assert client.get(BASE, params={"page": 0}, headers=headers).status_code == 422
|
||||||
assert client.get(BASE, params={"page_size": 100}, headers=headers).status_code == 200
|
assert client.get(BASE, params={"page_size": 100}, headers=headers).status_code == 200
|
||||||
|
|
||||||
def test_search_matches_title_and_url_case_insensitively(self, client, session) -> None:
|
def test_search_matches_title_and_content_case_insensitively(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
_seed_items(session, 5)
|
_seed_articles(session, 5)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
|
|
||||||
by_title = client.get(BASE, params={"search": "STORY 02"}, headers=headers).json()
|
by_title = client.get(BASE, params={"search": "STORY 02"}, headers=headers).json()
|
||||||
assert [i["title"] for i in by_title["items"]] == ["Story 02"]
|
assert [a["title"] for a in by_title["articles"]] == ["Story 02"]
|
||||||
|
|
||||||
# Seed URLs are https://example.com/story-<n> (no zero padding).
|
# Bodies are "<p>Body <n></p>" — search inside the HTML content.
|
||||||
by_url = client.get(BASE, params={"search": "EXAMPLE.COM/STORY-4"}, headers=headers).json()
|
by_content = client.get(BASE, params={"search": "BODY 4"}, headers=headers).json()
|
||||||
assert [i["title"] for i in by_url["items"]] == ["Story 04"]
|
assert [a["title"] for a in by_content["articles"]] == ["Story 04"]
|
||||||
|
|
||||||
none = client.get(BASE, params={"search": "does-not-exist"}, headers=headers).json()
|
none = client.get(BASE, params={"search": "does-not-exist"}, headers=headers).json()
|
||||||
assert none["items"] == []
|
assert none["articles"] == []
|
||||||
assert none["total"] == 0
|
assert none["total"] == 0
|
||||||
|
|
||||||
def test_search_with_sql_metacharacters_is_treated_as_text(self, client, session) -> None:
|
def test_search_with_sql_metacharacters_is_treated_as_text(self, client, session) -> None:
|
||||||
"""Search input is a parameterized substring filter, never raw SQL."""
|
"""Search input is a parameterized substring filter, never raw SQL."""
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
_seed_items(session, 5)
|
_seed_articles(session, 5)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
|
|
||||||
attack = "1=1' OR '1'='1"
|
attack = "1=1' OR '1'='1"
|
||||||
resp = client.get(BASE, params={"search": attack}, headers=headers)
|
resp = client.get(BASE, params={"search": attack}, headers=headers)
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
body = resp.json()
|
body = resp.json()
|
||||||
assert body["items"] == []
|
assert body["articles"] == []
|
||||||
assert body["total"] == 0
|
assert body["total"] == 0
|
||||||
|
|
||||||
# The table is intact after the "attack".
|
# The table is intact after the "attack".
|
||||||
@@ -196,47 +210,39 @@ class TestListItems:
|
|||||||
@pytest.mark.parametrize("order, expected_first", [("asc", "Story 00"), ("desc", "Story 04")])
|
@pytest.mark.parametrize("order, expected_first", [("asc", "Story 00"), ("desc", "Story 04")])
|
||||||
def test_sort_by_title(self, client, session, order, expected_first) -> None:
|
def test_sort_by_title(self, client, session, order, expected_first) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
_seed_items(session, 5)
|
_seed_articles(session, 5)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
body = client.get(
|
body = client.get(
|
||||||
BASE, params={"sort_by": "title", "sort_order": order}, headers=headers
|
BASE, params={"sort_by": "title", "sort_order": order}, headers=headers
|
||||||
).json()
|
).json()
|
||||||
assert body["items"][0]["title"] == expected_first
|
assert body["articles"][0]["title"] == expected_first
|
||||||
assert [i["title"] for i in body["items"]] == sorted(
|
assert [a["title"] for a in body["articles"]] == sorted(
|
||||||
(i["title"] for i in body["items"]), reverse=(order == "desc")
|
(a["title"] for a in body["articles"]), reverse=(order == "desc")
|
||||||
)
|
)
|
||||||
|
|
||||||
@pytest.mark.parametrize("order, expected_first_points", [("asc", 0), ("desc", 4)])
|
|
||||||
def test_sort_by_points(self, client, session, order, expected_first_points) -> None:
|
|
||||||
_make_user(session, "root", is_admin=True)
|
|
||||||
_seed_items(session, 5)
|
|
||||||
headers = _headers(session, "root")
|
|
||||||
body = client.get(
|
|
||||||
BASE, params={"sort_by": "points", "sort_order": order}, headers=headers
|
|
||||||
).json()
|
|
||||||
assert body["items"][0]["points"] == expected_first_points
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("order", ["asc", "desc"])
|
@pytest.mark.parametrize("order", ["asc", "desc"])
|
||||||
def test_sort_by_created_at(self, client, session, order) -> None:
|
def test_sort_by_created_at(self, client, session, order) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
items = _seed_items(session, 5)
|
articles = _seed_articles(session, 5)
|
||||||
# Distinct timestamps so the ordering is deterministic.
|
# Distinct timestamps so the ordering is deterministic.
|
||||||
base = datetime(2025, 1, 1, tzinfo=timezone.utc)
|
base = datetime(2025, 1, 1, tzinfo=timezone.utc)
|
||||||
for index, item in enumerate(items):
|
for index, article in enumerate(articles):
|
||||||
item.created_at = base + timedelta(minutes=index)
|
article.created_at = base + timedelta(minutes=index)
|
||||||
session.commit()
|
session.commit()
|
||||||
|
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
body = client.get(
|
body = client.get(
|
||||||
BASE, params={"sort_by": "created_at", "sort_order": order}, headers=headers
|
BASE, params={"sort_by": "created_at", "sort_order": order}, headers=headers
|
||||||
).json()
|
).json()
|
||||||
stamps = [i["created_at"] for i in body["items"]]
|
stamps = [a["created_at"] for a in body["articles"]]
|
||||||
assert stamps == sorted(stamps, reverse=(order == "desc"))
|
assert stamps == sorted(stamps, reverse=(order == "desc"))
|
||||||
|
|
||||||
def test_invalid_sort_values_rejected(self, client, session) -> None:
|
def test_invalid_sort_values_rejected(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
assert client.get(BASE, params={"sort_by": "points"}, headers=headers).status_code == 200
|
assert client.get(BASE, params={"sort_by": "title"}, headers=headers).status_code == 200
|
||||||
|
# "points" was an Item column — it is no longer a valid sort field.
|
||||||
|
assert client.get(BASE, params={"sort_by": "points"}, headers=headers).status_code == 422
|
||||||
assert (
|
assert (
|
||||||
client.get(BASE, params={"sort_by": "username"}, headers=headers).status_code == 422
|
client.get(BASE, params={"sort_by": "username"}, headers=headers).status_code == 422
|
||||||
)
|
)
|
||||||
@@ -244,27 +250,42 @@ class TestListItems:
|
|||||||
client.get(BASE, params={"sort_order": "up"}, headers=headers).status_code == 422
|
client.get(BASE, params={"sort_order": "up"}, headers=headers).status_code == 422
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_item_payload_shape(self, client, session) -> None:
|
def test_article_payload_shape(self, client, session) -> None:
|
||||||
|
"""List entries embed the related author and category."""
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
_seed_items(session, 1)
|
author = _make_author(session, name="Amara Osei", email="amara@example.com")
|
||||||
|
category = _make_category(session, name="Culture", slug="culture")
|
||||||
|
_seed_articles(session, 1, author=author, category=category)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
body = client.get(BASE, headers=headers).json()
|
body = client.get(BASE, headers=headers).json()
|
||||||
item = body["items"][0]
|
article = body["articles"][0]
|
||||||
assert set(item) == {"id", "title", "url", "points", "username", "content", "created_at"}
|
assert set(article) == {
|
||||||
|
"id", "title", "content", "author_id", "category_id",
|
||||||
|
"created_at", "published", "author", "category",
|
||||||
|
}
|
||||||
|
assert article["author"] == {
|
||||||
|
"id": author.id, "name": "Amara Osei", "email": "amara@example.com", "bio": None
|
||||||
|
}
|
||||||
|
assert article["category"] == {
|
||||||
|
"id": category.id, "name": "Culture", "slug": "culture"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class TestGetItem:
|
class TestGetArticle:
|
||||||
def test_returns_full_item_including_content(self, client, session) -> None:
|
def test_returns_full_article_including_content(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
items = _seed_items(session, 1)
|
author = _make_author(session, name="Jonas Weber", email="jonas@example.com")
|
||||||
|
category = _make_category(session, name="Science", slug="science")
|
||||||
|
articles = _seed_articles(session, 1, author=author, category=category)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
response = client.get(f"{BASE}/{items[0].id}", headers=headers)
|
response = client.get(f"{BASE}/{articles[0].id}", headers=headers)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
body = response.json()
|
body = response.json()
|
||||||
assert body["id"] == items[0].id
|
assert body["id"] == articles[0].id
|
||||||
assert body["title"] == "Story 00"
|
assert body["title"] == "Story 00"
|
||||||
assert body["content"] == "<p>Body 0</p>"
|
assert body["content"] == "<p>Body 0</p>"
|
||||||
assert body["username"] == "alice"
|
assert body["author"]["name"] == "Jonas Weber"
|
||||||
|
assert body["category"]["slug"] == "science"
|
||||||
|
|
||||||
def test_unknown_id_returns_404(self, client, session) -> None:
|
def test_unknown_id_returns_404(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
@@ -274,142 +295,255 @@ class TestGetItem:
|
|||||||
assert response.json()["code"] == "not_found"
|
assert response.json()["code"] == "not_found"
|
||||||
|
|
||||||
|
|
||||||
class TestCreateItem:
|
class TestCreateArticle:
|
||||||
def test_create_with_title_only_uses_defaults(self, client, session) -> None:
|
def test_create_defaults_published_false(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
|
||||||
headers = _headers(session, "root")
|
|
||||||
response = client.post(BASE, json={"title": "Fresh news"}, headers=headers)
|
|
||||||
assert response.status_code == 201
|
|
||||||
body = response.json()
|
|
||||||
assert body["title"] == "Fresh news"
|
|
||||||
assert body["url"] == ""
|
|
||||||
assert body["points"] == 0
|
|
||||||
assert body["content"] == ""
|
|
||||||
# The item belongs to the admin that created it.
|
|
||||||
assert body["username"] == "root"
|
|
||||||
|
|
||||||
def test_create_with_all_fields(self, client, session) -> None:
|
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
|
author = _make_author(session)
|
||||||
|
category = _make_category(session)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
payload = {
|
payload = {
|
||||||
"title": " Padded title ",
|
"title": "Fresh news",
|
||||||
"url": " https://example.com/story ",
|
"content": "<p>Hello world.</p>",
|
||||||
"points": 12,
|
"author_id": author.id,
|
||||||
"username": "bob",
|
"category_id": category.id,
|
||||||
"content": "<p>Hello <strong>world</strong></p>",
|
|
||||||
}
|
}
|
||||||
response = client.post(BASE, json=payload, headers=headers)
|
response = client.post(BASE, json=payload, headers=headers)
|
||||||
assert response.status_code == 201
|
assert response.status_code == 201
|
||||||
body = response.json()
|
body = response.json()
|
||||||
# Strings are stripped on the wire.
|
assert body["title"] == "Fresh news"
|
||||||
assert body["title"] == "Padded title"
|
assert body["content"] == "<p>Hello world.</p>"
|
||||||
assert body["url"] == "https://example.com/story"
|
assert body["author_id"] == author.id
|
||||||
assert body["points"] == 12
|
assert body["category_id"] == category.id
|
||||||
assert body["username"] == "bob"
|
assert body["published"] is False
|
||||||
assert body["content"] == "<p>Hello <strong>world</strong></p>"
|
assert body["created_at"]
|
||||||
|
|
||||||
|
def test_create_with_published_true(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
author = _make_author(session)
|
||||||
|
category = _make_category(session)
|
||||||
|
payload = {
|
||||||
|
"title": "Ready to ship",
|
||||||
|
"content": "<p>Live now.</p>",
|
||||||
|
"author_id": author.id,
|
||||||
|
"category_id": category.id,
|
||||||
|
"published": True,
|
||||||
|
}
|
||||||
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
||||||
|
assert response.status_code == 201
|
||||||
|
assert response.json()["published"] is True
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"payload",
|
"payload",
|
||||||
[
|
[
|
||||||
{}, # missing title
|
{}, # everything missing
|
||||||
|
{"title": "t", "content": "<p>c</p>"}, # missing author/category
|
||||||
|
{"title": "t", "author_id": 1, "category_id": 1}, # missing content
|
||||||
{"title": ""}, # empty title
|
{"title": ""}, # empty title
|
||||||
{"title": " "}, # blank title
|
{"title": "x" * 201}, # too long
|
||||||
{"title": "x" * 301}, # too long
|
{"title": "t", "content": "<p>c</p>", "author_id": 0}, # invalid ids
|
||||||
{"title": "ok", "points": -1}, # negative points
|
|
||||||
{"title": "ok", "url": "not-a-url"}, # invalid URL
|
|
||||||
{"title": "ok", "url": "ftp://example.com/x"}, # wrong scheme
|
|
||||||
{"title": "ok", "url": "https://"}, # missing host
|
|
||||||
{"title": "ok", "url": "x" * 501}, # too long
|
|
||||||
{"title": "ok", "points": 1.5}, # not an integer
|
|
||||||
{"title": "ok", "username": ""}, # empty username
|
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_validation_failures_return_422(self, client, session, payload) -> None:
|
def test_validation_failures_return_422(self, client, session, payload) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
headers = _headers(session, "root")
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
||||||
response = client.post(BASE, json=payload, headers=headers)
|
|
||||||
assert response.status_code == 422
|
assert response.status_code == 422
|
||||||
assert response.json()["code"] == "validation_error"
|
assert response.json()["code"] == "validation_error"
|
||||||
|
|
||||||
|
def test_unknown_author_returns_422(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
category = _make_category(session)
|
||||||
|
payload = {
|
||||||
|
"title": "Orphan author",
|
||||||
|
"content": "<p>x</p>",
|
||||||
|
"author_id": 9999,
|
||||||
|
"category_id": category.id,
|
||||||
|
}
|
||||||
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
||||||
|
assert response.status_code == 422
|
||||||
|
assert response.json()["detail"] == "Author 9999 not found"
|
||||||
|
|
||||||
class TestUpdateItem:
|
def test_unknown_category_returns_422(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
author = _make_author(session)
|
||||||
|
payload = {
|
||||||
|
"title": "Orphan category",
|
||||||
|
"content": "<p>x</p>",
|
||||||
|
"author_id": author.id,
|
||||||
|
"category_id": 9999,
|
||||||
|
}
|
||||||
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
||||||
|
assert response.status_code == 422
|
||||||
|
assert response.json()["detail"] == "Category 9999 not found"
|
||||||
|
|
||||||
|
def test_duplicate_title_returns_409(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
author = _make_author(session)
|
||||||
|
category = _make_category(session)
|
||||||
|
_seed_articles(session, 1, author=author, category=category)
|
||||||
|
payload = {
|
||||||
|
"title": "Story 00",
|
||||||
|
"content": "<p>another body</p>",
|
||||||
|
"author_id": author.id,
|
||||||
|
"category_id": category.id,
|
||||||
|
}
|
||||||
|
response = client.post(BASE, json=payload, headers=_headers(session, "root"))
|
||||||
|
assert response.status_code == 409
|
||||||
|
assert response.json()["code"] == "conflict"
|
||||||
|
|
||||||
|
|
||||||
|
class TestUpdateArticle:
|
||||||
def test_partial_update_changes_only_provided_fields(self, client, session) -> None:
|
def test_partial_update_changes_only_provided_fields(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
items = _seed_items(session, 1)
|
articles = _seed_articles(session, 1)
|
||||||
headers = _headers(session, "root")
|
headers = _headers(session, "root")
|
||||||
|
|
||||||
response = client.put(
|
response = client.put(
|
||||||
f"{BASE}/{items[0].id}", json={"points": 99}, headers=headers
|
f"{BASE}/{articles[0].id}", json={"published": False}, headers=headers
|
||||||
)
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
body = response.json()
|
body = response.json()
|
||||||
assert body["points"] == 99
|
assert body["published"] is False
|
||||||
# Untouched fields keep their values.
|
# Untouched fields keep their values.
|
||||||
assert body["title"] == "Story 00"
|
assert body["title"] == "Story 00"
|
||||||
assert body["url"] == "https://example.com/story-0"
|
|
||||||
assert body["content"] == "<p>Body 0</p>"
|
assert body["content"] == "<p>Body 0</p>"
|
||||||
|
|
||||||
def test_full_update(self, client, session) -> None:
|
def test_full_update(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
items = _seed_items(session, 1)
|
author = _make_author(session, name="Old Byline", email="old@example.com")
|
||||||
headers = _headers(session, "root")
|
category = _make_category(session, name="Old Cat", slug="old-cat")
|
||||||
|
articles = _seed_articles(session, 1, author=author, category=category)
|
||||||
|
new_author = _make_author(session, name="New Byline", email="new@example.com")
|
||||||
|
new_category = _make_category(session, name="New Cat", slug="new-cat")
|
||||||
payload = {
|
payload = {
|
||||||
"title": "Retitled",
|
"title": "Retitled",
|
||||||
"url": "https://example.com/new",
|
|
||||||
"points": 7,
|
|
||||||
"username": "carol",
|
|
||||||
"content": "<p>Updated</p>",
|
"content": "<p>Updated</p>",
|
||||||
|
"author_id": new_author.id,
|
||||||
|
"category_id": new_category.id,
|
||||||
|
"published": False,
|
||||||
}
|
}
|
||||||
response = client.put(f"{BASE}/{items[0].id}", json=payload, headers=headers)
|
response = client.put(
|
||||||
|
f"{BASE}/{articles[0].id}", json=payload, headers=_headers(session, "root")
|
||||||
|
)
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
body = response.json()
|
body = response.json()
|
||||||
assert body == {**body, **payload, "id": items[0].id}
|
assert body["title"] == "Retitled"
|
||||||
|
assert body["content"] == "<p>Updated</p>"
|
||||||
|
assert body["author_id"] == new_author.id
|
||||||
|
assert body["category_id"] == new_category.id
|
||||||
|
assert body["published"] is False
|
||||||
|
assert body["author"]["name"] == "New Byline"
|
||||||
|
|
||||||
def test_unknown_id_returns_404(self, client, session) -> None:
|
def test_unknown_id_returns_404(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
headers = _headers(session, "root")
|
response = client.put(f"{BASE}/9999", json={"title": "x"}, headers=_headers(session, "root"))
|
||||||
response = client.put(f"{BASE}/9999", json={"title": "x"}, headers=headers)
|
|
||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
|
|
||||||
def test_invalid_payload_returns_422(self, client, session) -> None:
|
def test_invalid_payload_returns_422(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
items = _seed_items(session, 1)
|
articles = _seed_articles(session, 1)
|
||||||
headers = _headers(session, "root")
|
|
||||||
response = client.put(
|
response = client.put(
|
||||||
f"{BASE}/{items[0].id}", json={"title": "", "points": -3}, headers=headers
|
f"{BASE}/{articles[0].id}",
|
||||||
|
json={"title": "", "author_id": -3},
|
||||||
|
headers=_headers(session, "root"),
|
||||||
)
|
)
|
||||||
assert response.status_code == 422
|
assert response.status_code == 422
|
||||||
|
|
||||||
def test_empty_payload_is_a_no_op(self, client, session) -> None:
|
def test_empty_payload_is_a_no_op(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
items = _seed_items(session, 1)
|
articles = _seed_articles(session, 1)
|
||||||
headers = _headers(session, "root")
|
response = client.put(f"{BASE}/{articles[0].id}", json={}, headers=_headers(session, "root"))
|
||||||
response = client.put(f"{BASE}/{items[0].id}", json={}, headers=headers)
|
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert response.json()["title"] == "Story 00"
|
assert response.json()["title"] == "Story 00"
|
||||||
|
|
||||||
|
def test_title_collision_returns_409(self, client, session) -> None:
|
||||||
class TestDeleteItem:
|
|
||||||
def test_delete_removes_the_item(self, client, session) -> None:
|
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
items = _seed_items(session, 1)
|
articles = _seed_articles(session, 2)
|
||||||
headers = _headers(session, "root")
|
response = client.put(
|
||||||
item_id = items[0].id
|
f"{BASE}/{articles[1].id}",
|
||||||
|
json={"title": "Story 00"},
|
||||||
|
headers=_headers(session, "root"),
|
||||||
|
)
|
||||||
|
assert response.status_code == 409
|
||||||
|
|
||||||
response = client.delete(f"{BASE}/{item_id}", headers=headers)
|
def test_update_to_unknown_author_returns_422(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
articles = _seed_articles(session, 1)
|
||||||
|
response = client.put(
|
||||||
|
f"{BASE}/{articles[0].id}",
|
||||||
|
json={"author_id": 9999},
|
||||||
|
headers=_headers(session, "root"),
|
||||||
|
)
|
||||||
|
assert response.status_code == 422
|
||||||
|
assert response.json()["detail"] == "Author 9999 not found"
|
||||||
|
|
||||||
|
def test_update_to_unknown_category_returns_422(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
articles = _seed_articles(session, 1)
|
||||||
|
response = client.put(
|
||||||
|
f"{BASE}/{articles[0].id}",
|
||||||
|
json={"category_id": 9999},
|
||||||
|
headers=_headers(session, "root"),
|
||||||
|
)
|
||||||
|
assert response.status_code == 422
|
||||||
|
assert response.json()["detail"] == "Category 9999 not found"
|
||||||
|
|
||||||
|
|
||||||
|
class TestDeleteArticle:
|
||||||
|
def test_delete_removes_the_article(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
articles = _seed_articles(session, 1)
|
||||||
|
headers = _headers(session, "root")
|
||||||
|
article_id = articles[0].id
|
||||||
|
|
||||||
|
response = client.delete(f"{BASE}/{article_id}", headers=headers)
|
||||||
assert response.status_code == 204
|
assert response.status_code == 204
|
||||||
assert response.content == b""
|
assert response.content == b""
|
||||||
|
|
||||||
assert client.get(f"{BASE}/{item_id}", headers=headers).status_code == 404
|
assert client.get(f"{BASE}/{article_id}", headers=headers).status_code == 404
|
||||||
assert session.query(Item).filter(Item.id == item_id).first() is None
|
assert session.query(Article).filter(Article.id == article_id).first() is None
|
||||||
|
|
||||||
def test_delete_unknown_id_returns_404(self, client, session) -> None:
|
def test_delete_unknown_id_returns_404(self, client, session) -> None:
|
||||||
_make_user(session, "root", is_admin=True)
|
_make_user(session, "root", is_admin=True)
|
||||||
headers = _headers(session, "root")
|
response = client.delete(f"{BASE}/9999", headers=_headers(session, "root"))
|
||||||
response = client.delete(f"{BASE}/9999", headers=headers)
|
|
||||||
assert response.status_code == 404
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
class TestReferenceData:
|
||||||
|
def test_list_authors_ordered_by_name(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
zed = _make_author(session, name="Zed Last", email="zed@example.com")
|
||||||
|
amy = _make_author(session, name="Amy First", email="amy@example.com")
|
||||||
|
response = client.get("/api/v1/admin/authors", headers=_headers(session, "root"))
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.json()
|
||||||
|
assert [a["id"] for a in body] == [amy.id, zed.id]
|
||||||
|
assert body[0] == {
|
||||||
|
"id": amy.id, "name": "Amy First", "email": "amy@example.com", "bio": None
|
||||||
|
}
|
||||||
|
|
||||||
|
def test_list_authors_empty(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
response = client.get("/api/v1/admin/authors", headers=_headers(session, "root"))
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == []
|
||||||
|
|
||||||
|
def test_list_categories_ordered_by_name(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
world = _make_category(session, name="World", slug="world")
|
||||||
|
tech = _make_category(session, name="Technology", slug="technology")
|
||||||
|
response = client.get("/api/v1/admin/categories", headers=_headers(session, "root"))
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.json()
|
||||||
|
assert [c["id"] for c in body] == [tech.id, world.id]
|
||||||
|
assert body[0] == {"id": tech.id, "name": "Technology", "slug": "technology"}
|
||||||
|
|
||||||
|
def test_list_categories_empty(self, client, session) -> None:
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
response = client.get("/api/v1/admin/categories", headers=_headers(session, "root"))
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == []
|
||||||
|
|
||||||
|
|
||||||
class TestStartupMigration:
|
class TestStartupMigration:
|
||||||
"""Pre-M6 databases (users table without is_admin) get the column."""
|
"""Pre-M6 databases (users table without is_admin) get the column."""
|
||||||
|
|
||||||
@@ -456,7 +590,7 @@ class TestStartupMigration:
|
|||||||
|
|
||||||
|
|
||||||
class TestSeedAdminScript:
|
class TestSeedAdminScript:
|
||||||
def test_creates_admin_user(self, session, monkeypatch, tmp_path, capsys) -> None:
|
def test_creates_admin_user(self, session, monkeypatch, capsys) -> None:
|
||||||
import seed_admin
|
import seed_admin
|
||||||
|
|
||||||
monkeypatch.setenv("ADMIN_USERNAME", "root")
|
monkeypatch.setenv("ADMIN_USERNAME", "root")
|
||||||
@@ -517,3 +651,21 @@ class TestRateLimiting:
|
|||||||
finally:
|
finally:
|
||||||
admin_api._limiter.limit = 1000
|
admin_api._limiter.limit = 1000
|
||||||
admin_api._limiter._hits.clear()
|
admin_api._limiter._hits.clear()
|
||||||
|
|
||||||
|
def test_budget_is_per_admin(self, client, session, monkeypatch) -> None:
|
||||||
|
"""One admin exhausting the budget does not block another admin."""
|
||||||
|
_make_user(session, "root", is_admin=True)
|
||||||
|
_make_user(session, "other", is_admin=True)
|
||||||
|
admin_api._limiter._hits.clear()
|
||||||
|
monkeypatch.setattr(admin_api._limiter, "limit", 1)
|
||||||
|
monkeypatch.setattr(admin_api._limiter, "window_seconds", 60.0)
|
||||||
|
try:
|
||||||
|
root = _headers(session, "root")
|
||||||
|
other = _headers(session, "other")
|
||||||
|
assert client.get(BASE, headers=root).status_code == 200
|
||||||
|
assert client.get(BASE, headers=root).status_code == 429
|
||||||
|
# "other" still has its own budget.
|
||||||
|
assert client.get(BASE, headers=other).status_code == 200
|
||||||
|
finally:
|
||||||
|
admin_api._limiter.limit = 1000
|
||||||
|
admin_api._limiter._hits.clear()
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
"""Tests for the public article read API (``/api/v1/articles``).
|
||||||
|
|
||||||
|
These endpoints power the site front end. They require no authentication,
|
||||||
|
expose *published* articles only, and embed the related author/category so
|
||||||
|
the front page can render full details from a single payload.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
from models import Article, Author, Category
|
||||||
|
|
||||||
|
BASE = "/api/v1/articles"
|
||||||
|
|
||||||
|
|
||||||
|
def _make_author(session, name="Byline Writer", email="writer@example.com") -> Author:
|
||||||
|
author = Author(name=name, email=email)
|
||||||
|
session.add(author)
|
||||||
|
session.commit()
|
||||||
|
return author
|
||||||
|
|
||||||
|
|
||||||
|
def _make_category(session, name="Technology", slug="technology") -> Category:
|
||||||
|
category = Category(name=name, slug=slug)
|
||||||
|
session.add(category)
|
||||||
|
session.commit()
|
||||||
|
return category
|
||||||
|
|
||||||
|
|
||||||
|
def _make_article(
|
||||||
|
session,
|
||||||
|
title,
|
||||||
|
author,
|
||||||
|
category,
|
||||||
|
published=True,
|
||||||
|
created_at=None,
|
||||||
|
) -> Article:
|
||||||
|
article = Article(
|
||||||
|
title=title,
|
||||||
|
content=f"<p>Body for {title}</p>",
|
||||||
|
author_id=author.id,
|
||||||
|
category_id=category.id,
|
||||||
|
published=published,
|
||||||
|
created_at=created_at or datetime.now(timezone.utc),
|
||||||
|
)
|
||||||
|
session.add(article)
|
||||||
|
session.commit()
|
||||||
|
session.refresh(article)
|
||||||
|
return article
|
||||||
|
|
||||||
|
|
||||||
|
class TestListPublishedArticles:
|
||||||
|
def test_requires_no_authentication(self, client, session) -> None:
|
||||||
|
author = _make_author(session)
|
||||||
|
category = _make_category(session)
|
||||||
|
_make_article(session, "Public story", author, category)
|
||||||
|
response = client.get(BASE)
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
def test_returns_only_published_newest_first(self, client, session) -> None:
|
||||||
|
author = _make_author(session)
|
||||||
|
category = _make_category(session)
|
||||||
|
base = datetime(2025, 1, 1, tzinfo=timezone.utc)
|
||||||
|
old = _make_article(session, "Old published", author, category, created_at=base)
|
||||||
|
new = _make_article(
|
||||||
|
session, "New published", author, category, created_at=base + timedelta(days=2)
|
||||||
|
)
|
||||||
|
draft = _make_article(
|
||||||
|
session, "Still a draft", author, category, published=False,
|
||||||
|
created_at=base + timedelta(days=3),
|
||||||
|
)
|
||||||
|
response = client.get(BASE)
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.json()
|
||||||
|
assert [a["title"] for a in body] == ["New published", "Old published"]
|
||||||
|
assert all(a["published"] is True for a in body)
|
||||||
|
assert draft.id not in {a["id"] for a in body}
|
||||||
|
|
||||||
|
def test_entry_embeds_author_and_category(self, client, session) -> None:
|
||||||
|
author = _make_author(session, name="Amara Osei", email="amara@example.com")
|
||||||
|
category = _make_category(session, name="Culture", slug="culture")
|
||||||
|
article = _make_article(session, "Gallery nights", author, category)
|
||||||
|
body = client.get(BASE).json()
|
||||||
|
entry = body[0]
|
||||||
|
assert entry["id"] == article.id
|
||||||
|
assert entry["content"] == f"<p>Body for {article.title}</p>"
|
||||||
|
assert entry["author"] == {
|
||||||
|
"id": author.id, "name": "Amara Osei", "email": "amara@example.com", "bio": None
|
||||||
|
}
|
||||||
|
assert entry["category"] == {"id": category.id, "name": "Culture", "slug": "culture"}
|
||||||
|
|
||||||
|
def test_empty_when_nothing_published(self, client, session) -> None:
|
||||||
|
author = _make_author(session)
|
||||||
|
category = _make_category(session)
|
||||||
|
_make_article(session, "Only a draft", author, category, published=False)
|
||||||
|
assert client.get(BASE).json() == []
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetPublishedArticle:
|
||||||
|
def test_returns_published_article(self, client, session) -> None:
|
||||||
|
author = _make_author(session)
|
||||||
|
category = _make_category(session)
|
||||||
|
article = _make_article(session, "The one", author, category)
|
||||||
|
response = client.get(f"{BASE}/{article.id}")
|
||||||
|
assert response.status_code == 200
|
||||||
|
body = response.json()
|
||||||
|
assert body["id"] == article.id
|
||||||
|
assert body["title"] == "The one"
|
||||||
|
assert body["author"]["id"] == author.id
|
||||||
|
assert body["category"]["id"] == category.id
|
||||||
|
|
||||||
|
def test_draft_returns_404(self, client, session) -> None:
|
||||||
|
author = _make_author(session)
|
||||||
|
category = _make_category(session)
|
||||||
|
draft = _make_article(session, "Hidden", author, category, published=False)
|
||||||
|
response = client.get(f"{BASE}/{draft.id}")
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.json()["code"] == "not_found"
|
||||||
|
|
||||||
|
def test_unknown_id_returns_404(self, client, session) -> None:
|
||||||
|
response = client.get(f"{BASE}/9999")
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.json()["code"] == "not_found"
|
||||||
|
|
||||||
|
|
||||||
|
class TestSeedContentScript:
|
||||||
|
"""The seeder creates the demo authors/categories/articles, idempotently."""
|
||||||
|
|
||||||
|
def _run_seed(self, session, monkeypatch) -> str:
|
||||||
|
import seed_content
|
||||||
|
|
||||||
|
monkeypatch.setattr(seed_content, "SessionLocal", lambda: session)
|
||||||
|
assert seed_content.main() == 0
|
||||||
|
captured = __import__("io").StringIO()
|
||||||
|
return captured.getvalue()
|
||||||
|
|
||||||
|
def test_creates_demo_content(self, session, monkeypatch, capsys) -> None:
|
||||||
|
import seed_content
|
||||||
|
|
||||||
|
monkeypatch.setattr(seed_content, "SessionLocal", lambda: session)
|
||||||
|
assert seed_content.main() == 0
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
|
||||||
|
assert session.query(Author).count() == 3
|
||||||
|
assert session.query(Category).count() == 4
|
||||||
|
articles = session.query(Article).all()
|
||||||
|
assert len(articles) == 6
|
||||||
|
assert all(a.published is True for a in articles)
|
||||||
|
# The feed is newest-first and every article resolves its relations.
|
||||||
|
titles = [a.title for a in articles]
|
||||||
|
assert titles[0] == "Inside the new wave of open-source language models"
|
||||||
|
for article in articles:
|
||||||
|
assert article.author.name
|
||||||
|
assert article.category.slug
|
||||||
|
assert "Created author 'Ada Lovelace'" in out
|
||||||
|
assert "Done." in out
|
||||||
|
|
||||||
|
def test_is_idempotent(self, session, monkeypatch, capsys) -> None:
|
||||||
|
import seed_content
|
||||||
|
|
||||||
|
monkeypatch.setattr(seed_content, "SessionLocal", lambda: session)
|
||||||
|
assert seed_content.main() == 0
|
||||||
|
capsys.readouterr()
|
||||||
|
|
||||||
|
# Capture the id (plain int) — main() closes the shared session,
|
||||||
|
# detaching ORM instances.
|
||||||
|
first_article_id = session.query(Article).first().id
|
||||||
|
assert seed_content.main() == 0
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
|
||||||
|
# No duplicates on the second run; nothing was re-created.
|
||||||
|
assert session.query(Author).count() == 3
|
||||||
|
assert session.query(Category).count() == 4
|
||||||
|
assert session.query(Article).count() == 6
|
||||||
|
assert session.query(Article).first().id == first_article_id
|
||||||
|
assert "Created author" not in out
|
||||||
|
assert "Created article" not in out
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
|
||||||
from models import Article, Author, Category, Item, User, slugify
|
from models import Article, Author, Category, User, slugify
|
||||||
|
|
||||||
|
|
||||||
class TestAuthor:
|
class TestAuthor:
|
||||||
@@ -162,34 +162,3 @@ class TestArticle:
|
|||||||
with pytest.raises(IntegrityError):
|
with pytest.raises(IntegrityError):
|
||||||
session.commit()
|
session.commit()
|
||||||
session.rollback()
|
session.rollback()
|
||||||
|
|
||||||
|
|
||||||
class TestItem:
|
|
||||||
def test_create_and_commit_defaults(self, session) -> None:
|
|
||||||
item = Item(title="Breaking: things happen")
|
|
||||||
session.add(item)
|
|
||||||
session.commit()
|
|
||||||
session.refresh(item)
|
|
||||||
assert item.id is not None
|
|
||||||
assert item.url == ""
|
|
||||||
assert item.points == 0
|
|
||||||
assert item.username == "anonymous"
|
|
||||||
assert item.content == ""
|
|
||||||
assert item.created_at is not None
|
|
||||||
|
|
||||||
def test_create_with_all_fields(self, session) -> None:
|
|
||||||
item = Item(
|
|
||||||
title="Show HN: a new tool",
|
|
||||||
url="https://example.com/show-hn",
|
|
||||||
points=42,
|
|
||||||
username="alice",
|
|
||||||
content="<p>Hello <strong>world</strong></p>",
|
|
||||||
)
|
|
||||||
session.add(item)
|
|
||||||
session.commit()
|
|
||||||
session.refresh(item)
|
|
||||||
assert item.title == "Show HN: a new tool"
|
|
||||||
assert item.url == "https://example.com/show-hn"
|
|
||||||
assert item.points == 42
|
|
||||||
assert item.username == "alice"
|
|
||||||
assert item.content == "<p>Hello <strong>world</strong></p>"
|
|
||||||
@@ -1,421 +1,547 @@
|
|||||||
import { expect, test, type Page } from '@playwright/test';
|
import { expect, test } from '@playwright/test';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* E2E tests for the admin area (M6) with a fully mocked backend
|
* E2E tests for the admin area (M6). The Vite dev-server proxy is
|
||||||
* (in-memory item store + token-based auth), following the approach of
|
* intercepted with page.route, so these tests run without a backend.
|
||||||
* the other specs in this directory.
|
*
|
||||||
|
* The admin area manages the article domain:
|
||||||
|
* - list/search/sort/paginate articles (GET /api/v1/admin/articles)
|
||||||
|
* - create articles (POST /api/v1/admin/articles) with a Lexical editor
|
||||||
|
* - edit articles (PUT /api/v1/admin/articles/:id)
|
||||||
|
* - delete articles (DELETE /api/v1/admin/articles/:id)
|
||||||
|
* - reference data: GET /api/v1/admin/authors, /api/v1/admin/categories
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const ADMIN_TOKEN = 'mock-admin-token';
|
type WireAuthor = { id: number; name: string; email: string; bio: string | null };
|
||||||
const USER_TOKEN = 'mock-user-token';
|
type WireCategory = { id: number; name: string; slug: string };
|
||||||
const TOKEN_KEY = 'AUTH_TOKEN';
|
type WireArticle = {
|
||||||
|
|
||||||
interface Item {
|
|
||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
url: string;
|
|
||||||
points: number;
|
|
||||||
username: string;
|
|
||||||
content: string;
|
content: string;
|
||||||
|
author_id: number;
|
||||||
|
category_id: number;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
}
|
published: boolean;
|
||||||
|
author: WireAuthor;
|
||||||
|
category: WireCategory;
|
||||||
|
};
|
||||||
|
|
||||||
const envelope = (detail: string, code: string) => JSON.stringify({ detail, code });
|
const AUTHORS: WireAuthor[] = [
|
||||||
|
{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com', bio: null },
|
||||||
|
{ id: 2, name: 'Grace Hopper', email: 'grace@example.com', bio: null },
|
||||||
|
{ id: 3, name: 'Alan Turing', email: 'alan@example.com', bio: null },
|
||||||
|
];
|
||||||
|
const CATEGORIES: WireCategory[] = [
|
||||||
|
{ id: 1, name: 'Technology', slug: 'technology' },
|
||||||
|
{ id: 2, name: 'Science', slug: 'science' },
|
||||||
|
{ id: 3, name: 'Sports', slug: 'sports' },
|
||||||
|
{ id: 4, name: 'Culture', slug: 'culture' },
|
||||||
|
];
|
||||||
|
|
||||||
/** Build the auth + admin API mock with a per-test item store. */
|
function seedArticles(): WireArticle[] {
|
||||||
function mockAdminApi(page: Page): { store: Item[]; nextId: () => number } {
|
return [
|
||||||
let idCounter = 100;
|
|
||||||
const store: Item[] = [
|
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
title: 'Breaking: local cat discovers keyboard',
|
title: 'Fusion milestone: net energy gain repeated',
|
||||||
url: 'https://example.com/cat-keyboard',
|
content:
|
||||||
points: 42,
|
'<p>Scientists again drew net energy from the reactor, marking the third repeat of the landmark result.</p>',
|
||||||
username: 'alice',
|
author_id: 2,
|
||||||
content: '<p>Amazing news.</p>',
|
category_id: 2,
|
||||||
created_at: '2024-05-01T10:00:00Z',
|
created_at: '2024-05-03T11:30:00Z',
|
||||||
|
published: true,
|
||||||
|
author: AUTHORS[1],
|
||||||
|
category: CATEGORIES[1],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 2,
|
id: 2,
|
||||||
title: 'Study: coffee improves code reviews',
|
title: 'City marathon sets record turnout',
|
||||||
url: 'https://example.com/coffee-reviews',
|
content:
|
||||||
points: 17,
|
'<p>First-timers flooded the course on Sunday as organizers beat last year\u2019s turnout.</p>',
|
||||||
username: 'bob',
|
author_id: 3,
|
||||||
content: '<p>Peer-reviewed.</p>',
|
category_id: 3,
|
||||||
created_at: '2024-05-02T11:30:00Z',
|
created_at: '2024-05-02T09:15:00Z',
|
||||||
|
published: false,
|
||||||
|
author: AUTHORS[2],
|
||||||
|
category: CATEGORIES[2],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 3,
|
id: 3,
|
||||||
title: 'Show HN: I built a tiny news app',
|
title: 'Inside the new wave of open-source language models',
|
||||||
url: 'https://example.com/show-hn-newz',
|
content:
|
||||||
points: 5,
|
'<p>Open-weight language models are reshaping who can build and deploy AI.</p>',
|
||||||
username: 'alice',
|
author_id: 1,
|
||||||
content: '<p>Feedback welcome.</p>',
|
category_id: 1,
|
||||||
created_at: '2024-05-03T09:15:00Z',
|
created_at: '2024-05-01T10:00:00Z',
|
||||||
|
published: true,
|
||||||
|
author: AUTHORS[0],
|
||||||
|
category: CATEGORIES[0],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
}
|
||||||
|
|
||||||
const requireAdmin = (route: Parameters<Parameters<Page['route']>[1]>[0]): boolean => {
|
async function mockAdminApi(
|
||||||
const header = route.request().headers()['authorization'];
|
page: import('@playwright/test').Page,
|
||||||
if (header !== `Bearer ${ADMIN_TOKEN}`) {
|
opts: { admin?: boolean; token?: string; signedOut?: boolean } = {},
|
||||||
route.fulfill({
|
) {
|
||||||
status: 403,
|
const store = seedArticles();
|
||||||
|
const nextId = { value: 100 };
|
||||||
|
const token = opts.token ?? (opts.admin === false ? 'user-token' : 'admin-token');
|
||||||
|
|
||||||
|
await page.route('**/api/v1/auth/me', async (route) => {
|
||||||
|
if (opts.signedOut) {
|
||||||
|
return route.fulfill({
|
||||||
|
status: 401,
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
body: envelope('Admin access required', 'forbidden'),
|
body: JSON.stringify({ detail: 'Not authenticated', code: 'unauthorized' }),
|
||||||
});
|
});
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
return true;
|
if (opts.admin === false) {
|
||||||
};
|
|
||||||
|
|
||||||
page.route('**/api/v1/auth/me', (route) => {
|
|
||||||
const header = route.request().headers()['authorization'];
|
|
||||||
if (header === `Bearer ${ADMIN_TOKEN}`) {
|
|
||||||
return route.fulfill({
|
return route.fulfill({
|
||||||
status: 200,
|
status: 200,
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
body: JSON.stringify({ username: 'alice', is_admin: true }),
|
body: JSON.stringify({ id: 2, username: 'user', is_admin: false }),
|
||||||
});
|
|
||||||
}
|
|
||||||
if (header === `Bearer ${USER_TOKEN}`) {
|
|
||||||
return route.fulfill({
|
|
||||||
status: 200,
|
|
||||||
contentType: 'application/json',
|
|
||||||
body: JSON.stringify({ username: 'bob', is_admin: false }),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return route.fulfill({
|
return route.fulfill({
|
||||||
status: 401,
|
status: 200,
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
body: envelope('Invalid or expired token', 'unauthorized'),
|
body: JSON.stringify({ id: 1, username: 'admin', is_admin: true }),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 }));
|
|
||||||
|
|
||||||
// Collection endpoint: GET (list) + POST (create).
|
await page.route('**/api/v1/auth/logout', async (route) =>
|
||||||
page.route(/\/api\/v1\/admin\/items(\?.*)?$/, (route) => {
|
route.fulfill({
|
||||||
const request = route.request();
|
status: 204,
|
||||||
if (request.method() === 'GET') {
|
contentType: 'application/json',
|
||||||
if (!requireAdmin(route)) return;
|
body: JSON.stringify({}),
|
||||||
const url = new URL(request.url());
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await page.route('**/api/v1/admin/authors', async (route) => {
|
||||||
|
if (opts.admin === false) {
|
||||||
|
return route.fulfill({
|
||||||
|
status: 403,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ detail: 'Admin access required', code: 'forbidden' }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify(AUTHORS),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.route('**/api/v1/admin/categories', async (route) => {
|
||||||
|
if (opts.admin === false) {
|
||||||
|
return route.fulfill({
|
||||||
|
status: 403,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ detail: 'Admin access required', code: 'forbidden' }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify(CATEGORIES),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.route('**/api/v1/admin/articles**', async (route) => {
|
||||||
|
const url = new URL(route.request().url());
|
||||||
|
const idMatch = url.pathname.match(/\/api\/v1\/admin\/articles\/(\d+)/);
|
||||||
|
|
||||||
|
if (idMatch) {
|
||||||
|
const id = Number(idMatch[1]);
|
||||||
|
const article = store.find((a) => a.id === id);
|
||||||
|
const method = route.request().method();
|
||||||
|
if (method === 'GET') {
|
||||||
|
if (!article) {
|
||||||
|
return route.fulfill({
|
||||||
|
status: 404,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify(article),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (method === 'PUT') {
|
||||||
|
if (!article) {
|
||||||
|
return route.fulfill({
|
||||||
|
status: 404,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const body = JSON.parse(route.request().postData() ?? '{}') as {
|
||||||
|
title: string;
|
||||||
|
content: string;
|
||||||
|
author_id: number;
|
||||||
|
category_id: number;
|
||||||
|
published: boolean;
|
||||||
|
};
|
||||||
|
Object.assign(article, {
|
||||||
|
title: body.title,
|
||||||
|
content: body.content,
|
||||||
|
author_id: body.author_id,
|
||||||
|
category_id: body.category_id,
|
||||||
|
published: body.published,
|
||||||
|
});
|
||||||
|
return route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify(article),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (method === 'DELETE') {
|
||||||
|
if (!article) {
|
||||||
|
return route.fulfill({
|
||||||
|
status: 404,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ detail: 'Article not found', code: 'not_found' }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const index = store.indexOf(article);
|
||||||
|
if (index >= 0) store.splice(index, 1);
|
||||||
|
return route.fulfill({ status: 204, body: '' });
|
||||||
|
}
|
||||||
|
return route.fulfill({
|
||||||
|
status: 405,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ detail: 'Method not allowed', code: 'method_not_allowed' }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const method = route.request().method();
|
||||||
|
if (method === 'GET') {
|
||||||
const search = (url.searchParams.get('search') ?? '').toLowerCase();
|
const search = (url.searchParams.get('search') ?? '').toLowerCase();
|
||||||
const sortBy = (url.searchParams.get('sort_by') ?? 'created_at') as keyof Item;
|
const sortBy = url.searchParams.get('sort_by') ?? 'created_at';
|
||||||
const sortOrder = url.searchParams.get('sort_order') ?? 'desc';
|
const sortOrder = url.searchParams.get('sort_order') ?? 'desc';
|
||||||
const pageSize = Number(url.searchParams.get('page_size') ?? 20);
|
const page = Number(url.searchParams.get('page') ?? '1');
|
||||||
const page_ = Number(url.searchParams.get('page') ?? 1);
|
const pageSize = Number(url.searchParams.get('page_size') ?? '20');
|
||||||
|
|
||||||
const filtered = store.filter(
|
const filtered = store.filter(
|
||||||
(item) =>
|
(a) => !search || a.title.toLowerCase().includes(search) || a.content.toLowerCase().includes(search),
|
||||||
!search ||
|
|
||||||
item.title.toLowerCase().includes(search) ||
|
|
||||||
item.url.toLowerCase().includes(search),
|
|
||||||
);
|
);
|
||||||
|
const direction = sortOrder === 'asc' ? 1 : -1;
|
||||||
filtered.sort((a, b) => {
|
filtered.sort((a, b) => {
|
||||||
const cmp = String(a[sortBy]).localeCompare(String(b[sortBy]));
|
if (sortBy === 'title') {
|
||||||
return sortOrder === 'asc' ? cmp : -cmp;
|
return a.title.localeCompare(b.title) * direction;
|
||||||
|
}
|
||||||
|
return a.created_at.localeCompare(b.created_at) * direction;
|
||||||
});
|
});
|
||||||
const start = (page_ - 1) * pageSize;
|
const start = (page - 1) * pageSize;
|
||||||
const slice = filtered.slice(start, start + pageSize);
|
const slice = filtered.slice(start, start + pageSize);
|
||||||
|
|
||||||
return route.fulfill({
|
return route.fulfill({
|
||||||
status: 200,
|
status: 200,
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
items: slice,
|
articles: slice,
|
||||||
total: filtered.length,
|
total: filtered.length,
|
||||||
page: page_,
|
page,
|
||||||
page_size: pageSize,
|
page_size: pageSize,
|
||||||
total_pages: Math.ceil(filtered.length / pageSize) || 0,
|
total_pages: Math.max(1, Math.ceil(filtered.length / pageSize)),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (request.method() === 'POST') {
|
|
||||||
if (!requireAdmin(route)) return;
|
if (method === 'POST') {
|
||||||
const body = request.postDataJSON() as Partial<Item>;
|
const body = JSON.parse(route.request().postData() ?? '{}') as {
|
||||||
const item: Item = {
|
title: string;
|
||||||
id: ++idCounter,
|
content: string;
|
||||||
title: body.title ?? '',
|
author_id: number;
|
||||||
url: body.url ?? '',
|
category_id: number;
|
||||||
points: body.points ?? 0,
|
published: boolean;
|
||||||
username: body.username ?? 'alice',
|
|
||||||
content: body.content ?? '',
|
|
||||||
created_at: new Date().toISOString(),
|
|
||||||
};
|
};
|
||||||
store.push(item);
|
const article: WireArticle = {
|
||||||
|
id: nextId.value++,
|
||||||
|
title: body.title,
|
||||||
|
content: body.content,
|
||||||
|
author_id: body.author_id,
|
||||||
|
category_id: body.category_id,
|
||||||
|
created_at: new Date().toISOString(),
|
||||||
|
published: body.published,
|
||||||
|
author: AUTHORS.find((a) => a.id === body.author_id) ?? AUTHORS[0],
|
||||||
|
category: CATEGORIES.find((c) => c.id === body.category_id) ?? CATEGORIES[0],
|
||||||
|
};
|
||||||
|
store.push(article);
|
||||||
return route.fulfill({
|
return route.fulfill({
|
||||||
status: 201,
|
status: 201,
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
body: JSON.stringify(item),
|
body: JSON.stringify(article),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') });
|
|
||||||
|
return route.fulfill({
|
||||||
|
status: 405,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ detail: 'Method not allowed', code: 'method_not_allowed' }),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Item endpoint: GET / PUT / DELETE by id.
|
return {
|
||||||
page.route('**/api/v1/admin/items/*', (route) => {
|
store,
|
||||||
const request = route.request();
|
token,
|
||||||
const id = Number(request.url().split('/').pop());
|
count: () => store.length,
|
||||||
if (!requireAdmin(route)) return;
|
all: () => store.map((a) => a.id).sort((a, b) => a - b),
|
||||||
const item = store.find((entry) => entry.id === id);
|
byId: (id: number) => store.find((a) => a.id === id),
|
||||||
|
};
|
||||||
if (request.method() === 'GET') {
|
|
||||||
if (!item) {
|
|
||||||
return route.fulfill({
|
|
||||||
status: 404,
|
|
||||||
contentType: 'application/json',
|
|
||||||
body: envelope('Item not found', 'not_found'),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) });
|
|
||||||
}
|
|
||||||
if (request.method() === 'PUT') {
|
|
||||||
if (!item) {
|
|
||||||
return route.fulfill({
|
|
||||||
status: 404,
|
|
||||||
contentType: 'application/json',
|
|
||||||
body: envelope('Item not found', 'not_found'),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const body = request.postDataJSON() as Partial<Item>;
|
|
||||||
Object.assign(item, body);
|
|
||||||
return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(item) });
|
|
||||||
}
|
|
||||||
if (request.method() === 'DELETE') {
|
|
||||||
if (!item) {
|
|
||||||
return route.fulfill({
|
|
||||||
status: 404,
|
|
||||||
contentType: 'application/json',
|
|
||||||
body: envelope('Item not found', 'not_found'),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
store.splice(store.indexOf(item), 1);
|
|
||||||
return route.fulfill({ status: 204 });
|
|
||||||
}
|
|
||||||
return route.fulfill({ status: 405, contentType: 'application/json', body: envelope('Method not allowed', 'method_not_allowed') });
|
|
||||||
});
|
|
||||||
|
|
||||||
return { store, nextId: () => idCounter };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function seedToken(page: Page, token: string | null): Promise<void> {
|
test.describe('Admin area (E2E)', () => {
|
||||||
if (token === null) {
|
test('redirects signed-out users to /login', async ({ page }) => {
|
||||||
await page.addInitScript((key) => localStorage.removeItem(key), TOKEN_KEY);
|
await mockAdminApi(page, { signedOut: true });
|
||||||
} else {
|
// No token in storage: RequireAuth redirects to /login (the intended
|
||||||
await page.addInitScript(
|
// path is remembered in router state, not a query parameter).
|
||||||
([key, value]) => localStorage.setItem(key, value),
|
|
||||||
[TOKEN_KEY, token] as const,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
test.describe('admin area (M6)', () => {
|
|
||||||
test('signed-out users are redirected to /login', async ({ page }) => {
|
|
||||||
mockAdminApi(page);
|
|
||||||
await seedToken(page, null);
|
|
||||||
|
|
||||||
await page.goto('/admin');
|
await page.goto('/admin');
|
||||||
|
|
||||||
await expect(page).toHaveURL('/login');
|
await expect(page).toHaveURL('/login');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('non-admins see the 403 page', async ({ page }) => {
|
test('redirects non-admin users away with a 403 message', async ({ page }) => {
|
||||||
mockAdminApi(page);
|
const { token } = await mockAdminApi(page, { admin: false, token: 'user-token' });
|
||||||
await seedToken(page, USER_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
token,
|
||||||
|
);
|
||||||
await page.goto('/admin');
|
await page.goto('/admin');
|
||||||
|
// RequireAdmin shows the 403 page in place (no redirect).
|
||||||
await expect(page.getByRole('heading', { level: 1, name: '403' })).toBeVisible();
|
await expect(page.getByRole('heading', { level: 1, name: '403' })).toBeVisible();
|
||||||
await expect(
|
await expect(
|
||||||
page.getByTestId('forbidden-page').getByText(/admin area/i),
|
page.getByText(/does not have access to the admin area/i),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
|
await expect(page).toHaveURL('/admin');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('admins see the dashboard with all items and an Admin header link', async ({
|
test('renders the admin dashboard with all articles and the Admin header link', async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
mockAdminApi(page);
|
const { token, count } = await mockAdminApi(page, { admin: true });
|
||||||
await seedToken(page, ADMIN_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
// The header exposes the admin link for admin accounts.
|
token,
|
||||||
await page.goto('/');
|
);
|
||||||
await expect(page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i })).toBeVisible();
|
|
||||||
|
|
||||||
await page.goto('/admin');
|
await page.goto('/admin');
|
||||||
|
|
||||||
await expect(page.getByRole('heading', { level: 1, name: 'Items' })).toBeVisible();
|
// Dashboard heading + rows.
|
||||||
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
|
await expect(page.getByRole('heading', { level: 1, name: 'Articles' })).toBeVisible();
|
||||||
await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible();
|
await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible();
|
||||||
await expect(page.getByText('Show HN: I built a tiny news app')).toBeVisible();
|
await expect(page.getByText('City marathon sets record turnout')).toBeVisible();
|
||||||
|
await expect(page.getByText('Inside the new wave of open-source language models')).toBeVisible();
|
||||||
|
// Author and category columns.
|
||||||
|
await expect(page.getByText('Grace Hopper')).toBeVisible();
|
||||||
|
await expect(page.getByText('Technology')).toBeVisible();
|
||||||
|
// Pagination summary.
|
||||||
await expect(page.getByText('Showing 1–3 of 3')).toBeVisible();
|
await expect(page.getByText('Showing 1–3 of 3')).toBeVisible();
|
||||||
|
// The admin shell shows the signed-in admin and a link back to the public site.
|
||||||
|
await expect(page.getByText('Signed in as')).toBeVisible();
|
||||||
|
await expect(page.getByRole('link', { name: /back to newzy/i })).toBeVisible();
|
||||||
|
expect(count()).toBe(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('non-admin accounts do not get the Admin header link', async ({ page }) => {
|
test('hides the Admin header link for non-admins', async ({ page }) => {
|
||||||
mockAdminApi(page);
|
const { token } = await mockAdminApi(page, { admin: false, token: 'user-token' });
|
||||||
await seedToken(page, USER_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
token,
|
||||||
|
);
|
||||||
await page.goto('/');
|
await page.goto('/');
|
||||||
|
await page.waitForTimeout(200);
|
||||||
await expect(
|
await expect(page.getByRole('link', { name: /^admin$/i })).toHaveCount(0);
|
||||||
page.getByRole('navigation', { name: 'Main navigation' }).getByRole('link', { name: /admin/i }),
|
|
||||||
).toHaveCount(0);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('search filters the list by title or URL', async ({ page }) => {
|
test('search filters articles by title or content', async ({ page }) => {
|
||||||
mockAdminApi(page);
|
const { token } = await mockAdminApi(page, { admin: true });
|
||||||
await seedToken(page, ADMIN_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
token,
|
||||||
|
);
|
||||||
await page.goto('/admin');
|
await page.goto('/admin');
|
||||||
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
|
await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible();
|
||||||
|
|
||||||
await page.getByLabel('Search items').fill('coffee');
|
// Title match.
|
||||||
await expect(page.getByText('Study: coffee improves code reviews')).toBeVisible();
|
const search = page.getByLabel('Search articles');
|
||||||
await expect(
|
await search.fill('fusion');
|
||||||
page.getByText('Breaking: local cat discovers keyboard'),
|
await expect(page.getByText('Fusion milestone: net energy gain repeated')).toBeVisible();
|
||||||
).toHaveCount(0);
|
await expect(page.getByText('City marathon sets record turnout')).toHaveCount(0);
|
||||||
|
await expect(page.getByText('Inside the new wave of open-source language models')).toHaveCount(0);
|
||||||
// URL search (case-insensitive on the server side).
|
|
||||||
await page.getByLabel('Search items').fill('EXAMPLE.COM/CAT');
|
|
||||||
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
|
|
||||||
await expect(page.getByText('Showing 1–1 of 1')).toBeVisible();
|
await expect(page.getByText('Showing 1–1 of 1')).toBeVisible();
|
||||||
|
|
||||||
|
// Content match.
|
||||||
|
await search.fill('course');
|
||||||
|
await expect(page.getByText('City marathon sets record turnout')).toBeVisible();
|
||||||
|
await expect(page.getByText('Fusion milestone: net energy gain repeated')).toHaveCount(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('sorting by title toggles direction', async ({ page }) => {
|
test('sorts by title in both directions', async ({ page }) => {
|
||||||
mockAdminApi(page);
|
const { token } = await mockAdminApi(page, { admin: true });
|
||||||
await seedToken(page, ADMIN_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
token,
|
||||||
|
);
|
||||||
await page.goto('/admin');
|
await page.goto('/admin');
|
||||||
const firstTitle = page.locator('tbody tr').first().locator('td').first().locator('span, a').first();
|
|
||||||
|
|
||||||
// Default: created_at desc -> newest first.
|
const firstCell = () => page.locator('tbody tr').first().locator('td').first();
|
||||||
await expect(firstTitle).toHaveText('Show HN: I built a tiny news app');
|
const titleButton = page.getByRole('button', { name: /sort by title/i });
|
||||||
|
|
||||||
await page.getByRole('button', { name: /sort by title/i }).click();
|
// Default ordering is newest first (created_at desc).
|
||||||
await expect(firstTitle).toHaveText('Breaking: local cat discovers keyboard');
|
await expect(firstCell()).toContainText('Fusion milestone: net energy gain repeated');
|
||||||
|
|
||||||
await page.getByRole('button', { name: /sort by title/i }).click();
|
// Click title → ascending: City… is first.
|
||||||
await expect(firstTitle).toHaveText('Study: coffee improves code reviews');
|
await titleButton.click();
|
||||||
|
await expect(firstCell()).toContainText('City marathon sets record turnout');
|
||||||
|
|
||||||
|
// Click again → descending: Inside… is first.
|
||||||
|
await titleButton.click();
|
||||||
|
await expect(firstCell()).toContainText('Inside the new wave of open-source language models');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('create: fills the form, saves with the Lexical editor and lists the item', async ({
|
test('creates an article with the Lexical editor and navigates back', async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
const { store } = mockAdminApi(page);
|
const { token, byId, all } = await mockAdminApi(page, { admin: true });
|
||||||
await seedToken(page, ADMIN_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
token,
|
||||||
|
);
|
||||||
|
await page.goto('/admin/articles/new');
|
||||||
|
|
||||||
await page.goto('/admin/items/new');
|
await expect(
|
||||||
await expect(page.getByRole('heading', { level: 1, name: 'New item' })).toBeVisible();
|
page.getByRole('heading', { level: 1, name: 'New article' }),
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
await page.getByLabel(/^Title/).fill('E2E: fresh story from the admin area');
|
await page.getByLabel(/^Title/).fill('E2E: fresh story from the admin area');
|
||||||
await page.getByLabel(/^URL/).fill('https://example.com/e2e-story');
|
await page.getByLabel(/^Author/).selectOption('2');
|
||||||
await page.getByLabel('Points').fill('3');
|
await page.getByLabel(/^Category/).selectOption('4');
|
||||||
// The author is pre-filled from the session.
|
await page.getByLabel(/^Published/).check();
|
||||||
await expect(page.getByLabel('Author')).toHaveValue('alice');
|
const editable = page.getByLabel('Article content');
|
||||||
|
await editable.click();
|
||||||
// Type into the Lexical contenteditable (rich text editor).
|
|
||||||
await page.getByLabel('Item content').click();
|
|
||||||
await page.keyboard.type('Written with the Lexical editor.');
|
await page.keyboard.type('Written with the Lexical editor.');
|
||||||
|
await page.getByRole('button', { name: /create article/i }).click();
|
||||||
|
|
||||||
await page.getByRole('button', { name: /create item/i }).click();
|
await page.waitForURL('/admin');
|
||||||
|
await expect(page.getByRole('status')).toContainText('was saved');
|
||||||
|
// Exact match: the success notice also quotes the title.
|
||||||
|
await expect(
|
||||||
|
page.getByText('E2E: fresh story from the admin area', { exact: true }),
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
// Back on the dashboard with the success notice.
|
const created = byId(Math.max(...all()));
|
||||||
await expect(page).toHaveURL('/admin');
|
expect(created?.title).toBe('E2E: fresh story from the admin area');
|
||||||
await expect(page.getByRole('status')).toHaveText(/was saved/i);
|
expect(created?.author_id).toBe(2);
|
||||||
await expect(page.getByText('E2E: fresh story from the admin area', { exact: true })).toBeVisible();
|
expect(created?.category_id).toBe(4);
|
||||||
|
expect(created?.published).toBe(true);
|
||||||
// The backend received the rich content.
|
|
||||||
const created = store.find((item) =>
|
|
||||||
item.title.includes('E2E: fresh story'),
|
|
||||||
);
|
|
||||||
expect(created).toBeTruthy();
|
|
||||||
expect(created?.content).toContain('Written with the Lexical editor.');
|
expect(created?.content).toContain('Written with the Lexical editor.');
|
||||||
expect(created?.points).toBe(3);
|
|
||||||
expect(created?.username).toBe('alice');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('edit: loads the item, updates fields and saves', async ({ page }) => {
|
test('edits an article and persists the changes', async ({ page }) => {
|
||||||
const { store } = mockAdminApi(page);
|
const { token, byId } = await mockAdminApi(page, { admin: true });
|
||||||
await seedToken(page, ADMIN_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
token,
|
||||||
|
);
|
||||||
await page.goto('/admin');
|
await page.goto('/admin');
|
||||||
await page.locator('tbody tr', { hasText: 'Breaking: local cat' }).getByRole('link', { name: /edit/i }).click();
|
|
||||||
|
|
||||||
await expect(page.getByRole('heading', { level: 1, name: /edit item/i })).toBeVisible();
|
await page
|
||||||
await expect(page.getByLabel(/^Title/)).toHaveValue('Breaking: local cat discovers keyboard');
|
.getByRole('row', { name: /Fusion milestone: net energy gain repeated/ })
|
||||||
await expect(page.getByLabel('Points')).toHaveValue('42');
|
.getByRole('link', { name: /edit/i })
|
||||||
// The stored body loads into the WYSIWYG editor.
|
.click();
|
||||||
await expect(page.getByLabel('Item content')).toContainText('Amazing news.');
|
|
||||||
|
|
||||||
await page.getByLabel(/^Title/).fill('Breaking: local cat becomes famous');
|
await expect(page).toHaveURL(/\/admin\/articles\/1\/edit$/);
|
||||||
|
await expect(
|
||||||
|
page.getByRole('heading', { level: 1, name: /edit article/i }),
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
|
const titleInput = page.getByLabel(/^Title/);
|
||||||
|
await expect(titleInput).toHaveValue('Fusion milestone: net energy gain repeated');
|
||||||
|
const editable = page.getByLabel('Article content');
|
||||||
|
await expect(editable).toContainText('Scientists again drew net energy');
|
||||||
|
|
||||||
|
await titleInput.fill('Fusion milestone: record energy gain');
|
||||||
await page.getByRole('button', { name: /save changes/i }).click();
|
await page.getByRole('button', { name: /save changes/i }).click();
|
||||||
|
|
||||||
await expect(page).toHaveURL('/admin');
|
await page.waitForURL('/admin');
|
||||||
await expect(page.getByRole('status')).toHaveText(/was saved/i);
|
await expect(page.getByRole('status')).toContainText('was saved');
|
||||||
await expect(page.getByRole('cell', { name: 'Breaking: local cat becomes famous', exact: true })).toBeVisible();
|
// Exact match: the success notice also quotes the title.
|
||||||
|
await expect(
|
||||||
|
page.getByText('Fusion milestone: record energy gain', { exact: true }),
|
||||||
|
).toBeVisible();
|
||||||
|
|
||||||
const updated = store.find((item) => item.id === 1);
|
expect(byId(1)?.title).toBe('Fusion milestone: record energy gain');
|
||||||
expect(updated?.title).toBe('Breaking: local cat becomes famous');
|
expect(byId(1)?.published).toBe(true);
|
||||||
// Untouched fields survive the partial save.
|
expect(byId(1)?.author_id).toBe(2);
|
||||||
expect(updated?.points).toBe(42);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('delete: requires confirmation, then removes the item', async ({ page }) => {
|
test('deletes an article only after explicit confirmation', async ({ page }) => {
|
||||||
const { store } = mockAdminApi(page);
|
const { token, count, all } = await mockAdminApi(page, { admin: true });
|
||||||
await seedToken(page, ADMIN_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
token,
|
||||||
|
);
|
||||||
await page.goto('/admin');
|
await page.goto('/admin');
|
||||||
const target = page.getByText('Study: coffee improves code reviews');
|
|
||||||
await expect(target).toBeVisible();
|
|
||||||
|
|
||||||
// Open the confirmation dialog (first row's delete button).
|
const targetRow = page.getByRole('row', {
|
||||||
page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click();
|
name: /City marathon sets record turnout/,
|
||||||
|
});
|
||||||
|
await targetRow.getByRole('button', { name: /delete/i }).click();
|
||||||
|
|
||||||
const dialog = page.getByRole('dialog');
|
const dialog = page.getByRole('dialog');
|
||||||
await expect(dialog).toBeVisible();
|
|
||||||
await expect(
|
await expect(
|
||||||
dialog.getByRole('heading', { name: /are you sure you want to delete/i }),
|
dialog.getByRole('heading', { name: /are you sure you want to delete/i }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
await expect(dialog.getByText(/cannot be undone/i)).toBeVisible();
|
await expect(dialog).toContainText('City marathon sets record turnout');
|
||||||
|
await expect(dialog).toContainText(/cannot be undone/i);
|
||||||
|
|
||||||
// Cancel keeps the item.
|
// Cancel: nothing is deleted.
|
||||||
await dialog.getByRole('button', { name: /cancel/i }).click();
|
await dialog.getByRole('button', { name: /cancel/i }).click();
|
||||||
await expect(dialog).toHaveCount(0);
|
await expect(dialog).toHaveCount(0);
|
||||||
await expect(target).toBeVisible();
|
expect(count()).toBe(3);
|
||||||
expect(store).toHaveLength(3);
|
expect(all()).toEqual([1, 2, 3]);
|
||||||
|
|
||||||
// Confirm with the explicit "Yes, delete" action.
|
// Confirm: the article is removed.
|
||||||
page.locator('tbody tr', { hasText: 'Study: coffee' }).getByRole('button', { name: /delete/i }).click();
|
await targetRow.getByRole('button', { name: /delete/i }).click();
|
||||||
await expect(page.getByRole('dialog')).toBeVisible();
|
await expect(page.getByRole('dialog')).toBeVisible();
|
||||||
await page.getByRole('button', { name: /yes, delete/i }).click();
|
await page.getByRole('button', { name: /yes, delete/i }).click();
|
||||||
|
|
||||||
await expect(page.getByText('Breaking: local cat discovers keyboard')).toBeVisible();
|
await expect(page.getByRole('status')).toContainText('was deleted');
|
||||||
await expect(page.getByRole('cell', { name: 'Study: coffee improves code reviews', exact: true })).toHaveCount(0);
|
// The row is gone (the success notice still quotes the title).
|
||||||
await expect(page.getByRole('status')).toHaveText(/was deleted/i);
|
await expect(
|
||||||
expect(store).toHaveLength(2);
|
page.getByRole('row', { name: /City marathon sets record turnout/ }),
|
||||||
|
).toHaveCount(0);
|
||||||
|
expect(count()).toBe(2);
|
||||||
|
expect(all()).toEqual([1, 3]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('pagination: next/previous and the page size selector work', async ({ page }) => {
|
test('pagination controls stay disabled with a single page', async ({
|
||||||
mockAdminApi(page);
|
|
||||||
await seedToken(page, ADMIN_TOKEN);
|
|
||||||
|
|
||||||
await page.goto('/admin');
|
|
||||||
|
|
||||||
// 3 seeded items fit on one page: navigation is disabled.
|
|
||||||
await expect(page.getByRole('button', { name: /next/i })).toBeDisabled();
|
|
||||||
await expect(page.getByRole('button', { name: /previous/i })).toBeDisabled();
|
|
||||||
|
|
||||||
// Smaller page size splits the list across pages.
|
|
||||||
await page.getByLabel('Rows per page').selectOption('10');
|
|
||||||
await expect(page).toHaveURL(/\/admin/);
|
|
||||||
// (Still one page for 3 items — assert the selector round-trips.)
|
|
||||||
await expect(page.getByLabel('Rows per page')).toHaveValue('10');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('editor sanitizes hostile stored HTML (no scripts or handlers survive)', async ({
|
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
const { store } = mockAdminApi(page);
|
const { token } = await mockAdminApi(page, { admin: true });
|
||||||
await seedToken(page, ADMIN_TOKEN);
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
token,
|
||||||
|
);
|
||||||
|
await page.goto('/admin');
|
||||||
|
await expect(page.getByText('Showing 1–3 of 3')).toBeVisible();
|
||||||
|
|
||||||
// Simulate a hostile item body persisted by the backend.
|
await expect(page.getByRole('button', { name: /previous/i })).toBeDisabled();
|
||||||
store[0].content = [
|
await expect(page.getByRole('button', { name: /next/i })).toBeDisabled();
|
||||||
|
|
||||||
|
// The page size control round-trips without moving pages.
|
||||||
|
const perPage = page.getByLabel('Rows per page');
|
||||||
|
await perPage.selectOption('50');
|
||||||
|
await perPage.selectOption('20');
|
||||||
|
await expect(page.getByText('Showing 1–3 of 3')).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('editor sanitizes hostile HTML from stored content', async ({ page }) => {
|
||||||
|
const mock = await mockAdminApi(page, { admin: true });
|
||||||
|
// Simulate a hostile article body persisted by the backend.
|
||||||
|
mock.store[0].content = [
|
||||||
'<p>Safe <strong>text</strong></p>',
|
'<p>Safe <strong>text</strong></p>',
|
||||||
'<script>alert(1)</script>',
|
'<script>alert(1)</script>',
|
||||||
'<img src="x" onerror="alert(1)"/>',
|
'<img src="x" onerror="alert(1)"/>',
|
||||||
@@ -431,12 +557,18 @@ test.describe('admin area (M6)', () => {
|
|||||||
});
|
});
|
||||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||||
|
|
||||||
await page.goto('/admin/items/1/edit');
|
await page.addInitScript(
|
||||||
|
(value) => localStorage.setItem('AUTH_TOKEN', value),
|
||||||
|
mock.token,
|
||||||
|
);
|
||||||
|
await page.goto('/admin/articles/1/edit');
|
||||||
|
|
||||||
const editable = page.getByLabel('Item content');
|
const editable = page.getByLabel('Article content');
|
||||||
await expect(editable).toContainText('Safe');
|
await expect(editable).toContainText('Safe');
|
||||||
|
|
||||||
const html = await editable.evaluate((el) => el.innerHTML);
|
const html = await editable.evaluate(
|
||||||
|
(el) => (el as HTMLElement).innerHTML,
|
||||||
|
);
|
||||||
expect(html).not.toContain('<script');
|
expect(html).not.toContain('<script');
|
||||||
expect(html).not.toContain('onerror');
|
expect(html).not.toContain('onerror');
|
||||||
expect(html).not.toContain('onload');
|
expect(html).not.toContain('onload');
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import Account from './pages/Account';
|
|||||||
import AdminDashboard from './pages/AdminDashboard';
|
import AdminDashboard from './pages/AdminDashboard';
|
||||||
import ArticlePage from './pages/ArticlePage';
|
import ArticlePage from './pages/ArticlePage';
|
||||||
import CategoriesPage from './pages/CategoriesPage';
|
import CategoriesPage from './pages/CategoriesPage';
|
||||||
import EditItemPage from './pages/EditItemPage';
|
import EditArticlePage from './pages/EditArticlePage';
|
||||||
import Home from './pages/Home';
|
import Home from './pages/Home';
|
||||||
import Login from './pages/Login';
|
import Login from './pages/Login';
|
||||||
import Register from './pages/Register';
|
import Register from './pages/Register';
|
||||||
@@ -61,8 +61,8 @@ export default function App() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
<Route index element={<AdminDashboard />} />
|
<Route index element={<AdminDashboard />} />
|
||||||
<Route path="items/new" element={<EditItemPage />} />
|
<Route path="articles/new" element={<EditArticlePage />} />
|
||||||
<Route path="items/:id/edit" element={<EditItemPage />} />
|
<Route path="articles/:id/edit" element={<EditArticlePage />} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|
||||||
{/* Public site */}
|
{/* Public site */}
|
||||||
|
|||||||
+35
-19
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Admin API client (item CRUD, admin-only endpoints).
|
* Admin API client (article CRUD, admin-only endpoints).
|
||||||
*
|
*
|
||||||
* Built on the shared fetch wrapper from `api/client.ts`, which attaches
|
* Built on the shared fetch wrapper from `api/client.ts`, which attaches
|
||||||
* the JWT session token to every request. All endpoints require the
|
* the JWT session token to every request. All endpoints require the
|
||||||
@@ -7,40 +7,56 @@
|
|||||||
* `api/v1/admin.py`).
|
* `api/v1/admin.py`).
|
||||||
*/
|
*/
|
||||||
import { api } from './client';
|
import { api } from './client';
|
||||||
|
import type { Author, Category } from '../types';
|
||||||
import type {
|
import type {
|
||||||
AdminItem,
|
AdminArticle,
|
||||||
AdminItemInput,
|
AdminArticleInput,
|
||||||
AdminItemsPage,
|
AdminArticlesPage,
|
||||||
AdminListParams,
|
AdminListParams,
|
||||||
} from '../types/admin';
|
} from '../types/admin';
|
||||||
|
|
||||||
/** `GET /api/v1/admin/items` — paginated, searchable, sortable list. */
|
/** `GET /api/v1/admin/articles` — paginated, searchable, sortable list. */
|
||||||
export function adminListItems(params: AdminListParams): Promise<AdminItemsPage> {
|
export function adminListArticles(
|
||||||
|
params: AdminListParams,
|
||||||
|
): Promise<AdminArticlesPage> {
|
||||||
const query = new URLSearchParams();
|
const query = new URLSearchParams();
|
||||||
query.set('page', String(params.page));
|
query.set('page', String(params.page));
|
||||||
query.set('page_size', String(params.pageSize));
|
query.set('page_size', String(params.pageSize));
|
||||||
if (params.search.trim()) query.set('search', params.search.trim());
|
if (params.search.trim()) query.set('search', params.search.trim());
|
||||||
query.set('sort_by', params.sortBy);
|
query.set('sort_by', params.sortBy);
|
||||||
query.set('sort_order', params.sortOrder);
|
query.set('sort_order', params.sortOrder);
|
||||||
return api.get<AdminItemsPage>(`/admin/items?${query.toString()}`);
|
return api.get<AdminArticlesPage>(`/admin/articles?${query.toString()}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `GET /api/v1/admin/items/{id}` — a single item (including content). */
|
/** `GET /api/v1/admin/articles/{id}` — a single article (with author + category). */
|
||||||
export function adminGetItem(id: number): Promise<AdminItem> {
|
export function adminGetArticle(id: number): Promise<AdminArticle> {
|
||||||
return api.get<AdminItem>(`/admin/items/${id}`);
|
return api.get<AdminArticle>(`/admin/articles/${id}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `POST /api/v1/admin/items` — create a new item. */
|
/** `POST /api/v1/admin/articles` — create a new article. */
|
||||||
export function adminCreateItem(input: AdminItemInput): Promise<AdminItem> {
|
export function adminCreateArticle(input: AdminArticleInput): Promise<AdminArticle> {
|
||||||
return api.post<AdminItem>('/admin/items', input);
|
return api.post<AdminArticle>('/admin/articles', input);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `PUT /api/v1/admin/items/{id}` — update an item. */
|
/** `PUT /api/v1/admin/articles/{id}` — update an article. */
|
||||||
export function adminUpdateItem(id: number, input: AdminItemInput): Promise<AdminItem> {
|
export function adminUpdateArticle(
|
||||||
return api.put<AdminItem>(`/admin/items/${id}`, input);
|
id: number,
|
||||||
|
input: AdminArticleInput,
|
||||||
|
): Promise<AdminArticle> {
|
||||||
|
return api.put<AdminArticle>(`/admin/articles/${id}`, input);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** `DELETE /api/v1/admin/items/{id}` — hard-delete an item (204). */
|
/** `DELETE /api/v1/admin/articles/{id}` — hard-delete an article (204). */
|
||||||
export function adminDeleteItem(id: number): Promise<void> {
|
export function adminDeleteArticle(id: number): Promise<void> {
|
||||||
return api.delete<void>(`/admin/items/${id}`);
|
return api.delete<void>(`/admin/articles/${id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `GET /api/v1/admin/authors` — reference list for the article form. */
|
||||||
|
export function adminListAuthors(): Promise<Author[]> {
|
||||||
|
return api.get<Author[]>('/admin/authors');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `GET /api/v1/admin/categories` — reference list for the article form. */
|
||||||
|
export function adminListCategories(): Promise<Category[]> {
|
||||||
|
return api.get<Category[]>('/admin/categories');
|
||||||
}
|
}
|
||||||
@@ -195,10 +195,10 @@ export function logout(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* `GET /api/v1/articles` — list of published articles.
|
* `GET /api/v1/articles` — list of published articles (newest first).
|
||||||
*
|
*
|
||||||
* The endpoint is provided by a later backend milestone; until then the
|
* The Home page falls back to sample data (see `src/data/sample.ts`)
|
||||||
* UI falls back to sample data (see `src/data/sample.ts`).
|
* when the backend is unreachable or has no published articles yet.
|
||||||
*/
|
*/
|
||||||
export function getArticles(): Promise<Article[]> {
|
export function getArticles(): Promise<Article[]> {
|
||||||
return api.get<BackendArticle[]>('/articles').then((articles) =>
|
return api.get<BackendArticle[]>('/articles').then((articles) =>
|
||||||
|
|||||||
@@ -94,11 +94,11 @@ export function AdminLayout({ className }: AdminLayoutProps) {
|
|||||||
<nav className="admin-sidebar__nav">
|
<nav className="admin-sidebar__nav">
|
||||||
<NavLink to="/admin" end className={sidebarLinkClasses}>
|
<NavLink to="/admin" end className={sidebarLinkClasses}>
|
||||||
<LayoutDashboard size={16} aria-hidden="true" />
|
<LayoutDashboard size={16} aria-hidden="true" />
|
||||||
<span>Items</span>
|
<span>Articles</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
<NavLink to="/admin/items/new" className={sidebarLinkClasses}>
|
<NavLink to="/admin/articles/new" className={sidebarLinkClasses}>
|
||||||
<Plus size={16} aria-hidden="true" />
|
<Plus size={16} aria-hidden="true" />
|
||||||
<span>New item</span>
|
<span>New article</span>
|
||||||
</NavLink>
|
</NavLink>
|
||||||
<Link to="/" className="admin-sidebar__link">
|
<Link to="/" className="admin-sidebar__link">
|
||||||
<ArrowLeft size={16} aria-hidden="true" />
|
<ArrowLeft size={16} aria-hidden="true" />
|
||||||
|
|||||||
@@ -8,11 +8,11 @@
|
|||||||
*/
|
*/
|
||||||
import { AlertTriangle } from 'lucide-react';
|
import { AlertTriangle } from 'lucide-react';
|
||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import type { AdminItem } from '../types/admin';
|
import type { AdminArticle } from '../types/admin';
|
||||||
|
|
||||||
export interface DeleteConfirmationProps {
|
export interface DeleteConfirmationProps {
|
||||||
/** The item about to be deleted. */
|
/** The article about to be deleted. */
|
||||||
item: AdminItem;
|
article: AdminArticle;
|
||||||
/** `true` while the delete request is in flight. */
|
/** `true` while the delete request is in flight. */
|
||||||
busy?: boolean;
|
busy?: boolean;
|
||||||
/** Error from a failed delete attempt (rendered above the actions). */
|
/** Error from a failed delete attempt (rendered above the actions). */
|
||||||
@@ -24,7 +24,7 @@ export interface DeleteConfirmationProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function DeleteConfirmation({
|
export function DeleteConfirmation({
|
||||||
item,
|
article,
|
||||||
busy = false,
|
busy = false,
|
||||||
error = null,
|
error = null,
|
||||||
onConfirm,
|
onConfirm,
|
||||||
@@ -66,10 +66,10 @@ export function DeleteConfirmation({
|
|||||||
</span>
|
</span>
|
||||||
<div>
|
<div>
|
||||||
<h2 id="delete-confirm-title" className="text-base font-semibold text-slate-900">
|
<h2 id="delete-confirm-title" className="text-base font-semibold text-slate-900">
|
||||||
Are you sure you want to delete this item?
|
Are you sure you want to delete this article?
|
||||||
</h2>
|
</h2>
|
||||||
<p className="mt-1 text-sm text-slate-600">
|
<p className="mt-1 text-sm text-slate-600">
|
||||||
“<span className="font-medium text-slate-800">{item.title}</span>” will be
|
“<span className="font-medium text-slate-800">{article.title}</span>” will be
|
||||||
permanently removed. This action cannot be undone.
|
permanently removed. This action cannot be undone.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
* Features: bold / italic / underline, H1–H6 headings, ordered &
|
* Features: bold / italic / underline, H1–H6 headings, ordered &
|
||||||
* unordered lists, links and code blocks. Content is exchanged with the
|
* unordered lists, links and code blocks. Content is exchanged with the
|
||||||
* parent as an HTML string (`initialHtml` in, `onChange` out) so it can
|
* parent as an HTML string (`initialHtml` in, `onChange` out) so it can
|
||||||
* be stored verbatim in the backend `items.content` column.
|
* be stored verbatim in the backend `articles.content` column.
|
||||||
*
|
*
|
||||||
* Lexical 0.25.x API (classic): `RichTextPlugin` + `ContentEditable`,
|
* Lexical 0.25.x API (classic): `RichTextPlugin` + `ContentEditable`,
|
||||||
* `FORMAT_TEXT_COMMAND` for inline marks, `$setBlocksType` for block
|
* `FORMAT_TEXT_COMMAND` for inline marks, `$setBlocksType` for block
|
||||||
@@ -177,7 +177,7 @@ function EditorShell({ initialHtml, onChange, placeholder }: EditorShellProps) {
|
|||||||
contentEditable={
|
contentEditable={
|
||||||
<ContentEditable
|
<ContentEditable
|
||||||
className="lex-editor__content"
|
className="lex-editor__content"
|
||||||
aria-label="Item content"
|
aria-label="Article content"
|
||||||
spellCheck
|
spellCheck
|
||||||
/>
|
/>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* Admin dashboard (M6): paginated list of all items with debounced
|
* Admin dashboard (M6): paginated list of all articles with debounced
|
||||||
* search (300ms), sortable columns (title / points / created date),
|
* search (300ms), sortable columns (title / created date), page-size
|
||||||
* page-size selector, row actions (edit / delete) and a success notice
|
* selector, row actions (edit / delete) and a success notice after
|
||||||
* after saves coming back from the edit page.
|
* saves coming back from the edit page.
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
ArrowDown,
|
ArrowDown,
|
||||||
@@ -16,13 +16,13 @@ import {
|
|||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
import { Link, useLocation } from 'react-router-dom';
|
import { Link, useLocation } from 'react-router-dom';
|
||||||
import { adminDeleteItem, adminListItems } from '../api/admin';
|
import { adminDeleteArticle, adminListArticles } from '../api/admin';
|
||||||
import { DeleteConfirmation } from '../components/DeleteConfirmation';
|
|
||||||
import { ApiError } from '../api/client';
|
import { ApiError } from '../api/client';
|
||||||
|
import { DeleteConfirmation } from '../components/DeleteConfirmation';
|
||||||
import { cn } from '../lib/utils';
|
import { cn } from '../lib/utils';
|
||||||
import type {
|
import type {
|
||||||
AdminItem,
|
AdminArticle,
|
||||||
AdminItemsPage,
|
AdminArticlesPage,
|
||||||
AdminSortBy,
|
AdminSortBy,
|
||||||
AdminSortOrder,
|
AdminSortOrder,
|
||||||
} from '../types/admin';
|
} from '../types/admin';
|
||||||
@@ -77,10 +77,10 @@ function pageWindow(current: number, total: number): (number | '…')[] {
|
|||||||
export function AdminDashboard() {
|
export function AdminDashboard() {
|
||||||
const [state, setState] = useState<AdminDashboardState>(INITIAL_STATE);
|
const [state, setState] = useState<AdminDashboardState>(INITIAL_STATE);
|
||||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||||
const [data, setData] = useState<AdminItemsPage | null>(null);
|
const [data, setData] = useState<AdminArticlesPage | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [pendingDelete, setPendingDelete] = useState<AdminItem | null>(null);
|
const [pendingDelete, setPendingDelete] = useState<AdminArticle | null>(null);
|
||||||
const [deleteBusy, setDeleteBusy] = useState(false);
|
const [deleteBusy, setDeleteBusy] = useState(false);
|
||||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||||
const [notice, setNotice] = useState<string | null>(null);
|
const [notice, setNotice] = useState<string | null>(null);
|
||||||
@@ -109,7 +109,7 @@ export function AdminDashboard() {
|
|||||||
setLoading(true);
|
setLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const result = await adminListItems({
|
const result = await adminListArticles({
|
||||||
page: state.page,
|
page: state.page,
|
||||||
pageSize: state.pageSize,
|
pageSize: state.pageSize,
|
||||||
search: searchActive,
|
search: searchActive,
|
||||||
@@ -123,7 +123,7 @@ export function AdminDashboard() {
|
|||||||
setError(
|
setError(
|
||||||
err instanceof ApiError
|
err instanceof ApiError
|
||||||
? err.message
|
? err.message
|
||||||
: 'Something went wrong while loading items.',
|
: 'Something went wrong while loading articles.',
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
if (!signal?.cancelled) setLoading(false);
|
if (!signal?.cancelled) setLoading(false);
|
||||||
@@ -165,12 +165,14 @@ export function AdminDashboard() {
|
|||||||
setDeleteBusy(true);
|
setDeleteBusy(true);
|
||||||
setDeleteError(null);
|
setDeleteError(null);
|
||||||
try {
|
try {
|
||||||
await adminDeleteItem(pendingDelete.id);
|
await adminDeleteArticle(pendingDelete.id);
|
||||||
setPendingDelete(null);
|
setPendingDelete(null);
|
||||||
setNotice(`“${pendingDelete.title}” was deleted.`);
|
setNotice(`“${pendingDelete.title}” was deleted.`);
|
||||||
await load();
|
await load();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setDeleteError(err instanceof ApiError ? err.message : 'Deleting the item failed.');
|
setDeleteError(
|
||||||
|
err instanceof ApiError ? err.message : 'Deleting the article failed.',
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
setDeleteBusy(false);
|
setDeleteBusy(false);
|
||||||
}
|
}
|
||||||
@@ -209,14 +211,14 @@ export function AdminDashboard() {
|
|||||||
{/* Heading + primary action */}
|
{/* Heading + primary action */}
|
||||||
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
|
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl font-bold text-slate-900">Items</h1>
|
<h1 className="text-2xl font-bold text-slate-900">Articles</h1>
|
||||||
<p className="text-sm text-slate-500">
|
<p className="text-sm text-slate-500">
|
||||||
Create, edit and delete the news items shown on the site.
|
Create, edit and delete the articles shown on the site.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Link to="/admin/items/new" className="btn">
|
<Link to="/admin/articles/new" className="btn">
|
||||||
<Plus size={15} aria-hidden="true" />
|
<Plus size={15} aria-hidden="true" />
|
||||||
New item
|
New article
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -243,18 +245,18 @@ export function AdminDashboard() {
|
|||||||
className="mb-4 flex items-center gap-3"
|
className="mb-4 flex items-center gap-3"
|
||||||
onSubmit={(event) => event.preventDefault()}
|
onSubmit={(event) => event.preventDefault()}
|
||||||
>
|
>
|
||||||
<label htmlFor="admin-item-search" className="sr-only">
|
<label htmlFor="admin-article-search" className="sr-only">
|
||||||
Search items
|
Search articles
|
||||||
</label>
|
</label>
|
||||||
<div className="relative w-full max-w-sm">
|
<div className="relative w-full max-w-sm">
|
||||||
<Search
|
<Search
|
||||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400"
|
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400 text-slate-400"
|
||||||
aria-hidden="true"
|
aria-hidden="true"
|
||||||
/>
|
/>
|
||||||
<input
|
<input
|
||||||
id="admin-item-search"
|
id="admin-article-search"
|
||||||
type="search"
|
type="search"
|
||||||
placeholder="Search by title or URL…"
|
placeholder="Search by title or content…"
|
||||||
value={state.search}
|
value={state.search}
|
||||||
onChange={(event) => onSearchChange(event.target.value)}
|
onChange={(event) => onSearchChange(event.target.value)}
|
||||||
className="w-full rounded-md border border-slate-300 bg-white py-2 pl-9 pr-3 text-sm text-slate-900 placeholder:text-slate-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/40"
|
className="w-full rounded-md border border-slate-300 bg-white py-2 pl-9 pr-3 text-sm text-slate-900 placeholder:text-slate-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/40"
|
||||||
@@ -275,7 +277,7 @@ export function AdminDashboard() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Item table */}
|
{/* Article table */}
|
||||||
<div className="overflow-x-auto rounded-xl border border-slate-200 bg-white shadow-sm">
|
<div className="overflow-x-auto rounded-xl border border-slate-200 bg-white shadow-sm">
|
||||||
<table className="min-w-full divide-y divide-slate-200 text-sm">
|
<table className="min-w-full divide-y divide-slate-200 text-sm">
|
||||||
<thead className="bg-slate-50">
|
<thead className="bg-slate-50">
|
||||||
@@ -291,20 +293,13 @@ export function AdminDashboard() {
|
|||||||
</button>
|
</button>
|
||||||
</th>
|
</th>
|
||||||
<th scope="col" className={thClasses}>
|
<th scope="col" className={thClasses}>
|
||||||
URL
|
Author
|
||||||
</th>
|
|
||||||
<th scope="col" className={cn(thClasses, 'text-right')}>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className={cn(sortButtonClasses, 'ml-auto flex-row-reverse')}
|
|
||||||
onClick={() => onSort('points')}
|
|
||||||
aria-label="Sort by points"
|
|
||||||
>
|
|
||||||
Points {sortIndicator('points')}
|
|
||||||
</button>
|
|
||||||
</th>
|
</th>
|
||||||
<th scope="col" className={thClasses}>
|
<th scope="col" className={thClasses}>
|
||||||
Author
|
Category
|
||||||
|
</th>
|
||||||
|
<th scope="col" className={thClasses}>
|
||||||
|
Published
|
||||||
</th>
|
</th>
|
||||||
<th scope="col" className={thClasses}>
|
<th scope="col" className={thClasses}>
|
||||||
<button
|
<button
|
||||||
@@ -325,43 +320,51 @@ export function AdminDashboard() {
|
|||||||
{loading && data === null ? (
|
{loading && data === null ? (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={6} className="px-4 py-12 text-center text-sm text-slate-500">
|
<td colSpan={6} className="px-4 py-12 text-center text-sm text-slate-500">
|
||||||
<span className="animate-pulse">Loading items…</span>
|
<span className="animate-pulse">Loading articles…</span>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
) : data && data.items.length > 0 ? (
|
) : data && data.articles.length > 0 ? (
|
||||||
data.items.map((item) => (
|
data.articles.map((article) => (
|
||||||
<tr key={item.id} className="transition-colors hover:bg-slate-50">
|
<tr key={article.id} className="transition-colors hover:bg-slate-50">
|
||||||
<td className="max-w-xs px-4 py-3">
|
<td className="max-w-xs px-4 py-3">
|
||||||
<span className="block truncate font-medium text-slate-900" title={item.title}>
|
<span
|
||||||
{item.title}
|
className="block truncate font-medium text-slate-900"
|
||||||
|
title={article.title}
|
||||||
|
>
|
||||||
|
{article.title}
|
||||||
</span>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="max-w-[14rem] px-4 py-3">
|
<td className="max-w-[12rem] px-4 py-3">
|
||||||
{item.url ? (
|
<span className="block truncate text-slate-600" title={article.author.name}>
|
||||||
<a
|
{article.author.name}
|
||||||
href={item.url}
|
</span>
|
||||||
target="_blank"
|
</td>
|
||||||
rel="noopener noreferrer"
|
<td className="max-w-[12rem] px-4 py-3">
|
||||||
className="block truncate text-blue-700 hover:underline"
|
<span
|
||||||
title={item.url}
|
className="block truncate rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-medium text-slate-600"
|
||||||
>
|
title={article.category.name}
|
||||||
{item.url}
|
>
|
||||||
</a>
|
{article.category.name}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td className="whitespace-nowrap px-4 py-3">
|
||||||
|
{article.published ? (
|
||||||
|
<span className="rounded-full bg-green-100 px-2.5 py-0.5 text-xs font-medium text-green-700">
|
||||||
|
Published
|
||||||
|
</span>
|
||||||
) : (
|
) : (
|
||||||
<span className="text-slate-400">—</span>
|
<span className="rounded-full bg-amber-100 px-2.5 py-0.5 text-xs font-medium text-amber-700">
|
||||||
|
Draft
|
||||||
|
</span>
|
||||||
)}
|
)}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3 text-right tabular-nums text-slate-700">
|
|
||||||
{item.points}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-slate-600">{item.username}</td>
|
|
||||||
<td className="whitespace-nowrap px-4 py-3 text-slate-500">
|
<td className="whitespace-nowrap px-4 py-3 text-slate-500">
|
||||||
{formatDateTime(item.created_at)}
|
{formatDateTime(article.created_at)}
|
||||||
</td>
|
</td>
|
||||||
<td className="whitespace-nowrap px-4 py-3 text-right">
|
<td className="whitespace-nowrap px-4 py-3 text-right">
|
||||||
<div className="inline-flex items-center gap-1">
|
<div className="inline-flex items-center gap-1">
|
||||||
<Link
|
<Link
|
||||||
to={`/admin/items/${item.id}/edit`}
|
to={`/admin/articles/${article.id}/edit`}
|
||||||
className="inline-flex items-center gap-1.5 rounded-md border border-slate-300 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 transition-colors hover:bg-slate-100"
|
className="inline-flex items-center gap-1.5 rounded-md border border-slate-300 bg-white px-2.5 py-1.5 text-xs font-medium text-slate-700 transition-colors hover:bg-slate-100"
|
||||||
>
|
>
|
||||||
<Pencil size={13} aria-hidden="true" />
|
<Pencil size={13} aria-hidden="true" />
|
||||||
@@ -370,7 +373,7 @@ export function AdminDashboard() {
|
|||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="inline-flex items-center gap-1.5 rounded-md border border-red-200 bg-white px-2.5 py-1.5 text-xs font-medium text-red-700 transition-colors hover:bg-red-50"
|
className="inline-flex items-center gap-1.5 rounded-md border border-red-200 bg-white px-2.5 py-1.5 text-xs font-medium text-red-700 transition-colors hover:bg-red-50"
|
||||||
onClick={() => setPendingDelete(item)}
|
onClick={() => setPendingDelete(article)}
|
||||||
>
|
>
|
||||||
<Trash2 size={13} aria-hidden="true" />
|
<Trash2 size={13} aria-hidden="true" />
|
||||||
Delete
|
Delete
|
||||||
@@ -383,8 +386,8 @@ export function AdminDashboard() {
|
|||||||
<tr>
|
<tr>
|
||||||
<td colSpan={6} className="px-4 py-12 text-center text-sm text-slate-500">
|
<td colSpan={6} className="px-4 py-12 text-center text-sm text-slate-500">
|
||||||
{searchActive
|
{searchActive
|
||||||
? `No items match “${searchActive}”.`
|
? `No articles match “${searchActive}”.`
|
||||||
: 'No items yet — create the first one.'}
|
: 'No articles yet — create the first one.'}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
)}
|
)}
|
||||||
@@ -466,7 +469,7 @@ export function AdminDashboard() {
|
|||||||
{/* Delete confirmation dialog */}
|
{/* Delete confirmation dialog */}
|
||||||
{pendingDelete && (
|
{pendingDelete && (
|
||||||
<DeleteConfirmation
|
<DeleteConfirmation
|
||||||
item={pendingDelete}
|
article={pendingDelete}
|
||||||
busy={deleteBusy}
|
busy={deleteBusy}
|
||||||
error={deleteError}
|
error={deleteError}
|
||||||
onConfirm={() => void confirmDelete()}
|
onConfirm={() => void confirmDelete()}
|
||||||
|
|||||||
@@ -0,0 +1,516 @@
|
|||||||
|
/**
|
||||||
|
* Create/edit article page (M6).
|
||||||
|
*
|
||||||
|
* Full form for an article: title, author (select), category (select),
|
||||||
|
* published flag and a Lexical WYSIWYG editor for the HTML body.
|
||||||
|
* Validates required fields client-side (mirroring the backend 422
|
||||||
|
* rules), shows a loading state while saving and surfaces success/error
|
||||||
|
* notifications. An optional debounced auto-save can be enabled.
|
||||||
|
*
|
||||||
|
* Routes:
|
||||||
|
* - `/admin/articles/new` -> create mode (no `:id` param)
|
||||||
|
* - `/admin/articles/:id/edit` -> edit mode (loads the article on mount)
|
||||||
|
*/
|
||||||
|
import { ArrowLeft, Loader2, Save } from 'lucide-react';
|
||||||
|
import {
|
||||||
|
FormEvent,
|
||||||
|
useCallback,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useRef,
|
||||||
|
useState,
|
||||||
|
} from 'react';
|
||||||
|
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||||
|
import {
|
||||||
|
adminCreateArticle,
|
||||||
|
adminGetArticle,
|
||||||
|
adminListAuthors,
|
||||||
|
adminListCategories,
|
||||||
|
adminUpdateArticle,
|
||||||
|
} from '../api/admin';
|
||||||
|
import { ApiError } from '../api/client';
|
||||||
|
import { LexicalEditor } from '../components/LexicalEditor';
|
||||||
|
import type { Author, Category } from '../types';
|
||||||
|
import type { AdminArticleInput } from '../types/admin';
|
||||||
|
|
||||||
|
const AUTO_SAVE_DELAY_MS = 2000;
|
||||||
|
|
||||||
|
interface FormValues {
|
||||||
|
title: string;
|
||||||
|
/** 0 = not selected yet (no author). */
|
||||||
|
authorId: number;
|
||||||
|
/** 0 = not selected yet (no category). */
|
||||||
|
categoryId: number;
|
||||||
|
/** Whether the article is visible on the public site. */
|
||||||
|
published: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FieldErrors {
|
||||||
|
title?: string;
|
||||||
|
authorId?: string;
|
||||||
|
categoryId?: string;
|
||||||
|
content?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Plain text of an HTML fragment (client-side "not empty" check). */
|
||||||
|
function textOf(html: string): string {
|
||||||
|
return html
|
||||||
|
.replace(/<[^>]*>/g, ' ')
|
||||||
|
.replace(/ /g, ' ')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Client-side validation mirroring the backend rules (422 on the server). */
|
||||||
|
function validate(values: FormValues, content: string): FieldErrors {
|
||||||
|
const errors: FieldErrors = {};
|
||||||
|
const title = values.title.trim();
|
||||||
|
if (!title) {
|
||||||
|
errors.title = 'Title is required.';
|
||||||
|
} else if (title.length > 200) {
|
||||||
|
errors.title = 'Title must be at most 200 characters.';
|
||||||
|
}
|
||||||
|
if (!values.authorId) errors.authorId = 'Select an author.';
|
||||||
|
if (!values.categoryId) errors.categoryId = 'Select a category.';
|
||||||
|
if (!textOf(content)) errors.content = 'Content is required.';
|
||||||
|
return errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EditArticlePage() {
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const editingId = id ? Number(id) : null;
|
||||||
|
const isCreate = editingId === null;
|
||||||
|
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const [values, setValues] = useState<FormValues>({
|
||||||
|
title: '',
|
||||||
|
authorId: 0,
|
||||||
|
categoryId: 0,
|
||||||
|
published: false,
|
||||||
|
});
|
||||||
|
const [contentHtml, setContentHtml] = useState('');
|
||||||
|
const [authors, setAuthors] = useState<Author[]>([]);
|
||||||
|
const [categories, setCategories] = useState<Category[]>([]);
|
||||||
|
const [refsLoaded, setRefsLoaded] = useState(false);
|
||||||
|
const [refsError, setRefsError] = useState<string | null>(null);
|
||||||
|
const [loadError, setLoadError] = useState<string | null>(null);
|
||||||
|
const [loading, setLoading] = useState(isCreate ? false : true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
|
||||||
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
const [autoSave, setAutoSave] = useState(false);
|
||||||
|
const [autoSaveStatus, setAutoSaveStatus] = useState<
|
||||||
|
'idle' | 'saving' | 'saved' | 'paused'
|
||||||
|
>('idle');
|
||||||
|
|
||||||
|
// After an auto-save in create mode, switch to updating the new article.
|
||||||
|
const [createdId, setCreatedId] = useState<number | null>(null);
|
||||||
|
const targetId = editingId ?? createdId;
|
||||||
|
|
||||||
|
const [initialValues, setInitialValues] = useState<FormValues | null>(null);
|
||||||
|
const lastSavedSignature = useRef<string | null>(null);
|
||||||
|
|
||||||
|
const applyBaseline = (next: FormValues, content: string) => {
|
||||||
|
setInitialValues(next);
|
||||||
|
lastSavedSignature.current = signature(next, content);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Load the author/category reference lists (shared by both modes).
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
Promise.all([adminListAuthors(), adminListCategories()])
|
||||||
|
.then(([authorList, categoryList]) => {
|
||||||
|
if (!active) return;
|
||||||
|
setAuthors(authorList);
|
||||||
|
setCategories(categoryList);
|
||||||
|
setRefsLoaded(true);
|
||||||
|
})
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
if (!active) return;
|
||||||
|
setRefsError(
|
||||||
|
err instanceof ApiError
|
||||||
|
? err.message
|
||||||
|
: 'Could not load the author and category lists.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Default the selects to the first entries so the form is usable right
|
||||||
|
// away (create mode; edit mode overwrites with the loaded values).
|
||||||
|
useEffect(() => {
|
||||||
|
if (!refsLoaded) return;
|
||||||
|
setValues((current) => ({
|
||||||
|
...current,
|
||||||
|
authorId: current.authorId || (authors[0]?.id ?? 0),
|
||||||
|
categoryId: current.categoryId || (categories[0]?.id ?? 0),
|
||||||
|
}));
|
||||||
|
}, [refsLoaded, authors, categories]);
|
||||||
|
|
||||||
|
// Create mode: snapshot the baseline once the defaults have been applied.
|
||||||
|
useEffect(() => {
|
||||||
|
if (editingId !== null || !refsLoaded || initialValues !== null) return;
|
||||||
|
applyBaseline(values, contentHtml);
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [editingId, refsLoaded, values, initialValues]);
|
||||||
|
|
||||||
|
// Load the article in edit mode.
|
||||||
|
useEffect(() => {
|
||||||
|
if (editingId === null) return;
|
||||||
|
let active = true;
|
||||||
|
adminGetArticle(editingId)
|
||||||
|
.then((article) => {
|
||||||
|
if (!active) return;
|
||||||
|
const loaded: FormValues = {
|
||||||
|
title: article.title,
|
||||||
|
authorId: article.author_id,
|
||||||
|
categoryId: article.category_id,
|
||||||
|
published: article.published,
|
||||||
|
};
|
||||||
|
setValues(loaded);
|
||||||
|
setContentHtml(article.content);
|
||||||
|
applyBaseline(loaded, article.content);
|
||||||
|
setLoadError(null);
|
||||||
|
})
|
||||||
|
.catch((err: unknown) => {
|
||||||
|
if (!active) return;
|
||||||
|
setLoadError(
|
||||||
|
err instanceof ApiError ? err.message : 'Could not load the article.',
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (active) setLoading(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [editingId]);
|
||||||
|
|
||||||
|
const dirty = useMemo(
|
||||||
|
() =>
|
||||||
|
initialValues !== null &&
|
||||||
|
signature(values, contentHtml) !== lastSavedSignature.current,
|
||||||
|
[values, contentHtml, initialValues],
|
||||||
|
);
|
||||||
|
|
||||||
|
const save = useCallback(
|
||||||
|
async (mode: 'manual' | 'auto' = 'manual') => {
|
||||||
|
const errors = validate(values, contentHtml);
|
||||||
|
setFieldErrors(errors);
|
||||||
|
if (Object.keys(errors).length > 0) {
|
||||||
|
if (mode === 'auto') {
|
||||||
|
setAutoSaveStatus('paused');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
setFormError('Please fix the highlighted fields and try again.');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
setFormError(null);
|
||||||
|
setSaving(true);
|
||||||
|
if (mode === 'auto') setAutoSaveStatus('saving');
|
||||||
|
try {
|
||||||
|
const payload: AdminArticleInput = {
|
||||||
|
title: values.title.trim(),
|
||||||
|
content: contentHtml,
|
||||||
|
author_id: values.authorId,
|
||||||
|
category_id: values.categoryId,
|
||||||
|
published: values.published,
|
||||||
|
};
|
||||||
|
const saved =
|
||||||
|
targetId !== null
|
||||||
|
? await adminUpdateArticle(targetId, payload)
|
||||||
|
: await adminCreateArticle(payload);
|
||||||
|
// Trim the title in the form too so the baseline signature matches.
|
||||||
|
setValues((current) => ({ ...current, title: current.title.trim() }));
|
||||||
|
lastSavedSignature.current = signature(
|
||||||
|
{ ...values, title: values.title.trim() },
|
||||||
|
contentHtml,
|
||||||
|
);
|
||||||
|
if (createdId === null && editingId === null) {
|
||||||
|
setCreatedId(saved.id);
|
||||||
|
}
|
||||||
|
setAutoSaveStatus('saved');
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
const message =
|
||||||
|
err instanceof ApiError ? err.message : 'Saving the article failed.';
|
||||||
|
if (mode === 'auto') {
|
||||||
|
setAutoSaveStatus('paused');
|
||||||
|
} else {
|
||||||
|
setFormError(message);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[values, contentHtml, targetId, createdId, editingId],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Debounced auto-save: fire 2s after the last change when enabled.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!autoSave || loading || saving || !dirty) return;
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
void save('auto');
|
||||||
|
}, AUTO_SAVE_DELAY_MS);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [autoSave, loading, saving, dirty, save]);
|
||||||
|
|
||||||
|
const onSubmit = async (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const ok = await save('manual');
|
||||||
|
if (ok) {
|
||||||
|
navigate('/admin', {
|
||||||
|
state: { notice: `“${values.title.trim()}” was saved.` },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="flex justify-center py-16" role="status">
|
||||||
|
<span className="animate-pulse text-sm text-slate-500">
|
||||||
|
Loading article…
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loadError) {
|
||||||
|
return (
|
||||||
|
<div className="text-center">
|
||||||
|
<h1 className="mb-2 text-2xl font-bold text-slate-900">
|
||||||
|
Article not found
|
||||||
|
</h1>
|
||||||
|
<p className="mb-6 text-sm text-slate-600">{loadError}</p>
|
||||||
|
<Link to="/admin" className="btn">
|
||||||
|
<ArrowLeft size={15} aria-hidden="true" />
|
||||||
|
Back to articles
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const autoSaveHint =
|
||||||
|
autoSaveStatus === 'saving'
|
||||||
|
? 'Saving…'
|
||||||
|
: autoSaveStatus === 'saved'
|
||||||
|
? 'All changes saved'
|
||||||
|
: autoSaveStatus === 'paused'
|
||||||
|
? 'Auto-save paused (fix validation errors)'
|
||||||
|
: 'Off';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<Link
|
||||||
|
to="/admin"
|
||||||
|
className="mb-2 inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800"
|
||||||
|
>
|
||||||
|
<ArrowLeft size={14} aria-hidden="true" />
|
||||||
|
Back to articles
|
||||||
|
</Link>
|
||||||
|
<h1 className="text-2xl font-bold text-slate-900">
|
||||||
|
{isCreate && createdId === null
|
||||||
|
? 'New article'
|
||||||
|
: `Edit article #${targetId}`}
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
<label className="flex items-center gap-2 text-sm text-slate-600">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
|
||||||
|
checked={autoSave}
|
||||||
|
disabled={saving}
|
||||||
|
onChange={(event) => {
|
||||||
|
setAutoSave(event.target.checked);
|
||||||
|
if (!event.target.checked) setAutoSaveStatus('idle');
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
Auto-save <span className="text-xs text-slate-400">({autoSaveHint})</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{refsError && (
|
||||||
|
<div
|
||||||
|
className="mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
|
||||||
|
role="alert"
|
||||||
|
>
|
||||||
|
{refsError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{formError && (
|
||||||
|
<div
|
||||||
|
className="mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
|
||||||
|
role="alert"
|
||||||
|
>
|
||||||
|
{formError}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form
|
||||||
|
onSubmit={(event) => void onSubmit(event)}
|
||||||
|
className="space-y-5 rounded-xl border border-slate-200 bg-white p-6 shadow-sm"
|
||||||
|
noValidate
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="article-title" className="mb-1 block text-sm font-medium text-slate-700">
|
||||||
|
Title <span className="text-red-600" aria-hidden="true">*</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="article-title"
|
||||||
|
className="input"
|
||||||
|
value={values.title}
|
||||||
|
maxLength={200}
|
||||||
|
placeholder="Headline of the story"
|
||||||
|
onChange={(event) =>
|
||||||
|
setValues((current) => ({ ...current, title: event.target.value }))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{fieldErrors.title && (
|
||||||
|
<p className="mt-1 text-sm text-red-600" role="alert">
|
||||||
|
{fieldErrors.title}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-5 sm:grid-cols-2">
|
||||||
|
<div>
|
||||||
|
<label htmlFor="article-author" className="mb-1 block text-sm font-medium text-slate-700">
|
||||||
|
Author <span className="text-red-600" aria-hidden="true">*</span>
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="article-author"
|
||||||
|
className="input"
|
||||||
|
value={values.authorId}
|
||||||
|
onChange={(event) =>
|
||||||
|
setValues((current) => ({
|
||||||
|
...current,
|
||||||
|
authorId: Number(event.target.value),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value={0} disabled>
|
||||||
|
Select an author…
|
||||||
|
</option>
|
||||||
|
{authors.map((author) => (
|
||||||
|
<option key={author.id} value={author.id}>
|
||||||
|
{author.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{fieldErrors.authorId && (
|
||||||
|
<p className="mt-1 text-sm text-red-600" role="alert">
|
||||||
|
{fieldErrors.authorId}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label htmlFor="article-category" className="mb-1 block text-sm font-medium text-slate-700">
|
||||||
|
Category <span className="text-red-600" aria-hidden="true">*</span>
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
id="article-category"
|
||||||
|
className="input"
|
||||||
|
value={values.categoryId}
|
||||||
|
onChange={(event) =>
|
||||||
|
setValues((current) => ({
|
||||||
|
...current,
|
||||||
|
categoryId: Number(event.target.value),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value={0} disabled>
|
||||||
|
Select a category…
|
||||||
|
</option>
|
||||||
|
{categories.map((category) => (
|
||||||
|
<option key={category.id} value={category.id}>
|
||||||
|
{category.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{fieldErrors.categoryId && (
|
||||||
|
<p className="mt-1 text-sm text-red-600" role="alert">
|
||||||
|
{fieldErrors.categoryId}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="article-published"
|
||||||
|
className="mb-1 block text-sm font-medium text-slate-700"
|
||||||
|
>
|
||||||
|
Published{' '}
|
||||||
|
<span className="text-xs font-normal text-slate-400">
|
||||||
|
(visible on the public site)
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
id="article-published"
|
||||||
|
type="checkbox"
|
||||||
|
className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
|
||||||
|
checked={values.published}
|
||||||
|
onChange={(event) =>
|
||||||
|
setValues((current) => ({
|
||||||
|
...current,
|
||||||
|
published: event.target.checked,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<span className="mb-1 block text-sm font-medium text-slate-700">
|
||||||
|
Content <span className="text-red-600" aria-hidden="true">*</span>
|
||||||
|
</span>
|
||||||
|
<LexicalEditor
|
||||||
|
initialHtml={contentHtml}
|
||||||
|
onChange={setContentHtml}
|
||||||
|
placeholder="Write the story body…"
|
||||||
|
/>
|
||||||
|
{fieldErrors.content && (
|
||||||
|
<p className="mt-1 text-sm text-red-600" role="alert">
|
||||||
|
{fieldErrors.content}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="mt-1 text-xs text-slate-400">
|
||||||
|
Rich text: bold, italic, underline, headings, lists, links and code blocks.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-3 border-t border-slate-100 pt-5">
|
||||||
|
<button type="submit" className="btn" disabled={saving}>
|
||||||
|
{saving ? (
|
||||||
|
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
||||||
|
) : (
|
||||||
|
<Save size={15} aria-hidden="true" />
|
||||||
|
)}
|
||||||
|
{saving
|
||||||
|
? 'Saving…'
|
||||||
|
: isCreate && createdId === null
|
||||||
|
? 'Create article'
|
||||||
|
: 'Save changes'}
|
||||||
|
</button>
|
||||||
|
<Link to="/admin" className="btn-secondary">
|
||||||
|
Cancel
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function signature(values: FormValues, content: string): string {
|
||||||
|
return JSON.stringify({ ...values, content });
|
||||||
|
}
|
||||||
|
|
||||||
|
export default EditArticlePage;
|
||||||
@@ -1,441 +0,0 @@
|
|||||||
/**
|
|
||||||
* Create/edit item page (M6).
|
|
||||||
*
|
|
||||||
* Full form for an item: title, optional external URL, points, author
|
|
||||||
* (username, pre-filled from the session on create) and a Lexical
|
|
||||||
* WYSIWYG editor for the HTML body. Validates required fields, shows a
|
|
||||||
* loading state while saving and surfaces success/error notifications.
|
|
||||||
* An optional debounced auto-save can be enabled.
|
|
||||||
*
|
|
||||||
* Routes:
|
|
||||||
* - `/admin/items/new` -> create mode (no `:id` param)
|
|
||||||
* - `/admin/items/:id/edit` -> edit mode (loads the item on mount)
|
|
||||||
*/
|
|
||||||
import { ArrowLeft, Loader2, Save } from 'lucide-react';
|
|
||||||
import {
|
|
||||||
FormEvent,
|
|
||||||
useCallback,
|
|
||||||
useEffect,
|
|
||||||
useMemo,
|
|
||||||
useRef,
|
|
||||||
useState,
|
|
||||||
} from 'react';
|
|
||||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
|
||||||
import {
|
|
||||||
adminCreateItem,
|
|
||||||
adminGetItem,
|
|
||||||
adminUpdateItem,
|
|
||||||
} from '../api/admin';
|
|
||||||
import { ApiError } from '../api/client';
|
|
||||||
import { LexicalEditor } from '../components/LexicalEditor';
|
|
||||||
import { useAuth } from '../auth';
|
|
||||||
import type { AdminItemInput } from '../types/admin';
|
|
||||||
|
|
||||||
const AUTO_SAVE_DELAY_MS = 2000;
|
|
||||||
|
|
||||||
interface FieldErrors {
|
|
||||||
title?: string;
|
|
||||||
url?: string;
|
|
||||||
points?: string;
|
|
||||||
username?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Client-side validation mirroring the backend rules (422 on the server). */
|
|
||||||
function validate(values: AdminItemInput): FieldErrors {
|
|
||||||
const errors: FieldErrors = {};
|
|
||||||
if (!values.title.trim()) {
|
|
||||||
errors.title = 'Title is required.';
|
|
||||||
} else if (values.title.length > 300) {
|
|
||||||
errors.title = 'Title must be at most 300 characters.';
|
|
||||||
}
|
|
||||||
const url = values.url.trim();
|
|
||||||
if (url) {
|
|
||||||
let parsed: URL | null = null;
|
|
||||||
try {
|
|
||||||
parsed = new URL(url);
|
|
||||||
} catch {
|
|
||||||
parsed = null;
|
|
||||||
}
|
|
||||||
if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
|
|
||||||
errors.url = 'URL must start with http:// or https://.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!Number.isInteger(values.points) || values.points < 0) {
|
|
||||||
errors.points = 'Points must be a whole number of 0 or more.';
|
|
||||||
}
|
|
||||||
if (!values.username.trim()) {
|
|
||||||
errors.username = 'Author is required.';
|
|
||||||
} else if (values.username.trim().length > 60) {
|
|
||||||
errors.username = 'Author must be at most 60 characters.';
|
|
||||||
}
|
|
||||||
return errors;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function EditItemPage() {
|
|
||||||
const { id } = useParams<{ id: string }>();
|
|
||||||
const editingId = id ? Number(id) : null;
|
|
||||||
const isCreate = editingId === null;
|
|
||||||
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const { username: adminUsername } = useAuth();
|
|
||||||
|
|
||||||
const [values, setValues] = useState<AdminItemInput>({
|
|
||||||
title: '',
|
|
||||||
url: '',
|
|
||||||
points: 0,
|
|
||||||
username: adminUsername ?? '',
|
|
||||||
content: '',
|
|
||||||
});
|
|
||||||
const [contentHtml, setContentHtml] = useState('');
|
|
||||||
const [loadError, setLoadError] = useState<string | null>(null);
|
|
||||||
const [loading, setLoading] = useState(isCreate ? false : true);
|
|
||||||
const [saving, setSaving] = useState(false);
|
|
||||||
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({});
|
|
||||||
const [formError, setFormError] = useState<string | null>(null);
|
|
||||||
const [autoSave, setAutoSave] = useState(false);
|
|
||||||
const [autoSaveStatus, setAutoSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'paused'>(
|
|
||||||
'idle',
|
|
||||||
);
|
|
||||||
const usernameTouched = useRef(false);
|
|
||||||
|
|
||||||
// After an auto-save in create mode, switch to updating the new item.
|
|
||||||
const [createdId, setCreatedId] = useState<number | null>(null);
|
|
||||||
const targetId = editingId ?? createdId;
|
|
||||||
|
|
||||||
const [initialValues, setInitialValues] = useState<AdminItemInput | null>(null);
|
|
||||||
const lastSavedSignature = useRef<string | null>(null);
|
|
||||||
|
|
||||||
// Pre-fill the author once the session restore has finished (the
|
|
||||||
// username is only known asynchronously) — unless the admin already
|
|
||||||
// typed into the field.
|
|
||||||
useEffect(() => {
|
|
||||||
if (adminUsername && !usernameTouched.current) {
|
|
||||||
setValues((current) =>
|
|
||||||
current.username === '' ? { ...current, username: adminUsername } : current,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}, [adminUsername]);
|
|
||||||
|
|
||||||
// Load the item in edit mode.
|
|
||||||
useEffect(() => {
|
|
||||||
if (editingId === null) {
|
|
||||||
setInitialValues({ title: '', url: '', points: 0, username: adminUsername ?? '', content: '' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let active = true;
|
|
||||||
adminGetItem(editingId)
|
|
||||||
.then((item) => {
|
|
||||||
if (!active) return;
|
|
||||||
const loaded: AdminItemInput = {
|
|
||||||
title: item.title,
|
|
||||||
url: item.url,
|
|
||||||
points: item.points,
|
|
||||||
username: item.username,
|
|
||||||
content: item.content,
|
|
||||||
};
|
|
||||||
setValues(loaded);
|
|
||||||
setContentHtml(item.content);
|
|
||||||
setInitialValues(loaded);
|
|
||||||
lastSavedSignature.current = signature(loaded, item.content);
|
|
||||||
setLoadError(null);
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
if (!active) return;
|
|
||||||
setLoadError(err instanceof ApiError ? err.message : 'Could not load the item.');
|
|
||||||
})
|
|
||||||
.finally(() => {
|
|
||||||
if (active) setLoading(false);
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
active = false;
|
|
||||||
};
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [editingId]);
|
|
||||||
|
|
||||||
const form = useMemo(
|
|
||||||
() => ({ ...values, content: contentHtml }),
|
|
||||||
[values, contentHtml],
|
|
||||||
);
|
|
||||||
|
|
||||||
const dirty = useMemo(
|
|
||||||
() =>
|
|
||||||
initialValues !== null &&
|
|
||||||
signature(form, contentHtml) !== lastSavedSignature.current,
|
|
||||||
[form, contentHtml, initialValues],
|
|
||||||
);
|
|
||||||
|
|
||||||
const save = useCallback(
|
|
||||||
async (mode: 'manual' | 'auto' = 'manual') => {
|
|
||||||
const errors = validate(form);
|
|
||||||
setFieldErrors(errors);
|
|
||||||
if (Object.keys(errors).length > 0) {
|
|
||||||
if (mode === 'auto') {
|
|
||||||
setAutoSaveStatus('paused');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
setFormError('Please fix the highlighted fields and try again.');
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
setFormError(null);
|
|
||||||
setSaving(true);
|
|
||||||
if (mode === 'auto') setAutoSaveStatus('saving');
|
|
||||||
try {
|
|
||||||
const payload: AdminItemInput = {
|
|
||||||
title: form.title.trim(),
|
|
||||||
url: form.url.trim(),
|
|
||||||
points: form.points,
|
|
||||||
username: form.username.trim(),
|
|
||||||
content: contentHtml,
|
|
||||||
};
|
|
||||||
const saved =
|
|
||||||
targetId !== null
|
|
||||||
? await adminUpdateItem(targetId, payload)
|
|
||||||
: await adminCreateItem(payload);
|
|
||||||
lastSavedSignature.current = signature(payload, contentHtml);
|
|
||||||
if (createdId === null && editingId === null) {
|
|
||||||
setCreatedId(saved.id);
|
|
||||||
}
|
|
||||||
setAutoSaveStatus('saved');
|
|
||||||
return true;
|
|
||||||
} catch (err) {
|
|
||||||
const message =
|
|
||||||
err instanceof ApiError ? err.message : 'Saving the item failed.';
|
|
||||||
if (mode === 'auto') {
|
|
||||||
setAutoSaveStatus('paused');
|
|
||||||
} else {
|
|
||||||
setFormError(message);
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
} finally {
|
|
||||||
setSaving(false);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[form, contentHtml, targetId, createdId, editingId],
|
|
||||||
);
|
|
||||||
|
|
||||||
// Debounced auto-save: fire 2s after the last change when enabled.
|
|
||||||
useEffect(() => {
|
|
||||||
if (!autoSave || loading || saving || !dirty) return;
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
void save('auto');
|
|
||||||
}, AUTO_SAVE_DELAY_MS);
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}, [autoSave, loading, saving, dirty, form, save]);
|
|
||||||
|
|
||||||
const onSubmit = async (event: FormEvent) => {
|
|
||||||
event.preventDefault();
|
|
||||||
const ok = await save('manual');
|
|
||||||
if (ok) {
|
|
||||||
navigate('/admin', { state: { notice: `“${values.title.trim()}” was saved.` } });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const onField = (field: keyof AdminItemInput) => (value: string | number) => {
|
|
||||||
if (field === 'username') usernameTouched.current = true;
|
|
||||||
setValues((current) => ({ ...current, [field]: value }));
|
|
||||||
};
|
|
||||||
|
|
||||||
if (loading) {
|
|
||||||
return (
|
|
||||||
<div className="flex justify-center py-16" role="status">
|
|
||||||
<span className="animate-pulse text-sm text-slate-500">Loading item…</span>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (loadError) {
|
|
||||||
return (
|
|
||||||
<div className="text-center">
|
|
||||||
<h1 className="mb-2 text-2xl font-bold text-slate-900">Item not found</h1>
|
|
||||||
<p className="mb-6 text-sm text-slate-600">{loadError}</p>
|
|
||||||
<Link to="/admin" className="btn">
|
|
||||||
<ArrowLeft size={15} aria-hidden="true" />
|
|
||||||
Back to items
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const autoSaveHint =
|
|
||||||
autoSaveStatus === 'saving'
|
|
||||||
? 'Saving…'
|
|
||||||
: autoSaveStatus === 'saved'
|
|
||||||
? 'All changes saved'
|
|
||||||
: autoSaveStatus === 'paused'
|
|
||||||
? 'Auto-save paused (fix validation errors)'
|
|
||||||
: 'Off';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div>
|
|
||||||
<div className="mb-6 flex flex-wrap items-center justify-between gap-3">
|
|
||||||
<div>
|
|
||||||
<Link
|
|
||||||
to="/admin"
|
|
||||||
className="mb-2 inline-flex items-center gap-1.5 text-sm text-slate-500 hover:text-slate-800"
|
|
||||||
>
|
|
||||||
<ArrowLeft size={14} aria-hidden="true" />
|
|
||||||
Back to items
|
|
||||||
</Link>
|
|
||||||
<h1 className="text-2xl font-bold text-slate-900">
|
|
||||||
{isCreate && createdId === null ? 'New item' : `Edit item #${targetId}`}
|
|
||||||
</h1>
|
|
||||||
</div>
|
|
||||||
<label className="flex items-center gap-2 text-sm text-slate-600">
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
|
|
||||||
checked={autoSave}
|
|
||||||
disabled={saving}
|
|
||||||
onChange={(event) => {
|
|
||||||
setAutoSave(event.target.checked);
|
|
||||||
if (!event.target.checked) setAutoSaveStatus('idle');
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
Auto-save <span className="text-xs text-slate-400">({autoSaveHint})</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{formError && (
|
|
||||||
<div
|
|
||||||
className="mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"
|
|
||||||
role="alert"
|
|
||||||
>
|
|
||||||
{formError}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<form
|
|
||||||
onSubmit={(event) => void onSubmit(event)}
|
|
||||||
className="space-y-5 rounded-xl border border-slate-200 bg-white p-6 shadow-sm"
|
|
||||||
noValidate
|
|
||||||
>
|
|
||||||
<div>
|
|
||||||
<label htmlFor="item-title" className="mb-1 block text-sm font-medium text-slate-700">
|
|
||||||
Title <span className="text-red-600" aria-hidden="true">*</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="item-title"
|
|
||||||
className="input"
|
|
||||||
value={values.title}
|
|
||||||
maxLength={300}
|
|
||||||
placeholder="Headline of the story"
|
|
||||||
onChange={(event) => onField('title')(event.target.value)}
|
|
||||||
/>
|
|
||||||
{fieldErrors.title && (
|
|
||||||
<p className="mt-1 text-sm text-red-600" role="alert">
|
|
||||||
{fieldErrors.title}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid gap-5 sm:grid-cols-2">
|
|
||||||
<div>
|
|
||||||
<label htmlFor="item-url" className="mb-1 block text-sm font-medium text-slate-700">
|
|
||||||
URL <span className="text-xs font-normal text-slate-400">(optional)</span>
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="item-url"
|
|
||||||
className="input"
|
|
||||||
type="url"
|
|
||||||
value={values.url}
|
|
||||||
maxLength={500}
|
|
||||||
placeholder="https://example.com/story"
|
|
||||||
onChange={(event) => onField('url')(event.target.value)}
|
|
||||||
/>
|
|
||||||
{fieldErrors.url && (
|
|
||||||
<p className="mt-1 text-sm text-red-600" role="alert">
|
|
||||||
{fieldErrors.url}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-4">
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="item-points"
|
|
||||||
className="mb-1 block text-sm font-medium text-slate-700"
|
|
||||||
>
|
|
||||||
Points
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="item-points"
|
|
||||||
className="input"
|
|
||||||
type="number"
|
|
||||||
min={0}
|
|
||||||
step={1}
|
|
||||||
value={Number.isFinite(values.points) ? values.points : 0}
|
|
||||||
onChange={(event) =>
|
|
||||||
onField('points')(event.target.value === '' ? 0 : Number(event.target.value))
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
{fieldErrors.points && (
|
|
||||||
<p className="mt-1 text-sm text-red-600" role="alert">
|
|
||||||
{fieldErrors.points}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
htmlFor="item-username"
|
|
||||||
className="mb-1 block text-sm font-medium text-slate-700"
|
|
||||||
>
|
|
||||||
Author
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
id="item-username"
|
|
||||||
className="input"
|
|
||||||
value={values.username}
|
|
||||||
maxLength={60}
|
|
||||||
placeholder="username"
|
|
||||||
onChange={(event) => onField('username')(event.target.value)}
|
|
||||||
/>
|
|
||||||
{fieldErrors.username && (
|
|
||||||
<p className="mt-1 text-sm text-red-600" role="alert">
|
|
||||||
{fieldErrors.username}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div>
|
|
||||||
<span className="mb-1 block text-sm font-medium text-slate-700">Content</span>
|
|
||||||
<LexicalEditor
|
|
||||||
initialHtml={contentHtml}
|
|
||||||
onChange={(html) => setContentHtml(html)}
|
|
||||||
placeholder="Write the story body…"
|
|
||||||
/>
|
|
||||||
<p className="mt-1 text-xs text-slate-400">
|
|
||||||
Rich text: bold, italic, underline, headings, lists, links and code blocks.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3 border-t border-slate-100 pt-5">
|
|
||||||
<button type="submit" className="btn" disabled={saving}>
|
|
||||||
{saving ? (
|
|
||||||
<Loader2 size={15} className="animate-spin" aria-hidden="true" />
|
|
||||||
) : (
|
|
||||||
<Save size={15} aria-hidden="true" />
|
|
||||||
)}
|
|
||||||
{saving ? 'Saving…' : isCreate && createdId === null ? 'Create item' : 'Save changes'}
|
|
||||||
</button>
|
|
||||||
<Link to="/admin" className="btn-secondary">
|
|
||||||
Cancel
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function signature(values: AdminItemInput, content: string): string {
|
|
||||||
return JSON.stringify({
|
|
||||||
title: values.title,
|
|
||||||
url: values.url,
|
|
||||||
points: values.points,
|
|
||||||
username: values.username,
|
|
||||||
content,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export default EditItemPage;
|
|
||||||
@@ -14,8 +14,9 @@ type FeedSource = 'api' | 'sample';
|
|||||||
* Homepage: featured (hero) article, search bar, article grid built from
|
* Homepage: featured (hero) article, search bar, article grid built from
|
||||||
* ArticleCard components, and a pagination placeholder.
|
* ArticleCard components, and a pagination placeholder.
|
||||||
*
|
*
|
||||||
* Articles are loaded from `GET /api/v1/articles`; until that backend
|
* Articles are loaded from `GET /api/v1/articles`; when the backend is
|
||||||
* endpoint exists the page falls back to sample data (clearly labelled).
|
* unreachable or has no published articles yet the page falls back to
|
||||||
|
* sample data (clearly labelled).
|
||||||
*/
|
*/
|
||||||
export function Home() {
|
export function Home() {
|
||||||
const [articles, setArticles] = useState<Article[]>([]);
|
const [articles, setArticles] = useState<Article[]>([]);
|
||||||
@@ -38,8 +39,8 @@ export function Home() {
|
|||||||
})
|
})
|
||||||
.catch((error: unknown) => {
|
.catch((error: unknown) => {
|
||||||
if (!active) return;
|
if (!active) return;
|
||||||
// 404 (endpoint not implemented yet) or network failure: fall back to
|
// Network failure (or non-2xx): fall back to sample data so the
|
||||||
// sample data so the UI stays useful without a running backend.
|
// UI stays useful without a running backend.
|
||||||
if (!(error instanceof ApiError)) {
|
if (!(error instanceof ApiError)) {
|
||||||
console.error('Unexpected error while loading articles:', error);
|
console.error('Unexpected error while loading articles:', error);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,24 +4,28 @@
|
|||||||
*/
|
*/
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import {
|
import {
|
||||||
adminCreateItem,
|
adminCreateArticle,
|
||||||
adminDeleteItem,
|
adminDeleteArticle,
|
||||||
adminGetItem,
|
adminGetArticle,
|
||||||
adminListItems,
|
adminListArticles,
|
||||||
adminUpdateItem,
|
adminListAuthors,
|
||||||
|
adminListCategories,
|
||||||
|
adminUpdateArticle,
|
||||||
} from '../../api/admin';
|
} from '../../api/admin';
|
||||||
import { ApiError, TOKEN_KEY } from '../../api/client';
|
import { ApiError, TOKEN_KEY } from '../../api/client';
|
||||||
import type { AdminItemsPage } from '../../types/admin';
|
import type { AdminArticlesPage } from '../../types/admin';
|
||||||
|
|
||||||
const SAMPLE_PAGE: AdminItemsPage = {
|
const SAMPLE_PAGE: AdminArticlesPage = {
|
||||||
items: [
|
articles: [
|
||||||
{
|
{
|
||||||
id: 1,
|
id: 1,
|
||||||
title: 'First story',
|
title: 'First story',
|
||||||
url: 'https://example.com/first',
|
|
||||||
points: 3,
|
|
||||||
username: 'alice',
|
|
||||||
content: '<p>Hello</p>',
|
content: '<p>Hello</p>',
|
||||||
|
author_id: 7,
|
||||||
|
category_id: 1,
|
||||||
|
author: { id: 7, name: 'Ada Lovelace', email: 'ada@example.com' },
|
||||||
|
category: { id: 1, name: 'Technology', slug: 'technology' },
|
||||||
|
published: true,
|
||||||
created_at: '2024-05-01T12:00:00Z',
|
created_at: '2024-05-01T12:00:00Z',
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -50,11 +54,11 @@ describe('admin API client', () => {
|
|||||||
vi.stubGlobal('fetch', fetchMock);
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('listItems builds the query string from all parameters', async () => {
|
it('listArticles builds the query string from all parameters', async () => {
|
||||||
localStorage.setItem(TOKEN_KEY, 'admin-token');
|
localStorage.setItem(TOKEN_KEY, 'admin-token');
|
||||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
|
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
|
||||||
|
|
||||||
const res = await adminListItems({
|
const res = await adminListArticles({
|
||||||
page: 2,
|
page: 2,
|
||||||
pageSize: 50,
|
pageSize: 50,
|
||||||
search: ' breaking news ',
|
search: ' breaking news ',
|
||||||
@@ -66,7 +70,7 @@ describe('admin API client', () => {
|
|||||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||||
// URLSearchParams encodes spaces as `+`.
|
// URLSearchParams encodes spaces as `+`.
|
||||||
expect(url).toBe(
|
expect(url).toBe(
|
||||||
'/api/v1/admin/items?page=2&page_size=50&search=breaking+news&sort_by=title&sort_order=asc',
|
'/api/v1/admin/articles?page=2&page_size=50&search=breaking+news&sort_by=title&sort_order=asc',
|
||||||
);
|
);
|
||||||
expect(init.method).toBeUndefined();
|
expect(init.method).toBeUndefined();
|
||||||
// The JWT is attached as a Bearer token.
|
// The JWT is attached as a Bearer token.
|
||||||
@@ -75,10 +79,10 @@ describe('admin API client', () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('listItems omits the search parameter when empty', async () => {
|
it('listArticles omits the search parameter when empty', async () => {
|
||||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
|
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE));
|
||||||
|
|
||||||
await adminListItems({
|
await adminListArticles({
|
||||||
page: 1,
|
page: 1,
|
||||||
pageSize: 20,
|
pageSize: 20,
|
||||||
search: ' ',
|
search: ' ',
|
||||||
@@ -88,79 +92,101 @@ describe('admin API client', () => {
|
|||||||
|
|
||||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||||
expect(url).toBe(
|
expect(url).toBe(
|
||||||
'/api/v1/admin/items?page=1&page_size=20&sort_by=created_at&sort_order=desc',
|
'/api/v1/admin/articles?page=1&page_size=20&sort_by=created_at&sort_order=desc',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('getItem requests the item by id', async () => {
|
it('getArticle requests the article by id', async () => {
|
||||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
|
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.articles[0]));
|
||||||
|
|
||||||
await adminGetItem(7);
|
await adminGetArticle(7);
|
||||||
|
|
||||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||||
expect(url).toBe('/api/v1/admin/items/7');
|
expect(url).toBe('/api/v1/admin/articles/7');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('createItem POSTs the payload', async () => {
|
it('createArticle POSTs the payload', async () => {
|
||||||
fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.items[0]));
|
fetchMock.mockResolvedValue(jsonResponse(201, SAMPLE_PAGE.articles[0]));
|
||||||
|
|
||||||
await adminCreateItem({
|
await adminCreateArticle({
|
||||||
title: 'New story',
|
title: 'New story',
|
||||||
url: '',
|
|
||||||
points: 0,
|
|
||||||
username: 'root',
|
|
||||||
content: '<p>Body</p>',
|
content: '<p>Body</p>',
|
||||||
|
author_id: 7,
|
||||||
|
category_id: 2,
|
||||||
|
published: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||||
expect(url).toBe('/api/v1/admin/items');
|
expect(url).toBe('/api/v1/admin/articles');
|
||||||
expect(init.method).toBe('POST');
|
expect(init.method).toBe('POST');
|
||||||
expect(JSON.parse(init.body as string)).toEqual({
|
expect(JSON.parse(init.body as string)).toEqual({
|
||||||
title: 'New story',
|
title: 'New story',
|
||||||
url: '',
|
|
||||||
points: 0,
|
|
||||||
username: 'root',
|
|
||||||
content: '<p>Body</p>',
|
content: '<p>Body</p>',
|
||||||
|
author_id: 7,
|
||||||
|
category_id: 2,
|
||||||
|
published: false,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('updateItem PUTs the payload to the item route', async () => {
|
it('updateArticle PUTs the payload to the article route', async () => {
|
||||||
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.items[0]));
|
fetchMock.mockResolvedValue(jsonResponse(200, SAMPLE_PAGE.articles[0]));
|
||||||
|
|
||||||
await adminUpdateItem(7, {
|
await adminUpdateArticle(7, {
|
||||||
title: 'Updated',
|
title: 'Updated',
|
||||||
url: 'https://example.com/new',
|
content: '<p>Body</p>',
|
||||||
points: 9,
|
author_id: 8,
|
||||||
username: 'root',
|
category_id: 1,
|
||||||
content: '',
|
published: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||||
expect(url).toBe('/api/v1/admin/items/7');
|
expect(url).toBe('/api/v1/admin/articles/7');
|
||||||
expect(init.method).toBe('PUT');
|
expect(init.method).toBe('PUT');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('deleteItem sends DELETE and resolves to undefined on 204', async () => {
|
it('deleteArticle sends DELETE and resolves to undefined on 204', async () => {
|
||||||
fetchMock.mockResolvedValue({
|
fetchMock.mockResolvedValue({
|
||||||
ok: true,
|
ok: true,
|
||||||
status: 204,
|
status: 204,
|
||||||
statusText: 'No Content',
|
statusText: 'No Content',
|
||||||
} as Response);
|
} as Response);
|
||||||
|
|
||||||
await expect(adminDeleteItem(7)).resolves.toBeUndefined();
|
await expect(adminDeleteArticle(7)).resolves.toBeUndefined();
|
||||||
|
|
||||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||||
expect(url).toBe('/api/v1/admin/items/7');
|
expect(url).toBe('/api/v1/admin/articles/7');
|
||||||
expect(init.method).toBe('DELETE');
|
expect(init.method).toBe('DELETE');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('listAuthors requests the author reference list', async () => {
|
||||||
|
const authors = [{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com', bio: null }];
|
||||||
|
fetchMock.mockResolvedValue(jsonResponse(200, authors));
|
||||||
|
|
||||||
|
const res = await adminListAuthors();
|
||||||
|
|
||||||
|
expect(res).toEqual(authors);
|
||||||
|
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||||
|
expect(url).toBe('/api/v1/admin/authors');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('listCategories requests the category reference list', async () => {
|
||||||
|
const categories = [{ id: 1, name: 'Technology', slug: 'technology' }];
|
||||||
|
fetchMock.mockResolvedValue(jsonResponse(200, categories));
|
||||||
|
|
||||||
|
const res = await adminListCategories();
|
||||||
|
|
||||||
|
expect(res).toEqual(categories);
|
||||||
|
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||||
|
expect(url).toBe('/api/v1/admin/categories');
|
||||||
|
});
|
||||||
|
|
||||||
it('surfaces the backend error for non-admin access (403)', async () => {
|
it('surfaces the backend error for non-admin access (403)', async () => {
|
||||||
localStorage.setItem(TOKEN_KEY, 'non-admin-token');
|
localStorage.setItem(TOKEN_KEY, 'non-admin-token');
|
||||||
fetchMock.mockResolvedValue(
|
fetchMock.mockResolvedValue(
|
||||||
jsonResponse(403, { detail: 'Admin access required', code: 'forbidden' }),
|
jsonResponse(403, { detail: 'Admin access required', code: 'forbidden' }),
|
||||||
);
|
);
|
||||||
|
|
||||||
const err = await adminListItems({
|
const err = await adminListArticles({
|
||||||
page: 1,
|
page: 1,
|
||||||
pageSize: 20,
|
pageSize: 20,
|
||||||
search: '',
|
search: '',
|
||||||
|
|||||||
@@ -6,33 +6,49 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|||||||
import { MemoryRouter } from 'react-router-dom';
|
import { MemoryRouter } from 'react-router-dom';
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import {
|
import {
|
||||||
adminDeleteItem,
|
adminDeleteArticle,
|
||||||
adminListItems,
|
adminListArticles,
|
||||||
} from '../../api/admin';
|
} from '../../api/admin';
|
||||||
import { AdminDashboard } from '../../pages/AdminDashboard';
|
import { AdminDashboard } from '../../pages/AdminDashboard';
|
||||||
import type { AdminItemsPage } from '../../types/admin';
|
import type { AdminArticlesPage } from '../../types/admin';
|
||||||
|
|
||||||
vi.mock('../../api/admin', () => ({
|
vi.mock('../../api/admin', () => ({
|
||||||
adminListItems: vi.fn(),
|
adminListArticles: vi.fn(),
|
||||||
adminGetItem: vi.fn(),
|
adminGetArticle: vi.fn(),
|
||||||
adminCreateItem: vi.fn(),
|
adminCreateArticle: vi.fn(),
|
||||||
adminUpdateItem: vi.fn(),
|
adminUpdateArticle: vi.fn(),
|
||||||
adminDeleteItem: vi.fn(),
|
adminDeleteArticle: vi.fn(),
|
||||||
|
adminListAuthors: vi.fn(),
|
||||||
|
adminListCategories: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const items = (count: number, offset = 0) =>
|
const AUTHORS = [
|
||||||
Array.from({ length: count }, (_, i) => ({
|
{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
|
||||||
id: i + 1 + offset,
|
{ id: 2, name: 'Grace Hopper', email: 'grace@example.com' },
|
||||||
title: `Story ${i + 1 + offset}`,
|
];
|
||||||
url: `https://example.com/story-${i + 1 + offset}`,
|
const CATEGORIES = [
|
||||||
points: i + offset,
|
{ id: 1, name: 'Technology', slug: 'technology' },
|
||||||
username: 'alice',
|
{ id: 2, name: 'Science', slug: 'science' },
|
||||||
content: `<p>Body ${i + 1 + offset}</p>`,
|
];
|
||||||
created_at: `2024-05-0${(i % 9) + 1}T12:00:00Z`,
|
|
||||||
}));
|
|
||||||
|
|
||||||
const page = (overrides: Partial<AdminItemsPage> = {}): AdminItemsPage => ({
|
const article = (id: number, overrides: Record<string, unknown> = {}) => ({
|
||||||
items: items(3),
|
id,
|
||||||
|
title: `Story ${id}`,
|
||||||
|
content: `<p>Body ${id}</p>`,
|
||||||
|
author_id: AUTHORS[(id - 1) % AUTHORS.length].id,
|
||||||
|
category_id: CATEGORIES[(id - 1) % CATEGORIES.length].id,
|
||||||
|
author: AUTHORS[(id - 1) % AUTHORS.length],
|
||||||
|
category: CATEGORIES[(id - 1) % CATEGORIES.length],
|
||||||
|
published: true,
|
||||||
|
created_at: `2024-05-0${(id % 9) + 1}T12:00:00Z`,
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
const articles = (count: number, offset = 0) =>
|
||||||
|
Array.from({ length: count }, (_, i) => article(i + 1 + offset));
|
||||||
|
|
||||||
|
const page = (overrides: Partial<AdminArticlesPage> = {}): AdminArticlesPage => ({
|
||||||
|
articles: articles(3),
|
||||||
total: 3,
|
total: 3,
|
||||||
page: 1,
|
page: 1,
|
||||||
page_size: 20,
|
page_size: 20,
|
||||||
@@ -47,7 +63,7 @@ function lastCallParams(): {
|
|||||||
sortBy: string;
|
sortBy: string;
|
||||||
sortOrder: string;
|
sortOrder: string;
|
||||||
} {
|
} {
|
||||||
const calls = vi.mocked(adminListItems).mock.calls;
|
const calls = vi.mocked(adminListArticles).mock.calls;
|
||||||
const last = calls[calls.length - 1][0];
|
const last = calls[calls.length - 1][0];
|
||||||
return {
|
return {
|
||||||
page: last.page,
|
page: last.page,
|
||||||
@@ -71,23 +87,27 @@ function renderDashboard() {
|
|||||||
describe('AdminDashboard', () => {
|
describe('AdminDashboard', () => {
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks();
|
vi.clearAllMocks();
|
||||||
vi.mocked(adminListItems).mockResolvedValue(page());
|
vi.mocked(adminListArticles).mockResolvedValue(page());
|
||||||
vi.mocked(adminDeleteItem).mockResolvedValue(undefined);
|
vi.mocked(adminDeleteArticle).mockResolvedValue(undefined);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders the fetched items with their details', async () => {
|
it('renders the fetched articles with their details', async () => {
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
|
|
||||||
expect(await screen.findByText('Story 1')).toBeInTheDocument();
|
expect(await screen.findByText('Story 1')).toBeInTheDocument();
|
||||||
expect(screen.getByText('Story 2')).toBeInTheDocument();
|
expect(screen.getByText('Story 2')).toBeInTheDocument();
|
||||||
expect(screen.getByText('Story 3')).toBeInTheDocument();
|
expect(screen.getByText('Story 3')).toBeInTheDocument();
|
||||||
// All three seed items belong to "alice".
|
// Each row shows its author and category.
|
||||||
expect(screen.getAllByText('alice').length).toBe(3);
|
expect(screen.getAllByText('Ada Lovelace').length).toBeGreaterThan(0);
|
||||||
expect(screen.getByText('https://example.com/story-1')).toBeInTheDocument();
|
expect(screen.getAllByText('Grace Hopper').length).toBeGreaterThan(0);
|
||||||
|
expect(screen.getAllByText('Technology').length).toBeGreaterThan(0);
|
||||||
expect(screen.getByText('Showing 1–3 of 3')).toBeInTheDocument();
|
expect(screen.getByText('Showing 1–3 of 3')).toBeInTheDocument();
|
||||||
|
// Published badges: one per row (the "Published" column header is a
|
||||||
|
// columnheader role, not a cell).
|
||||||
|
expect(screen.getAllByRole('cell', { name: 'Published' })).toHaveLength(3);
|
||||||
// Edit links point at the edit route.
|
// Edit links point at the edit route.
|
||||||
const editLinks = screen.getAllByRole('link', { name: /edit/i });
|
const editLinks = screen.getAllByRole('link', { name: /edit/i });
|
||||||
expect(editLinks[0].getAttribute('href')).toBe('/admin/items/1/edit');
|
expect(editLinks[0].getAttribute('href')).toBe('/admin/articles/1/edit');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('requests the initial page with the default parameters', async () => {
|
it('requests the initial page with the default parameters', async () => {
|
||||||
@@ -106,7 +126,7 @@ describe('AdminDashboard', () => {
|
|||||||
renderDashboard();
|
renderDashboard();
|
||||||
await screen.findByText('Story 1');
|
await screen.findByText('Story 1');
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText('Search items'), {
|
fireEvent.change(screen.getByLabelText('Search articles'), {
|
||||||
target: { value: 'breaking' },
|
target: { value: 'breaking' },
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -134,13 +154,13 @@ describe('AdminDashboard', () => {
|
|||||||
expect(lastCallParams().sortOrder).toBe('desc');
|
expect(lastCallParams().sortOrder).toBe('desc');
|
||||||
|
|
||||||
// Switching columns starts on ascending again.
|
// Switching columns starts on ascending again.
|
||||||
fireEvent.click(screen.getByRole('button', { name: /sort by points/i }));
|
fireEvent.click(screen.getByRole('button', { name: /sort by creation date/i }));
|
||||||
expect(lastCallParams().sortBy).toBe('points');
|
expect(lastCallParams().sortBy).toBe('created_at');
|
||||||
expect(lastCallParams().sortOrder).toBe('asc');
|
expect(lastCallParams().sortOrder).toBe('asc');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('navigates pages and changes the page size', async () => {
|
it('navigates pages and changes the page size', async () => {
|
||||||
vi.mocked(adminListItems).mockResolvedValue(
|
vi.mocked(adminListArticles).mockResolvedValue(
|
||||||
page({ total: 45, page: 2, total_pages: 3 }),
|
page({ total: 45, page: 2, total_pages: 3 }),
|
||||||
);
|
);
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
@@ -160,23 +180,23 @@ describe('AdminDashboard', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('shows an empty state when nothing matches the search', async () => {
|
it('shows an empty state when nothing matches the search', async () => {
|
||||||
vi.mocked(adminListItems).mockResolvedValue(page({ items: [], total: 0 }));
|
vi.mocked(adminListArticles).mockResolvedValue(page({ articles: [], total: 0 }));
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
await screen.findByText(/no items yet/i);
|
await screen.findByText(/no articles yet/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shows the error state with a retry action', async () => {
|
it('shows the error state with a retry action', async () => {
|
||||||
vi.mocked(adminListItems).mockRejectedValue(new Error('boom'));
|
vi.mocked(adminListArticles).mockRejectedValue(new Error('boom'));
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
|
|
||||||
expect(await screen.findByRole('alert')).toHaveTextContent(/boom|went wrong/i);
|
expect(await screen.findByRole('alert')).toHaveTextContent(/boom|went wrong/i);
|
||||||
screen.getByRole('button', { name: /retry/i }).click();
|
screen.getByRole('button', { name: /retry/i }).click();
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(vi.mocked(adminListItems).mock.calls.length).toBeGreaterThanOrEqual(2),
|
expect(vi.mocked(adminListArticles).mock.calls.length).toBeGreaterThanOrEqual(2),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('deletes an item only after explicit confirmation', async () => {
|
it('deletes an article only after explicit confirmation', async () => {
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
await screen.findByText('Story 1');
|
await screen.findByText('Story 1');
|
||||||
|
|
||||||
@@ -184,30 +204,30 @@ describe('AdminDashboard', () => {
|
|||||||
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
||||||
const dialog = await screen.findByRole('dialog');
|
const dialog = await screen.findByRole('dialog');
|
||||||
expect(dialog).toHaveTextContent('Story 1');
|
expect(dialog).toHaveTextContent('Story 1');
|
||||||
expect(vi.mocked(adminDeleteItem)).not.toHaveBeenCalled();
|
expect(vi.mocked(adminDeleteArticle)).not.toHaveBeenCalled();
|
||||||
|
|
||||||
// Cancel: no API call.
|
// Cancel: no API call.
|
||||||
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
|
fireEvent.click(screen.getByRole('button', { name: /cancel/i }));
|
||||||
expect(await screen.findByText('Story 1')).toBeInTheDocument();
|
expect(await screen.findByText('Story 1')).toBeInTheDocument();
|
||||||
expect(vi.mocked(adminDeleteItem)).not.toHaveBeenCalled();
|
expect(vi.mocked(adminDeleteArticle)).not.toHaveBeenCalled();
|
||||||
|
|
||||||
// Confirm: the API is called and the list refreshes.
|
// Confirm: the API is called and the list refreshes.
|
||||||
const listCallsBefore = vi.mocked(adminListItems).mock.calls.length;
|
const listCallsBefore = vi.mocked(adminListArticles).mock.calls.length;
|
||||||
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
fireEvent.click(screen.getAllByRole('button', { name: /delete/i })[0]);
|
||||||
await screen.findByRole('dialog');
|
await screen.findByRole('dialog');
|
||||||
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
|
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
|
||||||
|
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
expect(vi.mocked(adminDeleteItem)).toHaveBeenCalledWith(1),
|
expect(vi.mocked(adminDeleteArticle)).toHaveBeenCalledWith(1),
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
vi.mocked(adminListItems).mock.calls.length,
|
vi.mocked(adminListArticles).mock.calls.length,
|
||||||
).toBeGreaterThanOrEqual(listCallsBefore + 1);
|
).toBeGreaterThanOrEqual(listCallsBefore + 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps the dialog open and shows the error when the delete fails', async () => {
|
it('keeps the dialog open and shows the error when the delete fails', async () => {
|
||||||
vi.mocked(adminDeleteItem).mockRejectedValue(
|
vi.mocked(adminDeleteArticle).mockRejectedValue(
|
||||||
new Error('Deleting the item failed.') as Error & { status?: number },
|
new Error('Deleting the article failed.') as Error & { status?: number },
|
||||||
);
|
);
|
||||||
renderDashboard();
|
renderDashboard();
|
||||||
await screen.findByText('Story 1');
|
await screen.findByText('Story 1');
|
||||||
@@ -217,7 +237,7 @@ describe('AdminDashboard', () => {
|
|||||||
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
|
fireEvent.click(screen.getByRole('button', { name: /yes, delete/i }));
|
||||||
|
|
||||||
const alert = await screen.findByRole('alert');
|
const alert = await screen.findByRole('alert');
|
||||||
expect(alert).toHaveTextContent(/deleting the item failed/i);
|
expect(alert).toHaveTextContent(/deleting the article failed/i);
|
||||||
// Dialog still open.
|
// Dialog still open.
|
||||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,15 +6,17 @@
|
|||||||
import { act, fireEvent, render, screen } from '@testing-library/react';
|
import { act, fireEvent, render, screen } from '@testing-library/react';
|
||||||
import { describe, expect, it, vi } from 'vitest';
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
import { DeleteConfirmation } from '../../components/DeleteConfirmation';
|
import { DeleteConfirmation } from '../../components/DeleteConfirmation';
|
||||||
import type { AdminItem } from '../../types/admin';
|
import type { AdminArticle } from '../../types/admin';
|
||||||
|
|
||||||
const ITEM: AdminItem = {
|
const ARTICLE: AdminArticle = {
|
||||||
id: 42,
|
id: 42,
|
||||||
title: 'Breaking: the sky is falling',
|
title: 'Breaking: the sky is falling',
|
||||||
url: 'https://example.com/sky',
|
|
||||||
points: 12,
|
|
||||||
username: 'alice',
|
|
||||||
content: '<p>…</p>',
|
content: '<p>…</p>',
|
||||||
|
author_id: 1,
|
||||||
|
category_id: 1,
|
||||||
|
author: { id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
|
||||||
|
category: { id: 1, name: 'Technology', slug: 'technology' },
|
||||||
|
published: true,
|
||||||
created_at: '2024-05-01T12:00:00Z',
|
created_at: '2024-05-01T12:00:00Z',
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -23,7 +25,7 @@ function renderModal(props: Partial<Parameters<typeof DeleteConfirmation>[0]> =
|
|||||||
const onCancel = vi.fn();
|
const onCancel = vi.fn();
|
||||||
const utils = render(
|
const utils = render(
|
||||||
<DeleteConfirmation
|
<DeleteConfirmation
|
||||||
item={ITEM}
|
article={ARTICLE}
|
||||||
onConfirm={onConfirm}
|
onConfirm={onConfirm}
|
||||||
onCancel={onCancel}
|
onCancel={onCancel}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -33,7 +35,7 @@ function renderModal(props: Partial<Parameters<typeof DeleteConfirmation>[0]> =
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('DeleteConfirmation', () => {
|
describe('DeleteConfirmation', () => {
|
||||||
it('shows the warning layout with the item title', () => {
|
it('shows the warning layout with the article title', () => {
|
||||||
renderModal();
|
renderModal();
|
||||||
|
|
||||||
const dialog = screen.getByRole('dialog');
|
const dialog = screen.getByRole('dialog');
|
||||||
@@ -104,8 +106,8 @@ describe('DeleteConfirmation', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('renders an error message when provided', () => {
|
it('renders an error message when provided', () => {
|
||||||
renderModal({ error: 'Deleting the item failed.' });
|
renderModal({ error: 'Deleting the article failed.' });
|
||||||
|
|
||||||
expect(screen.getByRole('alert')).toHaveTextContent('Deleting the item failed.');
|
expect(screen.getByRole('alert')).toHaveTextContent('Deleting the article failed.');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
/**
|
||||||
|
* Tests for the EditArticlePage (M6): create/edit form validation,
|
||||||
|
* reference-list prefill in create mode, prefill in edit mode, save
|
||||||
|
* flows (success navigation + error display) and the load-failure view.
|
||||||
|
* The Lexical editor is stubbed; its HTML contract is exercised through
|
||||||
|
* the `editor-body` textarea.
|
||||||
|
*/
|
||||||
|
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||||
|
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import {
|
||||||
|
adminCreateArticle,
|
||||||
|
adminGetArticle,
|
||||||
|
adminListAuthors,
|
||||||
|
adminListCategories,
|
||||||
|
adminUpdateArticle,
|
||||||
|
} from '../../api/admin';
|
||||||
|
import { ApiError } from '../../api/client';
|
||||||
|
import { EditArticlePage as EditPage } from '../../pages/EditArticlePage';
|
||||||
|
import type { AdminArticle } from '../../types/admin';
|
||||||
|
|
||||||
|
vi.mock('../../api/admin', () => ({
|
||||||
|
adminListArticles: vi.fn(),
|
||||||
|
adminGetArticle: vi.fn(),
|
||||||
|
adminCreateArticle: vi.fn(),
|
||||||
|
adminUpdateArticle: vi.fn(),
|
||||||
|
adminDeleteArticle: vi.fn(),
|
||||||
|
adminListAuthors: vi.fn(),
|
||||||
|
adminListCategories: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../components/LexicalEditor', () => ({
|
||||||
|
LexicalEditor: ({
|
||||||
|
initialHtml,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
initialHtml: string;
|
||||||
|
onChange: (html: string) => void;
|
||||||
|
placeholder?: string;
|
||||||
|
}) => (
|
||||||
|
<div data-testid="lexical-stub">
|
||||||
|
<textarea
|
||||||
|
data-testid="editor-body"
|
||||||
|
defaultValue={initialHtml}
|
||||||
|
aria-label="Article content"
|
||||||
|
onChange={(event) => onChange(event.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const AUTHORS = [
|
||||||
|
{ id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
|
||||||
|
{ id: 2, name: 'Grace Hopper', email: 'grace@example.com' },
|
||||||
|
];
|
||||||
|
const CATEGORIES = [
|
||||||
|
{ id: 1, name: 'Technology', slug: 'technology' },
|
||||||
|
{ id: 2, name: 'Science', slug: 'science' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ARTICLE: AdminArticle = {
|
||||||
|
id: 5,
|
||||||
|
title: 'Original headline',
|
||||||
|
content: '<p>Original body</p>',
|
||||||
|
author_id: 2,
|
||||||
|
category_id: 1,
|
||||||
|
author: AUTHORS[1],
|
||||||
|
category: CATEGORIES[0],
|
||||||
|
published: true,
|
||||||
|
created_at: '2024-05-01T12:00:00Z',
|
||||||
|
};
|
||||||
|
|
||||||
|
function DashboardStub() {
|
||||||
|
const location = useLocation();
|
||||||
|
const notice = (location.state as { notice?: string } | null)?.notice ?? '';
|
||||||
|
return (
|
||||||
|
<div data-testid="dashboard-stub">
|
||||||
|
{notice && <p data-testid="dashboard-notice">{notice}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderAt(path: string) {
|
||||||
|
return render(
|
||||||
|
<MemoryRouter
|
||||||
|
initialEntries={[path]}
|
||||||
|
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||||
|
>
|
||||||
|
<Routes>
|
||||||
|
<Route path="/admin" element={<DashboardStub />} />
|
||||||
|
<Route path="/admin/articles/new" element={<EditPage />} />
|
||||||
|
<Route path="/admin/articles/:id/edit" element={<EditPage />} />
|
||||||
|
</Routes>
|
||||||
|
</MemoryRouter>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('EditArticlePage (create)', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.mocked(adminListAuthors).mockResolvedValue(AUTHORS);
|
||||||
|
vi.mocked(adminListCategories).mockResolvedValue(CATEGORIES);
|
||||||
|
vi.mocked(adminCreateArticle).mockResolvedValue({ ...ARTICLE, id: 99 });
|
||||||
|
vi.mocked(adminUpdateArticle).mockResolvedValue(ARTICLE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('pre-fills the first author and category from the reference lists', async () => {
|
||||||
|
renderAt('/admin/articles/new');
|
||||||
|
|
||||||
|
await screen.findByTestId('lexical-stub');
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||||
|
);
|
||||||
|
expect(screen.getByLabelText(/^Category/)).toHaveValue('1');
|
||||||
|
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('New article');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('blocks submission with an empty title and does not call the API', async () => {
|
||||||
|
renderAt('/admin/articles/new');
|
||||||
|
await screen.findByTestId('lexical-stub');
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||||
|
);
|
||||||
|
|
||||||
|
screen.getByRole('button', { name: /create article/i }).click();
|
||||||
|
|
||||||
|
// The field error and the form-level error are both alerts.
|
||||||
|
const alerts = await screen.findAllByRole('alert');
|
||||||
|
expect(
|
||||||
|
alerts.some((el) => /title is required/i.test(el.textContent ?? '')),
|
||||||
|
).toBe(true);
|
||||||
|
expect(vi.mocked(adminCreateArticle)).not.toHaveBeenCalled();
|
||||||
|
expect(screen.queryByTestId('dashboard-stub')).not.toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('blocks submission with an empty body', async () => {
|
||||||
|
renderAt('/admin/articles/new');
|
||||||
|
await screen.findByTestId('lexical-stub');
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Only a title' } });
|
||||||
|
screen.getByRole('button', { name: /create article/i }).click();
|
||||||
|
|
||||||
|
const alerts = await screen.findAllByRole('alert');
|
||||||
|
expect(
|
||||||
|
alerts.some((el) => /content is required/i.test(el.textContent ?? '')),
|
||||||
|
).toBe(true);
|
||||||
|
expect(vi.mocked(adminCreateArticle)).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates the article with trimmed values and navigates back with a notice', async () => {
|
||||||
|
renderAt('/admin/articles/new');
|
||||||
|
await screen.findByTestId('lexical-stub');
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText(/^Title/), {
|
||||||
|
target: { value: ' Fresh story ' },
|
||||||
|
});
|
||||||
|
fireEvent.change(screen.getByLabelText(/^Author/), { target: { value: '2' } });
|
||||||
|
fireEvent.change(screen.getByLabelText(/^Category/), { target: { value: '2' } });
|
||||||
|
fireEvent.click(screen.getByLabelText(/^Published/));
|
||||||
|
fireEvent.change(screen.getByTestId('editor-body'), {
|
||||||
|
target: { value: '<p>Body <strong>here</strong></p>' },
|
||||||
|
});
|
||||||
|
|
||||||
|
screen.getByRole('button', { name: /create article/i }).click();
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(vi.mocked(adminCreateArticle)).toHaveBeenCalledWith({
|
||||||
|
title: 'Fresh story',
|
||||||
|
content: '<p>Body <strong>here</strong></p>',
|
||||||
|
author_id: 2,
|
||||||
|
category_id: 2,
|
||||||
|
published: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
||||||
|
expect(screen.getByTestId('dashboard-notice')).toHaveTextContent(
|
||||||
|
'“Fresh story” was saved.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('disables the create button while the request is in flight', async () => {
|
||||||
|
let resolveCreate!: (value: AdminArticle) => void;
|
||||||
|
vi.mocked(adminCreateArticle).mockReturnValueOnce(
|
||||||
|
new Promise<AdminArticle>((resolve) => {
|
||||||
|
resolveCreate = resolve;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
renderAt('/admin/articles/new');
|
||||||
|
await screen.findByTestId('lexical-stub');
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Pending' } });
|
||||||
|
fireEvent.change(screen.getByTestId('editor-body'), {
|
||||||
|
target: { value: '<p>Body</p>' },
|
||||||
|
});
|
||||||
|
screen.getByRole('button', { name: /create article/i }).click();
|
||||||
|
|
||||||
|
const button = screen.getByRole('button', { name: /create article/i });
|
||||||
|
await waitFor(() => expect(button).toBeDisabled());
|
||||||
|
|
||||||
|
resolveCreate({ ...ARTICLE, id: 99, title: 'Pending' });
|
||||||
|
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the backend error when the create request fails', async () => {
|
||||||
|
vi.mocked(adminCreateArticle).mockRejectedValue(
|
||||||
|
new ApiError(422, 'Validation failed', 'validation_error'),
|
||||||
|
);
|
||||||
|
renderAt('/admin/articles/new');
|
||||||
|
await screen.findByTestId('lexical-stub');
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByLabelText(/^Author/)).toHaveValue('1'),
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'x' } });
|
||||||
|
fireEvent.change(screen.getByTestId('editor-body'), {
|
||||||
|
target: { value: '<p>Body</p>' },
|
||||||
|
});
|
||||||
|
screen.getByRole('button', { name: /create article/i }).click();
|
||||||
|
|
||||||
|
expect(await screen.findByRole('alert')).toHaveTextContent('Validation failed');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('EditArticlePage (edit)', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
vi.mocked(adminListAuthors).mockResolvedValue(AUTHORS);
|
||||||
|
vi.mocked(adminListCategories).mockResolvedValue(CATEGORIES);
|
||||||
|
vi.mocked(adminGetArticle).mockResolvedValue(ARTICLE);
|
||||||
|
vi.mocked(adminUpdateArticle).mockResolvedValue(ARTICLE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('loads and pre-fills the article, then updates it on save', async () => {
|
||||||
|
renderAt('/admin/articles/5/edit');
|
||||||
|
|
||||||
|
// Loading state first.
|
||||||
|
expect(screen.getByRole('status')).toHaveTextContent(/loading article/i);
|
||||||
|
|
||||||
|
await screen.findByTestId('lexical-stub');
|
||||||
|
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(
|
||||||
|
'Edit article #5',
|
||||||
|
);
|
||||||
|
expect(screen.getByLabelText(/^Title/)).toHaveValue('Original headline');
|
||||||
|
expect(screen.getByLabelText(/^Author/)).toHaveValue('2');
|
||||||
|
expect(screen.getByLabelText(/^Category/)).toHaveValue('1');
|
||||||
|
expect(screen.getByLabelText(/^Published/)).toBeChecked();
|
||||||
|
expect(screen.getByTestId('editor-body')).toHaveValue('<p>Original body</p>');
|
||||||
|
|
||||||
|
fireEvent.change(screen.getByLabelText(/^Title/), {
|
||||||
|
target: { value: 'Retitled' },
|
||||||
|
});
|
||||||
|
screen.getByRole('button', { name: /save changes/i }).click();
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(vi.mocked(adminUpdateArticle)).toHaveBeenCalledWith(5, {
|
||||||
|
title: 'Retitled',
|
||||||
|
content: '<p>Original body</p>',
|
||||||
|
author_id: 2,
|
||||||
|
category_id: 1,
|
||||||
|
published: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the not-found view when the article cannot be loaded', async () => {
|
||||||
|
vi.mocked(adminGetArticle).mockRejectedValue(
|
||||||
|
new ApiError(404, 'Article not found', 'not_found'),
|
||||||
|
);
|
||||||
|
renderAt('/admin/articles/999/edit');
|
||||||
|
|
||||||
|
expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(
|
||||||
|
/article not found/i,
|
||||||
|
);
|
||||||
|
expect(screen.getByRole('link', { name: /back to articles/i })).toHaveAttribute(
|
||||||
|
'href',
|
||||||
|
'/admin',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,275 +0,0 @@
|
|||||||
/**
|
|
||||||
* Tests for the EditItemPage (M6): create/edit form validation, prefill
|
|
||||||
* in edit mode, save flows (success navigation + error display) and the
|
|
||||||
* load-failure view. The Lexical editor is stubbed; its HTML contract
|
|
||||||
* is exercised through the `editor-body` textarea.
|
|
||||||
*/
|
|
||||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
|
||||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
|
|
||||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
import type { Mock } from 'vitest';
|
|
||||||
import {
|
|
||||||
adminCreateItem,
|
|
||||||
adminGetItem,
|
|
||||||
adminUpdateItem,
|
|
||||||
} from '../../api/admin';
|
|
||||||
import { ApiError, TOKEN_KEY, me as clientMe } from '../../api/client';
|
|
||||||
import { AuthProvider } from '../../auth';
|
|
||||||
import { EditItemPage as EditPage } from '../../pages/EditItemPage';
|
|
||||||
import type { AdminItem } from '../../types/admin';
|
|
||||||
|
|
||||||
vi.mock('../../api/admin', () => ({
|
|
||||||
adminListItems: vi.fn(),
|
|
||||||
adminGetItem: vi.fn(),
|
|
||||||
adminCreateItem: vi.fn(),
|
|
||||||
adminUpdateItem: vi.fn(),
|
|
||||||
adminDeleteItem: vi.fn(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('../../components/LexicalEditor', () => ({
|
|
||||||
LexicalEditor: ({
|
|
||||||
initialHtml,
|
|
||||||
onChange,
|
|
||||||
}: {
|
|
||||||
initialHtml: string;
|
|
||||||
onChange: (html: string) => void;
|
|
||||||
placeholder?: string;
|
|
||||||
}) => (
|
|
||||||
<div data-testid="lexical-stub">
|
|
||||||
<textarea
|
|
||||||
data-testid="editor-body"
|
|
||||||
defaultValue={initialHtml}
|
|
||||||
aria-label="Item content"
|
|
||||||
onChange={(event) => onChange(event.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('../../api/client', async () => {
|
|
||||||
const actual = await vi.importActual<typeof import('../../api/client')>(
|
|
||||||
'../../api/client',
|
|
||||||
);
|
|
||||||
return {
|
|
||||||
...actual,
|
|
||||||
me: vi.fn(),
|
|
||||||
login: vi.fn(),
|
|
||||||
register: vi.fn(),
|
|
||||||
logout: vi.fn(),
|
|
||||||
TOKEN_KEY: 'AUTH_TOKEN',
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const ITEM: AdminItem = {
|
|
||||||
id: 5,
|
|
||||||
title: 'Original headline',
|
|
||||||
url: 'https://example.com/original',
|
|
||||||
points: 11,
|
|
||||||
username: 'alice',
|
|
||||||
content: '<p>Original body</p>',
|
|
||||||
created_at: '2024-05-01T12:00:00Z',
|
|
||||||
};
|
|
||||||
|
|
||||||
function DashboardStub() {
|
|
||||||
const location = useLocation();
|
|
||||||
const notice = (location.state as { notice?: string } | null)?.notice ?? '';
|
|
||||||
return (
|
|
||||||
<div data-testid="dashboard-stub">
|
|
||||||
{notice && <p data-testid="dashboard-notice">{notice}</p>}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderAt(path: string) {
|
|
||||||
return render(
|
|
||||||
<MemoryRouter
|
|
||||||
initialEntries={[path]}
|
|
||||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
|
||||||
>
|
|
||||||
<AuthProvider>
|
|
||||||
<Routes>
|
|
||||||
<Route path="/admin" element={<DashboardStub />} />
|
|
||||||
<Route path="/admin/items/new" element={<EditPage />} />
|
|
||||||
<Route path="/admin/items/:id/edit" element={<EditPage />} />
|
|
||||||
</Routes>
|
|
||||||
</AuthProvider>
|
|
||||||
</MemoryRouter>,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
describe('EditItemPage (create)', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
localStorage.clear();
|
|
||||||
vi.clearAllMocks();
|
|
||||||
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
|
|
||||||
localStorage.setItem(TOKEN_KEY, 'token');
|
|
||||||
vi.mocked(adminCreateItem).mockResolvedValue({ ...ITEM, id: 99 });
|
|
||||||
vi.mocked(adminUpdateItem).mockResolvedValue(ITEM);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('pre-fills the author with the signed-in admin', async () => {
|
|
||||||
renderAt('/admin/items/new');
|
|
||||||
|
|
||||||
await screen.findByTestId('lexical-stub');
|
|
||||||
expect(screen.getByLabelText('Author')).toHaveValue('root');
|
|
||||||
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('New item');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('blocks submission with an empty title and does not call the API', async () => {
|
|
||||||
renderAt('/admin/items/new');
|
|
||||||
await screen.findByTestId('lexical-stub');
|
|
||||||
|
|
||||||
screen.getByRole('button', { name: /create item/i }).click();
|
|
||||||
|
|
||||||
// The field error and the form-level error are both alerts.
|
|
||||||
const alerts = await screen.findAllByRole('alert');
|
|
||||||
expect(
|
|
||||||
alerts.some((el) => /title is required/i.test(el.textContent ?? '')),
|
|
||||||
).toBe(true);
|
|
||||||
expect(vi.mocked(adminCreateItem)).not.toHaveBeenCalled();
|
|
||||||
expect(screen.queryByTestId('dashboard-stub')).not.toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('rejects an invalid URL client-side', async () => {
|
|
||||||
renderAt('/admin/items/new');
|
|
||||||
await screen.findByTestId('lexical-stub');
|
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'Has url' } });
|
|
||||||
fireEvent.change(screen.getByLabelText(/^URL/), {
|
|
||||||
target: { value: 'not a url' },
|
|
||||||
});
|
|
||||||
screen.getByRole('button', { name: /create item/i }).click();
|
|
||||||
|
|
||||||
const alerts = await screen.findAllByRole('alert');
|
|
||||||
expect(
|
|
||||||
alerts.some((el) => /http:\/\/ or https:\/\//i.test(el.textContent ?? '')),
|
|
||||||
).toBe(true);
|
|
||||||
expect(vi.mocked(adminCreateItem)).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('creates the item with trimmed values and navigates back with a notice', async () => {
|
|
||||||
renderAt('/admin/items/new');
|
|
||||||
await screen.findByTestId('lexical-stub');
|
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText(/^Title/), {
|
|
||||||
target: { value: ' Fresh story ' },
|
|
||||||
});
|
|
||||||
fireEvent.change(screen.getByLabelText(/^URL/), {
|
|
||||||
target: { value: ' https://example.com/fresh ' },
|
|
||||||
});
|
|
||||||
fireEvent.change(screen.getByLabelText('Points'), { target: { value: '7' } });
|
|
||||||
fireEvent.change(screen.getByTestId('editor-body'), {
|
|
||||||
target: { value: '<p>Body <strong>here</strong></p>' },
|
|
||||||
});
|
|
||||||
|
|
||||||
screen.getByRole('button', { name: /create item/i }).click();
|
|
||||||
|
|
||||||
await waitFor(() =>
|
|
||||||
expect(vi.mocked(adminCreateItem)).toHaveBeenCalledWith({
|
|
||||||
title: 'Fresh story',
|
|
||||||
url: 'https://example.com/fresh',
|
|
||||||
points: 7,
|
|
||||||
username: 'root',
|
|
||||||
content: '<p>Body <strong>here</strong></p>',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
|
||||||
expect(screen.getByTestId('dashboard-notice')).toHaveTextContent(
|
|
||||||
'“Fresh story” was saved.',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('disables the create button while the request is in flight', async () => {
|
|
||||||
let resolveCreate!: (value: AdminItem) => void;
|
|
||||||
vi.mocked(adminCreateItem).mockReturnValueOnce(
|
|
||||||
new Promise<AdminItem>((resolve) => {
|
|
||||||
resolveCreate = resolve;
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
renderAt('/admin/items/new');
|
|
||||||
await screen.findByTestId('lexical-stub');
|
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText(/^Title/), {
|
|
||||||
target: { value: 'Pending' },
|
|
||||||
});
|
|
||||||
screen.getByRole('button', { name: /create item/i }).click();
|
|
||||||
|
|
||||||
const button = screen.getByRole('button', { name: /create item/i });
|
|
||||||
await waitFor(() => expect(button).toBeDisabled());
|
|
||||||
|
|
||||||
resolveCreate({ ...ITEM, id: 99, title: 'Pending' });
|
|
||||||
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows the backend error when the create request fails', async () => {
|
|
||||||
vi.mocked(adminCreateItem).mockRejectedValue(
|
|
||||||
new ApiError(422, 'Validation failed', 'validation_error'),
|
|
||||||
);
|
|
||||||
renderAt('/admin/items/new');
|
|
||||||
await screen.findByTestId('lexical-stub');
|
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText(/^Title/), { target: { value: 'x' } });
|
|
||||||
screen.getByRole('button', { name: /create item/i }).click();
|
|
||||||
|
|
||||||
expect(await screen.findByRole('alert')).toHaveTextContent('Validation failed');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('EditItemPage (edit)', () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
localStorage.clear();
|
|
||||||
vi.clearAllMocks();
|
|
||||||
(clientMe as Mock).mockResolvedValue({ username: 'root', is_admin: true });
|
|
||||||
localStorage.setItem(TOKEN_KEY, 'token');
|
|
||||||
vi.mocked(adminGetItem).mockResolvedValue(ITEM);
|
|
||||||
vi.mocked(adminUpdateItem).mockResolvedValue(ITEM);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('loads and pre-fills the item, then updates it on save', async () => {
|
|
||||||
renderAt('/admin/items/5/edit');
|
|
||||||
|
|
||||||
// Loading state first.
|
|
||||||
expect(screen.getByRole('status')).toHaveTextContent(/loading item/i);
|
|
||||||
|
|
||||||
await screen.findByTestId('lexical-stub');
|
|
||||||
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(
|
|
||||||
'Edit item #5',
|
|
||||||
);
|
|
||||||
expect(screen.getByLabelText(/^Title/)).toHaveValue('Original headline');
|
|
||||||
expect(screen.getByLabelText(/^URL/)).toHaveValue('https://example.com/original');
|
|
||||||
expect(screen.getByLabelText('Points')).toHaveValue(11);
|
|
||||||
expect(screen.getByLabelText('Author')).toHaveValue('alice');
|
|
||||||
expect(screen.getByTestId('editor-body')).toHaveValue('<p>Original body</p>');
|
|
||||||
|
|
||||||
fireEvent.change(screen.getByLabelText(/^Title/), {
|
|
||||||
target: { value: 'Retitled' },
|
|
||||||
});
|
|
||||||
screen.getByRole('button', { name: /save changes/i }).click();
|
|
||||||
|
|
||||||
await waitFor(() =>
|
|
||||||
expect(vi.mocked(adminUpdateItem)).toHaveBeenCalledWith(5, {
|
|
||||||
title: 'Retitled',
|
|
||||||
url: 'https://example.com/original',
|
|
||||||
points: 11,
|
|
||||||
username: 'alice',
|
|
||||||
content: '<p>Original body</p>',
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(await screen.findByTestId('dashboard-stub')).toBeInTheDocument();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('shows the not-found view when the item cannot be loaded', async () => {
|
|
||||||
vi.mocked(adminGetItem).mockRejectedValue(
|
|
||||||
Object.assign(new Error('Item not found'), { status: 404 }),
|
|
||||||
);
|
|
||||||
renderAt('/admin/items/999/edit');
|
|
||||||
|
|
||||||
expect(await screen.findByRole('heading', { level: 1 })).toHaveTextContent(
|
|
||||||
/item not found/i,
|
|
||||||
);
|
|
||||||
expect(screen.getByRole('link', { name: /back to items/i })).toHaveAttribute(
|
|
||||||
'href',
|
|
||||||
'/admin',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+29
-20
@@ -1,54 +1,63 @@
|
|||||||
/**
|
/**
|
||||||
* Admin area types (mirror the backend `schemas.item` payloads).
|
* Admin area types (mirror the backend `schemas.article` payloads).
|
||||||
*
|
*
|
||||||
* The backend returns snake_case JSON; these interfaces keep the wire
|
* The backend returns snake_case JSON; these interfaces keep the wire
|
||||||
* shape 1:1 (no remapping) because they are only consumed by the admin
|
* shape 1:1 (no remapping) because they are only consumed by the admin
|
||||||
* pages.
|
* pages. The related `author` and `category` are always embedded by the
|
||||||
|
* backend (`ArticleRead`), so they are required here.
|
||||||
*/
|
*/
|
||||||
|
import type { Author, Category } from './index';
|
||||||
|
|
||||||
/** One news item as managed in the admin area. */
|
/** One article as managed in the admin area. */
|
||||||
export interface AdminItem {
|
export interface AdminArticle {
|
||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
url: string;
|
|
||||||
points: number;
|
|
||||||
/** Username the item belongs to (denormalized). */
|
|
||||||
username: string;
|
|
||||||
/** HTML body produced by the Lexical editor. */
|
/** HTML body produced by the Lexical editor. */
|
||||||
content: string;
|
content: string;
|
||||||
|
author_id: number;
|
||||||
|
category_id: number;
|
||||||
|
/** Embedded author (always present on the wire). */
|
||||||
|
author: Author;
|
||||||
|
/** Embedded category (always present on the wire). */
|
||||||
|
category: Category;
|
||||||
|
/** Whether the article is visible on the public site. */
|
||||||
|
published: boolean;
|
||||||
/** ISO-8601 timestamp. */
|
/** ISO-8601 timestamp. */
|
||||||
created_at: string;
|
created_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload of `GET /api/v1/admin/items` (paginated list). */
|
/** Payload of `GET /api/v1/admin/articles` (paginated list). */
|
||||||
export interface AdminItemsPage {
|
export interface AdminArticlesPage {
|
||||||
items: AdminItem[];
|
articles: AdminArticle[];
|
||||||
total: number;
|
total: number;
|
||||||
page: number;
|
page: number;
|
||||||
page_size: number;
|
page_size: number;
|
||||||
total_pages: number;
|
total_pages: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Sortable columns of the item list. */
|
/** Sortable columns of the article list. */
|
||||||
export type AdminSortBy = 'title' | 'created_at' | 'points';
|
export type AdminSortBy = 'title' | 'created_at';
|
||||||
|
|
||||||
export type AdminSortOrder = 'asc' | 'desc';
|
export type AdminSortOrder = 'asc' | 'desc';
|
||||||
|
|
||||||
/** Query parameters of the item list endpoint. */
|
/** Query parameters of the article list endpoint. */
|
||||||
export interface AdminListParams {
|
export interface AdminListParams {
|
||||||
page: number;
|
page: number;
|
||||||
pageSize: number;
|
pageSize: number;
|
||||||
/** Case-insensitive match on title OR url. */
|
/** Case-insensitive match on title OR content. */
|
||||||
search: string;
|
search: string;
|
||||||
sortBy: AdminSortBy;
|
sortBy: AdminSortBy;
|
||||||
sortOrder: AdminSortOrder;
|
sortOrder: AdminSortOrder;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Payload of `POST /api/v1/admin/items` and `PUT /api/v1/admin/items/{id}`. */
|
/**
|
||||||
export interface AdminItemInput {
|
* Payload of `POST /api/v1/admin/articles` and
|
||||||
|
* `PUT /api/v1/admin/articles/{id}`.
|
||||||
|
*/
|
||||||
|
export interface AdminArticleInput {
|
||||||
title: string;
|
title: string;
|
||||||
url: string;
|
|
||||||
points: number;
|
|
||||||
username: string;
|
|
||||||
content: string;
|
content: string;
|
||||||
|
author_id: number;
|
||||||
|
category_id: number;
|
||||||
|
published: boolean;
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user