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:
@@ -2,7 +2,9 @@
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.routes import health
|
||||
from app.api.routes import health, section_fields, templates
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(health.router)
|
||||
api_router.include_router(section_fields.router)
|
||||
api_router.include_router(templates.router)
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Section-field library endpoints (字段管理).
|
||||
|
||||
The library is global and reusable: a field exists once and is then placed into
|
||||
any number of templates. That is why deleting a field is guarded — the join
|
||||
table is the only thing keeping a template's outline intact, and silently
|
||||
dropping a live heading from every template would be data loss, not cleanup.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud import section_field as crud
|
||||
from app.db.session import get_db
|
||||
from app.models import SectionField
|
||||
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
|
||||
from app.schemas.section_field import (
|
||||
SectionFieldCreate,
|
||||
SectionFieldRead,
|
||||
SectionFieldUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/section-fields", tags=["section-fields"])
|
||||
|
||||
|
||||
def _get_or_404(db: Session, field_id: int) -> SectionField:
|
||||
field = crud.get(db, field_id)
|
||||
if field is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"字段 {field_id} 不存在",
|
||||
)
|
||||
return field
|
||||
|
||||
|
||||
def _assert_unused(db: Session, fields: list[SectionField]) -> None:
|
||||
"""Refuse the delete if any field is still placed in a template.
|
||||
|
||||
All offenders are reported at once rather than one per attempt, so a batch
|
||||
delete does not turn into trial and error.
|
||||
"""
|
||||
counts = crud.usage_counts(db, [field.id for field in fields])
|
||||
if not counts:
|
||||
return
|
||||
|
||||
by_id = {field.id: field.name for field in fields}
|
||||
blockers = "、".join(
|
||||
f"“{by_id.get(field_id, field_id)}”({count} 个模板)"
|
||||
for field_id, count in sorted(counts.items())
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"以下字段正被模板使用,请先在模板中移除:{blockers}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=PageResult[SectionFieldRead],
|
||||
summary="List the field library",
|
||||
)
|
||||
def list_fields(
|
||||
db: Session = Depends(get_db),
|
||||
keyword: str | None = Query(default=None, description="按字段名称模糊搜索"),
|
||||
level: int | None = Query(default=None, ge=1, le=9, description="按字段等级过滤"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=500),
|
||||
) -> PageResult[SectionFieldRead]:
|
||||
"""Browse the field library, grouped by level then creation order."""
|
||||
rows, total = crud.list_fields(
|
||||
db,
|
||||
keyword=keyword,
|
||||
level=level,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return PageResult.build(
|
||||
items=[SectionFieldRead.model_validate(row) for row in rows],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=SectionFieldRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a section field",
|
||||
)
|
||||
def create_field(
|
||||
payload: SectionFieldCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> SectionFieldRead:
|
||||
"""Add a heading to the library, with its typography."""
|
||||
return SectionFieldRead.model_validate(crud.create(db, payload))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-delete",
|
||||
response_model=BatchDeleteResult,
|
||||
summary="Delete several section fields",
|
||||
)
|
||||
def batch_delete_fields(
|
||||
payload: BatchDeleteRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> BatchDeleteResult:
|
||||
"""Delete the given fields, refusing wholesale if any is still in use."""
|
||||
fields = crud.get_many(db, payload.ids)
|
||||
_assert_unused(db, fields)
|
||||
|
||||
for field in fields:
|
||||
crud.delete(db, field)
|
||||
return BatchDeleteResult(deleted=len(fields))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{field_id}",
|
||||
response_model=SectionFieldRead,
|
||||
summary="Fetch one section field",
|
||||
)
|
||||
def get_field(field_id: int, db: Session = Depends(get_db)) -> SectionFieldRead:
|
||||
"""Return a single field."""
|
||||
return SectionFieldRead.model_validate(_get_or_404(db, field_id))
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/{field_id}",
|
||||
response_model=SectionFieldRead,
|
||||
summary="Update a section field",
|
||||
)
|
||||
def update_field(
|
||||
field_id: int,
|
||||
payload: SectionFieldUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> SectionFieldRead:
|
||||
"""Rename or restyle a field.
|
||||
|
||||
The change is visible in every template that places the field, because
|
||||
templates store a reference rather than a copy.
|
||||
"""
|
||||
field = _get_or_404(db, field_id)
|
||||
return SectionFieldRead.model_validate(crud.update(db, field, payload))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{field_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Delete a section field",
|
||||
)
|
||||
def delete_field(field_id: int, db: Session = Depends(get_db)) -> Response:
|
||||
"""Delete an unused field."""
|
||||
field = _get_or_404(db, field_id)
|
||||
_assert_unused(db, [field])
|
||||
crud.delete(db, field)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Paper-template endpoints (模板管理).
|
||||
|
||||
A template is created from two pieces of free text plus a free selection of
|
||||
library fields. Nothing constrains the selection: the same field may be picked
|
||||
twice, the picks may arrive in any order, and the only thing that decides how
|
||||
the outline reads is ``sort``.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud import paper_template as crud
|
||||
from app.db.session import get_db
|
||||
from app.models import PaperTemplate
|
||||
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
|
||||
from app.schemas.paper_template import (
|
||||
PaperTemplateCreate,
|
||||
PaperTemplateListItem,
|
||||
PaperTemplateRead,
|
||||
PaperTemplateUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/templates", tags=["templates"])
|
||||
|
||||
|
||||
def _get_or_404(db: Session, template_id: int) -> PaperTemplate:
|
||||
template = crud.get(db, template_id)
|
||||
if template is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"模板 {template_id} 不存在",
|
||||
)
|
||||
return template
|
||||
|
||||
|
||||
def _assert_name_free(db: Session, name: str, *, exclude_id: int | None = None) -> None:
|
||||
if crud.name_taken(db, name, exclude_id=exclude_id):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"模板名称“{name}”已存在",
|
||||
)
|
||||
|
||||
|
||||
def _assert_fields_exist(db: Session, field_ids: list[int]) -> None:
|
||||
"""Reject a selection that references fields the library does not have.
|
||||
|
||||
Checked in Python rather than by a foreign key because TiDB parses but does
|
||||
not enforce ``FOREIGN KEY``, so an unchecked write would happily leave a
|
||||
template pointing at nothing.
|
||||
"""
|
||||
missing = crud.missing_field_ids(db, field_ids)
|
||||
if missing:
|
||||
joined = "、".join(str(field_id) for field_id in missing)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"字段不存在:{joined}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=PageResult[PaperTemplateListItem],
|
||||
summary="List paper templates",
|
||||
)
|
||||
def list_templates(
|
||||
db: Session = Depends(get_db),
|
||||
keyword: str | None = Query(default=None, description="按模板名称或摘要模糊搜索"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=200),
|
||||
) -> PageResult[PaperTemplateListItem]:
|
||||
"""Browse templates, most recently edited first."""
|
||||
items, total = crud.list_templates(
|
||||
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=PaperTemplateRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a paper template",
|
||||
)
|
||||
def create_template(
|
||||
payload: PaperTemplateCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> PaperTemplateRead:
|
||||
"""Create a template from a name, an abstract, and a field selection."""
|
||||
_assert_name_free(db, payload.name)
|
||||
_assert_fields_exist(db, [item.field_id for item in payload.fields])
|
||||
|
||||
template = crud.create(
|
||||
db,
|
||||
name=payload.name,
|
||||
abstract=payload.abstract,
|
||||
fields=payload.fields,
|
||||
)
|
||||
return PaperTemplateRead.from_model(template)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-delete",
|
||||
response_model=BatchDeleteResult,
|
||||
summary="Delete several paper templates",
|
||||
)
|
||||
def batch_delete_templates(
|
||||
payload: BatchDeleteRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> BatchDeleteResult:
|
||||
"""Delete the given templates and all of their placement rows."""
|
||||
return BatchDeleteResult(deleted=crud.delete_many(db, payload.ids))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{template_id}",
|
||||
response_model=PaperTemplateRead,
|
||||
summary="Fetch one paper template with its outline",
|
||||
)
|
||||
def get_template(template_id: int, db: Session = Depends(get_db)) -> PaperTemplateRead:
|
||||
"""Return a template; ``fields`` arrives already ordered by ``sort``."""
|
||||
return PaperTemplateRead.from_model(_get_or_404(db, template_id))
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/{template_id}",
|
||||
response_model=PaperTemplateRead,
|
||||
summary="Update a paper template",
|
||||
)
|
||||
def update_template(
|
||||
template_id: int,
|
||||
payload: PaperTemplateUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> PaperTemplateRead:
|
||||
"""Update the name, the abstract, the field selection, or any combination.
|
||||
|
||||
``fields`` is a full replacement when present. Omitting it leaves the
|
||||
outline untouched; sending ``[]`` clears it.
|
||||
"""
|
||||
template = _get_or_404(db, template_id)
|
||||
|
||||
if payload.name is not None:
|
||||
_assert_name_free(db, payload.name, exclude_id=template_id)
|
||||
if payload.fields is not None:
|
||||
_assert_fields_exist(db, [item.field_id for item in payload.fields])
|
||||
|
||||
updated = crud.update(
|
||||
db,
|
||||
template,
|
||||
name=payload.name,
|
||||
abstract=payload.abstract,
|
||||
# Both "field omitted" and "field set to null" arrive as None; only
|
||||
# model_fields_set records which one the client actually sent.
|
||||
abstract_provided="abstract" in payload.model_fields_set,
|
||||
fields=payload.fields,
|
||||
)
|
||||
return PaperTemplateRead.from_model(updated)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{template_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Delete a paper template",
|
||||
)
|
||||
def delete_template(template_id: int, db: Session = Depends(get_db)) -> Response:
|
||||
"""Delete a template. Library fields it referenced are left alone."""
|
||||
crud.delete(db, _get_or_404(db, template_id))
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
Reference in New Issue
Block a user