backend: tag the literature, in a table of its own
A tag is the writer's filing of a row — 「综述」, 「必读」 — and it is a different fact from `reference.keywords`, which are the 关键词 printed on the article. A tag never prints, one document carries several, and the same label is on many documents, so it gets two tables rather than a column: reference_tag name (unique), colour, note reference_tag_link reference_id + tag_id — the pair is the primary key The link is a bare link, which is why it is `_link` and not `_placement`: there is no `sort` to own, so the pair *is* the row and the same label cannot be applied twice. A tag is made first and applied second: `tag_ids`, never tag names, so a typo cannot invent a label — an unknown id is a 400 naming it, and nothing is written. Deleting a tag is deliberately *not* guarded the way deleting a cited reference is: both foreign keys cascade, so the labels go and the literature stays. `GET /references?tag=1&tag=2` narrows rather than widens — the rows carrying both labels — because that is what a second filter reads as. The smoke test now walks the whole flow in the order the feature intends: labels first, then tagged references, then a rename that follows every row.
This commit is contained in:
@@ -2,11 +2,19 @@
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.routes import health, papers, references, template_titles, templates
|
||||
from app.api.routes import (
|
||||
health,
|
||||
papers,
|
||||
reference_tags,
|
||||
references,
|
||||
template_titles,
|
||||
templates,
|
||||
)
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(health.router)
|
||||
api_router.include_router(papers.router)
|
||||
api_router.include_router(reference_tags.router)
|
||||
api_router.include_router(references.router)
|
||||
api_router.include_router(template_titles.router)
|
||||
api_router.include_router(templates.router)
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Reference-tag endpoints (文献标签).
|
||||
|
||||
The label library the reference table and the reference form draw on. It is
|
||||
managed first and applied second: a reference is created *with* tags, and an id
|
||||
that names a label that does not exist is refused rather than silently ignored.
|
||||
|
||||
Deleting a tag is **not** guarded the way deleting a field or a cited reference
|
||||
is. A tag is the writer's own filing — it says "this is one of the papers I
|
||||
should reread", not something the document claims — so removing it removes
|
||||
labels and leaves the literature exactly where it was. The confirmation in the
|
||||
UI says how many rows will lose the label, which is the honest form of that
|
||||
warning.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud import reference_tag as crud
|
||||
from app.crud.reference_tag import DuplicateTagName
|
||||
from app.db.session import get_db
|
||||
from app.models import ReferenceTag
|
||||
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
|
||||
from app.schemas.reference_tag import (
|
||||
ReferenceTagCreate,
|
||||
ReferenceTagRead,
|
||||
ReferenceTagUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/reference-tags", tags=["reference-tags"])
|
||||
|
||||
|
||||
def _get_or_404(db: Session, tag_id: int) -> ReferenceTag:
|
||||
tag = crud.get(db, tag_id)
|
||||
if tag is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"标签 {tag_id} 不存在",
|
||||
)
|
||||
return tag
|
||||
|
||||
|
||||
def _conflict(error: DuplicateTagName) -> HTTPException:
|
||||
"""Report a taken name as ``409`` naming the label."""
|
||||
return HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(error))
|
||||
|
||||
|
||||
@router.get("", response_model=PageResult[ReferenceTagRead], summary="List tags")
|
||||
def list_tags(
|
||||
db: Session = Depends(get_db),
|
||||
keyword: str | None = Query(default=None, description="按标签名称或备注模糊搜索"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=50, ge=1, le=500),
|
||||
) -> PageResult[ReferenceTagRead]:
|
||||
"""Browse the tag library, alphabetical, each with how many rows carry it."""
|
||||
items, total = crud.list_tags(
|
||||
db,
|
||||
keyword=keyword,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return PageResult.build(items=items, total=total, page=page, page_size=page_size)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=ReferenceTagRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a tag",
|
||||
)
|
||||
def create_tag(
|
||||
payload: ReferenceTagCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> ReferenceTagRead:
|
||||
"""Add one label to the library."""
|
||||
try:
|
||||
tag = crud.create(db, payload)
|
||||
except DuplicateTagName as error:
|
||||
raise _conflict(error) from error
|
||||
return crud.read(db, tag)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-delete",
|
||||
response_model=BatchDeleteResult,
|
||||
summary="Delete several tags",
|
||||
)
|
||||
def batch_delete_tags(
|
||||
payload: BatchDeleteRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> BatchDeleteResult:
|
||||
"""Delete the given tags, removing their labels from the literature."""
|
||||
return BatchDeleteResult(deleted=crud.delete_many(db, payload.ids))
|
||||
|
||||
|
||||
@router.get("/{tag_id}", response_model=ReferenceTagRead, summary="Fetch one tag")
|
||||
def get_tag(tag_id: int, db: Session = Depends(get_db)) -> ReferenceTagRead:
|
||||
"""Return one label, with how many references carry it."""
|
||||
return crud.read(db, _get_or_404(db, tag_id))
|
||||
|
||||
|
||||
@router.patch("/{tag_id}", response_model=ReferenceTagRead, summary="Update a tag")
|
||||
def update_tag(
|
||||
tag_id: int,
|
||||
payload: ReferenceTagUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> ReferenceTagRead:
|
||||
"""Rename or recolour a label.
|
||||
|
||||
Every reference carrying it follows, because a reference links to the tag
|
||||
rather than storing its name.
|
||||
"""
|
||||
tag = _get_or_404(db, tag_id)
|
||||
try:
|
||||
updated = crud.update(db, tag, payload)
|
||||
except DuplicateTagName as error:
|
||||
raise _conflict(error) from error
|
||||
return crud.read(db, updated)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{tag_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Delete a tag",
|
||||
)
|
||||
def delete_tag(tag_id: int, db: Session = Depends(get_db)) -> Response:
|
||||
"""Delete a label. Its literature stays; only the labelling goes."""
|
||||
crud.delete(db, _get_or_404(db, tag_id))
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -15,6 +15,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud import reference as crud
|
||||
from app.crud.reference_tag import UnknownTag
|
||||
from app.db.session import get_db
|
||||
from app.models import REFERENCE_TYPES, Reference
|
||||
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
|
||||
@@ -64,6 +65,16 @@ def _assert_not_cited(db: Session, references: list[Reference]) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _unknown_tag(error: UnknownTag) -> HTTPException:
|
||||
"""Report an applied tag that does not exist as ``400`` naming it.
|
||||
|
||||
A ``400`` rather than a ``422``: the body parsed, and the offending value is
|
||||
a real integer — it is the library that has no such label. The message names
|
||||
the ids so the client can tell a stale picker from a typo.
|
||||
"""
|
||||
return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(error))
|
||||
|
||||
|
||||
@router.get("", response_model=PageResult[ReferenceListItem], summary="List references")
|
||||
def list_references(
|
||||
db: Session = Depends(get_db),
|
||||
@@ -79,6 +90,10 @@ def list_references(
|
||||
cited: bool | None = Query(
|
||||
default=None, description="true 只看已被引用的,false 只看还没用过的"
|
||||
),
|
||||
tag: list[int] | None = Query(
|
||||
default=None,
|
||||
description="按标签过滤,可重复;给多个标签时取交集(都打了才留下)",
|
||||
),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=200),
|
||||
) -> PageResult[ReferenceListItem]:
|
||||
@@ -89,6 +104,7 @@ def list_references(
|
||||
type_=type_filter,
|
||||
year=year,
|
||||
cited_only=cited,
|
||||
tag_ids=tag,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
@@ -105,8 +121,12 @@ def create_reference(
|
||||
payload: ReferenceCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> ReferenceRead:
|
||||
"""Add one document to the library, with its contributors in order."""
|
||||
return crud.read(db, crud.create(db, payload))
|
||||
"""Add one document to the library, with its contributors and its tags."""
|
||||
try:
|
||||
created = crud.create(db, payload)
|
||||
except UnknownTag as error:
|
||||
raise _unknown_tag(error) from error
|
||||
return crud.read(db, created)
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -158,11 +178,16 @@ def update_reference(
|
||||
) -> ReferenceRead:
|
||||
"""Update any part of a reference.
|
||||
|
||||
``authors`` is a full replacement when present — the citation prints them in
|
||||
the order sent, so there is no partial form of that list.
|
||||
``authors`` and ``tag_ids`` are full replacements when present — the citation
|
||||
prints the contributors in the order sent, and the tag list *is* the set of
|
||||
labels on the row, so ``[]`` clears them.
|
||||
"""
|
||||
reference = _get_or_404(db, reference_id)
|
||||
return crud.read(db, crud.update(db, reference, payload))
|
||||
try:
|
||||
updated = crud.update(db, reference, payload)
|
||||
except UnknownTag as error:
|
||||
raise _unknown_tag(error) from error
|
||||
return crud.read(db, updated)
|
||||
|
||||
|
||||
@router.delete(
|
||||
|
||||
Reference in New Issue
Block a user