from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel, Field from sqlalchemy.orm import Session from app.core.deps import require_staff from app.db import get_db from app.models.about import ( admin_about_page, admin_experts, create_expert, delete_expert, save_about_page, update_expert, ) from app.models.home import admin_column_articles router = APIRouter(dependencies=[Depends(require_staff)]) class AboutPageWrite(BaseModel): published: bool = False bodyHtml: str = "" attachmentFileIds: list[int] = Field(default_factory=list) class ExpertWrite(BaseModel): name: str bodyHtml: str = "" sortOrder: int = 0 published: bool = False attachmentFileIds: list[int] = Field(default_factory=list) @router.get("/about/pages/{page_key}") def read_about_page(page_key: str, db: Session = Depends(get_db)) -> dict: body = admin_about_page(db, page_key) if body is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="单篇页键不正确") return body @router.put("/about/pages/{page_key}") def write_about_page(page_key: str, body: AboutPageWrite, db: Session = Depends(get_db)) -> dict: try: save_about_page(db, page_key, body.model_dump()) except ValueError as exc: code = status.HTTP_404_NOT_FOUND if "不正确" in str(exc) else status.HTTP_400_BAD_REQUEST raise HTTPException(status_code=code, detail=str(exc)) from exc return {"ok": True} @router.get("/about/articles/{category}") def list_column_articles(category: str, db: Session = Depends(get_db)) -> dict: body = admin_column_articles(db, category) if body is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="文章类别不正确") return body @router.get("/about/experts") def list_experts(db: Session = Depends(get_db)) -> dict: return admin_experts(db) @router.post("/about/experts") def write_expert(body: ExpertWrite, db: Session = Depends(get_db)) -> dict: try: expert_id = create_expert(db, body.model_dump()) except ValueError as exc: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc return {"id": expert_id} @router.put("/about/experts/{expert_id}") def revise_expert(expert_id: int, body: ExpertWrite, db: Session = Depends(get_db)) -> dict: try: update_expert(db, expert_id, body.model_dump()) except ValueError as exc: code = status.HTTP_404_NOT_FOUND if str(exc) == "专家委员会不存在" else status.HTTP_400_BAD_REQUEST raise HTTPException(status_code=code, detail=str(exc)) from exc return {"ok": True} @router.delete("/about/experts/{expert_id}") def remove_expert(expert_id: int, db: Session = Depends(get_db)) -> dict: try: delete_expert(db, expert_id) except ValueError as exc: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc return {"ok": True}