refactor: prefix every table with its module

Two tables were named after the concept they came from rather than the module
they belong to, so the schema read as if the template tables were part of the
paper module. Renamed (data preserved, `RENAME TABLE` moves rows in place):

    paper_template  -> template                 the 模板 module
    section_field   -> template_field_library   the 字段库 the 模板 module owns

The paper tables and `template_field` already followed the rule. The rename
carries through everything that named a module:

  models   Template, TemplateField, TemplateFieldLibrary
  schemas  Template*, TemplateFieldLibrary*
  crud     app/crud/template.py, app/crud/template_field_library.py
  API      /template-field-library (was /section-fields); handlers are now
           named after library entries, which removes the ambiguity with
           TemplateField — a placement, a different thing entirely
  client   src/api/templateFieldLibrary.ts

`paper_template_filed_sort` is deliberately untouched: it is a column of the
paper module, spelled as the feature was specified.

TiDB v8.5 with tidb_enable_foreign_key on — as this cluster runs — enforces
foreign keys rather than ignoring them, so the docs' "TiDB does not enforce
foreign keys" was wrong. Corrected, with what actually follows from it: the
rename was rehearsed (RENAME TABLE carries a referencing constraint along), the
API keeps checking first so a violation names the row instead of surfacing a
driver error, and the ORM cascades stay so behaviour does not depend on a
cluster setting.

Revision f27a1c6d9e04 verified both ways; 40 smoke checks, type-check and build
all pass.
This commit is contained in:
2026-09-18 17:48:11 +08:00
parent 2d113f9f6b
commit a5f884f440
25 changed files with 371 additions and 260 deletions
@@ -0,0 +1,50 @@
"""rename tables so every module prefixes its own
Two tables were named after the concept they came from rather than the module
they belong to, which made the schema read as if the template tables were part
of the paper module:
paper_template -> template the 模板 module
section_field -> template_field_library the 字段库, which the 模板 module
owns and every template draws on
The paper module (``paper``, ``paper_sentence``, ``paper_sentence_reference``)
and the join table (``template_field``) already followed the rule and are not
touched. After this revision the naming is:
template template_field template_field_library
paper paper_sentence paper_sentence_reference
A rename, not a copy: ``RENAME TABLE`` moves the rows and leaves the data in
place, and TiDB carries a referencing foreign key along with the renamed table
(verified against the running cluster before this migration was written), so
the constraints in ``template_field``, ``paper`` and ``paper_sentence`` now
point at ``template`` and ``template_field_library`` with no drop/recreate
step. Index names are left alone: they are per-table in MySQL and TiDB, and
``template_field`` — whose indexes embed its own name — is not renamed.
Revision ID: f27a1c6d9e04
Revises: c41d7b09e5af
Create Date: 2026-09-18
"""
from collections.abc import Sequence
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "f27a1c6d9e04"
down_revision: str | None = "c41d7b09e5af"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
op.rename_table("paper_template", "template")
op.rename_table("section_field", "template_field_library")
def downgrade() -> None:
op.rename_table("template_field_library", "section_field")
op.rename_table("template", "paper_template")
+2 -2
View File
@@ -2,10 +2,10 @@
from fastapi import APIRouter
from app.api.routes import health, papers, section_fields, templates
from app.api.routes import health, papers, template_field_library, templates
api_router = APIRouter()
api_router.include_router(health.router)
api_router.include_router(papers.router)
api_router.include_router(section_fields.router)
api_router.include_router(template_field_library.router)
api_router.include_router(templates.router)
+2 -2
View File
@@ -20,7 +20,7 @@ from sqlalchemy.orm import Session
from app.crud import paper as crud
from app.db.session import get_db
from app.models import Paper, PaperSentence, PaperTemplate
from app.models import Paper, PaperSentence, Template
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.paper import (
PaperCreate,
@@ -72,7 +72,7 @@ def _assert_template_exists(db: Session, template_id: int | None) -> None:
"""
if template_id is None:
return
if db.get(PaperTemplate, template_id) is None:
if db.get(Template, template_id) is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"模板 {template_id} 不存在",
@@ -1,4 +1,4 @@
"""Section-field library endpoints (字段管理).
"""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
@@ -9,20 +9,20 @@ 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 section_field as crud
from app.crud import template_field_library as crud
from app.db.session import get_db
from app.models import SectionField
from app.models import TemplateFieldLibrary
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.section_field import (
SectionFieldCreate,
SectionFieldRead,
SectionFieldUpdate,
from app.schemas.template_field_library import (
TemplateFieldLibraryCreate,
TemplateFieldLibraryRead,
TemplateFieldLibraryUpdate,
)
router = APIRouter(prefix="/section-fields", tags=["section-fields"])
router = APIRouter(prefix="/template-field-library", tags=["template-field-library"])
def _get_or_404(db: Session, field_id: int) -> SectionField:
def _get_or_404(db: Session, field_id: int) -> TemplateFieldLibrary:
field = crud.get(db, field_id)
if field is None:
raise HTTPException(
@@ -32,7 +32,7 @@ def _get_or_404(db: Session, field_id: int) -> SectionField:
return field
def _assert_unused(db: Session, fields: list[SectionField]) -> None:
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
@@ -55,16 +55,16 @@ def _assert_unused(db: Session, fields: list[SectionField]) -> None:
@router.get(
"",
response_model=PageResult[SectionFieldRead],
response_model=PageResult[TemplateFieldLibraryRead],
summary="List the field library",
)
def list_fields(
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[SectionFieldRead]:
) -> PageResult[TemplateFieldLibraryRead]:
"""Browse the field library, grouped by level then creation order."""
rows, total = crud.list_fields(
db,
@@ -74,7 +74,7 @@ def list_fields(
page_size=page_size,
)
return PageResult.build(
items=[SectionFieldRead.model_validate(row) for row in rows],
items=[TemplateFieldLibraryRead.model_validate(row) for row in rows],
total=total,
page=page,
page_size=page_size,
@@ -83,24 +83,24 @@ def list_fields(
@router.post(
"",
response_model=SectionFieldRead,
response_model=TemplateFieldLibraryRead,
status_code=status.HTTP_201_CREATED,
summary="Create a section field",
summary="Create a library entry",
)
def create_field(
payload: SectionFieldCreate,
def create_library_entry(
payload: TemplateFieldLibraryCreate,
db: Session = Depends(get_db),
) -> SectionFieldRead:
) -> TemplateFieldLibraryRead:
"""Add a heading to the library, with its typography."""
return SectionFieldRead.model_validate(crud.create(db, payload))
return TemplateFieldLibraryRead.model_validate(crud.create(db, payload))
@router.post(
"/batch-delete",
response_model=BatchDeleteResult,
summary="Delete several section fields",
summary="Delete several library entries",
)
def batch_delete_fields(
def batch_delete_library_entries(
payload: BatchDeleteRequest,
db: Session = Depends(get_db),
) -> BatchDeleteResult:
@@ -115,40 +115,42 @@ def batch_delete_fields(
@router.get(
"/{field_id}",
response_model=SectionFieldRead,
summary="Fetch one section field",
response_model=TemplateFieldLibraryRead,
summary="Fetch one library entry",
)
def get_field(field_id: int, db: Session = Depends(get_db)) -> SectionFieldRead:
"""Return a single field."""
return SectionFieldRead.model_validate(_get_or_404(db, field_id))
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=SectionFieldRead,
summary="Update a section field",
response_model=TemplateFieldLibraryRead,
summary="Update one library entry",
)
def update_field(
def update_library_entry(
field_id: int,
payload: SectionFieldUpdate,
payload: TemplateFieldLibraryUpdate,
db: Session = Depends(get_db),
) -> SectionFieldRead:
"""Rename or restyle a field.
) -> 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 SectionFieldRead.model_validate(crud.update(db, field, payload))
return TemplateFieldLibraryRead.model_validate(crud.update(db, field, payload))
@router.delete(
"/{field_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Delete a section field",
summary="Delete one library entry",
)
def delete_field(field_id: int, db: Session = Depends(get_db)) -> Response:
"""Delete an unused field."""
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)
+22 -22
View File
@@ -15,21 +15,21 @@ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from sqlalchemy.orm import Session
from app.crud import paper as paper_crud
from app.crud import paper_template as crud
from app.crud import template as crud
from app.db.session import get_db
from app.models import PaperTemplate
from app.models import Template
from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult
from app.schemas.paper_template import (
PaperTemplateCreate,
PaperTemplateListItem,
PaperTemplateRead,
PaperTemplateUpdate,
from app.schemas.template import (
TemplateCreate,
TemplateListItem,
TemplateRead,
TemplateUpdate,
)
router = APIRouter(prefix="/templates", tags=["templates"])
def _get_or_404(db: Session, template_id: int) -> PaperTemplate:
def _get_or_404(db: Session, template_id: int) -> Template:
template = crud.get(db, template_id)
if template is None:
raise HTTPException(
@@ -60,7 +60,7 @@ def _assert_not_used_by_papers(db: Session, template_ids: list[int]) -> None:
blockers = []
for template_id, count in sorted(counts.items()):
template = db.get(PaperTemplate, template_id)
template = db.get(Template, template_id)
name = template.name if template is not None else template_id
blockers.append(f"{name}”({count} 篇论文)")
@@ -91,7 +91,7 @@ def _assert_fields_exist(db: Session, field_ids: list[int]) -> None:
@router.get(
"",
response_model=PageResult[PaperTemplateListItem],
response_model=PageResult[TemplateListItem],
summary="List paper templates",
)
def list_templates(
@@ -99,7 +99,7 @@ def list_templates(
keyword: str | None = Query(default=None, description="按模板名称或摘要模糊搜索"),
page: int = Query(default=1, ge=1),
page_size: int = Query(default=20, ge=1, le=200),
) -> PageResult[PaperTemplateListItem]:
) -> PageResult[TemplateListItem]:
"""Browse templates, most recently edited first."""
items, total = crud.list_templates(
db, keyword=keyword, page=page, page_size=page_size
@@ -109,14 +109,14 @@ def list_templates(
@router.post(
"",
response_model=PaperTemplateRead,
response_model=TemplateRead,
status_code=status.HTTP_201_CREATED,
summary="Create a paper template",
)
def create_template(
payload: PaperTemplateCreate,
payload: TemplateCreate,
db: Session = Depends(get_db),
) -> PaperTemplateRead:
) -> TemplateRead:
"""Create a template from a name, an abstract, and a field selection."""
_assert_name_free(db, payload.name)
_assert_fields_exist(db, [item.field_id for item in payload.fields])
@@ -127,7 +127,7 @@ def create_template(
abstract=payload.abstract,
fields=payload.fields,
)
return PaperTemplateRead.from_model(template)
return TemplateRead.from_model(template)
@router.post(
@@ -146,24 +146,24 @@ def batch_delete_templates(
@router.get(
"/{template_id}",
response_model=PaperTemplateRead,
response_model=TemplateRead,
summary="Fetch one paper template with its outline",
)
def get_template(template_id: int, db: Session = Depends(get_db)) -> PaperTemplateRead:
def get_template(template_id: int, db: Session = Depends(get_db)) -> TemplateRead:
"""Return a template; ``fields`` arrives already ordered by ``sort``."""
return PaperTemplateRead.from_model(_get_or_404(db, template_id))
return TemplateRead.from_model(_get_or_404(db, template_id))
@router.patch(
"/{template_id}",
response_model=PaperTemplateRead,
response_model=TemplateRead,
summary="Update a paper template",
)
def update_template(
template_id: int,
payload: PaperTemplateUpdate,
payload: TemplateUpdate,
db: Session = Depends(get_db),
) -> PaperTemplateRead:
) -> TemplateRead:
"""Update the name, the abstract, the field selection, or any combination.
``fields`` is a full replacement when present. Omitting it leaves the
@@ -186,7 +186,7 @@ def update_template(
abstract_provided="abstract" in payload.model_fields_set,
fields=payload.fields,
)
return PaperTemplateRead.from_model(updated)
return TemplateRead.from_model(updated)
@router.delete(
+2 -2
View File
@@ -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, paper_template, section_field
from app.crud import paper, template, template_field_library
__all__ = ["paper", "paper_template", "section_field"]
__all__ = ["paper", "template", "template_field_library"]
+1 -1
View File
@@ -36,7 +36,7 @@ from app.models import (
Paper,
PaperSentence,
PaperSentenceReference,
PaperTemplate,
Template,
TemplateField,
)
from app.schemas.paper import (
@@ -1,4 +1,4 @@
"""Data access for paper templates and their ordered field selections."""
"""Data access for templates and their ordered field 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 PaperTemplate, SectionField, TemplateField
from app.schemas.paper_template import PaperTemplateListItem, TemplateFieldInput
from app.models import Template, TemplateFieldLibrary, TemplateField
from app.schemas.template import TemplateListItem, TemplateFieldInput
def _conditions(keyword: str | None) -> list:
@@ -17,8 +17,8 @@ def _conditions(keyword: str | None) -> list:
pattern = like_pattern(keyword)
return [
or_(
PaperTemplate.name.like(pattern, escape=LIKE_ESCAPE),
PaperTemplate.abstract.like(pattern, escape=LIKE_ESCAPE),
Template.name.like(pattern, escape=LIKE_ESCAPE),
Template.abstract.like(pattern, escape=LIKE_ESCAPE),
)
]
@@ -27,8 +27,8 @@ def _field_count_column():
"""A correlated ``COUNT`` of the template's placement rows."""
return (
select(func.count(TemplateField.id))
.where(TemplateField.template_id == PaperTemplate.id)
.correlate(PaperTemplate)
.where(TemplateField.template_id == Template.id)
.correlate(Template)
.scalar_subquery()
)
@@ -39,7 +39,7 @@ def list_templates(
keyword: str | None = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[PaperTemplateListItem], int]:
) -> tuple[list[TemplateListItem], int]:
"""Return one page of templates with their field counts, plus the total.
The outline itself is left out: a table row needs the count, not the rows.
@@ -48,19 +48,19 @@ def list_templates(
conditions = _conditions(keyword)
total = db.scalar(
select(func.count(PaperTemplate.id)).where(*conditions)
select(func.count(Template.id)).where(*conditions)
) or 0
stmt = (
select(PaperTemplate, _field_count_column().label("field_count"))
select(Template, _field_count_column().label("field_count"))
.where(*conditions)
.order_by(PaperTemplate.updated_at.desc(), PaperTemplate.id.desc())
.order_by(Template.updated_at.desc(), Template.id.desc())
.offset((page - 1) * page_size)
.limit(page_size)
)
items = [
PaperTemplateListItem(
TemplateListItem(
id=template.id,
name=template.name,
abstract=template.abstract,
@@ -73,21 +73,21 @@ def list_templates(
return items, total
def get(db: Session, template_id: int) -> PaperTemplate | None:
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.
"""
return db.get(PaperTemplate, template_id)
return db.get(Template, template_id)
def name_taken(db: Session, name: str, *, exclude_id: int | None = None) -> bool:
"""Whether another template already uses ``name``."""
stmt = select(func.count(PaperTemplate.id)).where(PaperTemplate.name == name)
stmt = select(func.count(Template.id)).where(Template.name == name)
if exclude_id is not None:
stmt = stmt.where(PaperTemplate.id != exclude_id)
stmt = stmt.where(Template.id != exclude_id)
return bool(db.scalar(stmt))
@@ -101,7 +101,7 @@ def missing_field_ids(db: Session, field_ids: Sequence[int]) -> list[int]:
if not wanted:
return []
found = set(
db.scalars(select(SectionField.id).where(SectionField.id.in_(wanted))).all()
db.scalars(select(TemplateFieldLibrary.id).where(TemplateFieldLibrary.id.in_(wanted))).all()
)
return sorted(wanted - found)
@@ -117,9 +117,9 @@ def create(
name: str,
abstract: str | None,
fields: Sequence[TemplateFieldInput],
) -> PaperTemplate:
) -> Template:
"""Insert a template together with its ordered selection."""
template = PaperTemplate(name=name, abstract=abstract)
template = Template(name=name, abstract=abstract)
template.items = _build_items(fields)
db.add(template)
db.commit()
@@ -129,13 +129,13 @@ def create(
def update(
db: Session,
template: PaperTemplate,
template: Template,
*,
name: str | None = None,
abstract: str | None = None,
abstract_provided: bool = False,
fields: Sequence[TemplateFieldInput] | None = None,
) -> PaperTemplate:
) -> Template:
"""Apply a partial update. ``fields=None`` leaves the selection untouched.
``abstract_provided`` distinguishes "clear the abstract" from "leave it"
@@ -159,7 +159,7 @@ def update(
return template
def delete(db: Session, template: PaperTemplate) -> None:
def delete(db: Session, template: Template) -> None:
"""Delete a template and its placement rows."""
db.delete(template)
db.commit()
@@ -171,7 +171,7 @@ def delete_many(db: Session, template_ids: Sequence[int]) -> int:
return 0
templates = list(
db.scalars(
select(PaperTemplate).where(PaperTemplate.id.in_(list(template_ids)))
select(Template).where(Template.id.in_(list(template_ids)))
).all()
)
for template in templates:
@@ -1,4 +1,4 @@
"""Data access for the reusable section-field library (字段管理)."""
"""Data access for the reusable template-field library (字段管理)."""
from collections.abc import Sequence
@@ -6,8 +6,11 @@ from sqlalchemy import Select, func, select
from sqlalchemy.orm import Session
from app.crud.filters import LIKE_ESCAPE, like_pattern
from app.models import SectionField, TemplateField
from app.schemas.section_field import SectionFieldCreate, SectionFieldUpdate
from app.models import TemplateField, TemplateFieldLibrary
from app.schemas.template_field_library import (
TemplateFieldLibraryCreate,
TemplateFieldLibraryUpdate,
)
def _conditions(keyword: str | None, level: int | None) -> list:
@@ -15,10 +18,10 @@ def _conditions(keyword: str | None, level: int | None) -> list:
conditions = []
if keyword:
conditions.append(
SectionField.name.like(like_pattern(keyword), escape=LIKE_ESCAPE)
TemplateFieldLibrary.name.like(like_pattern(keyword), escape=LIKE_ESCAPE)
)
if level is not None:
conditions.append(SectionField.level == level)
conditions.append(TemplateFieldLibrary.level == level)
return conditions
@@ -30,7 +33,7 @@ def _ordered(stmt: Select) -> Select:
ordered by ``name``: names carry hand-written numbering ("1.", "10.",
"2."), and string ordering would scramble it.
"""
return stmt.order_by(SectionField.level.asc(), SectionField.id.asc())
return stmt.order_by(TemplateFieldLibrary.level.asc(), TemplateFieldLibrary.id.asc())
def list_fields(
@@ -40,16 +43,16 @@ def list_fields(
level: int | None = None,
page: int = 1,
page_size: int = 20,
) -> tuple[list[SectionField], int]:
) -> 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(SectionField.id)).where(*conditions)
select(func.count(TemplateFieldLibrary.id)).where(*conditions)
) or 0
stmt = _ordered(
select(SectionField)
select(TemplateFieldLibrary)
.where(*conditions)
.offset((page - 1) * page_size)
.limit(page_size)
@@ -57,16 +60,16 @@ def list_fields(
return list(db.scalars(stmt).all()), total
def get(db: Session, field_id: int) -> SectionField | None:
def get(db: Session, field_id: int) -> TemplateFieldLibrary | None:
"""Return one field, or ``None``."""
return db.get(SectionField, field_id)
return db.get(TemplateFieldLibrary, field_id)
def get_many(db: Session, field_ids: Sequence[int]) -> list[SectionField]:
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(SectionField).where(SectionField.id.in_(list(field_ids)))
stmt = select(TemplateFieldLibrary).where(TemplateFieldLibrary.id.in_(list(field_ids)))
return list(db.scalars(stmt).all())
@@ -89,16 +92,20 @@ def usage_counts(db: Session, field_ids: Sequence[int]) -> dict[int, int]:
return {field_id: count for field_id, count in db.execute(stmt).all()}
def create(db: Session, data: SectionFieldCreate) -> SectionField:
def create(db: Session, data: TemplateFieldLibraryCreate) -> TemplateFieldLibrary:
"""Insert a field."""
field = SectionField(**data.model_dump())
field = TemplateFieldLibrary(**data.model_dump())
db.add(field)
db.commit()
db.refresh(field)
return field
def update(db: Session, field: SectionField, data: SectionFieldUpdate) -> SectionField:
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
@@ -112,7 +119,7 @@ def update(db: Session, field: SectionField, data: SectionFieldUpdate) -> Sectio
return field
def delete(db: Session, field: SectionField) -> None:
def delete(db: Session, field: TemplateFieldLibrary) -> None:
"""Delete a field. Callers must check :func:`usage_counts` first."""
db.delete(field)
db.commit()
+20 -4
View File
@@ -7,6 +7,22 @@ be added to the imports below, not only to its own module.
The import order here is for readability only: relationships are declared by
name and resolved through the SQLAlchemy registry after every module has been
imported, so a cycle between two model modules is not a problem.
Table naming
------------
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
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
opposite things: the first is a *placement* (this template puts this field
here, ``sort`` included), the second is the *catalogue* it was picked from.
"""
from app.models.mixins import TimestampMixin
@@ -19,9 +35,9 @@ from app.models.paper import (
)
from app.models.paper_sentence import PaperSentence
from app.models.paper_sentence_reference import PaperSentenceReference
from app.models.paper_template import PaperTemplate
from app.models.section_field import SectionField
from app.models.template import Template
from app.models.template_field import TemplateField
from app.models.template_field_library import TemplateFieldLibrary
__all__ = [
"PAPER_STATUSES",
@@ -31,8 +47,8 @@ __all__ = [
"Paper",
"PaperSentence",
"PaperSentenceReference",
"PaperTemplate",
"SectionField",
"Template",
"TemplateField",
"TemplateFieldLibrary",
"TimestampMixin",
]
+4 -4
View File
@@ -3,7 +3,7 @@
A paper is a bag of metadata plus two things that are deliberately kept apart:
* its **structure**, which is not stored here at all. Every render reads the
:class:`~app.models.paper_template.PaperTemplate` the paper points at, live.
:class:`~app.models.template.Template` the paper points at, live.
Nothing is copied, so switching ``template_id`` re-shapes the whole document
in one write.
* its **content**, which lives in
@@ -33,7 +33,7 @@ from app.models.mixins import TimestampMixin
if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.paper_sentence import PaperSentence
from app.models.paper_template import PaperTemplate
from app.models.template import Template
#: Writing state of a paper: 草稿 / 撰写中 / 已完成.
#:
@@ -65,7 +65,7 @@ class Paper(TimestampMixin, Base):
#: ``RESTRICT`` documents the intent (a template in use must not vanish);
#: TiDB does not enforce it, so the API refuses the template delete too.
template_id: Mapped[int | None] = mapped_column(
ForeignKey("paper_template.id", ondelete="RESTRICT"),
ForeignKey("template.id", ondelete="RESTRICT"),
nullable=True,
)
@@ -93,7 +93,7 @@ class Paper(TimestampMixin, Base):
#: Eager-loaded with the paper: every read of a paper shows its template
#: name, and a lazy load there would be one query per row in the table.
template: Mapped["PaperTemplate | None"] = relationship(lazy="joined")
template: Mapped["Template | None"] = relationship(lazy="joined")
#: The paper's sentences, in document order.
#:
+3 -3
View File
@@ -10,7 +10,7 @@ whole design:
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 ``paper_template_field_sort``.)
with; it reads ``template_field_sort``.)
``sort``
Where this sentence sits *inside* that paragraph. A paragraph is reassembled
@@ -40,7 +40,7 @@ from app.models.mixins import TimestampMixin
if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.paper import Paper
from app.models.paper_sentence_reference import PaperSentenceReference
from app.models.paper_template import PaperTemplate
from app.models.template import Template
class PaperSentence(TimestampMixin, Base):
@@ -70,7 +70,7 @@ class PaperSentence(TimestampMixin, Base):
#: The template this sentence was written against — provenance only. Reads
#: never filter on it; see the module docstring.
template_id: Mapped[int | None] = mapped_column(
ForeignKey("paper_template.id", ondelete="SET NULL"),
ForeignKey("template.id", ondelete="SET NULL"),
nullable=True,
)
@@ -1,8 +1,9 @@
"""Paper templates (模板表).
"""Templates (模板表) — the outlines a paper can be written against.
A template is a named, ordered selection of library fields 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.section_field.SectionField`,
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.
"""
@@ -18,10 +19,10 @@ if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.template_field import TemplateField
class PaperTemplate(TimestampMixin, Base):
class Template(TimestampMixin, Base):
"""A named outline: a template name, a summary, and its ordered fields."""
__tablename__ = "paper_template"
__tablename__ = "template"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
@@ -43,4 +44,4 @@ class PaperTemplate(TimestampMixin, Base):
)
def __repr__(self) -> str: # pragma: no cover - debugging aid
return f"<PaperTemplate id={self.id} name={self.name!r}>"
return f"<Template id={self.id} name={self.name!r}>"
+6 -6
View File
@@ -25,8 +25,8 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.base import Base
if TYPE_CHECKING: # pragma: no cover - typing only
from app.models.paper_template import PaperTemplate
from app.models.section_field import SectionField
from app.models.template import Template
from app.models.template_field_library import TemplateFieldLibrary
class TemplateField(Base):
@@ -44,7 +44,7 @@ class TemplateField(Base):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
template_id: Mapped[int] = mapped_column(
ForeignKey("paper_template.id", ondelete="CASCADE"),
ForeignKey("template.id", ondelete="CASCADE"),
nullable=False,
)
@@ -52,7 +52,7 @@ class TemplateField(Base):
#: 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("section_field.id", ondelete="RESTRICT"),
ForeignKey("template_field_library.id", ondelete="RESTRICT"),
nullable=False,
)
@@ -60,11 +60,11 @@ class TemplateField(Base):
#: sorts render first regardless of the field's ``level``.
sort: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
template: Mapped["PaperTemplate"] = relationship(back_populates="items")
template: Mapped["Template"] = relationship(back_populates="items")
#: Eager-loaded because every template read needs the field's name and
#: typography; lazy loading would emit one query per row.
field: Mapped["SectionField"] = relationship(lazy="joined")
field: Mapped["TemplateFieldLibrary"] = relationship(lazy="joined")
def __repr__(self) -> str: # pragma: no cover - debugging aid
return (
@@ -1,6 +1,6 @@
"""The reusable section-field library (字段).
"""The reusable template-field library (字段).
A *section field* is one heading a paper can contain "1. Introduction",
A *library entry* is one heading a paper can contain "1. Introduction",
"2.1 Dataset", "0 Abstract". Fields live in this one global library and are
never owned by a template.
@@ -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:`SectionField.level` (1, 2, 3 ...), which is a *rendering hint* it
:attr:`TemplateFieldLibrary.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.
@@ -20,6 +20,11 @@ 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
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
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.
"""
from decimal import Decimal
@@ -31,10 +36,10 @@ from app.db.base import Base
from app.models.mixins import TimestampMixin
class SectionField(TimestampMixin, Base):
class TemplateFieldLibrary(TimestampMixin, Base):
"""A single reusable heading, with the typography it should render in."""
__tablename__ = "section_field"
__tablename__ = "template_field_library"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
@@ -72,6 +77,6 @@ class SectionField(TimestampMixin, Base):
def __repr__(self) -> str: # pragma: no cover - debugging aid
return (
f"<SectionField id={self.id} name={self.name!r} "
f"<TemplateFieldLibrary id={self.id} name={self.name!r} "
f"level={self.level} color={self.font_color}>"
)
+18 -18
View File
@@ -23,19 +23,19 @@ from app.schemas.paper import (
SentenceRead,
SentenceUpdate,
)
from app.schemas.paper_template import (
PaperTemplateCreate,
PaperTemplateListItem,
PaperTemplateRead,
PaperTemplateUpdate,
from app.schemas.template import (
TemplateCreate,
TemplateListItem,
TemplateRead,
TemplateUpdate,
TemplateFieldInput,
TemplateFieldRead,
)
from app.schemas.section_field import (
SectionFieldCreate,
SectionFieldRead,
SectionFieldRef,
SectionFieldUpdate,
from app.schemas.template_field_library import (
TemplateFieldLibraryCreate,
TemplateFieldLibraryRead,
TemplateFieldLibraryRef,
TemplateFieldLibraryUpdate,
)
__all__ = [
@@ -57,14 +57,14 @@ __all__ = [
"SentenceUpdate",
"BatchDeleteResult",
"PageResult",
"PaperTemplateCreate",
"PaperTemplateListItem",
"PaperTemplateRead",
"PaperTemplateUpdate",
"SectionFieldCreate",
"SectionFieldRead",
"SectionFieldRef",
"SectionFieldUpdate",
"TemplateCreate",
"TemplateListItem",
"TemplateRead",
"TemplateUpdate",
"TemplateFieldLibraryCreate",
"TemplateFieldLibraryRead",
"TemplateFieldLibraryRef",
"TemplateFieldLibraryUpdate",
"TemplateFieldInput",
"TemplateFieldRead",
"normalize_hex_color",
@@ -1,11 +1,11 @@
"""Request/response schemas for paper templates (模板管理)."""
"""Request/response schemas for templates (模板管理)."""
from datetime import datetime
from decimal import Decimal
from pydantic import BaseModel, ConfigDict, Field
from app.models.paper_template import PaperTemplate
from app.models.template import Template
from app.models.template_field import TemplateField
from app.schemas.common import TypographyMixin
@@ -54,14 +54,14 @@ class TemplateFieldRead(TypographyMixin, BaseModel):
)
class PaperTemplateBase(BaseModel):
class TemplateBase(BaseModel):
"""Shared body of the create/update payloads."""
name: str = Field(min_length=1, max_length=255)
abstract: str | None = None
class PaperTemplateCreate(PaperTemplateBase):
class TemplateCreate(TemplateBase):
"""Payload for ``POST /templates``.
The field selection is free: any subset, any order, repeats allowed. The
@@ -71,7 +71,7 @@ class PaperTemplateCreate(PaperTemplateBase):
fields: list[TemplateFieldInput] = Field(default_factory=list)
class PaperTemplateUpdate(BaseModel):
class TemplateUpdate(BaseModel):
"""Payload for ``PATCH /templates/{id}``.
``fields`` is a full replacement when present omit it to leave the
@@ -83,7 +83,7 @@ class PaperTemplateUpdate(BaseModel):
fields: list[TemplateFieldInput] | None = None
class PaperTemplateListItem(BaseModel):
class TemplateListItem(BaseModel):
"""A template as it appears in the list table — no field rows."""
model_config = ConfigDict(from_attributes=True)
@@ -96,7 +96,7 @@ class PaperTemplateListItem(BaseModel):
updated_at: datetime
class PaperTemplateRead(BaseModel):
class TemplateRead(BaseModel):
"""A template with its outline, already ordered by ``sort``."""
model_config = ConfigDict(from_attributes=True)
@@ -111,7 +111,7 @@ class PaperTemplateRead(BaseModel):
updated_at: datetime
@classmethod
def from_model(cls, template: PaperTemplate) -> "PaperTemplateRead":
def from_model(cls, template: Template) -> "TemplateRead":
"""Build the response from a template and its placement rows."""
return cls(
id=template.id,
@@ -1,4 +1,4 @@
"""Request/response schemas for the section-field library (字段管理)."""
"""Request/response schemas for the template-field library (字段管理)."""
from datetime import datetime
from decimal import Decimal
@@ -8,8 +8,8 @@ from pydantic import BaseModel, ConfigDict, Field
from app.schemas.common import TypographyMixin
class SectionFieldBase(TypographyMixin, BaseModel):
"""Fields a client may set on a section field."""
class TemplateFieldLibraryBase(TypographyMixin, BaseModel):
"""Fields a client may set on a library entry."""
#: Display name, numbering included — e.g. ``"1. Introduction"``. Stored
#: and rendered verbatim; the API never rewrites it.
@@ -25,12 +25,12 @@ class SectionFieldBase(TypographyMixin, BaseModel):
font_color: str = Field(default="#000000", max_length=32)
class SectionFieldCreate(SectionFieldBase):
"""Payload for ``POST /section-fields``."""
class TemplateFieldLibraryCreate(TemplateFieldLibraryBase):
"""Payload for ``POST /template-field-library``."""
class SectionFieldUpdate(TypographyMixin, BaseModel):
"""Payload for ``PATCH /section-fields/{id}`` — every part optional.
class TemplateFieldLibraryUpdate(TypographyMixin, BaseModel):
"""Payload for ``PATCH /template-field-library/{id}`` — every part optional.
The colour normaliser tolerates ``None`` here; the validator returns
non-strings untouched, so an omitted colour stays omitted.
@@ -42,8 +42,8 @@ class SectionFieldUpdate(TypographyMixin, BaseModel):
font_color: str | None = Field(default=None, max_length=32)
class SectionFieldRead(SectionFieldBase):
"""A stored section field."""
class TemplateFieldLibraryRead(TemplateFieldLibraryBase):
"""A stored library entry."""
model_config = ConfigDict(from_attributes=True)
@@ -52,7 +52,7 @@ class SectionFieldRead(SectionFieldBase):
updated_at: datetime
class SectionFieldRef(BaseModel):
class TemplateFieldLibraryRef(BaseModel):
"""How many templates currently place a field — used to explain a refusal."""
field_id: int
+15 -12
View File
@@ -1,4 +1,4 @@
"""Seed the section-field library and a couple of starter templates.
"""Seed the template-field library and a couple of starter templates.
Idempotent: fields are matched by name and templates by name, so running it
twice adds nothing. ``--reset`` empties the three tables first, which is the
@@ -27,7 +27,7 @@ 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 PaperTemplate, SectionField, TemplateField # noqa: E402
from app.models import Template, TemplateFieldLibrary, TemplateField # noqa: E402
# --- the field library -------------------------------------------------------
#
@@ -118,20 +118,20 @@ 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(PaperTemplate))
db.execute(delete(SectionField))
db.execute(delete(Template))
db.execute(delete(TemplateFieldLibrary))
db.commit()
def seed_fields(db: Session) -> dict[str, SectionField]:
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(SectionField)).all()}
existing = {field.name: field for field in db.scalars(select(TemplateFieldLibrary)).all()}
created = 0
for name, level, font_size, font_color in FIELDS:
if name in existing:
continue
field = SectionField(
field = TemplateFieldLibrary(
name=name, level=level, font_size=font_size, font_color=font_color
)
db.add(field)
@@ -142,13 +142,16 @@ def seed_fields(db: Session) -> dict[str, SectionField]:
for field in existing.values():
db.refresh(field)
print(f" section_field : {created} created, {len(existing) - created} already present")
print(
f" template_field_library : {created} created, "
f"{len(existing) - created} already present"
)
return existing
def seed_templates(db: Session, fields: dict[str, SectionField]) -> None:
def seed_templates(db: Session, fields: dict[str, TemplateFieldLibrary]) -> None:
"""Insert any missing starter templates."""
existing = {name for name in db.scalars(select(PaperTemplate.name)).all()}
existing = {name for name in db.scalars(select(Template.name)).all()}
created = 0
for name, abstract, field_names in TEMPLATES:
@@ -159,7 +162,7 @@ def seed_templates(db: Session, fields: dict[str, SectionField]) -> None:
if missing:
raise SystemExit(f"template {name!r} references unknown fields: {missing}")
template = PaperTemplate(name=name, abstract=abstract)
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 = [
@@ -170,7 +173,7 @@ def seed_templates(db: Session, fields: dict[str, SectionField]) -> None:
created += 1
db.commit()
print(f" paper_template: {created} created, {len(existing)} already present")
print(f" template: {created} created, {len(existing)} already present")
def main() -> None:
+49 -25
View File
@@ -57,17 +57,19 @@ Browser ──HTTP/JSON──▶ FastAPI ──SQLAlchemy──▶ TiDB (k3s)
## Domain Model
Six tables, and one rule that the last three follow from.
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:
```
section_field the reusable heading library
template_field_library the 字段库: reusable headings
id, name, level, font_size, font_color
paper_template a named outline
template a named outline (模板)
id, name, abstract
template_field the join, and the only home of display order
id, template_id → paper_template, field_id → section_field, sort
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
paper the document
id, title, template_id, abstract, author, status, keywords,
@@ -80,9 +82,15 @@ paper_sentence_reference the citations of one sentence
id, sentence_id → paper_sentence, reference_id, quote, sort
```
`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 field library is flat, not a tree
`section_field` has no `parent_id`. Hierarchy is expressed only by `level`
`template_field_library` 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.
@@ -123,7 +131,7 @@ work.
`paper_sentence.paper_template_filed_sort` holds the `sort` of the template
placement the sentence belongs to — **not** `template_field.id`, and not
`section_field.id`. Together with `sort`, the sentence's own position inside
`template_field_library.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
@@ -161,22 +169,34 @@ rejected with `422` rather than stored as a half-record. `reference_id` is a
plain nullable integer with **no** foreign key, because the reference library
does not exist yet; a citation may therefore be written now and linked later.
### TiDB does not enforce foreign keys
### Foreign keys are declared, and this cluster enforces them
TiDB parses `FOREIGN KEY` for compatibility, and from v6.6 honours it when
`tidb_enable_foreign_key` is on. On the cluster this project runs against it is
on, so the constraints are real integrity rather than documentation: a dangling
insert is rejected (`1452`) and `ON DELETE CASCADE` / `SET NULL` actually fire.
Two consequences are worth knowing before touching a migration:
TiDB parses `FOREIGN KEY` for compatibility and then ignores it. The constraints
are declared to document the relationships, and the integrity they would provide
is enforced in the application layer instead:
- deleting a field still placed in a template is refused with `409`, naming the
- **Tables must be created in dependency order**, and a rename must be checked
rather than assumed. `RENAME TABLE` does carry a referencing constraint along
with the renamed table here (the rename in revision `f27a1c6d9e04` was
rehearsed against the cluster before it was written), but that is a property
of the deployment, not of SQL.
- **The API still checks first.** A database violation surfaces as a generic
driver error, while the application refuses with a message that names the row
and the count:
- deleting a library field still placed in a template → `409`, naming the
field and how many templates use it;
- deleting a template that a paper is written against is refused with `409`,
naming the template and how many papers use it — the template is that paper's
structure, so removing it would empty the paper rather than tidy up;
- creating a template that references a missing field is refused with `400`, and
creating or patching a paper that references a missing template likewise;
- `PaperTemplate.items`, `Paper.sentences` and `PaperSentence.citations` all use
`cascade="all, delete-orphan"`, so deleting a row removes its dependents.
- deleting a template a paper is written against `409`, naming the template
and how many papers use it — the template *is* that paper's structure, so
removing it would empty the paper rather than tidy up;
- creating a template that references a missing field `400`, and creating
or patching a paper that references a missing template likewise.
The ORM cascades stay as well. `Template.items`, `Paper.sentences` and
`PaperSentence.citations` use `cascade="all, delete-orphan"`, so deleting a row
removes its dependents whether or not the database would have done it too —
which keeps behaviour identical on a cluster with foreign keys switched off.
## API
@@ -185,10 +205,10 @@ All routes are mounted under `/api`. Interactive docs at `/docs`.
| Method | Path | Notes |
|---|---|---|
| `GET` | `/health` | liveness plus a TiDB probe |
| `GET` | `/section-fields` | `keyword`, `level`, `page`, `page_size` |
| `POST` | `/section-fields` | create |
| `GET` `PATCH` `DELETE` | `/section-fields/{id}` | read / partial update / delete |
| `POST` | `/section-fields/batch-delete` | body `{ "ids": [...] }` |
| `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` | `/templates` | `keyword` matches name **or** abstract |
| `POST` | `/templates` | name + abstract + ordered `fields` |
| `GET` `PATCH` `DELETE` | `/templates/{id}` | `PATCH` with `fields` replaces the selection |
@@ -211,6 +231,9 @@ Conventions worth knowing:
it before using it in a CSS rule.
- 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
`paper`.
- A paper document returns its `paragraphs` in ascending position order,
already carrying their sentences and citation numbering. The client sorts
nothing and merges nothing: two implementations of the same ordering rule
@@ -311,7 +334,8 @@ silent re-shape of the document is exactly what the preview exists to prevent.
paper-doc/
├── backend/ # FastAPI application
│ ├── app/
│ │ ├── api/routes/ # route handlers (health, papers, section_fields, templates)
│ │ ├── api/routes/ # route handlers (health, papers, templates,
│ │ │ # template_field_library)
│ │ ├── core/ # settings and configuration
│ │ ├── crud/ # data-access helpers
│ │ ├── db/ # engine, session, declarative base
@@ -1,8 +1,8 @@
import http from './client'
import type { BatchDeleteResult, PageQuery, PageResult } from './types'
/** Mirrors `app.schemas.section_field.SectionFieldRead`. */
export interface SectionField {
/** Mirrors `app.schemas.template_field_library.TemplateFieldLibraryRead`. */
export interface TemplateFieldLibrary {
id: number
/** Display name, numbering included — e.g. `1. Introduction`. */
name: string
@@ -17,23 +17,23 @@ export interface SectionField {
}
/** Body for creating or updating a library field. */
export interface SectionFieldPayload {
export interface TemplateFieldLibraryPayload {
name: string
level: number
font_size: number
font_color: string
}
export interface SectionFieldQuery extends PageQuery {
export interface TemplateFieldLibraryQuery 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 listSectionFields(
query: SectionFieldQuery = {},
): Promise<PageResult<SectionField>> {
export async function listTemplateFieldLibrary(
query: TemplateFieldLibraryQuery = {},
): Promise<PageResult<TemplateFieldLibrary>> {
// Drop empty filters so the URL stays clean and the backend sees "no filter"
// rather than `keyword=`.
const params: Record<string, unknown> = {}
@@ -42,7 +42,10 @@ export async function listSectionFields(
if (query.page) params.page = query.page
if (query.page_size) params.page_size = query.page_size
const { data } = await http.get<PageResult<SectionField>>('/section-fields', { params })
const { data } = await http.get<PageResult<TemplateFieldLibrary>>(
'/template-field-library',
{ params },
)
return data
}
@@ -52,12 +55,12 @@ export async function listSectionFields(
* 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 fetchAllSectionFields(keyword?: string): Promise<SectionField[]> {
const all: SectionField[] = []
export async function fetchAllTemplateFieldLibrary(keyword?: string): Promise<TemplateFieldLibrary[]> {
const all: TemplateFieldLibrary[] = []
let page = 1
for (;;) {
const result = await listSectionFields({
const result = await listTemplateFieldLibrary({
keyword,
page,
page_size: LIBRARY_PAGE_SIZE,
@@ -70,29 +73,29 @@ export async function fetchAllSectionFields(keyword?: string): Promise<SectionFi
}
}
export async function createSectionField(
payload: SectionFieldPayload,
): Promise<SectionField> {
const { data } = await http.post<SectionField>('/section-fields', payload)
export async function createTemplateFieldLibrary(
payload: TemplateFieldLibraryPayload,
): Promise<TemplateFieldLibrary> {
const { data } = await http.post<TemplateFieldLibrary>('/template-field-library', payload)
return data
}
export async function updateSectionField(
export async function updateTemplateFieldLibrary(
id: number,
payload: Partial<SectionFieldPayload>,
): Promise<SectionField> {
const { data } = await http.patch<SectionField>(`/section-fields/${id}`, payload)
payload: Partial<TemplateFieldLibraryPayload>,
): Promise<TemplateFieldLibrary> {
const { data } = await http.patch<TemplateFieldLibrary>(`/template-field-library/${id}`, payload)
return data
}
export async function deleteSectionField(id: number): Promise<void> {
await http.delete(`/section-fields/${id}`)
export async function deleteTemplateFieldLibrary(id: number): Promise<void> {
await http.delete(`/template-field-library/${id}`)
}
export async function batchDeleteSectionFields(
export async function batchDeleteTemplateFieldLibrary(
ids: number[],
): Promise<BatchDeleteResult> {
const { data } = await http.post<BatchDeleteResult>('/section-fields/batch-delete', {
const { data } = await http.post<BatchDeleteResult>('/template-field-library/batch-delete', {
ids,
})
return data
@@ -11,18 +11,18 @@ import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
createSectionField,
updateSectionField,
type SectionField,
type SectionFieldPayload,
} from '@/api/sectionFields'
createTemplateFieldLibrary,
updateTemplateFieldLibrary,
type TemplateFieldLibrary,
type TemplateFieldLibraryPayload,
} from '@/api/templateFieldLibrary'
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: SectionField | null
field: TemplateFieldLibrary | null
}>()
const emit = defineEmits<{
@@ -39,7 +39,7 @@ const visible = computed({
const formRef = ref<FormInstance>()
const saving = ref(false)
const form = reactive<SectionFieldPayload>({
const form = reactive<TemplateFieldLibraryPayload>({
name: '',
level: 1,
// , the conventional body size for a Chinese thesis.
@@ -47,7 +47,7 @@ const form = reactive<SectionFieldPayload>({
font_color: '#000000',
})
const rules: FormRules<SectionFieldPayload> = {
const rules: FormRules<TemplateFieldLibraryPayload> = {
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 updateSectionField(props.field.id, { ...form })
await updateTemplateFieldLibrary(props.field.id, { ...form })
ElMessage.success('字段已更新,使用它的模板会同步生效')
} else {
await createSectionField({ ...form })
await createTemplateFieldLibrary({ ...form })
ElMessage.success('字段已创建')
}
emit('saved')
@@ -28,7 +28,7 @@ import {
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { errorMessage } from '@/api/client'
import { fetchAllSectionFields, type SectionField } from '@/api/sectionFields'
import { fetchAllTemplateFieldLibrary, type TemplateFieldLibrary } from '@/api/templateFieldLibrary'
import {
createTemplate,
getTemplate,
@@ -70,7 +70,7 @@ const formRef = ref<FormInstance>()
const loading = ref(false)
const saving = ref(false)
const library = ref<SectionField[]>([])
const library = ref<TemplateFieldLibrary[]>([])
const libraryKeyword = ref('')
const selected = ref<Placement[]>([])
@@ -145,7 +145,7 @@ watch(
try {
// The whole library, so a field that was placed before the keyword
// filter existed still resolves to a name in the selection.
library.value = await fetchAllSectionFields()
library.value = await fetchAllTemplateFieldLibrary()
if (props.template) {
const detail = await getTemplate(props.template.id)
@@ -166,7 +166,7 @@ watch(
)
/** Append a placement, at the end of the current order. */
function addField(field: SectionField): void {
function addField(field: TemplateFieldLibrary): 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 })
}
+2 -2
View File
@@ -12,7 +12,7 @@ import { useRouter } from 'vue-router'
import { Files, Notebook, Setting } from '@element-plus/icons-vue'
import { listPapers } from '@/api/papers'
import { listSectionFields } from '@/api/sectionFields'
import { listTemplateFieldLibrary } from '@/api/templateFieldLibrary'
import { listTemplates } from '@/api/templates'
import AppLogo from '@/components/AppLogo.vue'
@@ -33,7 +33,7 @@ onMounted(async () => {
const [papers, templates, fields] = await Promise.allSettled([
listPapers({ page: 1, page_size: 1 }),
listTemplates({ page: 1, page_size: 1 }),
listSectionFields({ page: 1, page_size: 1 }),
listTemplateFieldLibrary({ page: 1, page_size: 1 }),
])
if (papers.status === 'fulfilled') paperCount.value = papers.value.total
if (templates.status === 'fulfilled') templateCount.value = templates.value.total
@@ -14,18 +14,18 @@ import { ElMessage, ElMessageBox } from 'element-plus'
import { errorMessage } from '@/api/client'
import {
batchDeleteSectionFields,
deleteSectionField,
listSectionFields,
type SectionField,
} from '@/api/sectionFields'
batchDeleteTemplateFieldLibrary,
deleteTemplateFieldLibrary,
listTemplateFieldLibrary,
type TemplateFieldLibrary,
} from '@/api/templateFieldLibrary'
import FieldFormDialog from '@/components/fields/FieldFormDialog.vue'
import { formatDateTime, levelIndent, typographyStyle } from '@/utils/format'
const loading = ref(false)
const rows = ref<SectionField[]>([])
const rows = ref<TemplateFieldLibrary[]>([])
const total = ref(0)
const selection = ref<SectionField[]>([])
const selection = ref<TemplateFieldLibrary[]>([])
const query = reactive({
keyword: '',
@@ -35,7 +35,7 @@ const query = reactive({
})
const dialogVisible = ref(false)
const editing = ref<SectionField | null>(null)
const editing = ref<TemplateFieldLibrary | 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 listSectionFields(query)
const result = await listTemplateFieldLibrary(query)
rows.value = result.items
total.value = result.total
@@ -81,12 +81,12 @@ function onCreate(): void {
dialogVisible.value = true
}
function onEdit(row: SectionField): void {
function onEdit(row: TemplateFieldLibrary): void {
editing.value = row
dialogVisible.value = true
}
async function onDelete(row: SectionField): Promise<void> {
async function onDelete(row: TemplateFieldLibrary): Promise<void> {
try {
await ElMessageBox.confirm(`确定删除字段「${row.name}」?`, '删除字段', {
type: 'warning',
@@ -98,7 +98,7 @@ async function onDelete(row: SectionField): Promise<void> {
}
try {
await deleteSectionField(row.id)
await deleteTemplateFieldLibrary(row.id)
ElMessage.success('已删除')
await load()
} catch (error) {
@@ -121,7 +121,7 @@ async function onBatchDelete(): Promise<void> {
}
try {
const result = await batchDeleteSectionFields(ids)
const result = await batchDeleteTemplateFieldLibrary(ids)
ElMessage.success(`已删除 ${result.deleted} 个字段`)
selection.value = []
await load()
@@ -194,7 +194,7 @@ onMounted(load)
row-key="id"
stripe
class="table"
@selection-change="(value: SectionField[]) => (selection = value)"
@selection-change="(value: TemplateFieldLibrary[]) => (selection = value)"
>
<el-table-column type="selection" width="46" reserve-selection />