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

126 lines
3.9 KiB
Python

"""Data access for the reusable template-title library (字段管理)."""
from collections.abc import Sequence
from sqlalchemy import Select, func, select
from sqlalchemy.orm import Session
from app.crud.filters import LIKE_ESCAPE, like_pattern
from app.models import TemplateTitlePlacement, TemplateTitle
from app.schemas.template_title import (
TemplateTitleCreate,
TemplateTitleUpdate,
)
def _conditions(keyword: str | None, level: int | None) -> list:
"""Translate the list filters into SQLAlchemy predicates."""
conditions = []
if keyword:
conditions.append(
TemplateTitle.name.like(like_pattern(keyword), escape=LIKE_ESCAPE)
)
if level is not None:
conditions.append(TemplateTitle.level == level)
return conditions
def _ordered(stmt: Select) -> Select:
"""Apply the library's canonical browse order.
Grouped by ``level`` first so the picker reads as an outline, then by
insertion order so a title stays where the user put it. Deliberately *not*
ordered by ``name``: names carry hand-written numbering ("1.", "10.",
"2."), and string ordering would scramble it.
"""
return stmt.order_by(TemplateTitle.level.asc(), TemplateTitle.id.asc())
def list_titles(
db: Session,
*,
keyword: str | None = None,
level: int | None = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[TemplateTitle], int]:
"""Return one page of the title library, plus the unpaged total."""
conditions = _conditions(keyword, level)
total = db.scalar(
select(func.count(TemplateTitle.id)).where(*conditions)
) or 0
stmt = _ordered(
select(TemplateTitle)
.where(*conditions)
.offset((page - 1) * page_size)
.limit(page_size)
)
return list(db.scalars(stmt).all()), total
def get(db: Session, title_id: int) -> TemplateTitle | None:
"""Return one library entry, or ``None``."""
return db.get(TemplateTitle, title_id)
def get_many(db: Session, title_ids: Sequence[int]) -> list[TemplateTitle]:
"""Return every entry whose id is in ``title_ids`` (missing ids ignored)."""
if not title_ids:
return []
stmt = select(TemplateTitle).where(TemplateTitle.id.in_(list(title_ids)))
return list(db.scalars(stmt).all())
def usage_counts(db: Session, title_ids: Sequence[int]) -> dict[int, int]:
"""Count how many *distinct templates* place each title.
Drives the refusal message when a title in use is deleted. ``DISTINCT``
matters because one template may legitimately place the same title twice.
"""
if not title_ids:
return {}
stmt = (
select(
TemplateTitlePlacement.title_id,
func.count(func.distinct(TemplateTitlePlacement.template_id)),
)
.where(TemplateTitlePlacement.title_id.in_(list(title_ids)))
.group_by(TemplateTitlePlacement.title_id)
)
return {title_id: count for title_id, count in db.execute(stmt).all()}
def create(db: Session, data: TemplateTitleCreate) -> TemplateTitle:
"""Insert a library entry."""
title = TemplateTitle(**data.model_dump())
db.add(title)
db.commit()
db.refresh(title)
return title
def update(
db: Session,
title: TemplateTitle,
data: TemplateTitleUpdate,
) -> TemplateTitle:
"""Apply a partial update to a library entry.
``exclude_unset`` is what makes PATCH semantics work: a key the client did
not send leaves the column alone, while an explicit ``null`` — which the
schemas reject for every nullable-typed column here — would not.
"""
for key, value in data.model_dump(exclude_unset=True).items():
setattr(title, key, value)
db.commit()
db.refresh(title)
return title
def delete(db: Session, title: TemplateTitle) -> None:
"""Delete a library entry. Callers must check :func:`usage_counts` first."""
db.delete(title)
db.commit()