"""Reference-library endpoints (参考文献). The library is global and reusable: an article is added once and then cited from any number of sentences in any number of papers. That is why deleting one is guarded — the citation rows are the only thing tying a paper's 参考文献 list to the literature, and dropping a cited reference would quietly empty those citations rather than tidy up the library. The reverse lookup lives here too: ``GET /references/{id}/citations`` answers "which of my sentences use this?", which is the question a library exists to answer once the writing has started. """ from fastapi import APIRouter, Depends, HTTPException, Query, Response, status from sqlalchemy.orm import Session from app.crud import reference as crud from app.crud.reference_tag import UnknownTag from app.db.session import get_db from app.models import REFERENCE_TYPES, Reference from app.schemas.common import BatchDeleteRequest, BatchDeleteResult, PageResult from app.schemas.reference import ( ReferenceCitationRead, ReferenceCreate, ReferenceListItem, ReferenceRead, ReferenceUpdate, ) router = APIRouter(prefix="/references", tags=["references"]) def _get_or_404(db: Session, reference_id: int) -> Reference: reference = crud.get(db, reference_id) if reference is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"参考文献 {reference_id} 不存在", ) return reference def _assert_not_cited(db: Session, references: list[Reference]) -> None: """Refuse the delete while any sentence cites the reference. All offenders are reported at once rather than one per attempt, so a batch delete does not turn into trial and error. The message says what to do about it, because "in use" without a next step is a dead end. """ counts = crud.citation_counts(db, [reference.id for reference in references]) if not counts: return titles = {reference.id: reference.title for reference in references} blockers = "、".join( f"“{titles.get(reference_id, reference_id)}”({count} 处引用)" for reference_id, count in sorted(counts.items()) ) raise HTTPException( status_code=status.HTTP_409_CONFLICT, detail=( "以下文献正被论文引用,请先在段落里移除对应引用:" + blockers ), ) def _unknown_tag(error: UnknownTag) -> HTTPException: """Report an applied tag that does not exist as ``400`` naming it. A ``400`` rather than a ``422``: the body parsed, and the offending value is a real integer — it is the library that has no such label. The message names the ids so the client can tell a stale picker from a typo. """ return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(error)) @router.get("", response_model=PageResult[ReferenceListItem], summary="List references") def list_references( db: Session = Depends(get_db), keyword: str | None = Query( default=None, description="按题名、刊名、作者、DOI、关键词或备注模糊搜索" ), type_filter: str | None = Query( default=None, alias="type", description="按文献类型过滤:" + " / ".join(REFERENCE_TYPES), ), year: int | None = Query(default=None, ge=1, le=2999, description="按出版年过滤"), cited: bool | None = Query( default=None, description="true 只看已被引用的,false 只看还没用过的" ), tag: list[int] | None = Query( default=None, description="按标签过滤,可重复;给多个标签时取交集(都打了才留下)", ), page: int = Query(default=1, ge=1), page_size: int = Query(default=20, ge=1, le=200), ) -> PageResult[ReferenceListItem]: """Browse the library, newest publication first.""" items, total = crud.list_references( db, keyword=keyword, type_=type_filter, year=year, cited_only=cited, tag_ids=tag, page=page, page_size=page_size, ) return PageResult.build(items=items, total=total, page=page, page_size=page_size) @router.post( "", response_model=ReferenceRead, status_code=status.HTTP_201_CREATED, summary="Add a reference", ) def create_reference( payload: ReferenceCreate, db: Session = Depends(get_db), ) -> ReferenceRead: """Add one document to the library, with its contributors and its tags.""" try: created = crud.create(db, payload) except UnknownTag as error: raise _unknown_tag(error) from error return crud.read(db, created) @router.post( "/batch-delete", response_model=BatchDeleteResult, summary="Delete several references", ) def batch_delete_references( payload: BatchDeleteRequest, db: Session = Depends(get_db), ) -> BatchDeleteResult: """Delete the given references, refusing wholesale if any is cited.""" references = crud.get_many(db, payload.ids) _assert_not_cited(db, references) return BatchDeleteResult(deleted=crud.delete_many(db, payload.ids)) @router.get("/{reference_id}", response_model=ReferenceRead, summary="Fetch one reference") def get_reference(reference_id: int, db: Session = Depends(get_db)) -> ReferenceRead: """Return one reference, with its contributors and citation count.""" return crud.read(db, _get_or_404(db, reference_id)) @router.get( "/{reference_id}/citations", response_model=list[ReferenceCitationRead], summary="Which sentences cite this reference", ) def list_reference_citations( reference_id: int, db: Session = Depends(get_db) ) -> list[ReferenceCitationRead]: """Return every sentence that cites this reference, with its paragraph. This is the direction the paper side cannot answer: a sentence knows which articles it quotes, but only the library can say where an article has been used — which is what tells the writer whether it is safe to delete, and where to look when a citation has to change. """ return crud.list_citations(db, _get_or_404(db, reference_id)) @router.patch( "/{reference_id}", response_model=ReferenceRead, summary="Update a reference" ) def update_reference( reference_id: int, payload: ReferenceUpdate, db: Session = Depends(get_db), ) -> ReferenceRead: """Update any part of a reference. ``authors`` and ``tag_ids`` are full replacements when present — the citation prints the contributors in the order sent, and the tag list *is* the set of labels on the row, so ``[]`` clears them. """ reference = _get_or_404(db, reference_id) try: updated = crud.update(db, reference, payload) except UnknownTag as error: raise _unknown_tag(error) from error return crud.read(db, updated) @router.delete( "/{reference_id}", status_code=status.HTTP_204_NO_CONTENT, summary="Delete a reference", ) def delete_reference(reference_id: int, db: Session = Depends(get_db)) -> Response: """Delete a reference no sentence cites.""" reference = _get_or_404(db, reference_id) _assert_not_cited(db, [reference]) crud.delete(db, reference) return Response(status_code=status.HTTP_204_NO_CONTENT)