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:
@@ -0,0 +1,122 @@
|
||||
"""rename the template tables and columns to the title vocabulary
|
||||
|
||||
Three names described the same thing by different words, so the schema read as
|
||||
if it held four concepts:
|
||||
|
||||
template_field_library the catalogue of reusable headings (字段库)
|
||||
template_field one heading placed in one template, with its sort
|
||||
|
||||
``template_field`` is one word away from ``template_field_library`` and means
|
||||
the opposite kind of thing — a row versus the catalogue of rows — and neither
|
||||
name says 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. So the library becomes
|
||||
``template_title`` and the placement becomes ``template_title_placement``, and
|
||||
the placement's reference to the library becomes ``title_id``. The name now says
|
||||
which is the catalogue and which is a placement, which is the distinction the
|
||||
old pair hid.
|
||||
|
||||
template_title one reusable heading (字段库)
|
||||
template_title_placement that heading placed in a template, with `sort`
|
||||
|
||||
Nothing else moves: ``template`` keeps its name, and every row in every table is
|
||||
preserved. ``RENAME TABLE`` moves the data in place, and TiDB carries a
|
||||
referencing foreign key along with both a renamed table and a renamed column
|
||||
(rehearsed against the cluster before this revision was written), so the
|
||||
constraint in ``template_title_placement`` follows without a drop/recreate step
|
||||
and stays enforced.
|
||||
|
||||
Revision ID: b19e4d7a3c58
|
||||
Revises: a83f5c21d7b6
|
||||
Create Date: 2026-09-22
|
||||
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "b19e4d7a3c58"
|
||||
down_revision: str | None = "a83f5c21d7b6"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
#: (old, new) index names on the placement table. They embed the table name and
|
||||
#: the column name, so both renames have to reach them or the schema ends up
|
||||
#: with indexes named after tables that no longer exist.
|
||||
_INDEXES = (
|
||||
("ix_template_field_field_id", "ix_template_title_placement_title_id"),
|
||||
("ix_template_field_template_sort", "ix_template_title_placement_template_sort"),
|
||||
)
|
||||
|
||||
#: Index names that already say the new thing, so a rerun leaves them alone.
|
||||
_NEW_INDEXES = {new for _, new in _INDEXES}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Rename in place, tolerating a database where part of it already ran.
|
||||
|
||||
Each step is guarded by what the database actually holds, rather than
|
||||
assuming a clean start. That is not decoration: the first attempt at this
|
||||
revision renamed the two tables and then failed on the column, because
|
||||
Alembic's MySQL dialect wants an explicit type for ``alter_column`` and
|
||||
won't rename a column without one. A migration that re-runs is the only way
|
||||
to finish a database left in that state, and it costs three dict lookups to
|
||||
be able to.
|
||||
"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
|
||||
tables = set(inspector.get_table_names())
|
||||
if "template_field_library" in tables:
|
||||
op.rename_table("template_field_library", "template_title")
|
||||
if "template_field" in tables:
|
||||
op.rename_table("template_field", "template_title_placement")
|
||||
|
||||
columns = {
|
||||
column["name"]
|
||||
for column in inspector.get_columns("template_title_placement")
|
||||
}
|
||||
if "field_id" in columns:
|
||||
# Raw SQL rather than ``op.alter_column``: TiDB supports
|
||||
# ``RENAME COLUMN`` directly, and the Alembic spelling goes through
|
||||
# ``CHANGE COLUMN``, which demands the current type be repeated.
|
||||
op.execute(
|
||||
"ALTER TABLE template_title_placement RENAME COLUMN field_id TO title_id"
|
||||
)
|
||||
|
||||
indexes = {index["name"] for index in inspector.get_indexes("template_title_placement")}
|
||||
for old, new in _INDEXES:
|
||||
if old in indexes and new not in indexes:
|
||||
op.execute(
|
||||
f"ALTER TABLE template_title_placement RENAME INDEX {old} TO {new}"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
|
||||
indexes = {
|
||||
index["name"]
|
||||
for index in inspector.get_indexes("template_title_placement")
|
||||
}
|
||||
for old, new in _INDEXES:
|
||||
if new in indexes and old not in indexes:
|
||||
op.execute(
|
||||
f"ALTER TABLE template_title_placement RENAME INDEX {new} TO {old}"
|
||||
)
|
||||
|
||||
columns = {
|
||||
column["name"]
|
||||
for column in inspector.get_columns("template_title_placement")
|
||||
}
|
||||
if "title_id" in columns:
|
||||
op.execute(
|
||||
"ALTER TABLE template_title_placement RENAME COLUMN title_id TO field_id"
|
||||
)
|
||||
|
||||
op.rename_table("template_title_placement", "template_field")
|
||||
op.rename_table("template_title", "template_field_library")
|
||||
@@ -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
|
||||
|
||||
@@ -5,6 +5,6 @@ models. They own the commit: a route calls one function and gets back either a
|
||||
persisted object or ``None``.
|
||||
"""
|
||||
|
||||
from app.crud import paper, template, template_field_library
|
||||
from app.crud import paper, template, template_title
|
||||
|
||||
__all__ = ["paper", "template", "template_field_library"]
|
||||
__all__ = ["paper", "template", "template_title"]
|
||||
|
||||
+16
-16
@@ -37,7 +37,7 @@ from app.models import (
|
||||
PaperSentence,
|
||||
PaperSentenceReference,
|
||||
Template,
|
||||
TemplateField,
|
||||
TemplateTitlePlacement,
|
||||
)
|
||||
from app.schemas.paper import (
|
||||
CitationInput,
|
||||
@@ -112,8 +112,8 @@ def _template_paragraph_count_column():
|
||||
is one paragraph, not two. A paper with no template counts 0.
|
||||
"""
|
||||
return (
|
||||
select(func.count(func.distinct(TemplateField.sort)))
|
||||
.where(TemplateField.template_id == Paper.template_id)
|
||||
select(func.count(func.distinct(TemplateTitlePlacement.sort)))
|
||||
.where(TemplateTitlePlacement.template_id == Paper.template_id)
|
||||
.correlate(Paper)
|
||||
.scalar_subquery()
|
||||
)
|
||||
@@ -219,7 +219,7 @@ def read(paper: Paper) -> PaperRead:
|
||||
sentence_count=len(paper.sentences),
|
||||
paragraph_count=len({s.paper_template_filed_sort for s in paper.sentences}),
|
||||
template_paragraph_count=(
|
||||
len({placement.sort for placement in paper.template.items})
|
||||
len({placement.sort for placement in paper.template.placements})
|
||||
if paper.template is not None
|
||||
else 0
|
||||
),
|
||||
@@ -301,15 +301,15 @@ def build_document(db: Session, paper: Paper) -> PaperDocumentRead:
|
||||
# ``sort, id`` — is the one that renders the heading. The reader is told,
|
||||
# because two fields sharing a position is far more often a mistake than a
|
||||
# plan.
|
||||
placement_by_sort: dict[int, TemplateField] = {}
|
||||
placement_by_sort: dict[int, TemplateTitlePlacement] = {}
|
||||
tied: dict[int, list[str]] = defaultdict(list)
|
||||
for item in paper.template.items if paper.template is not None else []:
|
||||
for item in paper.template.placements if paper.template is not None else []:
|
||||
if item.sort in placement_by_sort:
|
||||
tied[item.sort].append(item.field.name)
|
||||
tied[item.sort].append(item.title.name)
|
||||
else:
|
||||
placement_by_sort[item.sort] = item
|
||||
for sort, names in sorted(tied.items()):
|
||||
head = placement_by_sort[sort].field.name
|
||||
head = placement_by_sort[sort].title.name
|
||||
warnings.append(
|
||||
f"模板在第 {sort} 段放了多个字段({head}、{'、'.join(names)}),"
|
||||
"正文按第一条显示。"
|
||||
@@ -322,7 +322,7 @@ def build_document(db: Session, paper: Paper) -> PaperDocumentRead:
|
||||
|
||||
if paper.template is None and paper.sentences:
|
||||
warnings.append("这篇论文还没有选择模板,段落没有对应标题,全部按未设定显示。")
|
||||
if paper.template is not None and not paper.template.items:
|
||||
if paper.template is not None and not paper.template.placements:
|
||||
warnings.append("所用模板还没有任何段落字段,论文暂时没有结构。")
|
||||
|
||||
# --- 3. the union, in ascending position order --------------------------
|
||||
@@ -334,7 +334,7 @@ def build_document(db: Session, paper: Paper) -> PaperDocumentRead:
|
||||
|
||||
for position in positions:
|
||||
placement = placement_by_sort.get(position)
|
||||
field = placement.field if placement is not None else None
|
||||
title = placement.title if placement is not None else None
|
||||
|
||||
# Re-sorted rather than trusted: the relationship already orders rows,
|
||||
# but ordering is a contract of this response, so it is stated here too.
|
||||
@@ -352,12 +352,12 @@ def build_document(db: Session, paper: Paper) -> PaperDocumentRead:
|
||||
|
||||
paragraph = ParagraphRead(
|
||||
paper_template_filed_sort=position,
|
||||
template_field_id=placement.id if placement is not None else None,
|
||||
field_id=field.id if field is not None else None,
|
||||
name=field.name if field is not None else None,
|
||||
level=field.level if field is not None else 1,
|
||||
font_size=float(field.font_size) if field is not None else None,
|
||||
font_color=field.font_color if field is not None else None,
|
||||
placement_id=placement.id if placement is not None else None,
|
||||
title_id=title.id if title is not None else None,
|
||||
name=title.name if title is not None else None,
|
||||
level=title.level if title is not None else 1,
|
||||
font_size=float(title.font_size) if title is not None else None,
|
||||
font_color=title.font_color if title is not None else None,
|
||||
matched=placement is not None,
|
||||
sentences=sentences,
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Data access for templates and their ordered field selections."""
|
||||
"""Data access for templates and their ordered title selections."""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
@@ -6,8 +6,8 @@ from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud.filters import LIKE_ESCAPE, like_pattern
|
||||
from app.models import Template, TemplateFieldLibrary, TemplateField
|
||||
from app.schemas.template import TemplateListItem, TemplateFieldInput
|
||||
from app.models import Template, TemplateTitle, TemplateTitlePlacement
|
||||
from app.schemas.template import TemplateListItem, TemplateTitlePlacementInput
|
||||
|
||||
|
||||
def _conditions(keyword: str | None) -> list:
|
||||
@@ -23,11 +23,11 @@ def _conditions(keyword: str | None) -> list:
|
||||
]
|
||||
|
||||
|
||||
def _field_count_column():
|
||||
def _placement_count_column():
|
||||
"""A correlated ``COUNT`` of the template's placement rows."""
|
||||
return (
|
||||
select(func.count(TemplateField.id))
|
||||
.where(TemplateField.template_id == Template.id)
|
||||
select(func.count(TemplateTitlePlacement.id))
|
||||
.where(TemplateTitlePlacement.template_id == Template.id)
|
||||
.correlate(Template)
|
||||
.scalar_subquery()
|
||||
)
|
||||
@@ -40,7 +40,7 @@ def list_templates(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> tuple[list[TemplateListItem], int]:
|
||||
"""Return one page of templates with their field counts, plus the total.
|
||||
"""Return one page of templates with their placement counts, plus the total.
|
||||
|
||||
The outline itself is left out: a table row needs the count, not the rows.
|
||||
Recently edited templates come first, since that is what a user returns to.
|
||||
@@ -52,7 +52,7 @@ def list_templates(
|
||||
) or 0
|
||||
|
||||
stmt = (
|
||||
select(Template, _field_count_column().label("field_count"))
|
||||
select(Template, _placement_count_column().label("placement_count"))
|
||||
.where(*conditions)
|
||||
.order_by(Template.updated_at.desc(), Template.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
@@ -64,11 +64,11 @@ def list_templates(
|
||||
id=template.id,
|
||||
name=template.name,
|
||||
abstract=template.abstract,
|
||||
field_count=field_count,
|
||||
placement_count=placement_count,
|
||||
created_at=template.created_at,
|
||||
updated_at=template.updated_at,
|
||||
)
|
||||
for template, field_count in db.execute(stmt).all()
|
||||
for template, placement_count in db.execute(stmt).all()
|
||||
]
|
||||
return items, total
|
||||
|
||||
@@ -76,9 +76,9 @@ def list_templates(
|
||||
def get(db: Session, template_id: int) -> Template | None:
|
||||
"""Return one template with its outline already loaded, or ``None``.
|
||||
|
||||
``items`` (ordered by ``sort``) and each item's ``field`` are both
|
||||
configured for eager loading on the relationships, so this is a fixed
|
||||
number of queries rather than one per field.
|
||||
``placements`` (ordered by ``sort``) and each placement's ``title`` are
|
||||
both configured for eager loading on the relationships, so this is a fixed
|
||||
number of queries rather than one per title.
|
||||
"""
|
||||
return db.get(Template, template_id)
|
||||
|
||||
@@ -91,24 +91,29 @@ def name_taken(db: Session, name: str, *, exclude_id: int | None = None) -> bool
|
||||
return bool(db.scalar(stmt))
|
||||
|
||||
|
||||
def missing_field_ids(db: Session, field_ids: Sequence[int]) -> list[int]:
|
||||
"""Which of ``field_ids`` do not exist in the field library.
|
||||
def missing_title_ids(db: Session, title_ids: Sequence[int]) -> list[int]:
|
||||
"""Which of ``title_ids`` do not exist in the title library.
|
||||
|
||||
Returning the offenders rather than a boolean lets the API name them, which
|
||||
is the difference between a usable error and "invalid request".
|
||||
"""
|
||||
wanted = set(field_ids)
|
||||
wanted = set(title_ids)
|
||||
if not wanted:
|
||||
return []
|
||||
found = set(
|
||||
db.scalars(select(TemplateFieldLibrary.id).where(TemplateFieldLibrary.id.in_(wanted))).all()
|
||||
db.scalars(select(TemplateTitle.id).where(TemplateTitle.id.in_(wanted))).all()
|
||||
)
|
||||
return sorted(wanted - found)
|
||||
|
||||
|
||||
def _build_items(fields: Sequence[TemplateFieldInput]) -> list[TemplateField]:
|
||||
def _build_placements(
|
||||
placements: Sequence[TemplateTitlePlacementInput],
|
||||
) -> list[TemplateTitlePlacement]:
|
||||
"""Materialise the client's selection into placement rows."""
|
||||
return [TemplateField(field_id=item.field_id, sort=item.sort) for item in fields]
|
||||
return [
|
||||
TemplateTitlePlacement(title_id=item.title_id, sort=item.sort)
|
||||
for item in placements
|
||||
]
|
||||
|
||||
|
||||
def create(
|
||||
@@ -116,11 +121,11 @@ def create(
|
||||
*,
|
||||
name: str,
|
||||
abstract: str | None,
|
||||
fields: Sequence[TemplateFieldInput],
|
||||
placements: Sequence[TemplateTitlePlacementInput],
|
||||
) -> Template:
|
||||
"""Insert a template together with its ordered selection."""
|
||||
template = Template(name=name, abstract=abstract)
|
||||
template.items = _build_items(fields)
|
||||
template.placements = _build_placements(placements)
|
||||
db.add(template)
|
||||
db.commit()
|
||||
db.refresh(template)
|
||||
@@ -134,9 +139,9 @@ def update(
|
||||
name: str | None = None,
|
||||
abstract: str | None = None,
|
||||
abstract_provided: bool = False,
|
||||
fields: Sequence[TemplateFieldInput] | None = None,
|
||||
placements: Sequence[TemplateTitlePlacementInput] | None = None,
|
||||
) -> Template:
|
||||
"""Apply a partial update. ``fields=None`` leaves the selection untouched.
|
||||
"""Apply a partial update. ``placements=None`` leaves the selection untouched.
|
||||
|
||||
``abstract_provided`` distinguishes "clear the abstract" from "leave it" —
|
||||
both arrive as ``None`` in the payload, and only the caller knows which the
|
||||
@@ -146,13 +151,12 @@ def update(
|
||||
template.name = name
|
||||
if abstract_provided:
|
||||
template.abstract = abstract
|
||||
if fields is not None:
|
||||
# delete-orphan removes the dropped rows on flush. TiDB does not
|
||||
# enforce ON DELETE CASCADE, so this ORM-level cascade is the only
|
||||
# thing cleaning up the join table.
|
||||
template.items.clear()
|
||||
if placements is not None:
|
||||
# delete-orphan removes the dropped rows on flush. The ORM cascade is
|
||||
# what cleans up the join table, whether or not the database would.
|
||||
template.placements.clear()
|
||||
db.flush()
|
||||
template.items.extend(_build_items(fields))
|
||||
template.placements.extend(_build_placements(placements))
|
||||
|
||||
db.commit()
|
||||
db.refresh(template)
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
"""Data access for the reusable template-field 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 TemplateField, TemplateFieldLibrary
|
||||
from app.schemas.template_field_library import (
|
||||
TemplateFieldLibraryCreate,
|
||||
TemplateFieldLibraryUpdate,
|
||||
)
|
||||
|
||||
|
||||
def _conditions(keyword: str | None, level: int | None) -> list:
|
||||
"""Translate the list filters into SQLAlchemy predicates."""
|
||||
conditions = []
|
||||
if keyword:
|
||||
conditions.append(
|
||||
TemplateFieldLibrary.name.like(like_pattern(keyword), escape=LIKE_ESCAPE)
|
||||
)
|
||||
if level is not None:
|
||||
conditions.append(TemplateFieldLibrary.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 field 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(TemplateFieldLibrary.level.asc(), TemplateFieldLibrary.id.asc())
|
||||
|
||||
|
||||
def list_fields(
|
||||
db: Session,
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
level: int | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> tuple[list[TemplateFieldLibrary], int]:
|
||||
"""Return one page of the field library, plus the unpaged total."""
|
||||
conditions = _conditions(keyword, level)
|
||||
|
||||
total = db.scalar(
|
||||
select(func.count(TemplateFieldLibrary.id)).where(*conditions)
|
||||
) or 0
|
||||
|
||||
stmt = _ordered(
|
||||
select(TemplateFieldLibrary)
|
||||
.where(*conditions)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
)
|
||||
return list(db.scalars(stmt).all()), total
|
||||
|
||||
|
||||
def get(db: Session, field_id: int) -> TemplateFieldLibrary | None:
|
||||
"""Return one field, or ``None``."""
|
||||
return db.get(TemplateFieldLibrary, field_id)
|
||||
|
||||
|
||||
def get_many(db: Session, field_ids: Sequence[int]) -> list[TemplateFieldLibrary]:
|
||||
"""Return every field whose id is in ``field_ids`` (missing ids ignored)."""
|
||||
if not field_ids:
|
||||
return []
|
||||
stmt = select(TemplateFieldLibrary).where(TemplateFieldLibrary.id.in_(list(field_ids)))
|
||||
return list(db.scalars(stmt).all())
|
||||
|
||||
|
||||
def usage_counts(db: Session, field_ids: Sequence[int]) -> dict[int, int]:
|
||||
"""Count how many *distinct templates* place each field.
|
||||
|
||||
Drives the refusal message when a field in use is deleted. ``DISTINCT``
|
||||
matters because one template may legitimately place the same field twice.
|
||||
"""
|
||||
if not field_ids:
|
||||
return {}
|
||||
stmt = (
|
||||
select(
|
||||
TemplateField.field_id,
|
||||
func.count(func.distinct(TemplateField.template_id)),
|
||||
)
|
||||
.where(TemplateField.field_id.in_(list(field_ids)))
|
||||
.group_by(TemplateField.field_id)
|
||||
)
|
||||
return {field_id: count for field_id, count in db.execute(stmt).all()}
|
||||
|
||||
|
||||
def create(db: Session, data: TemplateFieldLibraryCreate) -> TemplateFieldLibrary:
|
||||
"""Insert a field."""
|
||||
field = TemplateFieldLibrary(**data.model_dump())
|
||||
db.add(field)
|
||||
db.commit()
|
||||
db.refresh(field)
|
||||
return field
|
||||
|
||||
|
||||
def update(
|
||||
db: Session,
|
||||
field: TemplateFieldLibrary,
|
||||
data: TemplateFieldLibraryUpdate,
|
||||
) -> TemplateFieldLibrary:
|
||||
"""Apply a partial update to a field.
|
||||
|
||||
``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(field, key, value)
|
||||
db.commit()
|
||||
db.refresh(field)
|
||||
return field
|
||||
|
||||
|
||||
def delete(db: Session, field: TemplateFieldLibrary) -> None:
|
||||
"""Delete a field. Callers must check :func:`usage_counts` first."""
|
||||
db.delete(field)
|
||||
db.commit()
|
||||
@@ -0,0 +1,125 @@
|
||||
"""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()
|
||||
@@ -23,7 +23,7 @@ from sqlalchemy import func, select
|
||||
from app.core.config import get_settings
|
||||
from app.db.session import SessionLocal
|
||||
from app.mcp.server import SERVER_VERSION
|
||||
from app.models import Paper, PaperSentence, Template, TemplateFieldLibrary
|
||||
from app.models import Paper, PaperSentence, Template, TemplateTitle
|
||||
|
||||
|
||||
def run_selfcheck(server: MCPServer) -> int:
|
||||
@@ -38,8 +38,8 @@ def run_selfcheck(server: MCPServer) -> int:
|
||||
"paper": db.scalar(select(func.count(Paper.id))) or 0,
|
||||
"template": db.scalar(select(func.count(Template.id))) or 0,
|
||||
"paper_sentence": db.scalar(select(func.count(PaperSentence.id))) or 0,
|
||||
"template_field_library": db.scalar(
|
||||
select(func.count(TemplateFieldLibrary.id))
|
||||
"template_title": db.scalar(
|
||||
select(func.count(TemplateTitle.id))
|
||||
)
|
||||
or 0,
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ These are tool-argument models, not domain models: they exist so the JSON
|
||||
Schema a client receives is precise enough that the model gets the shape right
|
||||
the first time. Each one is converted into the project's own payload
|
||||
(:class:`~app.schemas.paper.SentenceInput`,
|
||||
:class:`~app.schemas.template.TemplateFieldInput`) before it reaches the CRUD
|
||||
:class:`~app.schemas.template.TemplateTitlePlacementInput`) before it reaches the CRUD
|
||||
layer, so the validation rules stay in one place — a citation with a blank
|
||||
quote is refused here for the same reason the REST API refuses it.
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ from app.models import (
|
||||
Paper,
|
||||
PaperSentence,
|
||||
Template,
|
||||
TemplateFieldLibrary,
|
||||
TemplateTitle,
|
||||
)
|
||||
from app.schemas.paper import (
|
||||
CitationInput,
|
||||
@@ -169,9 +169,9 @@ def template_or_fail(db: Session, template_id: int) -> Template:
|
||||
return template
|
||||
|
||||
|
||||
def field_or_fail(db: Session, field_id: int) -> TemplateFieldLibrary:
|
||||
def field_or_fail(db: Session, field_id: int) -> TemplateTitle:
|
||||
"""Return one library field, or refuse with the id that was not found."""
|
||||
from app.crud import template_field_library as field_crud
|
||||
from app.crud import template_title as field_crud
|
||||
|
||||
field = field_crud.get(db, field_id)
|
||||
if field is None:
|
||||
@@ -359,14 +359,16 @@ def heading_index(paper: Paper) -> list[dict]:
|
||||
return []
|
||||
|
||||
seen: dict[int, dict] = {}
|
||||
for placement in paper.template.items:
|
||||
for placement in paper.template.placements:
|
||||
if placement.sort in seen:
|
||||
continue
|
||||
seen[placement.sort] = {
|
||||
"position": placement.sort,
|
||||
"heading": placement.field.name,
|
||||
"level": placement.field.level,
|
||||
"field_id": placement.field_id,
|
||||
"heading": placement.title.name,
|
||||
"level": placement.title.level,
|
||||
# Emitted as "field_id" because that is the name this interface
|
||||
# uses for a library entry; the column behind it is title_id.
|
||||
"field_id": placement.title_id,
|
||||
}
|
||||
return [seen[position] for position in sorted(seen)]
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Field-library tools (字段库): the reusable headings templates are built from.
|
||||
|
||||
The library is the catalogue, and ``template_field`` is a placement in one
|
||||
The library is the catalogue, and ``template_title_placement`` is a placement in one
|
||||
template — one word apart, opposite meanings. A field exists once and may be
|
||||
placed by any number of templates, which is why editing a field restyles every
|
||||
outline that uses it and why deleting one is refused while any template still
|
||||
@@ -20,13 +20,13 @@ from mcp.server.mcpserver import MCPServer
|
||||
from pydantic import Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud import template_field_library as field_crud
|
||||
from app.crud import template_title as field_crud
|
||||
from app.mcp import support as s
|
||||
from app.mcp.tools.registry import mcp_tool
|
||||
from app.models import TemplateFieldLibrary
|
||||
from app.schemas.template_field_library import (
|
||||
TemplateFieldLibraryCreate,
|
||||
TemplateFieldLibraryUpdate,
|
||||
from app.models import TemplateTitle
|
||||
from app.schemas.template_title import (
|
||||
TemplateTitleCreate,
|
||||
TemplateTitleUpdate,
|
||||
)
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ def register(server: MCPServer) -> None:
|
||||
"""列出字段库(模板能用的所有标题)。建模板前先查这里的 id。"""
|
||||
page, page_size = s.page_args(page, page_size)
|
||||
with s.session() as db:
|
||||
rows, total = field_crud.list_fields(
|
||||
rows, total = field_crud.list_titles(
|
||||
db, keyword=keyword, level=level, page=page, page_size=page_size
|
||||
)
|
||||
return s.dumps(
|
||||
@@ -87,7 +87,7 @@ def register(server: MCPServer) -> None:
|
||||
] = "#000000",
|
||||
) -> str:
|
||||
"""往字段库加一个标题字段,可带字号颜色。"""
|
||||
payload = TemplateFieldLibraryCreate(
|
||||
payload = TemplateTitleCreate(
|
||||
name=name, level=level, font_size=font_size, font_color=font_color
|
||||
)
|
||||
with s.session() as db:
|
||||
@@ -117,7 +117,7 @@ def register(server: MCPServer) -> None:
|
||||
if not values:
|
||||
s.fail("没有给出任何要修改的内容")
|
||||
|
||||
payload = TemplateFieldLibraryUpdate(**values)
|
||||
payload = TemplateTitleUpdate(**values)
|
||||
|
||||
with s.session() as db:
|
||||
field = s.field_or_fail(db, field_id)
|
||||
@@ -155,7 +155,7 @@ def register(server: MCPServer) -> None:
|
||||
# --- helpers -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _field_row(field: TemplateFieldLibrary) -> dict:
|
||||
def _field_row(field: TemplateTitle) -> dict:
|
||||
"""One library entry as a model reads it."""
|
||||
return {
|
||||
"id": field.id,
|
||||
@@ -166,7 +166,7 @@ def _field_row(field: TemplateFieldLibrary) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _assert_unused(db: Session, fields: list[TemplateFieldLibrary]) -> None:
|
||||
def _assert_unused(db: Session, fields: list[TemplateTitle]) -> None:
|
||||
"""Refuse the delete while any template still places the field.
|
||||
|
||||
Dropping a field that is placed somewhere would silently remove a heading
|
||||
|
||||
@@ -28,7 +28,7 @@ from app.mcp import support as s
|
||||
from app.mcp.specs import FieldSpec
|
||||
from app.mcp.tools.registry import mcp_tool
|
||||
from app.models import Template
|
||||
from app.schemas.template import TemplateCreate, TemplateFieldInput
|
||||
from app.schemas.template import TemplateCreate, TemplateTitlePlacementInput
|
||||
|
||||
#: Spacing between generated sorts. Ties are legal in a template and gaps are
|
||||
#: expected — the editor numbers a fresh selection 1..N only on request — so
|
||||
@@ -99,16 +99,16 @@ def register(server: MCPServer) -> None:
|
||||
) -> str:
|
||||
"""新建模板:名称 + 说明 + 有序字段选择。用 field_list 先查字段 id。"""
|
||||
selection = _selection(field_ids, fields)
|
||||
payload = TemplateCreate(name=name, abstract=abstract, fields=selection)
|
||||
payload = TemplateCreate(name=name, abstract=abstract, placements=selection)
|
||||
|
||||
with s.session() as db:
|
||||
_assert_name_free(db, payload.name)
|
||||
_assert_fields_exist(db, payload.fields)
|
||||
_assert_titles_exist(db, payload.placements)
|
||||
template = template_crud.create(
|
||||
db,
|
||||
name=payload.name,
|
||||
abstract=payload.abstract,
|
||||
fields=payload.fields,
|
||||
placements=payload.placements,
|
||||
)
|
||||
return s.dumps(_template_row(template))
|
||||
|
||||
@@ -142,7 +142,7 @@ def register(server: MCPServer) -> None:
|
||||
if name is not None:
|
||||
_assert_name_free(db, name, exclude_id=template_id)
|
||||
if selection is not None:
|
||||
_assert_fields_exist(db, selection)
|
||||
_assert_titles_exist(db, selection)
|
||||
|
||||
updated = template_crud.update(
|
||||
db,
|
||||
@@ -150,7 +150,7 @@ def register(server: MCPServer) -> None:
|
||||
name=name,
|
||||
abstract=abstract,
|
||||
abstract_provided=clear_abstract or abstract is not None,
|
||||
fields=selection,
|
||||
placements=selection,
|
||||
)
|
||||
return s.dumps(_template_row(updated))
|
||||
|
||||
@@ -177,16 +177,19 @@ def _template_row(template: Template) -> dict:
|
||||
"id": template.id,
|
||||
"name": template.name,
|
||||
"abstract": template.abstract,
|
||||
# The keys here are this interface's own vocabulary ("fields",
|
||||
# "field_id"): agents call these tools with those names, so they stay
|
||||
# put while the storage layer below calls the same rows titles.
|
||||
"fields": [
|
||||
{
|
||||
"position": item.sort,
|
||||
"field_id": item.field_id,
|
||||
"name": item.field.name,
|
||||
"level": item.field.level,
|
||||
"font_size": float(item.field.font_size),
|
||||
"font_color": item.field.font_color,
|
||||
"field_id": item.title_id,
|
||||
"name": item.title.name,
|
||||
"level": item.title.level,
|
||||
"font_size": float(item.title.font_size),
|
||||
"font_color": item.title.font_color,
|
||||
}
|
||||
for item in template.items
|
||||
for item in template.placements
|
||||
],
|
||||
}
|
||||
|
||||
@@ -194,7 +197,7 @@ def _template_row(template: Template) -> dict:
|
||||
def _selection(
|
||||
field_ids: list[int] | None,
|
||||
fields: list[FieldSpec] | None,
|
||||
) -> list[TemplateFieldInput]:
|
||||
) -> list[TemplateTitlePlacementInput]:
|
||||
"""Turn either way of describing a selection into placement rows.
|
||||
|
||||
The order of ``field_ids`` is the outline order; the numbering is generated
|
||||
@@ -203,11 +206,12 @@ def _selection(
|
||||
"""
|
||||
if fields:
|
||||
return [
|
||||
TemplateFieldInput(field_id=item.field_id, sort=item.sort) for item in fields
|
||||
TemplateTitlePlacementInput(title_id=item.field_id, sort=item.sort)
|
||||
for item in fields
|
||||
]
|
||||
if field_ids:
|
||||
return [
|
||||
TemplateFieldInput(field_id=field_id, sort=(index + 1) * SORT_STEP)
|
||||
TemplateTitlePlacementInput(title_id=field_id, sort=(index + 1) * SORT_STEP)
|
||||
for index, field_id in enumerate(field_ids)
|
||||
]
|
||||
return []
|
||||
@@ -218,13 +222,13 @@ def _assert_name_free(db: Session, name: str, *, exclude_id: int | None = None)
|
||||
s.fail(f"模板名称“{name}”已存在")
|
||||
|
||||
|
||||
def _assert_fields_exist(db: Session, fields: list[Any]) -> None:
|
||||
def _assert_titles_exist(db: Session, fields: list[Any]) -> None:
|
||||
"""Reject a selection that points at fields the library does not have.
|
||||
|
||||
Checked in Python rather than by a foreign key, exactly as the REST route
|
||||
does: TiDB parses but does not enforce ``FOREIGN KEY``.
|
||||
"""
|
||||
missing = template_crud.missing_field_ids(db, [item.field_id for item in fields])
|
||||
missing = template_crud.missing_title_ids(db, [item.title_id for item in fields])
|
||||
if missing:
|
||||
joined = "、".join(str(field_id) for field_id in missing)
|
||||
s.fail(f"字段不存在:{joined}(先用 field_list 查可用的字段 id)")
|
||||
|
||||
@@ -14,13 +14,13 @@ Every table is prefixed with the module it belongs to, and a class is named
|
||||
after its table (``Template`` -> ``template``):
|
||||
|
||||
template the 模板 module
|
||||
template_field a field placed in a template, with its position
|
||||
template_field_library the 字段库 the template module draws on
|
||||
template_title_placement a field placed in a template, with its position
|
||||
template_title the 字段库 the template module draws on
|
||||
paper the 论文 module
|
||||
paper_sentence one sentence of one paper
|
||||
paper_sentence_reference a citation of one sentence
|
||||
|
||||
``template_field`` and ``template_field_library`` are one word apart and mean
|
||||
``template_title_placement`` and ``template_title`` are one word apart and mean
|
||||
opposite things: the first is a *placement* (this template puts this field
|
||||
here, ``sort`` included), the second is the *catalogue* it was picked from.
|
||||
"""
|
||||
@@ -36,8 +36,8 @@ from app.models.paper import (
|
||||
from app.models.paper_sentence import PaperSentence
|
||||
from app.models.paper_sentence_reference import PaperSentenceReference
|
||||
from app.models.template import Template
|
||||
from app.models.template_field import TemplateField
|
||||
from app.models.template_field_library import TemplateFieldLibrary
|
||||
from app.models.template_title_placement import TemplateTitlePlacement
|
||||
from app.models.template_title import TemplateTitle
|
||||
|
||||
__all__ = [
|
||||
"PAPER_STATUSES",
|
||||
@@ -48,7 +48,7 @@ __all__ = [
|
||||
"PaperSentence",
|
||||
"PaperSentenceReference",
|
||||
"Template",
|
||||
"TemplateField",
|
||||
"TemplateFieldLibrary",
|
||||
"TemplateTitlePlacement",
|
||||
"TemplateTitle",
|
||||
"TimestampMixin",
|
||||
]
|
||||
|
||||
@@ -9,7 +9,7 @@ A paper is a bag of metadata plus two things that are deliberately kept apart:
|
||||
* its **content**, which lives in
|
||||
:class:`~app.models.paper_sentence.PaperSentence` — one row per sentence,
|
||||
addressed by the paragraph's ``sort`` inside that template rather than by a
|
||||
foreign key to a ``template_field`` row.
|
||||
foreign key to a ``template_title_placement`` row.
|
||||
|
||||
That second choice is what makes the promised workflow work. Because a sentence
|
||||
remembers "I belong at position 7", not "I belong to placement #42", swapping
|
||||
|
||||
@@ -5,12 +5,12 @@ whole design:
|
||||
|
||||
``paper_template_filed_sort``
|
||||
The ``sort`` of the template placement this sentence belongs to — *not* a
|
||||
foreign key to ``template_field``. It is deliberately the position rather
|
||||
foreign key to ``template_title_placement``. It is deliberately the position rather
|
||||
than the row id, because the position is the only thing two templates can
|
||||
meaningfully have in common. Swap the paper's template and this sentence
|
||||
lands on whatever the new template puts at that position, with no per
|
||||
sentence editing. (The name keeps the spelling the feature was specified
|
||||
with; it reads ``template_field_sort``.)
|
||||
with; it reads ``template_title_placement_sort``.)
|
||||
|
||||
``sort``
|
||||
Where this sentence sits *inside* that paragraph. A paragraph is reassembled
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Templates (模板表) — the outlines a paper can be written against.
|
||||
|
||||
A template is a named, ordered selection of library fields — the outline a
|
||||
A template is a named, ordered selection of library titles — the outline a
|
||||
paper is written against. It stores no typography of its own: font size and
|
||||
colour are read from the referenced
|
||||
:class:`~app.models.template_field_library.TemplateFieldLibrary`,
|
||||
so correcting a field's styling updates every template that uses it.
|
||||
:class:`~app.models.template_title.TemplateTitle`,
|
||||
so correcting a title's styling updates every template that uses it.
|
||||
"""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
@@ -16,11 +16,11 @@ from app.db.base import Base
|
||||
from app.models.mixins import TimestampMixin
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from app.models.template_field import TemplateField
|
||||
from app.models.template_title_placement import TemplateTitlePlacement
|
||||
|
||||
|
||||
class Template(TimestampMixin, Base):
|
||||
"""A named outline: a template name, a summary, and its ordered fields."""
|
||||
"""A named outline: a template name, a summary, and its ordered titles."""
|
||||
|
||||
__tablename__ = "template"
|
||||
|
||||
@@ -31,15 +31,15 @@ class Template(TimestampMixin, Base):
|
||||
#: Free-text abstract (摘要) describing when to use this template.
|
||||
abstract: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
|
||||
#: The template's fields, always handed to callers in display order.
|
||||
#: The template's placements, always handed to callers in display order.
|
||||
#:
|
||||
#: ``delete-orphan`` is doing real work here: TiDB parses but does not
|
||||
#: enforce ``ON DELETE CASCADE``, so removing a template's rows in the join
|
||||
#: table is the ORM's job, not the database's.
|
||||
items: Mapped[list["TemplateField"]] = relationship(
|
||||
placements: Mapped[list["TemplateTitlePlacement"]] = relationship(
|
||||
back_populates="template",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="TemplateField.sort, TemplateField.id",
|
||||
order_by="TemplateTitlePlacement.sort, TemplateTitlePlacement.id",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ Why there is no ``parent_id``
|
||||
A tree would make a field usable under exactly one parent, so a level-2 heading
|
||||
such as "Background" could not sit under both "1. Introduction" and
|
||||
"2. Related Work". Hierarchy is therefore expressed only by
|
||||
:attr:`TemplateFieldLibrary.level` (1, 2, 3 ...), which is a *rendering hint* — it
|
||||
:attr:`TemplateTitle.level` (1, 2, 3 ...), which is a *rendering hint* — it
|
||||
drives indentation and numbering semantics in the UI — while a field stays
|
||||
free to be attached to any number of templates and any number of parents
|
||||
within them.
|
||||
@@ -18,10 +18,10 @@ The number that the reader sees is part of :attr:`name` and is written by the
|
||||
user ("1. Introduction", "0 Abstract"). Nothing derives or rewrites it.
|
||||
|
||||
Ordering inside a template is *not* stored here: it lives in
|
||||
``template_field.sort``. This table has no ``sort`` column on purpose, so that
|
||||
``template_title_placement.sort``. This table has no ``sort`` column on purpose, so that
|
||||
one library field can occupy a different position in every template.
|
||||
|
||||
Naming: the table is ``template_field_library`` and one row is one entry of it
|
||||
Naming: the table is ``template_title`` and one row is one entry of it
|
||||
— the class is named after the table, as everywhere else in this package. The
|
||||
library is global, but it belongs to the 模板 module: it is the raw material a
|
||||
template is built from, and it is managed from the same menu.
|
||||
@@ -36,10 +36,10 @@ from app.db.base import Base
|
||||
from app.models.mixins import TimestampMixin
|
||||
|
||||
|
||||
class TemplateFieldLibrary(TimestampMixin, Base):
|
||||
class TemplateTitle(TimestampMixin, Base):
|
||||
"""A single reusable heading, with the typography it should render in."""
|
||||
|
||||
__tablename__ = "template_field_library"
|
||||
__tablename__ = "template_title"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
|
||||
@@ -77,6 +77,6 @@ class TemplateFieldLibrary(TimestampMixin, Base):
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
||||
return (
|
||||
f"<TemplateFieldLibrary id={self.id} name={self.name!r} "
|
||||
f"<TemplateTitle id={self.id} name={self.name!r} "
|
||||
f"level={self.level} color={self.font_color}>"
|
||||
)
|
||||
+18
-18
@@ -26,19 +26,19 @@ from app.db.base import Base
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from app.models.template import Template
|
||||
from app.models.template_field_library import TemplateFieldLibrary
|
||||
from app.models.template_title import TemplateTitle
|
||||
|
||||
|
||||
class TemplateField(Base):
|
||||
"""One placement of one library field inside one template."""
|
||||
class TemplateTitlePlacement(Base):
|
||||
"""One placement of one library title inside one template."""
|
||||
|
||||
__tablename__ = "template_field"
|
||||
__tablename__ = "template_title_placement"
|
||||
|
||||
__table_args__ = (
|
||||
# Every read is "the fields of template X, in order", so the index
|
||||
# Every read is "the placements of template X, in order", so the index
|
||||
# covers both the filter and the sort.
|
||||
Index("ix_template_field_template_sort", "template_id", "sort"),
|
||||
Index("ix_template_field_field_id", "field_id"),
|
||||
Index("ix_template_title_placement_template_sort", "template_id", "sort"),
|
||||
Index("ix_template_title_placement_title_id", "title_id"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
@@ -48,26 +48,26 @@ class TemplateField(Base):
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
#: ``RESTRICT``: a field still placed in a template must not vanish from
|
||||
#: under it. The API enforces this in Python as well, since TiDB does not
|
||||
#: enforce foreign keys itself.
|
||||
field_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("template_field_library.id", ondelete="RESTRICT"),
|
||||
#: ``RESTRICT``: a title still placed in a template must not vanish from
|
||||
#: under it. The API checks this in Python too, so a refusal names the row
|
||||
#: rather than surfacing a driver error.
|
||||
title_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("template_title.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
#: Display position within the template. Plain ascending integer — lower
|
||||
#: sorts render first regardless of the field's ``level``.
|
||||
#: sorts render first regardless of the title's ``level``.
|
||||
sort: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
|
||||
template: Mapped["Template"] = relationship(back_populates="items")
|
||||
template: Mapped["Template"] = relationship(back_populates="placements")
|
||||
|
||||
#: Eager-loaded because every template read needs the field's name and
|
||||
#: Eager-loaded because every template read needs the title's name and
|
||||
#: typography; lazy loading would emit one query per row.
|
||||
field: Mapped["TemplateFieldLibrary"] = relationship(lazy="joined")
|
||||
title: Mapped["TemplateTitle"] = relationship(lazy="joined")
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debugging aid
|
||||
return (
|
||||
f"<TemplateField template_id={self.template_id} "
|
||||
f"field_id={self.field_id} sort={self.sort}>"
|
||||
f"<TemplateTitlePlacement template_id={self.template_id} "
|
||||
f"title_id={self.title_id} sort={self.sort}>"
|
||||
)
|
||||
@@ -28,14 +28,14 @@ from app.schemas.template import (
|
||||
TemplateListItem,
|
||||
TemplateRead,
|
||||
TemplateUpdate,
|
||||
TemplateFieldInput,
|
||||
TemplateFieldRead,
|
||||
TemplateTitlePlacementInput,
|
||||
TemplateTitlePlacementRead,
|
||||
)
|
||||
from app.schemas.template_field_library import (
|
||||
TemplateFieldLibraryCreate,
|
||||
TemplateFieldLibraryRead,
|
||||
TemplateFieldLibraryRef,
|
||||
TemplateFieldLibraryUpdate,
|
||||
from app.schemas.template_title import (
|
||||
TemplateTitleCreate,
|
||||
TemplateTitleRead,
|
||||
TemplateTitleRef,
|
||||
TemplateTitleUpdate,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@@ -61,11 +61,11 @@ __all__ = [
|
||||
"TemplateListItem",
|
||||
"TemplateRead",
|
||||
"TemplateUpdate",
|
||||
"TemplateFieldLibraryCreate",
|
||||
"TemplateFieldLibraryRead",
|
||||
"TemplateFieldLibraryRef",
|
||||
"TemplateFieldLibraryUpdate",
|
||||
"TemplateFieldInput",
|
||||
"TemplateFieldRead",
|
||||
"TemplateTitleCreate",
|
||||
"TemplateTitleRead",
|
||||
"TemplateTitleRef",
|
||||
"TemplateTitleUpdate",
|
||||
"TemplateTitlePlacementInput",
|
||||
"TemplateTitlePlacementRead",
|
||||
"normalize_hex_color",
|
||||
]
|
||||
|
||||
@@ -186,9 +186,9 @@ class ParagraphRead(BaseModel):
|
||||
"""
|
||||
|
||||
paper_template_filed_sort: int
|
||||
#: The placement this paragraph resolved to, when there was one.
|
||||
template_field_id: int | None = None
|
||||
field_id: int | None = None
|
||||
#: The placement row this paragraph resolved to, when there was one.
|
||||
placement_id: int | None = None
|
||||
title_id: int | None = None
|
||||
#: Heading text as written in the template — the numbering is part of it.
|
||||
name: str | None = None
|
||||
level: int = 1
|
||||
|
||||
@@ -6,34 +6,34 @@ from decimal import Decimal
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.models.template import Template
|
||||
from app.models.template_field import TemplateField
|
||||
from app.models.template_title_placement import TemplateTitlePlacement
|
||||
from app.schemas.common import TypographyMixin
|
||||
|
||||
|
||||
class TemplateFieldInput(BaseModel):
|
||||
"""One placement of a library field inside a template.
|
||||
class TemplateTitlePlacementInput(BaseModel):
|
||||
"""One placement of a library title inside a template.
|
||||
|
||||
The client sends the whole ordered selection on create and on update; the
|
||||
server replaces the stored rows with it. ``sort`` is a plain ascending
|
||||
integer and is the *only* thing that decides render order.
|
||||
"""
|
||||
|
||||
field_id: int
|
||||
title_id: int
|
||||
sort: int = Field(default=0, ge=-1_000_000, le=1_000_000)
|
||||
|
||||
|
||||
class TemplateFieldRead(TypographyMixin, BaseModel):
|
||||
"""A template's field, flattened with the library row it points at.
|
||||
class TemplateTitlePlacementRead(TypographyMixin, BaseModel):
|
||||
"""A template's placement, flattened with the library row it points at.
|
||||
|
||||
Persistence keeps the two apart — a placement row plus the library row it
|
||||
references — but a client rendering an outline wants one flat record, so
|
||||
the typography is denormalised into the response. That is also what keeps
|
||||
the outline in sync: there is only ever one copy of a field's name and
|
||||
the outline in sync: there is only ever one copy of a title's name and
|
||||
styling, in the library.
|
||||
"""
|
||||
|
||||
id: int
|
||||
field_id: int
|
||||
title_id: int
|
||||
sort: int
|
||||
name: str
|
||||
level: int
|
||||
@@ -41,16 +41,16 @@ class TemplateFieldRead(TypographyMixin, BaseModel):
|
||||
font_color: str
|
||||
|
||||
@classmethod
|
||||
def from_model(cls, item: TemplateField) -> "TemplateFieldRead":
|
||||
def from_model(cls, item: TemplateTitlePlacement) -> "TemplateTitlePlacementRead":
|
||||
"""Flatten a placement row and its library row into one record."""
|
||||
return cls(
|
||||
id=item.id,
|
||||
field_id=item.field_id,
|
||||
title_id=item.title_id,
|
||||
sort=item.sort,
|
||||
name=item.field.name,
|
||||
level=item.field.level,
|
||||
font_size=item.field.font_size,
|
||||
font_color=item.field.font_color,
|
||||
name=item.title.name,
|
||||
level=item.title.level,
|
||||
font_size=item.title.font_size,
|
||||
font_color=item.title.font_color,
|
||||
)
|
||||
|
||||
|
||||
@@ -64,34 +64,34 @@ class TemplateBase(BaseModel):
|
||||
class TemplateCreate(TemplateBase):
|
||||
"""Payload for ``POST /templates``.
|
||||
|
||||
The field selection is free: any subset, any order, repeats allowed. The
|
||||
server stores it as given and orders it by ``sort`` on read.
|
||||
The selection is free: any subset, any order, repeats allowed. The server
|
||||
stores it as given and orders it by ``sort`` on read.
|
||||
"""
|
||||
|
||||
fields: list[TemplateFieldInput] = Field(default_factory=list)
|
||||
placements: list[TemplateTitlePlacementInput] = Field(default_factory=list)
|
||||
|
||||
|
||||
class TemplateUpdate(BaseModel):
|
||||
"""Payload for ``PATCH /templates/{id}``.
|
||||
|
||||
``fields`` is a full replacement when present — omit it to leave the
|
||||
``placements`` is a full replacement when present — omit it to leave the
|
||||
selection untouched.
|
||||
"""
|
||||
|
||||
name: str | None = Field(default=None, min_length=1, max_length=255)
|
||||
abstract: str | None = None
|
||||
fields: list[TemplateFieldInput] | None = None
|
||||
placements: list[TemplateTitlePlacementInput] | None = None
|
||||
|
||||
|
||||
class TemplateListItem(BaseModel):
|
||||
"""A template as it appears in the list table — no field rows."""
|
||||
"""A template as it appears in the list table — no placement rows."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
abstract: str | None
|
||||
field_count: int
|
||||
placement_count: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -106,7 +106,7 @@ class TemplateRead(BaseModel):
|
||||
abstract: str | None
|
||||
#: The outline, ordered by ``sort`` — the ORM relationship sets that
|
||||
#: ordering, so this list is display-ready with no client-side sorting.
|
||||
fields: list[TemplateFieldRead]
|
||||
placements: list[TemplateTitlePlacementRead]
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
@@ -117,7 +117,10 @@ class TemplateRead(BaseModel):
|
||||
id=template.id,
|
||||
name=template.name,
|
||||
abstract=template.abstract,
|
||||
fields=[TemplateFieldRead.from_model(item) for item in template.items],
|
||||
placements=[
|
||||
TemplateTitlePlacementRead.from_model(item)
|
||||
for item in template.placements
|
||||
],
|
||||
created_at=template.created_at,
|
||||
updated_at=template.updated_at,
|
||||
)
|
||||
|
||||
+7
-7
@@ -8,7 +8,7 @@ from pydantic import BaseModel, ConfigDict, Field
|
||||
from app.schemas.common import TypographyMixin
|
||||
|
||||
|
||||
class TemplateFieldLibraryBase(TypographyMixin, BaseModel):
|
||||
class TemplateTitleBase(TypographyMixin, BaseModel):
|
||||
"""Fields a client may set on a library entry."""
|
||||
|
||||
#: Display name, numbering included — e.g. ``"1. Introduction"``. Stored
|
||||
@@ -25,12 +25,12 @@ class TemplateFieldLibraryBase(TypographyMixin, BaseModel):
|
||||
font_color: str = Field(default="#000000", max_length=32)
|
||||
|
||||
|
||||
class TemplateFieldLibraryCreate(TemplateFieldLibraryBase):
|
||||
"""Payload for ``POST /template-field-library``."""
|
||||
class TemplateTitleCreate(TemplateTitleBase):
|
||||
"""Payload for ``POST /template-titles``."""
|
||||
|
||||
|
||||
class TemplateFieldLibraryUpdate(TypographyMixin, BaseModel):
|
||||
"""Payload for ``PATCH /template-field-library/{id}`` — every part optional.
|
||||
class TemplateTitleUpdate(TypographyMixin, BaseModel):
|
||||
"""Payload for ``PATCH /template-titles/{id}`` — every part optional.
|
||||
|
||||
The colour normaliser tolerates ``None`` here; the validator returns
|
||||
non-strings untouched, so an omitted colour stays omitted.
|
||||
@@ -42,7 +42,7 @@ class TemplateFieldLibraryUpdate(TypographyMixin, BaseModel):
|
||||
font_color: str | None = Field(default=None, max_length=32)
|
||||
|
||||
|
||||
class TemplateFieldLibraryRead(TemplateFieldLibraryBase):
|
||||
class TemplateTitleRead(TemplateTitleBase):
|
||||
"""A stored library entry."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
@@ -52,7 +52,7 @@ class TemplateFieldLibraryRead(TemplateFieldLibraryBase):
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class TemplateFieldLibraryRef(BaseModel):
|
||||
class TemplateTitleRef(BaseModel):
|
||||
"""How many templates currently place a field — used to explain a refusal."""
|
||||
|
||||
field_id: int
|
||||
+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)))
|
||||
|
||||
+61
-37
@@ -62,15 +62,15 @@ Six tables. Every one is prefixed with the module it belongs to, and a model
|
||||
class is named after its table, so the schema can be read as three groups:
|
||||
|
||||
```
|
||||
template_field_library the 字段库: reusable headings
|
||||
template_title one reusable heading (字段库)
|
||||
id, name, level, font_size, font_color
|
||||
|
||||
template a named outline (模板)
|
||||
id, name, abstract
|
||||
|
||||
template_field a field placed in a template — and the only
|
||||
id, template_id → template, home of display order
|
||||
field_id → template_field_library, sort
|
||||
template_title_placement that heading placed in a template — and the
|
||||
id, template_id → template, only home of display order
|
||||
title_id → template_title, sort
|
||||
|
||||
paper the document
|
||||
id, title, template_id, author, status, keywords, target_journal
|
||||
@@ -82,6 +82,29 @@ paper_sentence_reference the citations of one sentence
|
||||
id, sentence_id → paper_sentence, reference_id, quote, sort
|
||||
```
|
||||
|
||||
### How the tables are named
|
||||
|
||||
Three rules, applied everywhere:
|
||||
|
||||
1. **A table is its module's name plus what it holds** — `template*` belongs to
|
||||
the 模板 module, `paper*` to the 论文 module.
|
||||
2. **A class is named after its table** (`TemplateTitle` → `template_title`), so
|
||||
reading a class name tells you which table to look at.
|
||||
3. **One concept, one word.** The library entry, the placement and the paper's
|
||||
paragraph are three different things and never share a name.
|
||||
|
||||
The join table is a *placement* rather than a `_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. Calling it a link
|
||||
would describe two foreign keys and hide the column the whole ordering rule
|
||||
rests on.
|
||||
|
||||
`template_title` and `template_title_placement` are one word apart on purpose —
|
||||
the first is the catalogue, the second is one use of it — and the earlier pair
|
||||
(`template_field_library` / `template_field`) hid that distinction behind a
|
||||
prefix that meant the opposite kind of thing. Revision `b19e4d7a3c58` renamed
|
||||
them.
|
||||
|
||||
`paper` has no `abstract` column, and that is a decision rather than an
|
||||
omission. A paper's abstract *is* a paragraph of its body — the template's
|
||||
`0 Abstract` field — so it has a position in the document, the heading and
|
||||
@@ -92,38 +115,39 @@ and the one in the column could drift from the one in the body. Revision
|
||||
`a83f5c21d7b6` removed it, moving each stored abstract into the abstract
|
||||
paragraph first.
|
||||
|
||||
`template_field` and `template_field_library` are one word apart and mean
|
||||
opposite things. The first is a *placement* — this template puts this field
|
||||
here, `sort` included. The second is the *catalogue* the field was picked from,
|
||||
shared by every template and owned by none. The library is managed from the
|
||||
模板 menu, because it is the raw material a template is built out of.
|
||||
The two template tables are one word apart and mean different things, which is
|
||||
what the names are for: `template_title_placement` is a *placement* — this
|
||||
template puts this title here, `sort` included — while `template_title` is the
|
||||
*catalogue* the title was picked from, shared by every template and owned by
|
||||
none. The library is managed from the 模板 menu, because it is the raw material
|
||||
a template is built out of.
|
||||
|
||||
### The field library is flat, not a tree
|
||||
### The title library is flat, not a tree
|
||||
|
||||
`template_field_library` has no `parent_id`. Hierarchy is expressed only by `level`
|
||||
`template_title` has no `parent_id`. Hierarchy is expressed only by `level`
|
||||
(1 for `1.`, 2 for `1.1`), which is a *rendering hint*: it drives indentation
|
||||
and numbering semantics in the UI and nothing else.
|
||||
|
||||
The reason is reuse. With a parent pointer a level-2 heading would belong to
|
||||
exactly one level-1 heading, so "Background" could not sit under both
|
||||
`1. Introduction` and `2. Related Work`. Flat fields are attached to templates,
|
||||
not to each other, so one field can appear in any number of templates, in a
|
||||
`1. Introduction` and `2. Related Work`. Titles are attached to templates,
|
||||
not to each other, so one title can appear in any number of templates, in a
|
||||
different position in each.
|
||||
|
||||
The numbering a reader sees is part of `name` and is written by the user
|
||||
(`"1. Introduction"`, `"0 Abstract"`). Nothing derives or rewrites it.
|
||||
|
||||
### Display order lives in the join table
|
||||
### Display order lives in the placement table
|
||||
|
||||
`template_field.sort` is a plain ascending integer and is the **only** thing
|
||||
that decides what order a template's fields appear in. The order the user
|
||||
clicked fields in is never stored, so selecting `字段1, 字段2.1, 字段2, 字段1.1`
|
||||
and setting sorts `1, 4, 3, 2` renders as `字段1, 字段1.1, 字段2, 字段2.1`.
|
||||
`template_title_placement.sort` is a plain ascending integer and is the **only**
|
||||
thing that decides what order a template's titles appear in. The order the user
|
||||
clicked titles in is never stored, so selecting `标题1, 标题2.1, 标题2, 标题1.1`
|
||||
and setting sorts `1, 4, 3, 2` renders as `标题1, 标题1.1, 标题2, 标题2.1`.
|
||||
|
||||
Two consequences are deliberate:
|
||||
|
||||
- **There is no unique constraint on `(template_id, field_id)`.** Placing the
|
||||
same field twice in one template is a legitimate layout — the same level-2
|
||||
- **There is no unique constraint on `(template_id, title_id)`.** Placing the
|
||||
same title twice in one template is a legitimate layout — the same level-2
|
||||
heading under two different level-1 headings. The UI warns about a repeat; it
|
||||
does not forbid one.
|
||||
- **Ties are legal.** Equal `sort` values are broken by insertion order, so the
|
||||
@@ -132,16 +156,16 @@ Two consequences are deliberate:
|
||||
|
||||
### Templates hold references, not copies
|
||||
|
||||
`template_field` points at a library field; it does not snapshot its name or
|
||||
typography. Renaming or restyling a field therefore updates every template that
|
||||
places it, which is what makes "fix the template and the section names follow"
|
||||
work.
|
||||
`template_title_placement` points at a library title; it does not snapshot its
|
||||
name or typography. Renaming or restyling a title therefore updates every
|
||||
template that places it, which is what makes "fix the template and the section
|
||||
names follow" work.
|
||||
|
||||
### A sentence is addressed by position, not by field id
|
||||
|
||||
`paper_sentence.paper_template_filed_sort` holds the `sort` of the template
|
||||
placement the sentence belongs to — **not** `template_field.id`, and not
|
||||
`template_field_library.id`. Together with `sort`, the sentence's own position inside
|
||||
placement the sentence belongs to — **not** `template_title_placement.id`, and not
|
||||
`template_title.id`. Together with `sort`, the sentence's own position inside
|
||||
that paragraph, it is everything needed to place a line of text.
|
||||
|
||||
The indirection is the feature. Two templates have no rows in common, but they
|
||||
@@ -160,12 +184,12 @@ Three behaviours fall out of that one choice:
|
||||
still rendered, in their place in the order, under the heading 未设定. Switch
|
||||
back and the old headings return, because the sentences never moved.
|
||||
- **Ties and gaps are fine.** Sentences may share a `sort` (broken by `id`) and
|
||||
may be numbered `10, 20, 30` to leave room, exactly as `template_field.sort`
|
||||
may be numbered `10, 20, 30` to leave room, exactly as `template_title_placement.sort`
|
||||
allows.
|
||||
|
||||
The name `paper_template_filed_sort` keeps the spelling the feature was
|
||||
specified with; it is the template field's `sort` (the `sort` column of
|
||||
`template_field`). `paper_sentence.template_id` is the template the sentence was
|
||||
`template_title_placement`). `paper_sentence.template_id` is the template the sentence was
|
||||
written against. It is kept in step with the paper's current template and is
|
||||
provenance rather than a lookup key: rendering never filters on it, which is
|
||||
precisely why content survives a switch.
|
||||
@@ -263,10 +287,10 @@ All routes are mounted under `/api`. Interactive docs at `/docs`.
|
||||
| Method | Path | Notes |
|
||||
|---|---|---|
|
||||
| `GET` | `/health` | liveness plus a TiDB probe |
|
||||
| `GET` | `/template-field-library` | `keyword`, `level`, `page`, `page_size` |
|
||||
| `POST` | `/template-field-library` | create a library entry |
|
||||
| `GET` `PATCH` `DELETE` | `/template-field-library/{id}` | read / partial update / delete |
|
||||
| `POST` | `/template-field-library/batch-delete` | body `{ "ids": [...] }` |
|
||||
| `GET` | `/template-titles` | `keyword`, `level`, `page`, `page_size` |
|
||||
| `POST` | `/template-titles` | create a library entry |
|
||||
| `GET` `PATCH` `DELETE` | `/template-titles/{id}` | read / partial update / delete |
|
||||
| `POST` | `/template-titles/batch-delete` | body `{ "ids": [...] }` |
|
||||
| `GET` | `/templates` | `keyword` matches name **or** abstract |
|
||||
| `POST` | `/templates` | name + abstract + ordered `fields` |
|
||||
| `GET` `PATCH` `DELETE` | `/templates/{id}` | `PATCH` with `fields` replaces the selection |
|
||||
@@ -290,7 +314,7 @@ Conventions worth knowing:
|
||||
- List endpoints return `{ items, total, page, page_size, pages }`.
|
||||
- A template read returns `fields` already ordered by `sort`; clients never sort.
|
||||
- Route paths mirror table names one for one: `/templates` for `template`,
|
||||
`/template-field-library` for `template_field_library`, `/papers` for
|
||||
`/template-titles` for `template_title`, `/papers` for
|
||||
`paper`.
|
||||
- A paper document returns its `paragraphs` in ascending position order,
|
||||
already carrying their sentences and citation numbering. The client sorts
|
||||
@@ -451,7 +475,7 @@ are not lists (the paper document) keep scrolling normally.
|
||||
| `/papers/:id` | one paper, read as a document | `papers` |
|
||||
| `/templates` | redirects to `/templates/list` | — |
|
||||
| `/templates/list` | template table + CRUD | `templates` |
|
||||
| `/templates/fields` | field library + CRUD | `templates` |
|
||||
| `/templates/fields` | title library + CRUD (the UI label is 字段管理) | `templates` |
|
||||
|
||||
### The paper view
|
||||
|
||||
@@ -479,7 +503,7 @@ paper-doc/
|
||||
├── backend/ # FastAPI application
|
||||
│ ├── app/
|
||||
│ │ ├── api/routes/ # route handlers (health, papers, templates,
|
||||
│ │ │ # template_field_library)
|
||||
│ │ │ # template_title)
|
||||
│ │ ├── core/ # settings and configuration
|
||||
│ │ ├── crud/ # data-access helpers
|
||||
│ │ ├── db/ # engine, session, declarative base
|
||||
@@ -487,7 +511,7 @@ paper-doc/
|
||||
│ │ ├── models/ # SQLAlchemy models
|
||||
│ │ └── schemas/ # Pydantic request/response models
|
||||
│ ├── alembic/ # migration environment and revisions
|
||||
│ ├── scripts/seed.py # idempotent seed for the field library + templates
|
||||
│ ├── scripts/seed.py # idempotent seed for the title library + templates
|
||||
│ ├── scripts/smoke_papers.py # end-to-end check of the writing loop
|
||||
│ ├── scripts/mcp_server.py # MCP entry point (stdio / http)
|
||||
│ ├── scripts/smoke_mcp.py # the same loop, spoken over MCP by a real client
|
||||
@@ -557,7 +581,7 @@ alembic upgrade head
|
||||
|
||||
**Seed data**
|
||||
|
||||
`scripts/seed.py` fills the field library with a standard academic outline (20
|
||||
`scripts/seed.py` fills the title library with a standard academic outline (20
|
||||
fields, from `0 Abstract` to `7 References`) and creates three starter
|
||||
templates. It matches fields and templates by name, so running it twice adds
|
||||
nothing:
|
||||
|
||||
@@ -102,8 +102,8 @@ export interface Sentence {
|
||||
/** One paragraph of a paper: its heading and the sentences under it. */
|
||||
export interface PaperParagraph {
|
||||
paper_template_filed_sort: number
|
||||
template_field_id: number | null
|
||||
field_id: number | null
|
||||
placement_id: number | null
|
||||
title_id: number | null
|
||||
/** `null` when the template has no placement here — rendered as 未设定. */
|
||||
name: string | null
|
||||
level: number
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import http from './client'
|
||||
import type { BatchDeleteResult, PageQuery, PageResult } from './types'
|
||||
|
||||
/** Mirrors `app.schemas.template_field_library.TemplateFieldLibraryRead`. */
|
||||
export interface TemplateFieldLibrary {
|
||||
/** Mirrors `app.schemas.template_title.TemplateTitleRead`. */
|
||||
export interface TemplateTitle {
|
||||
id: number
|
||||
/** Display name, numbering included — e.g. `1. Introduction`. */
|
||||
name: string
|
||||
@@ -17,23 +17,23 @@ export interface TemplateFieldLibrary {
|
||||
}
|
||||
|
||||
/** Body for creating or updating a library field. */
|
||||
export interface TemplateFieldLibraryPayload {
|
||||
export interface TemplateTitlePayload {
|
||||
name: string
|
||||
level: number
|
||||
font_size: number
|
||||
font_color: string
|
||||
}
|
||||
|
||||
export interface TemplateFieldLibraryQuery extends PageQuery {
|
||||
export interface TemplateTitleQuery extends PageQuery {
|
||||
level?: number | null
|
||||
}
|
||||
|
||||
/** The API caps `page_size` at 500; 200 keeps responses modest while looping. */
|
||||
const LIBRARY_PAGE_SIZE = 200
|
||||
|
||||
export async function listTemplateFieldLibrary(
|
||||
query: TemplateFieldLibraryQuery = {},
|
||||
): Promise<PageResult<TemplateFieldLibrary>> {
|
||||
export async function listTemplateTitle(
|
||||
query: TemplateTitleQuery = {},
|
||||
): Promise<PageResult<TemplateTitle>> {
|
||||
// Drop empty filters so the URL stays clean and the backend sees "no filter"
|
||||
// rather than `keyword=`.
|
||||
const params: Record<string, unknown> = {}
|
||||
@@ -42,8 +42,8 @@ export async function listTemplateFieldLibrary(
|
||||
if (query.page) params.page = query.page
|
||||
if (query.page_size) params.page_size = query.page_size
|
||||
|
||||
const { data } = await http.get<PageResult<TemplateFieldLibrary>>(
|
||||
'/template-field-library',
|
||||
const { data } = await http.get<PageResult<TemplateTitle>>(
|
||||
'/template-titles',
|
||||
{ params },
|
||||
)
|
||||
return data
|
||||
@@ -55,12 +55,12 @@ export async function listTemplateFieldLibrary(
|
||||
* The template form needs every field, not one page, so that a field placed
|
||||
* deep in the library can still be shown by name in an existing selection.
|
||||
*/
|
||||
export async function fetchAllTemplateFieldLibrary(keyword?: string): Promise<TemplateFieldLibrary[]> {
|
||||
const all: TemplateFieldLibrary[] = []
|
||||
export async function fetchAllTemplateTitle(keyword?: string): Promise<TemplateTitle[]> {
|
||||
const all: TemplateTitle[] = []
|
||||
let page = 1
|
||||
|
||||
for (;;) {
|
||||
const result = await listTemplateFieldLibrary({
|
||||
const result = await listTemplateTitle({
|
||||
keyword,
|
||||
page,
|
||||
page_size: LIBRARY_PAGE_SIZE,
|
||||
@@ -73,29 +73,29 @@ export async function fetchAllTemplateFieldLibrary(keyword?: string): Promise<Te
|
||||
}
|
||||
}
|
||||
|
||||
export async function createTemplateFieldLibrary(
|
||||
payload: TemplateFieldLibraryPayload,
|
||||
): Promise<TemplateFieldLibrary> {
|
||||
const { data } = await http.post<TemplateFieldLibrary>('/template-field-library', payload)
|
||||
export async function createTemplateTitle(
|
||||
payload: TemplateTitlePayload,
|
||||
): Promise<TemplateTitle> {
|
||||
const { data } = await http.post<TemplateTitle>('/template-titles', payload)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function updateTemplateFieldLibrary(
|
||||
export async function updateTemplateTitle(
|
||||
id: number,
|
||||
payload: Partial<TemplateFieldLibraryPayload>,
|
||||
): Promise<TemplateFieldLibrary> {
|
||||
const { data } = await http.patch<TemplateFieldLibrary>(`/template-field-library/${id}`, payload)
|
||||
payload: Partial<TemplateTitlePayload>,
|
||||
): Promise<TemplateTitle> {
|
||||
const { data } = await http.patch<TemplateTitle>(`/template-titles/${id}`, payload)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function deleteTemplateFieldLibrary(id: number): Promise<void> {
|
||||
await http.delete(`/template-field-library/${id}`)
|
||||
export async function deleteTemplateTitle(id: number): Promise<void> {
|
||||
await http.delete(`/template-titles/${id}`)
|
||||
}
|
||||
|
||||
export async function batchDeleteTemplateFieldLibrary(
|
||||
export async function batchDeleteTemplateTitle(
|
||||
ids: number[],
|
||||
): Promise<BatchDeleteResult> {
|
||||
const { data } = await http.post<BatchDeleteResult>('/template-field-library/batch-delete', {
|
||||
const { data } = await http.post<BatchDeleteResult>('/template-titles/batch-delete', {
|
||||
ids,
|
||||
})
|
||||
return data
|
||||
@@ -1,10 +1,11 @@
|
||||
import http from './client'
|
||||
import type { BatchDeleteResult, PageQuery, PageResult } from './types'
|
||||
|
||||
/** One placement of a library field inside a template, with its typography. */
|
||||
export interface TemplateField {
|
||||
/** One placement of a library title inside a template, with its typography. */
|
||||
export interface TemplateTitlePlacement {
|
||||
id: number
|
||||
field_id: number
|
||||
/** The library entry this placement puts here. */
|
||||
title_id: number
|
||||
/** Display position. The only thing that decides render order. */
|
||||
sort: number
|
||||
name: string
|
||||
@@ -18,7 +19,8 @@ export interface TemplateListItem {
|
||||
id: number
|
||||
name: string
|
||||
abstract: string | null
|
||||
field_count: number
|
||||
/** How many placements the template defines. */
|
||||
placement_count: number
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
@@ -28,21 +30,22 @@ export interface TemplateDetail {
|
||||
id: number
|
||||
name: string
|
||||
abstract: string | null
|
||||
fields: TemplateField[]
|
||||
/** The outline, already ordered by `sort`. */
|
||||
placements: TemplateTitlePlacement[]
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
/** One entry of the selection sent on create/update. */
|
||||
export interface TemplateFieldInput {
|
||||
field_id: number
|
||||
export interface TemplateTitlePlacementInput {
|
||||
title_id: number
|
||||
sort: number
|
||||
}
|
||||
|
||||
export interface TemplatePayload {
|
||||
name: string
|
||||
abstract: string | null
|
||||
fields: TemplateFieldInput[]
|
||||
placements: TemplateTitlePlacementInput[]
|
||||
}
|
||||
|
||||
export async function listTemplates(
|
||||
|
||||
@@ -11,18 +11,18 @@ import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
|
||||
|
||||
import { errorMessage } from '@/api/client'
|
||||
import {
|
||||
createTemplateFieldLibrary,
|
||||
updateTemplateFieldLibrary,
|
||||
type TemplateFieldLibrary,
|
||||
type TemplateFieldLibraryPayload,
|
||||
} from '@/api/templateFieldLibrary'
|
||||
createTemplateTitle,
|
||||
updateTemplateTitle,
|
||||
type TemplateTitle,
|
||||
type TemplateTitlePayload,
|
||||
} from '@/api/templateTitles'
|
||||
import { normalizeHexColor, typographyStyle } from '@/utils/format'
|
||||
|
||||
const props = defineProps<{
|
||||
/** Visibility, used with `v-model`. */
|
||||
modelValue: boolean
|
||||
/** The field being edited, or `null` to create a new one. */
|
||||
field: TemplateFieldLibrary | null
|
||||
field: TemplateTitle | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -39,7 +39,7 @@ const visible = computed({
|
||||
const formRef = ref<FormInstance>()
|
||||
const saving = ref(false)
|
||||
|
||||
const form = reactive<TemplateFieldLibraryPayload>({
|
||||
const form = reactive<TemplateTitlePayload>({
|
||||
name: '',
|
||||
level: 1,
|
||||
// 小四, the conventional body size for a Chinese thesis.
|
||||
@@ -47,7 +47,7 @@ const form = reactive<TemplateFieldLibraryPayload>({
|
||||
font_color: '#000000',
|
||||
})
|
||||
|
||||
const rules: FormRules<TemplateFieldLibraryPayload> = {
|
||||
const rules: FormRules<TemplateTitlePayload> = {
|
||||
name: [
|
||||
{ required: true, message: '请填写字段名称', trigger: 'blur' },
|
||||
{ max: 255, message: '字段名称最多 255 个字符', trigger: 'blur' },
|
||||
@@ -118,10 +118,10 @@ async function submit(): Promise<void> {
|
||||
saving.value = true
|
||||
try {
|
||||
if (props.field) {
|
||||
await updateTemplateFieldLibrary(props.field.id, { ...form })
|
||||
await updateTemplateTitle(props.field.id, { ...form })
|
||||
ElMessage.success('字段已更新,使用它的模板会同步生效')
|
||||
} else {
|
||||
await createTemplateFieldLibrary({ ...form })
|
||||
await createTemplateTitle({ ...form })
|
||||
ElMessage.success('字段已创建')
|
||||
}
|
||||
emit('saved')
|
||||
|
||||
@@ -173,7 +173,7 @@ async function submit(): Promise<void> {
|
||||
:label="template.name"
|
||||
>
|
||||
<span>{{ template.name }}</span>
|
||||
<span class="option-hint">{{ template.field_count }} 段</span>
|
||||
<span class="option-hint">{{ template.placement_count }} 段</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
<div v-if="templates.length === 0" class="field-hint">
|
||||
|
||||
@@ -107,7 +107,10 @@ async function loadCandidate(templateId: number | null): Promise<void> {
|
||||
previewing.value = true
|
||||
try {
|
||||
const detail = await getTemplate(templateId)
|
||||
candidate.value = detail.fields.map((field) => ({ sort: field.sort, name: field.name }))
|
||||
candidate.value = detail.placements.map((placement) => ({
|
||||
sort: placement.sort,
|
||||
name: placement.name,
|
||||
}))
|
||||
} catch (error) {
|
||||
ElMessage.error(errorMessage(error))
|
||||
candidate.value = []
|
||||
@@ -170,7 +173,7 @@ async function submit(): Promise<void> {
|
||||
:disabled="template.id === paper.template_id"
|
||||
>
|
||||
<span>{{ template.name }}</span>
|
||||
<span class="option-hint">{{ template.field_count }} 段</span>
|
||||
<span class="option-hint">{{ template.placement_count }} 段</span>
|
||||
</el-option>
|
||||
</el-select>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*
|
||||
* The picker is the heart of the feature, and it is deliberately *not* a tree.
|
||||
* Fields come from one flat library and are chosen freely: any subset, any
|
||||
* order, and the same field more than once. What the reader finally sees is
|
||||
* order, and the same title more than once. What the reader finally sees is
|
||||
* decided by `sort` alone, so the right-hand list is always rendered sorted by
|
||||
* `sort` — reordering the numbers reorders the outline immediately, and the
|
||||
* order the user clicked in is never stored.
|
||||
@@ -28,12 +28,12 @@ import {
|
||||
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
|
||||
|
||||
import { errorMessage } from '@/api/client'
|
||||
import { fetchAllTemplateFieldLibrary, type TemplateFieldLibrary } from '@/api/templateFieldLibrary'
|
||||
import { fetchAllTemplateTitle, type TemplateTitle } from '@/api/templateTitles'
|
||||
import {
|
||||
createTemplate,
|
||||
getTemplate,
|
||||
updateTemplate,
|
||||
type TemplateFieldInput,
|
||||
type TemplateTitlePlacementInput,
|
||||
type TemplateListItem,
|
||||
} from '@/api/templates'
|
||||
import { levelIndent, typographyStyle } from '@/utils/format'
|
||||
@@ -51,11 +51,11 @@ const emit = defineEmits<{
|
||||
saved: []
|
||||
}>()
|
||||
|
||||
/** One chosen field, at one position. The same field may appear many times. */
|
||||
/** One chosen title, at one position. The same title may appear many times. */
|
||||
interface Placement {
|
||||
/** Local identity for `v-for` / `row-key`; not sent to the server. */
|
||||
key: number
|
||||
field_id: number
|
||||
title_id: number
|
||||
sort: number
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ const formRef = ref<FormInstance>()
|
||||
const loading = ref(false)
|
||||
const saving = ref(false)
|
||||
|
||||
const library = ref<TemplateFieldLibrary[]>([])
|
||||
const library = ref<TemplateTitle[]>([])
|
||||
const libraryKeyword = ref('')
|
||||
const selected = ref<Placement[]>([])
|
||||
|
||||
@@ -81,12 +81,12 @@ const rules: FormRules = { name: [{ required: true, message: '请填写模板名
|
||||
/** Keys only ever count up, so a reopened dialog cannot collide with itself. */
|
||||
let nextKey = 1
|
||||
|
||||
const fieldMap = computed(() => new Map(library.value.map((field) => [field.id, field])))
|
||||
const titleMap = computed(() => new Map(library.value.map((title) => [title.id, title])))
|
||||
|
||||
const filteredLibrary = computed(() => {
|
||||
const keyword = libraryKeyword.value.trim().toLowerCase()
|
||||
if (!keyword) return library.value
|
||||
return library.value.filter((field) => field.name.toLowerCase().includes(keyword))
|
||||
return library.value.filter((title) => title.name.toLowerCase().includes(keyword))
|
||||
})
|
||||
|
||||
/** The selection in display order — ascending `sort`, ties by insertion. */
|
||||
@@ -98,15 +98,15 @@ const rows = computed(() =>
|
||||
// property name `key` rather than a function expression.
|
||||
key: placement.key,
|
||||
placement,
|
||||
field: fieldMap.value.get(placement.field_id),
|
||||
title: titleMap.value.get(placement.title_id),
|
||||
})),
|
||||
)
|
||||
|
||||
/** How many times each library field is placed. */
|
||||
/** How many times each library title is placed. */
|
||||
const repeatCounts = computed(() => {
|
||||
const counts = new Map<number, number>()
|
||||
for (const placement of selected.value) {
|
||||
counts.set(placement.field_id, (counts.get(placement.field_id) ?? 0) + 1)
|
||||
counts.set(placement.title_id, (counts.get(placement.title_id) ?? 0) + 1)
|
||||
}
|
||||
return counts
|
||||
})
|
||||
@@ -114,7 +114,7 @@ const repeatCounts = computed(() => {
|
||||
const repeatedNames = computed(() =>
|
||||
[...repeatCounts.value.entries()]
|
||||
.filter(([, count]) => count > 1)
|
||||
.map(([id, count]) => `${fieldMap.value.get(id)?.name ?? `#${id}`} ×${count}`),
|
||||
.map(([id, count]) => `${titleMap.value.get(id)?.name ?? `#${id}`} ×${count}`),
|
||||
)
|
||||
|
||||
const duplicatedSorts = computed(() => {
|
||||
@@ -143,18 +143,18 @@ watch(
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
// The whole library, so a field that was placed before the keyword
|
||||
// The whole library, so a title that was placed before the keyword
|
||||
// filter existed still resolves to a name in the selection.
|
||||
library.value = await fetchAllTemplateFieldLibrary()
|
||||
library.value = await fetchAllTemplateTitle()
|
||||
|
||||
if (props.template) {
|
||||
const detail = await getTemplate(props.template.id)
|
||||
form.name = detail.name
|
||||
form.abstract = detail.abstract ?? ''
|
||||
selected.value = detail.fields.map((field) => ({
|
||||
selected.value = detail.placements.map((placement) => ({
|
||||
key: nextKey++,
|
||||
field_id: field.field_id,
|
||||
sort: field.sort,
|
||||
title_id: placement.title_id,
|
||||
sort: placement.sort,
|
||||
}))
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -166,9 +166,9 @@ watch(
|
||||
)
|
||||
|
||||
/** Append a placement, at the end of the current order. */
|
||||
function addField(field: TemplateFieldLibrary): void {
|
||||
function addTitle(title: TemplateTitle): void {
|
||||
const highest = selected.value.reduce((max, item) => Math.max(max, item.sort), 0)
|
||||
selected.value.push({ key: nextKey++, field_id: field.id, sort: highest + 1 })
|
||||
selected.value.push({ key: nextKey++, title_id: title.id, sort: highest + 1 })
|
||||
}
|
||||
|
||||
function removePlacement(key: number): void {
|
||||
@@ -208,7 +208,7 @@ function autoSort(): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the field library in a second tab.
|
||||
* Open the title library in a second tab.
|
||||
*
|
||||
* Deliberately not an in-place navigation: a half-filled template form would
|
||||
* be lost, and the usual reason to go there is "the field I need does not
|
||||
@@ -240,14 +240,14 @@ async function submit(): Promise<void> {
|
||||
// Sent in display order, so that equal `sort` values get placement ids in
|
||||
// the same order the user sees and the backend's id tie-break agrees with
|
||||
// the screen.
|
||||
const fields: TemplateFieldInput[] = rows.value.map((row) => ({
|
||||
field_id: row.placement.field_id,
|
||||
const placements: TemplateTitlePlacementInput[] = rows.value.map((row) => ({
|
||||
title_id: row.placement.title_id,
|
||||
sort: row.placement.sort,
|
||||
}))
|
||||
const payload = {
|
||||
name: form.name.trim(),
|
||||
abstract: form.abstract.trim() || null,
|
||||
fields,
|
||||
placements,
|
||||
}
|
||||
|
||||
if (props.template) {
|
||||
@@ -321,18 +321,21 @@ async function submit(): Promise<void> {
|
||||
|
||||
<div class="picker-list">
|
||||
<button
|
||||
v-for="field in filteredLibrary"
|
||||
:key="field.id"
|
||||
v-for="title in filteredLibrary"
|
||||
:key="title.id"
|
||||
type="button"
|
||||
class="lib-item"
|
||||
@click="addField(field)"
|
||||
@click="addTitle(title)"
|
||||
>
|
||||
<span class="lib-name" :style="{ paddingLeft: levelIndent(field.level), ...typographyStyle(field) }">
|
||||
{{ field.name }}
|
||||
<span
|
||||
class="lib-name"
|
||||
:style="{ paddingLeft: levelIndent(title.level), ...typographyStyle(title) }"
|
||||
>
|
||||
{{ title.name }}
|
||||
</span>
|
||||
<span class="lib-side">
|
||||
<el-tag v-if="repeatCounts.get(field.id)" size="small" type="warning" effect="plain">
|
||||
×{{ repeatCounts.get(field.id) }}
|
||||
<el-tag v-if="repeatCounts.get(title.id)" size="small" type="warning" effect="plain">
|
||||
×{{ repeatCounts.get(title.id) }}
|
||||
</el-tag>
|
||||
<el-icon class="lib-add"><Plus /></el-icon>
|
||||
</span>
|
||||
@@ -404,7 +407,7 @@ async function submit(): Promise<void> {
|
||||
>
|
||||
{{ row.field.name }}
|
||||
</span>
|
||||
<span v-else class="missing">字段 #{{ row.placement.field_id }} 已不存在</span>
|
||||
<span v-else class="missing">标题 #{{ row.placement.title_id }} 已不存在</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
@@ -516,7 +519,7 @@ async function submit(): Promise<void> {
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
/* A button per field: clickable, focusable and keyboard-operable for free. */
|
||||
/* A button per title: clickable, focusable and keyboard-operable for free. */
|
||||
.lib-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -7,12 +7,12 @@
|
||||
* drawn at its own font size and colour. The `sort` value is shown alongside so
|
||||
* the order can be checked against the numbers rather than taken on trust.
|
||||
*/
|
||||
import type { TemplateField } from '@/api/templates'
|
||||
import type { TemplateTitlePlacement } from '@/api/templates'
|
||||
import { levelIndent, typographyStyle } from '@/utils/format'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
fields: TemplateField[]
|
||||
placements: TemplateTitlePlacement[]
|
||||
/** Show the sort value and typography under each heading. */
|
||||
showMeta?: boolean
|
||||
}>(),
|
||||
@@ -22,10 +22,10 @@ withDefaults(
|
||||
|
||||
<template>
|
||||
<div class="outline">
|
||||
<el-empty v-if="fields.length === 0" description="这个模板还没有选择任何字段" />
|
||||
<el-empty v-if="placements.length === 0" description="这个模板还没有选择任何字段" />
|
||||
|
||||
<ol v-else class="outline-list">
|
||||
<li v-for="field in fields" :key="field.id" class="outline-row">
|
||||
<li v-for="field in placements" :key="field.id" class="outline-row">
|
||||
<span class="outline-sort">{{ field.sort }}</span>
|
||||
<div class="outline-body">
|
||||
<div class="outline-name" :style="{ paddingLeft: levelIndent(field.level) }">
|
||||
|
||||
@@ -12,7 +12,7 @@ import { useRouter } from 'vue-router'
|
||||
import { Files, Notebook, Setting } from '@element-plus/icons-vue'
|
||||
|
||||
import { listPapers } from '@/api/papers'
|
||||
import { listTemplateFieldLibrary } from '@/api/templateFieldLibrary'
|
||||
import { listTemplateTitle } from '@/api/templateTitles'
|
||||
import { listTemplates } from '@/api/templates'
|
||||
import AppLogo from '@/components/AppLogo.vue'
|
||||
|
||||
@@ -20,7 +20,7 @@ const router = useRouter()
|
||||
|
||||
const paperCount = ref<number | null>(null)
|
||||
const templateCount = ref<number | null>(null)
|
||||
const fieldCount = ref<number | null>(null)
|
||||
const titleCount = ref<number | null>(null)
|
||||
|
||||
/** `null` renders as an em dash: unknown, not zero. */
|
||||
function display(value: number | null): string {
|
||||
@@ -30,14 +30,14 @@ function display(value: number | null): string {
|
||||
onMounted(async () => {
|
||||
// `page_size: 1` because only `total` is used. A failure leaves the count as
|
||||
// an em dash rather than blocking the page.
|
||||
const [papers, templates, fields] = await Promise.allSettled([
|
||||
const [papers, templates, titles] = await Promise.allSettled([
|
||||
listPapers({ page: 1, page_size: 1 }),
|
||||
listTemplates({ page: 1, page_size: 1 }),
|
||||
listTemplateFieldLibrary({ page: 1, page_size: 1 }),
|
||||
listTemplateTitle({ page: 1, page_size: 1 }),
|
||||
])
|
||||
if (papers.status === 'fulfilled') paperCount.value = papers.value.total
|
||||
if (templates.status === 'fulfilled') templateCount.value = templates.value.total
|
||||
if (fields.status === 'fulfilled') fieldCount.value = fields.value.total
|
||||
if (titles.status === 'fulfilled') titleCount.value = titles.value.total
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -81,7 +81,7 @@ onMounted(async () => {
|
||||
<div class="stat">
|
||||
<el-icon class="stat-icon"><Setting /></el-icon>
|
||||
<div>
|
||||
<div class="stat-value">{{ display(fieldCount) }}</div>
|
||||
<div class="stat-value">{{ display(titleCount) }}</div>
|
||||
<div class="stat-label">字段库</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -14,18 +14,18 @@ import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
|
||||
import { errorMessage } from '@/api/client'
|
||||
import {
|
||||
batchDeleteTemplateFieldLibrary,
|
||||
deleteTemplateFieldLibrary,
|
||||
listTemplateFieldLibrary,
|
||||
type TemplateFieldLibrary,
|
||||
} from '@/api/templateFieldLibrary'
|
||||
batchDeleteTemplateTitle,
|
||||
deleteTemplateTitle,
|
||||
listTemplateTitle,
|
||||
type TemplateTitle,
|
||||
} from '@/api/templateTitles'
|
||||
import FieldFormDialog from '@/components/fields/FieldFormDialog.vue'
|
||||
import { formatDateTime, levelIndent, typographyStyle } from '@/utils/format'
|
||||
|
||||
const loading = ref(false)
|
||||
const rows = ref<TemplateFieldLibrary[]>([])
|
||||
const rows = ref<TemplateTitle[]>([])
|
||||
const total = ref(0)
|
||||
const selection = ref<TemplateFieldLibrary[]>([])
|
||||
const selection = ref<TemplateTitle[]>([])
|
||||
|
||||
const query = reactive({
|
||||
keyword: '',
|
||||
@@ -35,7 +35,7 @@ const query = reactive({
|
||||
})
|
||||
|
||||
const dialogVisible = ref(false)
|
||||
const editing = ref<TemplateFieldLibrary | null>(null)
|
||||
const editing = ref<TemplateTitle | null>(null)
|
||||
|
||||
const LEVEL_FILTERS = [
|
||||
{ value: null, label: '全部等级' },
|
||||
@@ -47,7 +47,7 @@ const LEVEL_FILTERS = [
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await listTemplateFieldLibrary(query)
|
||||
const result = await listTemplateTitle(query)
|
||||
rows.value = result.items
|
||||
total.value = result.total
|
||||
|
||||
@@ -81,12 +81,12 @@ function onCreate(): void {
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
function onEdit(row: TemplateFieldLibrary): void {
|
||||
function onEdit(row: TemplateTitle): void {
|
||||
editing.value = row
|
||||
dialogVisible.value = true
|
||||
}
|
||||
|
||||
async function onDelete(row: TemplateFieldLibrary): Promise<void> {
|
||||
async function onDelete(row: TemplateTitle): Promise<void> {
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定删除字段「${row.name}」?`, '删除字段', {
|
||||
type: 'warning',
|
||||
@@ -98,7 +98,7 @@ async function onDelete(row: TemplateFieldLibrary): Promise<void> {
|
||||
}
|
||||
|
||||
try {
|
||||
await deleteTemplateFieldLibrary(row.id)
|
||||
await deleteTemplateTitle(row.id)
|
||||
ElMessage.success('已删除')
|
||||
await load()
|
||||
} catch (error) {
|
||||
@@ -121,7 +121,7 @@ async function onBatchDelete(): Promise<void> {
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await batchDeleteTemplateFieldLibrary(ids)
|
||||
const result = await batchDeleteTemplateTitle(ids)
|
||||
ElMessage.success(`已删除 ${result.deleted} 个字段`)
|
||||
selection.value = []
|
||||
await load()
|
||||
@@ -195,7 +195,7 @@ onMounted(load)
|
||||
stripe
|
||||
class="table table-fill"
|
||||
height="100%"
|
||||
@selection-change="(value: TemplateFieldLibrary[]) => (selection = value)"
|
||||
@selection-change="(value: TemplateTitle[]) => (selection = value)"
|
||||
>
|
||||
<el-table-column type="selection" width="46" reserve-selection />
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*
|
||||
* The full CRUD surface: search, create, edit, single and batch delete, with a
|
||||
* preview drawer that renders a template's outline exactly as it will read.
|
||||
* The drawer is the quickest way to confirm that a template's fields really do
|
||||
* The drawer is the quickest way to confirm that a template's titles really do
|
||||
* come out in `sort` order before committing to write against it.
|
||||
*/
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
@@ -210,7 +210,7 @@ onMounted(load)
|
||||
|
||||
<el-table-column label="段落数" width="100" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-tag size="small" effect="plain">{{ row.field_count }}</el-tag>
|
||||
<el-tag size="small" effect="plain">{{ row.placement_count }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
|
||||
@@ -262,7 +262,7 @@ onMounted(load)
|
||||
<div class="preview-meta">
|
||||
<el-tag size="small" effect="plain">
|
||||
<el-icon><Files /></el-icon>
|
||||
{{ preview.fields.length }} 个段落
|
||||
{{ preview.placements.length }} 个段落
|
||||
</el-tag>
|
||||
<span class="muted">更新于 {{ formatDateTime(preview.updated_at) }}</span>
|
||||
</div>
|
||||
@@ -274,7 +274,7 @@ onMounted(load)
|
||||
<span class="divider-hint">已按 sort 升序排列</span>
|
||||
</el-divider>
|
||||
|
||||
<TemplateOutline :fields="preview.fields" />
|
||||
<TemplateOutline :placements="preview.placements" />
|
||||
</template>
|
||||
</div>
|
||||
</el-drawer>
|
||||
|
||||
Reference in New Issue
Block a user