Files
paper-doc/backend/app/api/routes/templates.py
T
govin 199e328b48 refactor: call a heading a title, and its use a placement
`template_field_library` and `template_field` were one word apart and meant
opposite kinds of thing — a catalogue of rows versus one row — and neither name
said what a row actually is. Every row of the library is a **heading**: a piece
of text like 「1. Introduction」 with a level and typography, which is what the
reader sees at the top of a paragraph; and every row of the join table is that
heading *placed* in a template, `sort` included.

    template_field_library  -> template_title
    template_field          -> template_title_placement
    field_id (the column)   -> title_id
    TemplateFieldLibrary    -> TemplateTitle
    TemplateField           -> TemplateTitlePlacement

The join table keeps its own name rather than becoming `_link`, because it is
not a bare link: it carries `sort`, the only place display order is stored, and
it deliberately allows the same title twice in one template. `_link` would
describe two foreign keys and hide the column the ordering rule rests on.

Carried through every level, because a half-renamed layer is how the confusing
pair got there in the first place: HTTP paths (`/template-field-library` ->
`/template-titles`), the template payload (`fields`/`field_id` ->
`placements`/`title_id`, and `field_count` -> `placement_count`), the Pydantic
schemas, the CRUD modules, the seed script, the frontend API module and types,
and `docs/OVERVIEW.md`, which now states the naming rules outright.

Two deliberate exceptions:

* `paper_template_filed_sort` is untouched — it is a column of the paper module
  and is spelled as the feature was specified.
* The MCP tools keep their agent-facing names (`field_list`, `field_ids`, and
  the `fields`/`field_id` keys in their responses). Agents already call them by
  those names; the storage names they read underneath have changed.

The migration renames in place (data preserved: 4 templates, 45 titles, 63
placements) and is written to tolerate a database where part of it already ran,
which is not hypothetical — the first attempt renamed the tables and then failed
on the column, because Alembic's MySQL dialect wants an explicit type for
`alter_column` and will not rename a column without one. TiDB carries the
foreign key along with both the renamed table and the renamed column, rehearsed
against the cluster first, and it stays enforced.

Verified: seed re-runs clean, the paper smoke test's 45 checks and the MCP
smoke test's 47 pass, `vue-tsc` and the build are clean, and the UI was driven
in a headless browser through the template list, its preview drawer, the title
library page, the template form (which now posts `placements` with `title_id`)
and the paper document with no console errors.
2026-09-22 16:55:02 +08:00

208 lines
7.0 KiB
Python

"""Paper-template endpoints (模板管理).
A template is created from two pieces of free text plus a free selection of
library titles. Nothing constrains the selection: the same title may be picked
twice, the picks may arrive in any order, and the only thing that decides how
the outline reads is ``sort``.
A template that a paper is written against is also *structure* for that paper,
not only configuration: deleting it would leave the paper with nothing to
render. That delete is therefore refused, with the same 409 the title library
uses for a title still placed in a template.
"""
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from app.crud import paper as paper_crud
from app.crud import template as crud
from app.db.session import get_db
from app.models import Template
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.template import (
TemplateCreate,
TemplateListItem,
TemplateRead,
TemplateUpdate,
)
router = APIRouter(prefix="/templates", tags=["templates"])
def _get_or_404(db: Session, template_id: int) -> Template:
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_not_used_by_papers(db: Session, template_ids: list[int]) -> None:
"""Refuse to delete templates that papers are written against.
All offenders are reported at once, so a batch delete does not turn into
trial and error. The fix is a template switch on the paper, which is one
click in the paper's own view — the message says so.
"""
counts = paper_crud.template_paper_counts(db, template_ids)
if not counts:
return
blockers = []
for template_id, count in sorted(counts.items()):
template = db.get(Template, template_id)
name = template.name if template is not None else template_id
blockers.append(f"“{name}”({count} 篇论文)")
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=(
"以下模板正被论文使用,请先在论文里切换模板:"
+ "、".join(blockers)
),
)
def _assert_titles_exist(db: Session, title_ids: list[int]) -> None:
"""Reject a selection that references titles 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_title_ids(db, title_ids)
if missing:
joined = "、".join(str(title_id) for title_id in missing)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"标题不存在:{joined}",
)
@router.get(
"",
response_model=PageResult[TemplateListItem],
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[TemplateListItem]:
"""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=TemplateRead,
status_code=status.HTTP_201_CREATED,
summary="Create a paper template",
)
def create_template(
payload: TemplateCreate,
db: Session = Depends(get_db),
) -> TemplateRead:
"""Create a template from a name, an abstract, and a title selection."""
_assert_name_free(db, payload.name)
_assert_titles_exist(db, [item.title_id for item in payload.placements])
template = crud.create(
db,
name=payload.name,
abstract=payload.abstract,
placements=payload.placements,
)
return TemplateRead.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."""
_assert_not_used_by_papers(db, list(payload.ids))
return BatchDeleteResult(deleted=crud.delete_many(db, payload.ids))
@router.get(
"/{template_id}",
response_model=TemplateRead,
summary="Fetch one paper template with its outline",
)
def get_template(template_id: int, db: Session = Depends(get_db)) -> TemplateRead:
"""Return a template; ``placements`` arrives already ordered by ``sort``."""
return TemplateRead.from_model(_get_or_404(db, template_id))
@router.patch(
"/{template_id}",
response_model=TemplateRead,
summary="Update a paper template",
)
def update_template(
template_id: int,
payload: TemplateUpdate,
db: Session = Depends(get_db),
) -> TemplateRead:
"""Update the name, the abstract, the title selection, or any combination.
``placements`` 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.placements is not None:
_assert_titles_exist(db, [item.title_id for item in payload.placements])
updated = crud.update(
db,
template,
name=payload.name,
abstract=payload.abstract,
# Both "key omitted" and "key 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,
placements=payload.placements,
)
return TemplateRead.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 titles it referenced are left alone.
Refused while a paper is written against the template: the outline is the
paper's structure, and removing it would empty the paper rather than tidy
up configuration.
"""
template = _get_or_404(db, template_id)
_assert_not_used_by_papers(db, [template_id])
crud.delete(db, template)
return Response(status_code=status.HTTP_204_NO_CONTENT)