backend: add section-field and paper-template schema, API, and seed data
Three tables behind the template configuration feature:
section_field the reusable heading library (name, level, font size,
colour)
paper_template a named outline (name, abstract)
template_field the join, and the only home of display order (sort)
The field library is deliberately flat. A `parent_id` would tie a level-2
heading to exactly one level-1 heading, and the point of the feature is that
a field such as "Background" can sit under both "1. Introduction" and
"2. Related Work" — and in any number of templates, at a different position
in each. Hierarchy is expressed only by `level`, which is a rendering hint.
Display order lives entirely in `template_field.sort`. The order fields were
picked in is never stored, so selecting fields out of order and assigning
sorts renders in sort order. Two consequences are intentional and documented
on the model: repeats are allowed (no unique constraint on template+field)
and ties are legal (broken by insertion order, so the ordering is total).
Templates reference library fields rather than copying them, so renaming or
restyling a field updates every template that places it.
TiDB parses FOREIGN KEY and then ignores it, so the constraints are declared
for documentation and the integrity is enforced in the application layer:
deleting a field still in use is refused with the field names, creating a
template against a missing field is refused, and deleting a template removes
its join rows through the ORM's delete-orphan cascade.
Also normalises font_color to #RRGGBB on write (accepting rgb() and
shorthand) and emits font_size as a JSON number rather than pydantic's
default Decimal string.
scripts/seed.py is idempotent and fills the library with a standard academic
outline plus three starter templates.
This commit is contained in:
@@ -1 +1,39 @@
|
||||
"""Pydantic models describing request and response payloads."""
|
||||
"""Pydantic schemas for request and response payloads."""
|
||||
|
||||
from app.schemas.common import (
|
||||
BatchDeleteRequest,
|
||||
BatchDeleteResult,
|
||||
PageResult,
|
||||
normalize_hex_color,
|
||||
)
|
||||
from app.schemas.paper_template import (
|
||||
PaperTemplateCreate,
|
||||
PaperTemplateListItem,
|
||||
PaperTemplateRead,
|
||||
PaperTemplateUpdate,
|
||||
TemplateFieldInput,
|
||||
TemplateFieldRead,
|
||||
)
|
||||
from app.schemas.section_field import (
|
||||
SectionFieldCreate,
|
||||
SectionFieldRead,
|
||||
SectionFieldRef,
|
||||
SectionFieldUpdate,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"BatchDeleteRequest",
|
||||
"BatchDeleteResult",
|
||||
"PageResult",
|
||||
"PaperTemplateCreate",
|
||||
"PaperTemplateListItem",
|
||||
"PaperTemplateRead",
|
||||
"PaperTemplateUpdate",
|
||||
"SectionFieldCreate",
|
||||
"SectionFieldRead",
|
||||
"SectionFieldRef",
|
||||
"SectionFieldUpdate",
|
||||
"TemplateFieldInput",
|
||||
"TemplateFieldRead",
|
||||
"normalize_hex_color",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Shared request/response shapes and value normalisation helpers."""
|
||||
|
||||
import re
|
||||
from decimal import Decimal
|
||||
from typing import Generic, TypeVar
|
||||
|
||||
from pydantic import BaseModel, Field, field_serializer, field_validator
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class PageResult(BaseModel, Generic[T]):
|
||||
"""One page of a list endpoint."""
|
||||
|
||||
items: list[T]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
pages: int = 0
|
||||
|
||||
@classmethod
|
||||
def build(
|
||||
cls,
|
||||
*,
|
||||
items: list[T],
|
||||
total: int,
|
||||
page: int,
|
||||
page_size: int,
|
||||
) -> "PageResult[T]":
|
||||
"""Assemble a page and derive ``pages`` from the page size.
|
||||
|
||||
``ceil`` is done in integers so an empty result reports 0 pages rather
|
||||
than a misleading 1.
|
||||
"""
|
||||
pages = (total + page_size - 1) // page_size if page_size > 0 else 0
|
||||
return cls(items=items, total=total, page=page, page_size=page_size, pages=pages)
|
||||
|
||||
|
||||
class BatchDeleteRequest(BaseModel):
|
||||
"""Body for the batch-delete endpoints."""
|
||||
|
||||
ids: list[int] = Field(min_length=1, description="Primary keys to delete")
|
||||
|
||||
|
||||
class BatchDeleteResult(BaseModel):
|
||||
"""How many rows a batch delete actually removed."""
|
||||
|
||||
deleted: int
|
||||
|
||||
|
||||
# ``#rgb`` / ``#rrggbb`` / ``rrggbb`` — the ``#`` is optional.
|
||||
_HEX_RE = re.compile(r"^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
|
||||
# ``rgb(r, g, b)`` / ``rgba(r, g, b, a)`` — alpha, when present, is discarded:
|
||||
# the stored value is plain RGB.
|
||||
_RGB_RE = re.compile(
|
||||
r"^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*[\d.]+\s*)?\)$"
|
||||
)
|
||||
|
||||
COLOR_ERROR = "颜色格式无效,请使用 #RRGGBB 或 rgb(r,g,b),例如 #FF0000 / rgb(255, 0, 0)"
|
||||
|
||||
|
||||
def normalize_hex_color(value: str) -> str:
|
||||
"""Normalise any accepted colour spelling to canonical ``#RRGGBB``.
|
||||
|
||||
The database column is fixed-width ``CHAR(7)``, so exactly one spelling has
|
||||
to survive the write. Accepting the common variants costs little and means
|
||||
neither the colour picker nor a hand-written API call can produce a value
|
||||
the column cannot hold.
|
||||
|
||||
Raises:
|
||||
ValueError: if the value is not a recognisable colour.
|
||||
"""
|
||||
text = value.strip()
|
||||
|
||||
rgb_match = _RGB_RE.match(text)
|
||||
if rgb_match:
|
||||
channels = [int(part) for part in rgb_match.groups()]
|
||||
if any(channel > 255 for channel in channels):
|
||||
raise ValueError(COLOR_ERROR)
|
||||
return "#{:02X}{:02X}{:02X}".format(*channels)
|
||||
|
||||
hex_match = _HEX_RE.match(text)
|
||||
if hex_match:
|
||||
digits = hex_match.group(1)
|
||||
if len(digits) == 3: # #abc -> #AABBCC
|
||||
digits = "".join(char * 2 for char in digits)
|
||||
return "#" + digits.upper()
|
||||
|
||||
raise ValueError(COLOR_ERROR)
|
||||
|
||||
|
||||
class TypographyMixin:
|
||||
"""Shared handling of the two typography columns, ``font_size`` /
|
||||
``font_color``, for every schema that carries them.
|
||||
|
||||
A plain mixin rather than a :class:`BaseModel` subclass: pydantic v2
|
||||
collects ``field_validator`` / ``field_serializer`` from non-model bases in
|
||||
the MRO, so a schema picks these up with ``class Foo(TypographyMixin,
|
||||
BaseModel)`` and keeps its own base-model configuration.
|
||||
|
||||
Two rules, both about making the wire format unsurprising:
|
||||
|
||||
* **In** — any accepted colour spelling is normalised to ``#RRGGBB``, so a
|
||||
``CHAR(7)`` column always receives something it can hold.
|
||||
* **Out** — ``font_size`` is emitted as a JSON *number*, not the string
|
||||
pydantic produces for ``Decimal`` by default. A client should not have to
|
||||
parse a font size before putting it in a CSS rule.
|
||||
"""
|
||||
|
||||
@field_validator("font_color", mode="before", check_fields=False)
|
||||
@classmethod
|
||||
def _normalise_color(cls, value: object) -> object:
|
||||
# Non-strings pass through so an omitted colour stays omitted. The
|
||||
# colour normaliser tolerates a None-valued optional field this way.
|
||||
if isinstance(value, str):
|
||||
return normalize_hex_color(value)
|
||||
return value
|
||||
|
||||
@field_serializer("font_size", check_fields=False)
|
||||
def _serialize_font_size(self, value: Decimal) -> float:
|
||||
return float(value)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Request/response schemas for paper templates (模板管理)."""
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.models.paper_template import PaperTemplate
|
||||
from app.models.template_field import TemplateField
|
||||
from app.schemas.common import TypographyMixin
|
||||
|
||||
|
||||
class TemplateFieldInput(BaseModel):
|
||||
"""One placement of a library field inside a template.
|
||||
|
||||
The client sends the whole ordered selection on create and on update; the
|
||||
server replaces the stored rows with it. ``sort`` is a plain ascending
|
||||
integer and is the *only* thing that decides render order.
|
||||
"""
|
||||
|
||||
field_id: int
|
||||
sort: int = Field(default=0, ge=-1_000_000, le=1_000_000)
|
||||
|
||||
|
||||
class TemplateFieldRead(TypographyMixin, BaseModel):
|
||||
"""A template's field, flattened with the library row it points at.
|
||||
|
||||
Persistence keeps the two apart — a placement row plus the library row it
|
||||
references — but a client rendering an outline wants one flat record, so
|
||||
the typography is denormalised into the response. That is also what keeps
|
||||
the outline in sync: there is only ever one copy of a field's name and
|
||||
styling, in the library.
|
||||
"""
|
||||
|
||||
id: int
|
||||
field_id: int
|
||||
sort: int
|
||||
name: str
|
||||
level: int
|
||||
font_size: Decimal
|
||||
font_color: str
|
||||
|
||||
@classmethod
|
||||
def from_model(cls, item: TemplateField) -> "TemplateFieldRead":
|
||||
"""Flatten a placement row and its library row into one record."""
|
||||
return cls(
|
||||
id=item.id,
|
||||
field_id=item.field_id,
|
||||
sort=item.sort,
|
||||
name=item.field.name,
|
||||
level=item.field.level,
|
||||
font_size=item.field.font_size,
|
||||
font_color=item.field.font_color,
|
||||
)
|
||||
|
||||
|
||||
class PaperTemplateBase(BaseModel):
|
||||
"""Shared body of the create/update payloads."""
|
||||
|
||||
name: str = Field(min_length=1, max_length=255)
|
||||
abstract: str | None = None
|
||||
|
||||
|
||||
class PaperTemplateCreate(PaperTemplateBase):
|
||||
"""Payload for ``POST /templates``.
|
||||
|
||||
The field selection is free: any subset, any order, repeats allowed. The
|
||||
server stores it as given and orders it by ``sort`` on read.
|
||||
"""
|
||||
|
||||
fields: list[TemplateFieldInput] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PaperTemplateUpdate(BaseModel):
|
||||
"""Payload for ``PATCH /templates/{id}``.
|
||||
|
||||
``fields`` is a full replacement when present — omit it to leave the
|
||||
selection untouched.
|
||||
"""
|
||||
|
||||
name: str | None = Field(default=None, min_length=1, max_length=255)
|
||||
abstract: str | None = None
|
||||
fields: list[TemplateFieldInput] | None = None
|
||||
|
||||
|
||||
class PaperTemplateListItem(BaseModel):
|
||||
"""A template as it appears in the list table — no field rows."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
abstract: str | None
|
||||
field_count: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class PaperTemplateRead(BaseModel):
|
||||
"""A template with its outline, already ordered by ``sort``."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
abstract: str | None
|
||||
#: The outline, ordered by ``sort`` — the ORM relationship sets that
|
||||
#: ordering, so this list is display-ready with no client-side sorting.
|
||||
fields: list[TemplateFieldRead]
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@classmethod
|
||||
def from_model(cls, template: PaperTemplate) -> "PaperTemplateRead":
|
||||
"""Build the response from a template and its placement rows."""
|
||||
return cls(
|
||||
id=template.id,
|
||||
name=template.name,
|
||||
abstract=template.abstract,
|
||||
fields=[TemplateFieldRead.from_model(item) for item in template.items],
|
||||
created_at=template.created_at,
|
||||
updated_at=template.updated_at,
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Request/response schemas for the section-field library (字段管理)."""
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.schemas.common import TypographyMixin
|
||||
|
||||
|
||||
class SectionFieldBase(TypographyMixin, BaseModel):
|
||||
"""Fields a client may set on a section field."""
|
||||
|
||||
#: Display name, numbering included — e.g. ``"1. Introduction"``. Stored
|
||||
#: and rendered verbatim; the API never rewrites it.
|
||||
name: str = Field(min_length=1, max_length=255)
|
||||
|
||||
#: Heading depth. 1 = "1.", 2 = "1.1", 3 = "1.1.1". Rendering hint only.
|
||||
level: int = Field(default=1, ge=1, le=9)
|
||||
|
||||
#: Font size in points. Fractional because 五号 = 10.5pt.
|
||||
font_size: Decimal = Field(default=Decimal("12.0"), gt=0, le=99)
|
||||
|
||||
#: ``#RRGGBB``. ``rgb(...)`` and shorthand forms are normalised on write.
|
||||
font_color: str = Field(default="#000000", max_length=32)
|
||||
|
||||
|
||||
class SectionFieldCreate(SectionFieldBase):
|
||||
"""Payload for ``POST /section-fields``."""
|
||||
|
||||
|
||||
class SectionFieldUpdate(TypographyMixin, BaseModel):
|
||||
"""Payload for ``PATCH /section-fields/{id}`` — every part optional.
|
||||
|
||||
The colour normaliser tolerates ``None`` here; the validator returns
|
||||
non-strings untouched, so an omitted colour stays omitted.
|
||||
"""
|
||||
|
||||
name: str | None = Field(default=None, min_length=1, max_length=255)
|
||||
level: int | None = Field(default=None, ge=1, le=9)
|
||||
font_size: Decimal | None = Field(default=None, gt=0, le=99)
|
||||
font_color: str | None = Field(default=None, max_length=32)
|
||||
|
||||
|
||||
class SectionFieldRead(SectionFieldBase):
|
||||
"""A stored section field."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class SectionFieldRef(BaseModel):
|
||||
"""How many templates currently place a field — used to explain a refusal."""
|
||||
|
||||
field_id: int
|
||||
field_name: str
|
||||
template_count: int
|
||||
Reference in New Issue
Block a user