refactor: call a heading a title, and its use a placement
`template_field_library` and `template_field` were one word apart and meant
opposite kinds of thing — a catalogue of rows versus one row — and neither name
said what a row actually is. Every row of the library is a **heading**: a piece
of text like 「1. Introduction」 with a level and typography, which is what the
reader sees at the top of a paragraph; and every row of the join table is that
heading *placed* in a template, `sort` included.
template_field_library -> template_title
template_field -> template_title_placement
field_id (the column) -> title_id
TemplateFieldLibrary -> TemplateTitle
TemplateField -> TemplateTitlePlacement
The join table keeps its own name rather than becoming `_link`, because it is
not a bare link: it carries `sort`, the only place display order is stored, and
it deliberately allows the same title twice in one template. `_link` would
describe two foreign keys and hide the column the ordering rule rests on.
Carried through every level, because a half-renamed layer is how the confusing
pair got there in the first place: HTTP paths (`/template-field-library` ->
`/template-titles`), the template payload (`fields`/`field_id` ->
`placements`/`title_id`, and `field_count` -> `placement_count`), the Pydantic
schemas, the CRUD modules, the seed script, the frontend API module and types,
and `docs/OVERVIEW.md`, which now states the naming rules outright.
Two deliberate exceptions:
* `paper_template_filed_sort` is untouched — it is a column of the paper module
and is spelled as the feature was specified.
* The MCP tools keep their agent-facing names (`field_list`, `field_ids`, and
the `fields`/`field_id` keys in their responses). Agents already call them by
those names; the storage names they read underneath have changed.
The migration renames in place (data preserved: 4 templates, 45 titles, 63
placements) and is written to tolerate a database where part of it already ran,
which is not hypothetical — the first attempt renamed the tables and then failed
on the column, because Alembic's MySQL dialect wants an explicit type for
`alter_column` and will not rename a column without one. TiDB carries the
foreign key along with both the renamed table and the renamed column, rehearsed
against the cluster first, and it stays enforced.
Verified: seed re-runs clean, the paper smoke test's 45 checks and the MCP
smoke test's 47 pass, `vue-tsc` and the build are clean, and the UI was driven
in a headless browser through the template list, its preview drawer, the title
library page, the template form (which now posts `placements` with `title_id`)
and the paper document with no console errors.
This commit is contained in:
@@ -2,10 +2,10 @@
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.routes import health, papers, template_field_library, templates
|
||||
from app.api.routes import health, papers, template_titles, templates
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(health.router)
|
||||
api_router.include_router(papers.router)
|
||||
api_router.include_router(template_field_library.router)
|
||||
api_router.include_router(template_titles.router)
|
||||
api_router.include_router(templates.router)
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
"""Template-field library endpoints (字段管理).
|
||||
|
||||
The library is global and reusable: a field exists once and is then placed into
|
||||
any number of templates. That is why deleting a field is guarded — the join
|
||||
table is the only thing keeping a template's outline intact, and silently
|
||||
dropping a live heading from every template would be data loss, not cleanup.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud import template_field_library as crud
|
||||
from app.db.session import get_db
|
||||
from app.models import TemplateFieldLibrary
|
||||
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
|
||||
from app.schemas.template_field_library import (
|
||||
TemplateFieldLibraryCreate,
|
||||
TemplateFieldLibraryRead,
|
||||
TemplateFieldLibraryUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/template-field-library", tags=["template-field-library"])
|
||||
|
||||
|
||||
def _get_or_404(db: Session, field_id: int) -> TemplateFieldLibrary:
|
||||
field = crud.get(db, field_id)
|
||||
if field is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"字段 {field_id} 不存在",
|
||||
)
|
||||
return field
|
||||
|
||||
|
||||
def _assert_unused(db: Session, fields: list[TemplateFieldLibrary]) -> None:
|
||||
"""Refuse the delete if any field is still placed in a template.
|
||||
|
||||
All offenders are reported at once rather than one per attempt, so a batch
|
||||
delete does not turn into trial and error.
|
||||
"""
|
||||
counts = crud.usage_counts(db, [field.id for field in fields])
|
||||
if not counts:
|
||||
return
|
||||
|
||||
by_id = {field.id: field.name for field in fields}
|
||||
blockers = "、".join(
|
||||
f"“{by_id.get(field_id, field_id)}”({count} 个模板)"
|
||||
for field_id, count in sorted(counts.items())
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"以下字段正被模板使用,请先在模板中移除:{blockers}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=PageResult[TemplateFieldLibraryRead],
|
||||
summary="List the field library",
|
||||
)
|
||||
def list_library_entries(
|
||||
db: Session = Depends(get_db),
|
||||
keyword: str | None = Query(default=None, description="按字段名称模糊搜索"),
|
||||
level: int | None = Query(default=None, ge=1, le=9, description="按字段等级过滤"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=500),
|
||||
) -> PageResult[TemplateFieldLibraryRead]:
|
||||
"""Browse the field library, grouped by level then creation order."""
|
||||
rows, total = crud.list_fields(
|
||||
db,
|
||||
keyword=keyword,
|
||||
level=level,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return PageResult.build(
|
||||
items=[TemplateFieldLibraryRead.model_validate(row) for row in rows],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=TemplateFieldLibraryRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a library entry",
|
||||
)
|
||||
def create_library_entry(
|
||||
payload: TemplateFieldLibraryCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateFieldLibraryRead:
|
||||
"""Add a heading to the library, with its typography."""
|
||||
return TemplateFieldLibraryRead.model_validate(crud.create(db, payload))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-delete",
|
||||
response_model=BatchDeleteResult,
|
||||
summary="Delete several library entries",
|
||||
)
|
||||
def batch_delete_library_entries(
|
||||
payload: BatchDeleteRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> BatchDeleteResult:
|
||||
"""Delete the given fields, refusing wholesale if any is still in use."""
|
||||
fields = crud.get_many(db, payload.ids)
|
||||
_assert_unused(db, fields)
|
||||
|
||||
for field in fields:
|
||||
crud.delete(db, field)
|
||||
return BatchDeleteResult(deleted=len(fields))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{field_id}",
|
||||
response_model=TemplateFieldLibraryRead,
|
||||
summary="Fetch one library entry",
|
||||
)
|
||||
def get_library_entry(
|
||||
field_id: int, db: Session = Depends(get_db)
|
||||
) -> TemplateFieldLibraryRead:
|
||||
"""Return a single library entry."""
|
||||
return TemplateFieldLibraryRead.model_validate(_get_or_404(db, field_id))
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/{field_id}",
|
||||
response_model=TemplateFieldLibraryRead,
|
||||
summary="Update one library entry",
|
||||
)
|
||||
def update_library_entry(
|
||||
field_id: int,
|
||||
payload: TemplateFieldLibraryUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateFieldLibraryRead:
|
||||
"""Rename or restyle a library entry.
|
||||
|
||||
The change is visible in every template that places the field, because
|
||||
templates store a reference rather than a copy.
|
||||
"""
|
||||
field = _get_or_404(db, field_id)
|
||||
return TemplateFieldLibraryRead.model_validate(crud.update(db, field, payload))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{field_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Delete one library entry",
|
||||
)
|
||||
def delete_library_entry(field_id: int, db: Session = Depends(get_db)) -> Response:
|
||||
"""Delete a library entry no template places."""
|
||||
field = _get_or_404(db, field_id)
|
||||
_assert_unused(db, [field])
|
||||
crud.delete(db, field)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Template-title library endpoints (字段管理).
|
||||
|
||||
The library is global and reusable: a title exists once and is then placed into
|
||||
any number of templates. That is why deleting one is guarded — the join table
|
||||
is the only thing keeping a template's outline intact, and silently dropping a
|
||||
live heading from every template would be data loss, not cleanup.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud import template_title as crud
|
||||
from app.db.session import get_db
|
||||
from app.models import TemplateTitle
|
||||
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
|
||||
from app.schemas.template_title import (
|
||||
TemplateTitleCreate,
|
||||
TemplateTitleRead,
|
||||
TemplateTitleUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/template-titles", tags=["template-titles"])
|
||||
|
||||
|
||||
def _get_or_404(db: Session, title_id: int) -> TemplateTitle:
|
||||
title = crud.get(db, title_id)
|
||||
if title is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"标题 {title_id} 不存在",
|
||||
)
|
||||
return title
|
||||
|
||||
|
||||
def _assert_unused(db: Session, titles: list[TemplateTitle]) -> None:
|
||||
"""Refuse the delete if any title is still placed in a template.
|
||||
|
||||
All offenders are reported at once rather than one per attempt, so a batch
|
||||
delete does not turn into trial and error.
|
||||
"""
|
||||
counts = crud.usage_counts(db, [title.id for title in titles])
|
||||
if not counts:
|
||||
return
|
||||
|
||||
by_id = {title.id: title.name for title in titles}
|
||||
blockers = "、".join(
|
||||
f"“{by_id.get(title_id, title_id)}”({count} 个模板)"
|
||||
for title_id, count in sorted(counts.items())
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f"以下标题正被模板使用,请先在模板中移除:{blockers}",
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=PageResult[TemplateTitleRead],
|
||||
summary="List the title library",
|
||||
)
|
||||
def list_titles(
|
||||
db: Session = Depends(get_db),
|
||||
keyword: str | None = Query(default=None, description="按字段名称模糊搜索"),
|
||||
level: int | None = Query(default=None, ge=1, le=9, description="按字段等级过滤"),
|
||||
page: int = Query(default=1, ge=1),
|
||||
page_size: int = Query(default=20, ge=1, le=500),
|
||||
) -> PageResult[TemplateTitleRead]:
|
||||
"""Browse the title library, grouped by level then creation order."""
|
||||
rows, total = crud.list_titles(
|
||||
db,
|
||||
keyword=keyword,
|
||||
level=level,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return PageResult.build(
|
||||
items=[TemplateTitleRead.model_validate(row) for row in rows],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"",
|
||||
response_model=TemplateTitleRead,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
summary="Create a library entry",
|
||||
)
|
||||
def create_title(
|
||||
payload: TemplateTitleCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateTitleRead:
|
||||
"""Add a heading to the library, with its typography."""
|
||||
return TemplateTitleRead.model_validate(crud.create(db, payload))
|
||||
|
||||
|
||||
@router.post(
|
||||
"/batch-delete",
|
||||
response_model=BatchDeleteResult,
|
||||
summary="Delete several library entries",
|
||||
)
|
||||
def batch_delete_titles(
|
||||
payload: BatchDeleteRequest,
|
||||
db: Session = Depends(get_db),
|
||||
) -> BatchDeleteResult:
|
||||
"""Delete the given titles, refusing wholesale if any is still in use."""
|
||||
titles = crud.get_many(db, payload.ids)
|
||||
_assert_unused(db, titles)
|
||||
|
||||
for title in titles:
|
||||
crud.delete(db, title)
|
||||
return BatchDeleteResult(deleted=len(titles))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{title_id}",
|
||||
response_model=TemplateTitleRead,
|
||||
summary="Fetch one library entry",
|
||||
)
|
||||
def get_title(
|
||||
title_id: int, db: Session = Depends(get_db)
|
||||
) -> TemplateTitleRead:
|
||||
"""Return a single library entry."""
|
||||
return TemplateTitleRead.model_validate(_get_or_404(db, title_id))
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/{title_id}",
|
||||
response_model=TemplateTitleRead,
|
||||
summary="Update one library entry",
|
||||
)
|
||||
def update_title(
|
||||
title_id: int,
|
||||
payload: TemplateTitleUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateTitleRead:
|
||||
"""Rename or restyle a library entry.
|
||||
|
||||
The change is visible in every template that places the title, because
|
||||
templates store a reference rather than a copy.
|
||||
"""
|
||||
title = _get_or_404(db, title_id)
|
||||
return TemplateTitleRead.model_validate(crud.update(db, title, payload))
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/{title_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
summary="Delete one library entry",
|
||||
)
|
||||
def delete_title(title_id: int, db: Session = Depends(get_db)) -> Response:
|
||||
"""Delete a library entry no template places."""
|
||||
title = _get_or_404(db, title_id)
|
||||
_assert_unused(db, [title])
|
||||
crud.delete(db, title)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -1,14 +1,14 @@
|
||||
"""Paper-template endpoints (模板管理).
|
||||
|
||||
A template is created from two pieces of free text plus a free selection of
|
||||
library fields. Nothing constrains the selection: the same field may be picked
|
||||
library titles. Nothing constrains the selection: the same title may be picked
|
||||
twice, the picks may arrive in any order, and the only thing that decides how
|
||||
the outline reads is ``sort``.
|
||||
|
||||
A template that a paper is written against is also *structure* for that paper,
|
||||
not only configuration: deleting it would leave the paper with nothing to
|
||||
render. That delete is therefore refused, with the same 409 the field library
|
||||
uses for a field still placed in a template.
|
||||
render. That delete is therefore refused, with the same 409 the title library
|
||||
uses for a title still placed in a template.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
@@ -73,19 +73,19 @@ def _assert_not_used_by_papers(db: Session, template_ids: list[int]) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _assert_fields_exist(db: Session, field_ids: list[int]) -> None:
|
||||
"""Reject a selection that references fields the library does not have.
|
||||
def _assert_titles_exist(db: Session, title_ids: list[int]) -> None:
|
||||
"""Reject a selection that references titles the library does not have.
|
||||
|
||||
Checked in Python rather than by a foreign key because TiDB parses but does
|
||||
not enforce ``FOREIGN KEY``, so an unchecked write would happily leave a
|
||||
template pointing at nothing.
|
||||
"""
|
||||
missing = crud.missing_field_ids(db, field_ids)
|
||||
missing = crud.missing_title_ids(db, title_ids)
|
||||
if missing:
|
||||
joined = "、".join(str(field_id) for field_id in missing)
|
||||
joined = "、".join(str(title_id) for title_id in missing)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"字段不存在:{joined}",
|
||||
detail=f"标题不存在:{joined}",
|
||||
)
|
||||
|
||||
|
||||
@@ -117,15 +117,15 @@ def create_template(
|
||||
payload: TemplateCreate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateRead:
|
||||
"""Create a template from a name, an abstract, and a field selection."""
|
||||
"""Create a template from a name, an abstract, and a title selection."""
|
||||
_assert_name_free(db, payload.name)
|
||||
_assert_fields_exist(db, [item.field_id for item in payload.fields])
|
||||
_assert_titles_exist(db, [item.title_id for item in payload.placements])
|
||||
|
||||
template = crud.create(
|
||||
db,
|
||||
name=payload.name,
|
||||
abstract=payload.abstract,
|
||||
fields=payload.fields,
|
||||
placements=payload.placements,
|
||||
)
|
||||
return TemplateRead.from_model(template)
|
||||
|
||||
@@ -150,7 +150,7 @@ def batch_delete_templates(
|
||||
summary="Fetch one paper template with its outline",
|
||||
)
|
||||
def get_template(template_id: int, db: Session = Depends(get_db)) -> TemplateRead:
|
||||
"""Return a template; ``fields`` arrives already ordered by ``sort``."""
|
||||
"""Return a template; ``placements`` arrives already ordered by ``sort``."""
|
||||
return TemplateRead.from_model(_get_or_404(db, template_id))
|
||||
|
||||
|
||||
@@ -164,27 +164,27 @@ def update_template(
|
||||
payload: TemplateUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
) -> TemplateRead:
|
||||
"""Update the name, the abstract, the field selection, or any combination.
|
||||
"""Update the name, the abstract, the title selection, or any combination.
|
||||
|
||||
``fields`` is a full replacement when present. Omitting it leaves the
|
||||
``placements`` is a full replacement when present. Omitting it leaves the
|
||||
outline untouched; sending ``[]`` clears it.
|
||||
"""
|
||||
template = _get_or_404(db, template_id)
|
||||
|
||||
if payload.name is not None:
|
||||
_assert_name_free(db, payload.name, exclude_id=template_id)
|
||||
if payload.fields is not None:
|
||||
_assert_fields_exist(db, [item.field_id for item in payload.fields])
|
||||
if payload.placements is not None:
|
||||
_assert_titles_exist(db, [item.title_id for item in payload.placements])
|
||||
|
||||
updated = crud.update(
|
||||
db,
|
||||
template,
|
||||
name=payload.name,
|
||||
abstract=payload.abstract,
|
||||
# Both "field omitted" and "field set to null" arrive as None; only
|
||||
# Both "key omitted" and "key set to null" arrive as None; only
|
||||
# model_fields_set records which one the client actually sent.
|
||||
abstract_provided="abstract" in payload.model_fields_set,
|
||||
fields=payload.fields,
|
||||
placements=payload.placements,
|
||||
)
|
||||
return TemplateRead.from_model(updated)
|
||||
|
||||
@@ -195,7 +195,7 @@ def update_template(
|
||||
summary="Delete a paper template",
|
||||
)
|
||||
def delete_template(template_id: int, db: Session = Depends(get_db)) -> Response:
|
||||
"""Delete a template. Library fields it referenced are left alone.
|
||||
"""Delete a template. Library titles it referenced are left alone.
|
||||
|
||||
Refused while a paper is written against the template: the outline is the
|
||||
paper's structure, and removing it would empty the paper rather than tidy
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user