Files
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

158 lines
4.8 KiB
Python

"""Template-title library endpoints (字段管理).
The library is global and reusable: a title exists once and is then placed into
any number of templates. That is why deleting one 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 template_title as crud
from app.db.session import get_db
from app.models import TemplateTitle
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.template_title import (
TemplateTitleCreate,
TemplateTitleRead,
TemplateTitleUpdate,
)
router = APIRouter(prefix="/template-titles", tags=["template-titles"])
def _get_or_404(db: Session, title_id: int) -> TemplateTitle:
title = crud.get(db, title_id)
if title is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"标题 {title_id} 不存在",
)
return title
def _assert_unused(db: Session, titles: list[TemplateTitle]) -> None:
"""Refuse the delete if any title 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, [title.id for title in titles])
if not counts:
return
by_id = {title.id: title.name for title in titles}
blockers = "、".join(
f"“{by_id.get(title_id, title_id)}”({count} 个模板)"
for title_id, count in sorted(counts.items())
)
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"以下标题正被模板使用,请先在模板中移除:{blockers}",
)
@router.get(
"",
response_model=PageResult[TemplateTitleRead],
summary="List the title library",
)
def list_titles(
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[TemplateTitleRead]:
"""Browse the title library, grouped by level then creation order."""
rows, total = crud.list_titles(
db,
keyword=keyword,
level=level,
page=page,
page_size=page_size,
)
return PageResult.build(
items=[TemplateTitleRead.model_validate(row) for row in rows],
total=total,
page=page,
page_size=page_size,
)
@router.post(
"",
response_model=TemplateTitleRead,
status_code=status.HTTP_201_CREATED,
summary="Create a library entry",
)
def create_title(
payload: TemplateTitleCreate,
db: Session = Depends(get_db),
) -> TemplateTitleRead:
"""Add a heading to the library, with its typography."""
return TemplateTitleRead.model_validate(crud.create(db, payload))
@router.post(
"/batch-delete",
response_model=BatchDeleteResult,
summary="Delete several library entries",
)
def batch_delete_titles(
payload: BatchDeleteRequest,
db: Session = Depends(get_db),
) -> BatchDeleteResult:
"""Delete the given titles, refusing wholesale if any is still in use."""
titles = crud.get_many(db, payload.ids)
_assert_unused(db, titles)
for title in titles:
crud.delete(db, title)
return BatchDeleteResult(deleted=len(titles))
@router.get(
"/{title_id}",
response_model=TemplateTitleRead,
summary="Fetch one library entry",
)
def get_title(
title_id: int, db: Session = Depends(get_db)
) -> TemplateTitleRead:
"""Return a single library entry."""
return TemplateTitleRead.model_validate(_get_or_404(db, title_id))
@router.patch(
"/{title_id}",
response_model=TemplateTitleRead,
summary="Update one library entry",
)
def update_title(
title_id: int,
payload: TemplateTitleUpdate,
db: Session = Depends(get_db),
) -> TemplateTitleRead:
"""Rename or restyle a library entry.
The change is visible in every template that places the title, because
templates store a reference rather than a copy.
"""
title = _get_or_404(db, title_id)
return TemplateTitleRead.model_validate(crud.update(db, title, payload))
@router.delete(
"/{title_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Delete one library entry",
)
def delete_title(title_id: int, db: Session = Depends(get_db)) -> Response:
"""Delete a library entry no template places."""
title = _get_or_404(db, title_id)
_assert_unused(db, [title])
crud.delete(db, title)
return Response(status_code=status.HTTP_204_NO_CONTENT)