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:
2026-09-22 17:55:15 +08:00
parent d7bb777264
commit 6020310b3f
14 changed files with 1042 additions and 29 deletions
+10
View File
@@ -33,6 +33,12 @@ from app.schemas.reference import (
ReferenceUpdate,
normalize_doi,
)
from app.schemas.reference_tag import (
ReferenceTagCreate,
ReferenceTagRead,
ReferenceTagRef,
ReferenceTagUpdate,
)
from app.schemas.template import (
TemplateCreate,
TemplateListItem,
@@ -56,6 +62,10 @@ __all__ = [
"ReferenceCreate",
"ReferenceListItem",
"ReferenceRead",
"ReferenceTagCreate",
"ReferenceTagRead",
"ReferenceTagRef",
"ReferenceTagUpdate",
"ReferenceUpdate",
"normalize_doi",
"CitationInput",
+16
View File
@@ -23,6 +23,7 @@ from app.models.reference import (
REFERENCE_LANGUAGES,
REFERENCE_TYPES,
)
from app.schemas.reference_tag import ReferenceTagRef
#: Prefixes people paste along with a DOI. Stripped on write so the column has
#: one spelling, and so a citation builder never has to test for them.
@@ -141,6 +142,10 @@ class ReferenceBase(BaseModel):
citation_key: str | None = Field(default=None, max_length=64)
language: str | None = Field(default=None, max_length=16)
authors: list[ReferenceAuthorInput] = Field(default_factory=list)
#: The tags to apply, by id. Tags are made first and applied second, so this
#: names labels that already exist rather than carrying spellings that could
#: invent new ones. Unknown ids are refused by name.
tag_ids: list[int] = Field(default_factory=list)
@field_validator("title")
@classmethod
@@ -269,6 +274,10 @@ class ReferenceUpdate(BaseModel):
citation_key: str | None = Field(default=None, max_length=64)
language: str | None = Field(default=None, max_length=16)
authors: list[ReferenceAuthorInput] | None = None
#: Full replacement when present, like ``authors``: the list is the set of
#: labels on the row, so sending it means "these and no others" and ``[]``
#: clears every label. Omitting the key leaves the labels alone.
tag_ids: list[int] | None = None
@field_validator("title")
@classmethod
@@ -312,6 +321,9 @@ class ReferenceListItem(BaseModel):
title: str
subtitle: str | None
container_title: str | None
#: 出版者. Carried on the row because a book, a thesis and a report have no
#: container to show and the publisher *is* their "where".
publisher: str | None
publication_year: int | None
volume: str | None
issue: str | None
@@ -321,6 +333,9 @@ class ReferenceListItem(BaseModel):
#: rows behind it.
authors_line: str
author_count: int
#: The labels the writer put on it, ready to paint. Loading them here rather
#: than per row is what keeps a page of the library one query for the tags.
tags: list[ReferenceTagRef] = Field(default_factory=list)
#: How many sentences cite it. Drives the refusal message on delete, and
#: tells the writer at a glance what is already used.
citation_count: int
@@ -370,6 +385,7 @@ class ReferenceRead(BaseModel):
citation_key: str | None
language: str | None
authors: list[ReferenceAuthorRead]
tags: list[ReferenceTagRef] = Field(default_factory=list)
citation_count: int
created_at: datetime
updated_at: datetime
+123
View File
@@ -0,0 +1,123 @@
"""Request/response schemas for the reference tags (文献标签).
The tables and the reasoning behind them are documented on
:mod:`app.models.reference_tag`; this module is the wire format:
* A tag is **made first and applied second**. ``ReferenceCreate.tag_ids`` names
existing tags rather than carrying their names, so a typo cannot silently
invent a label and two clients tagging the same document cannot create two
spellings of it.
* Colours are canonicalised the same way a heading's are — :func:`normalize_hex_color`
accepts ``rgb(r, g, b)``, ``#abc`` and bare ``aabbcc`` — so the column has one
comparable spelling.
* A tag's ``reference_count`` is derived, never sent.
"""
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, field_validator
from app.models.reference_tag import DEFAULT_TAG_COLOR
from app.schemas.common import normalize_hex_color
class ReferenceTagBase(BaseModel):
"""The parts of a tag the writer sets."""
name: str = Field(min_length=1, max_length=64)
#: Accepted in any spelling the normaliser understands — ``rgb(64, 158, 255)``
#: is 17 characters — and stored as the canonical 7, so the bound here is on
#: what may *arrive*, not on what the column holds.
color: str = Field(default=DEFAULT_TAG_COLOR, max_length=32)
note: str | None = Field(default=None, max_length=255)
@field_validator("name")
@classmethod
def _require_name(cls, value: str) -> str:
text = value.strip()
if not text:
raise ValueError("标签名称不能为空")
# Inner runs collapse too: " 综述 " and "综述" are one label, and a
# name with a trailing space in it would be a second one.
return " ".join(text.split())
@field_validator("color")
@classmethod
def _canonical_colour(cls, value: str) -> str:
# Raises with its own message when the spelling is not a colour, which
# pydantic turns into a field error naming this field.
return normalize_hex_color(value)
@field_validator("note")
@classmethod
def _blank_to_none(cls, value: str | None) -> str | None:
if value is None:
return None
return value.strip() or None
class ReferenceTagCreate(ReferenceTagBase):
"""Payload for ``POST /reference-tags``."""
class ReferenceTagUpdate(BaseModel):
"""Payload for ``PATCH /reference-tags/{id}`` — every part optional."""
name: str | None = Field(default=None, min_length=1, max_length=64)
color: str | None = Field(default=None, max_length=32)
note: str | None = Field(default=None, max_length=255)
@field_validator("name")
@classmethod
def _require_name(cls, value: str | None) -> str | None:
if value is None:
return None
text = " ".join(value.split())
if not text:
raise ValueError("标签名称不能为空")
return text
@field_validator("color")
@classmethod
def _canonical_colour(cls, value: str | None) -> str | None:
if value is None:
return None
return normalize_hex_color(value)
class ReferenceTagRead(BaseModel):
"""A stored tag, with how much literature carries it."""
model_config = ConfigDict(from_attributes=True)
id: int
name: str
color: str
note: str | None
#: How many references carry this label. Computed on read; it is what the
#: tag table shows and what the delete confirmation warns about.
reference_count: int = 0
created_at: datetime
updated_at: datetime
class ReferenceTagRef(BaseModel):
"""A tag as it appears on a reference — the label, not its usage count.
The library table paints one of these per label, so it carries exactly what
a chip needs and nothing that would have to be loaded per row.
"""
model_config = ConfigDict(from_attributes=True)
id: int
name: str
color: str
__all__ = [
"ReferenceTagCreate",
"ReferenceTagRead",
"ReferenceTagRef",
"ReferenceTagUpdate",
]