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.
This commit is contained in:
@@ -2,10 +2,10 @@
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.routes import health, papers, template_field_library, templates
|
||||
from app.api.routes import health, papers, template_titles, templates
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(health.router)
|
||||
api_router.include_router(papers.router)
|
||||
api_router.include_router(template_field_library.router)
|
||||
api_router.include_router(template_titles.router)
|
||||
api_router.include_router(templates.router)
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
"""Template-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 template_field_library as crud
|
||||
from app.db.session import get_db
|
||||
from app.models import TemplateFieldLibrary
|
||||
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
|
||||
from app.schemas.template_field_library import (
|
||||
TemplateFieldLibraryCreate,
|
||||
TemplateFieldLibraryRead,
|
||||
TemplateFieldLibraryUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/template-field-library", tags=["template-field-library"])
|
||||
|
||||
|
||||
def _get_or_404(db: Session, field_id: int) -> TemplateFieldLibrary:
|
||||
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[TemplateFieldLibrary]) -> 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[TemplateFieldLibraryRead],
|
||||
summary="List the field library",
|
||||
)
|
||||
def list_library_entries(
|
||||
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[TemplateFieldLibraryRead]:
|
||||
"""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=[TemplateFieldLibraryRead.model_validate(row) for row in rows],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=TemplateFieldLibraryRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a library entry",
|
||||
)
|
||||
def create_library_entry(
|
||||
payload: TemplateFieldLibraryCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateFieldLibraryRead:
|
||||
"""Add a heading to the library, with its typography."""
|
||||
return TemplateFieldLibraryRead.model_validate(crud.create(db, payload))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-delete",
|
||||
response_model=BatchDeleteResult,
|
||||
summary="Delete several library entries",
|
||||
)
|
||||
def batch_delete_library_entries(
|
||||
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=TemplateFieldLibraryRead,
|
||||
summary="Fetch one library entry",
|
||||
)
|
||||
def get_library_entry(
|
||||
field_id: int, db: Session = Depends(get_db)
|
||||
) -> TemplateFieldLibraryRead:
|
||||
"""Return a single library entry."""
|
||||
return TemplateFieldLibraryRead.model_validate(_get_or_404(db, field_id))
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/{field_id}",
|
||||
response_model=TemplateFieldLibraryRead,
|
||||
summary="Update one library entry",
|
||||
)
|
||||
def update_library_entry(
|
||||
field_id: int,
|
||||
payload: TemplateFieldLibraryUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateFieldLibraryRead:
|
||||
"""Rename or restyle a library entry.
|
||||
|
||||
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 TemplateFieldLibraryRead.model_validate(crud.update(db, field, payload))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{field_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Delete one library entry",
|
||||
)
|
||||
def delete_library_entry(field_id: int, db: Session = Depends(get_db)) -> Response:
|
||||
"""Delete a library entry no template places."""
|
||||
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,157 @@
|
||||
"""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)
|
||||
@@ -1,14 +1,14 @@
|
||||
"""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
|
||||
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 field library
|
||||
uses for a field still placed in a template.
|
||||
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
|
||||
@@ -73,19 +73,19 @@ def _assert_not_used_by_papers(db: Session, template_ids: list[int]) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _assert_fields_exist(db: Session, field_ids: list[int]) -> None:
|
||||
"""Reject a selection that references fields the library does not have.
|
||||
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_field_ids(db, field_ids)
|
||||
missing = crud.missing_title_ids(db, title_ids)
|
||||
if missing:
|
||||
joined = "、".join(str(field_id) for field_id in missing)
|
||||
joined = "、".join(str(title_id) for title_id in missing)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"字段不存在:{joined}",
|
||||
detail=f"标题不存在:{joined}",
|
||||
)
|
||||
|
||||
|
||||
@@ -117,15 +117,15 @@ def create_template(
|
||||
payload: TemplateCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateRead:
|
||||
"""Create a template from a name, an abstract, and a field selection."""
|
||||
"""Create a template from a name, an abstract, and a title selection."""
|
||||
_assert_name_free(db, payload.name)
|
||||
_assert_fields_exist(db, [item.field_id for item in payload.fields])
|
||||
_assert_titles_exist(db, [item.title_id for item in payload.placements])
|
||||
|
||||
template = crud.create(
|
||||
db,
|
||||
name=payload.name,
|
||||
abstract=payload.abstract,
|
||||
fields=payload.fields,
|
||||
placements=payload.placements,
|
||||
)
|
||||
return TemplateRead.from_model(template)
|
||||
|
||||
@@ -150,7 +150,7 @@ def batch_delete_templates(
|
||||
summary="Fetch one paper template with its outline",
|
||||
)
|
||||
def get_template(template_id: int, db: Session = Depends(get_db)) -> TemplateRead:
|
||||
"""Return a template; ``fields`` arrives already ordered by ``sort``."""
|
||||
"""Return a template; ``placements`` arrives already ordered by ``sort``."""
|
||||
return TemplateRead.from_model(_get_or_404(db, template_id))
|
||||
|
||||
|
||||
@@ -164,27 +164,27 @@ def update_template(
|
||||
payload: TemplateUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateRead:
|
||||
"""Update the name, the abstract, the field selection, or any combination.
|
||||
"""Update the name, the abstract, the title selection, or any combination.
|
||||
|
||||
``fields`` is a full replacement when present. Omitting it leaves the
|
||||
``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.fields is not None:
|
||||
_assert_fields_exist(db, [item.field_id for item in payload.fields])
|
||||
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 "field omitted" and "field set to null" arrive as None; only
|
||||
# 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,
|
||||
fields=payload.fields,
|
||||
placements=payload.placements,
|
||||
)
|
||||
return TemplateRead.from_model(updated)
|
||||
|
||||
@@ -195,7 +195,7 @@ def update_template(
|
||||
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.
|
||||
"""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
|
||||
|
||||
Reference in New Issue
Block a user