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:
+30
-30
@@ -1,6 +1,6 @@
|
||||
"""Seed the template-field library and a couple of starter templates.
|
||||
"""Seed the template-title library and a couple of starter templates.
|
||||
|
||||
Idempotent: fields are matched by name and templates by name, so running it
|
||||
Idempotent: titles are matched by name and templates by name, so running it
|
||||
twice adds nothing. ``--reset`` empties the three tables first, which is the
|
||||
way to get back to the seeded baseline after experimenting.
|
||||
|
||||
@@ -27,9 +27,9 @@ from sqlalchemy import delete, select # noqa: E402
|
||||
from sqlalchemy.orm import Session # noqa: E402
|
||||
|
||||
from app.db.session import SessionLocal # noqa: E402
|
||||
from app.models import Template, TemplateFieldLibrary, TemplateField # noqa: E402
|
||||
from app.models import Template, TemplateTitle, TemplateTitlePlacement # noqa: E402
|
||||
|
||||
# --- the field library -------------------------------------------------------
|
||||
# --- the title library -------------------------------------------------------
|
||||
#
|
||||
# (name, level, font_size, font_color)
|
||||
#
|
||||
@@ -45,7 +45,7 @@ HEADING = "#1F1F1F"
|
||||
SUB = "#404040"
|
||||
GREY = "#595959"
|
||||
|
||||
FIELDS: list[tuple[str, int, Decimal, str]] = [
|
||||
TITLES: list[tuple[str, int, Decimal, str]] = [
|
||||
("0 Abstract", 1, Decimal("10.5"), GREY),
|
||||
("1 Introduction", 1, Decimal("12.0"), HEADING),
|
||||
("1.1 Research Background", 2, Decimal("10.5"), SUB),
|
||||
@@ -70,15 +70,15 @@ FIELDS: list[tuple[str, int, Decimal, str]] = [
|
||||
|
||||
# --- starter templates -------------------------------------------------------
|
||||
#
|
||||
# Each entry is (template name, abstract, [field names in display order]).
|
||||
# Each entry is (template name, abstract, [title names in display order]).
|
||||
# `sort` is assigned from the list position (1, 2, 3 ...), which is exactly
|
||||
# what the UI does when the user picks fields and orders them.
|
||||
# what the UI does when the user picks titles and orders them.
|
||||
TEMPLATES: list[tuple[str, str, list[str]]] = [
|
||||
(
|
||||
"标准学术论文(通用)",
|
||||
"完整的通用学术论文骨架,含摘要、引言、相关工作、方法、实验、讨论与结论。"
|
||||
"适合期刊或会议长文;先按此模板把结构填满,再按目标期刊微调字段。",
|
||||
[name for name, *_ in FIELDS],
|
||||
[name for name, *_ in TITLES],
|
||||
),
|
||||
(
|
||||
"四段式短文",
|
||||
@@ -117,57 +117,57 @@ TEMPLATES: list[tuple[str, str, list[str]]] = [
|
||||
|
||||
def reset(db: Session) -> None:
|
||||
"""Empty the three tables in dependency order."""
|
||||
db.execute(delete(TemplateField))
|
||||
db.execute(delete(TemplateTitlePlacement))
|
||||
db.execute(delete(Template))
|
||||
db.execute(delete(TemplateFieldLibrary))
|
||||
db.execute(delete(TemplateTitle))
|
||||
db.commit()
|
||||
|
||||
|
||||
def seed_fields(db: Session) -> dict[str, TemplateFieldLibrary]:
|
||||
"""Insert any missing library fields and return name -> field."""
|
||||
existing = {field.name: field for field in db.scalars(select(TemplateFieldLibrary)).all()}
|
||||
def seed_titles(db: Session) -> dict[str, TemplateTitle]:
|
||||
"""Insert any missing library titles and return name -> title."""
|
||||
existing = {title.name: title for title in db.scalars(select(TemplateTitle)).all()}
|
||||
|
||||
created = 0
|
||||
for name, level, font_size, font_color in FIELDS:
|
||||
for name, level, font_size, font_color in TITLES:
|
||||
if name in existing:
|
||||
continue
|
||||
field = TemplateFieldLibrary(
|
||||
title = TemplateTitle(
|
||||
name=name, level=level, font_size=font_size, font_color=font_color
|
||||
)
|
||||
db.add(field)
|
||||
existing[name] = field
|
||||
db.add(title)
|
||||
existing[name] = title
|
||||
created += 1
|
||||
|
||||
db.commit()
|
||||
for field in existing.values():
|
||||
db.refresh(field)
|
||||
for title in existing.values():
|
||||
db.refresh(title)
|
||||
|
||||
print(
|
||||
f" template_field_library : {created} created, "
|
||||
f" template_title : {created} created, "
|
||||
f"{len(existing) - created} already present"
|
||||
)
|
||||
return existing
|
||||
|
||||
|
||||
def seed_templates(db: Session, fields: dict[str, TemplateFieldLibrary]) -> None:
|
||||
def seed_templates(db: Session, titles: dict[str, TemplateTitle]) -> None:
|
||||
"""Insert any missing starter templates."""
|
||||
existing = {name for name in db.scalars(select(Template.name)).all()}
|
||||
|
||||
created = 0
|
||||
for name, abstract, field_names in TEMPLATES:
|
||||
for name, abstract, title_names in TEMPLATES:
|
||||
if name in existing:
|
||||
continue
|
||||
|
||||
missing = [field_name for field_name in field_names if field_name not in fields]
|
||||
missing = [title_name for title_name in title_names if title_name not in titles]
|
||||
if missing:
|
||||
raise SystemExit(f"template {name!r} references unknown fields: {missing}")
|
||||
raise SystemExit(f"template {name!r} references unknown titles: {missing}")
|
||||
|
||||
template = Template(name=name, abstract=abstract)
|
||||
# sort is the list position: 1-based, ascending, with gaps allowed
|
||||
# because the UI lets the user type any integer.
|
||||
template.items = [
|
||||
TemplateField(field_id=fields[field_name].id, sort=index)
|
||||
for index, field_name in enumerate(field_names, start=1)
|
||||
template.placements = [
|
||||
TemplateTitlePlacement(title_id=titles[title_name].id, sort=index)
|
||||
for index, title_name in enumerate(title_names, start=1)
|
||||
]
|
||||
db.add(template)
|
||||
created += 1
|
||||
@@ -181,7 +181,7 @@ def main() -> None:
|
||||
parser.add_argument(
|
||||
"--reset",
|
||||
action="store_true",
|
||||
help="delete all fields and templates before seeding",
|
||||
help="delete all titles and templates before seeding",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
@@ -190,8 +190,8 @@ def main() -> None:
|
||||
reset(db)
|
||||
print(" reset : all rows deleted")
|
||||
|
||||
fields = seed_fields(db)
|
||||
seed_templates(db, fields)
|
||||
titles = seed_titles(db)
|
||||
seed_templates(db, titles)
|
||||
|
||||
print("seed complete")
|
||||
|
||||
|
||||
@@ -98,14 +98,15 @@ async def expect_error(session: ClientSession, tool: str, **arguments: Any) -> s
|
||||
|
||||
|
||||
def pick_template() -> tuple[int, list[dict[str, Any]]]:
|
||||
"""The template with the most fields, and its outline as the tools see it."""
|
||||
"""The template with the most titles, and its outline as the tools see it."""
|
||||
with SessionLocal() as db:
|
||||
template = db.scalars(
|
||||
select(Template).order_by(Template.id.asc())
|
||||
).all()
|
||||
best = max(template, key=lambda item: len(item.items))
|
||||
best = max(template, key=lambda item: len(item.placements))
|
||||
return best.id, [
|
||||
{"position": item.sort, "name": item.field.name} for item in best.items
|
||||
{"position": item.sort, "name": item.title.name}
|
||||
for item in best.placements
|
||||
]
|
||||
|
||||
|
||||
@@ -437,11 +438,11 @@ async def run(url: str | None = None, token: str | None = None) -> int:
|
||||
|
||||
def _field_id(name: str) -> int:
|
||||
"""The library field behind a heading name, for the template-create step."""
|
||||
from app.models import TemplateFieldLibrary
|
||||
from app.models import TemplateTitle
|
||||
|
||||
with SessionLocal() as db:
|
||||
row = db.scalars(
|
||||
select(TemplateFieldLibrary).where(TemplateFieldLibrary.name == name)
|
||||
select(TemplateTitle).where(TemplateTitle.name == name)
|
||||
).first()
|
||||
if row is None:
|
||||
raise AssertionError(f"field {name!r} not in the library")
|
||||
|
||||
@@ -73,11 +73,11 @@ def main() -> int:
|
||||
print("1. pick two templates with different paragraph positions")
|
||||
templates = call("GET", "/templates?page_size=50")["items"]
|
||||
check("templates exist", len(templates) >= 2, f"got {len(templates)}")
|
||||
wide = max(templates, key=lambda item: item["field_count"])
|
||||
narrow = min(templates, key=lambda item: item["field_count"])
|
||||
wide = max(templates, key=lambda item: item["placement_count"])
|
||||
narrow = min(templates, key=lambda item: item["placement_count"])
|
||||
wide_full = call("GET", f"/templates/{wide['id']}")
|
||||
narrow_full = call("GET", f"/templates/{narrow['id']}")
|
||||
print(f" wide={wide['name']} ({wide['field_count']}), narrow={narrow['name']}")
|
||||
print(f" wide={wide['name']} ({wide['placement_count']}), narrow={narrow['name']}")
|
||||
|
||||
print("2. create a paper")
|
||||
paper = call(
|
||||
@@ -97,7 +97,8 @@ def main() -> int:
|
||||
check("keywords normalised", paper["keywords"] == "关键词A, 关键词B", paper["keywords"])
|
||||
check(
|
||||
"paragraph denominator counts the template",
|
||||
paper["template_paragraph_count"] == len({f["sort"] for f in wide_full["fields"]}),
|
||||
paper["template_paragraph_count"]
|
||||
== len({p["sort"] for p in wide_full["placements"]}),
|
||||
str(paper["template_paragraph_count"]),
|
||||
)
|
||||
check("no sentences yet", paper["sentence_count"] == 0)
|
||||
@@ -106,7 +107,7 @@ def main() -> int:
|
||||
document = call("GET", f"/papers/{paper['id']}/document")
|
||||
check(
|
||||
"every template position is a paragraph",
|
||||
len(document["paragraphs"]) == len({f["sort"] for f in wide_full["fields"]}),
|
||||
len(document["paragraphs"]) == len({p["sort"] for p in wide_full["placements"]}),
|
||||
str(len(document["paragraphs"])),
|
||||
)
|
||||
check("all paragraphs empty", all(not p["sentences"] for p in document["paragraphs"]))
|
||||
@@ -238,7 +239,11 @@ def main() -> int:
|
||||
# A position neither template defines, so the check means the same
|
||||
# thing before and after the switch below.
|
||||
orphan_sort = (
|
||||
max(f["sort"] for f in wide_full["fields"] + narrow_full["fields"]) + 5
|
||||
max(
|
||||
p["sort"]
|
||||
for p in wide_full["placements"] + narrow_full["placements"]
|
||||
)
|
||||
+ 5
|
||||
)
|
||||
call(
|
||||
"POST",
|
||||
@@ -266,7 +271,7 @@ def main() -> int:
|
||||
unmatched = [p for p in document["paragraphs"] if not p["matched"]]
|
||||
check(
|
||||
"structure follows the new template",
|
||||
len(matched) == len({f["sort"] for f in narrow_full["fields"]}),
|
||||
len(matched) == len({p["sort"] for p in narrow_full["placements"]}),
|
||||
str(len(matched)),
|
||||
)
|
||||
check("unmatched positions kept", len(unmatched) >= 1, str(len(unmatched)))
|
||||
|
||||
Reference in New Issue
Block a user