"""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.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 ), ) @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 只看还没用过的" ), 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, 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 in order.""" return crud.read(db, crud.create(db, payload)) @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`` is a full replacement when present — the citation prints them in the order sent, so there is no partial form of that list. """ reference = _get_or_404(db, reference_id) return crud.read(db, crud.update(db, reference, payload)) @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)